scoping assertion

Michael McCandless mail at mikemccandless.com
Wed Jul 7 13:55:29 EDT 1999


I wonder if Python could be extended to allow a prefix in front of
variable names (lvalues?) to assert that the name did not previously
exist in this scope.  EG, call it "nonexist":

  nonexist x = 0
  while x < 10:
    ...

Or

  for nonexist x in xrange(1, 1000):
    ...

If x had previously existed in this scope at the time of assignment, an
appropriate exception would be raised.

Jim Hugunin pointed out that this could be achieved as follows:

  assert not locals().has_key('x')

But because there are no macros in Python, and because you can't make
this a function (?), I think you'd need to type this out every time.

The reason I ask is because I've had some sneaky bugs whereby I assigned
to what I thought was a new variable name, but inadvertantly wiped out a
value that I later used.

Statically typed languages basically give you this "for free" ;),
meaning if you try to "declare" the variable again, the
compiler/interpreter will typically generate an error saying the
variable is already defined in this scope.

Mike




More information about the Python-list mailing list