Changing behaviour of namespaces - solved, I think

Peter Otten __peter__ at web.de
Thu Sep 21 16:16:03 CEST 2006


Mikael Olofsson wrote:

> Peter Otten wrote:
>> To feed an arbitrary mapping object to execfile() you need to upgrade to
>> Python 2.4.
> 
> Thanks! As clear as possible. I will do that.
> 
> FYI: I think I managed to achieve what I want in Py2.3 using the
> compiler module:
> 
>     def getNamesFromAstNode(node,varSet):
>         if node.__class__ in (compiler.ast.Global,compiler.ast.Import):
>             varSet.union_update(node.names)
>         if node.__class__ in (compiler.ast.Name,):
>             varSet.add(node.name)
>         for subNode in node.getChildNodes():
>             getNamesFromAstNode(subNode,varSet)
> 
>     # Get all variable names that are referenced in the file:
>     varSet = sets.Set()
>     mainNode = compiler.parseFile(filePath)
>     getNamesFromAstNode(mainNode,varSet)
> 
>     # Define a namespace and update it:
>     ns = {}
>     for varName in varSet:
>         ns[varName] = dummyObject
> 
>     # Execute the file without NameErrors:
>     execfile(filePath,ns)
> 
> Batteries included!

Clearly more elegant than:

>>> print open(filename).read()
b = a
>>> dummy = 42
>>> names = []
>>> while 1:
...     ns = dict((n, dummy) for n in names)
...     try:
...             execfile(filename, ns)
...     except NameError, e:
...             names.append(e[0][6:-16])
...     else:
...             break
...
>>> names
['a']

:-)

Peter



More information about the Python-list mailing list