scoping assertion

Michael Hudson mwh21 at cam.ac.uk
Wed Jul 7 14:32:00 EDT 1999


Michael McCandless <mail at mikemccandless.com> writes:

> 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

Well, it's a bit baroque, but it works (if you have my bytecodehacks
package: http://starship.python.net/crew/mwh/):

from bytecodehacks.macro import add_macro, expand
from bytecodehacks.code_editor import EditableCode,Function
EditableCode.AUTO_RATIONALIZE = 0

def notexist((x)):
    try:
        x
    except:
        return
    del x
    x

ff = Function(notexist)
ff.func_code.rationalize()

add_macro(ff.make_function())

if __name__ == '__main__':
    def test():
        notexist(y) # should succeed
        y = 1
        notexist(y) # should fail
    test=expand(test)
    test()

and to prove it:

[mwh21 at atrus python]$ python notexist.py
Traceback (innermost last):
  File "notexist.py", line 24, in ?
    test()
  File "notexist.py", line 22, in test
    notexist(y) # should fail
NameError: y

unhelpful-ly y'rs
Michael




More information about the Python-list mailing list