Changing behaviour of namespaces - solved, I think

Mikael Olofsson mikael at isy.liu.se
Thu Sep 21 15:34:18 CEST 2006


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!

/MiO



More information about the Python-list mailing list