2010-08-05

Python 'global' Keyword Considered Harmful

Looking at Python's global keyword led me to think how I'd like scoping to work. Some languages have lexical scoping, some dynamic scoping and some a mixture of two. I think scoping should be entirely lexical. My language (let's call it Klop) is dynamically typed, and variables are declared the first time they are assigned, so if you wrote:
x = 0

def f():
return x

def g():
x = 1
return f()
Calling g() would return 1. In most languages with lexical scoping you can declare a variable with the same name, at a more local scope. With Klop you can't, and I think that this would make programs more readable.

2 comments:

  1. If you didn't scope this at a module level (or provide some way of renaming variables on import) then either code reuse becomes very hit and miss, or people will be reduced to mangling variable names (e.g. inserting a java style package as a prefix for all).

    Don't deny that all other types of scoping have issues.

    ReplyDelete
  2. Lexical scoping can only apply within a single source file. What you do about importing other files is a separate question. I think the Java importing solution is a practical one, but I'm open to suggestions!

    ReplyDelete