Thursday, March 24, 2005

How well do you know Python, part 1

Here is a stripped down script that tests a part of Spyce's code to "export" variables from an active tag to the main spyceProcess scope. Even without knowing the background, though, you should be able to figure out: What error will running this code produce?
class spyceImpl:
  def spyceProcess(self):
    ___tagexports={'y': 1, 'item': 0}
    for ___tagkey in ___tagexports:
      exec("%s = ___tagexports['%s']"%(___tagkey,___tagkey))

test = spyceImpl()
test.spyceProcess()

5 comments:

Ian Bicking said...

OK, I'll guess... name mangling in the function doesn't match the name mangling in the exec'd statement (which doesn't know about its function scope), so you get a NameError.

Jonathan Ellis said...

Correct.

NotAnExpert said...

Not a Python Expert.

Can someone please explain this more? Name mangling? Does that mean the double underscores?

Jonathan Ellis said...

From the 1.4 release notes: "Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is now textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard of the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, as well as globals, and even to store instance variables private to this class on instances of other classes. Truncation may occur when the mangled name would be longer than 255 characters. Outside classes, or when the class name consists of only underscores, no mangling occurs."

Anonymous said...

That is so great!
It's also possible to run python in parallel on SMP: Parallel Python