scoping assertion

Andrew Dalke dalke at bioreason.com
Wed Jul 7 17:36:56 EDT 1999


Michael McCandless <mail at mikemccandless.com> said:
> 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.

Try this:

import sys

def nonexist(name):
  try:
    1/0
  except ZeroDivisionError:
    assert not sys.exc_info()[2].tb_frame.f_back.f_locals.has_key(name),\
      "variable %s already exists" % `name`

def test():
    nonexist("x")
    print "x does not exist"
    x = 1
    print "What about now?"
    nonexist("x")
    print "x does not exist"

>>> test()
x does not exist
What about now?
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in test
  File "<stdin>", line 5, in nonexist
AssertionError: variable 'x' already exists

  There is a lot of tricky things you can do by peering at the
stack.


						Andrew Dalke
						dalke at acm.org




More information about the Python-list mailing list