class derived from dict in eval

Andrew Dalke adalke at mindspring.com
Sun Mar 2 05:50:05 EST 2003


Alex:
> So, I _did_ get help, and enhanced this approach, but
> for the case of expressions that use qualified names,
> and mappings that may take a lot of computational
> effort to produce the values for some of their keys,
> it's hard to see how to make things satisfactory...

Sounds like a challange.  What about

>>> import compiler
>>> from compiler import visitor
>>> s = "a.b+c+''.find('d')"
>>> class GetNames(visitor.ASTVisitor):
...    def __init__(self):
...        self.names = {}
...    def visitName(self, obj):
...        self.names[obj.name] = 1
...

>>> a = compiler.parse(s)
>>> names = compiler.walk(a, GetNames()).names.keys()
>>> names
['a', 'c']
>>>

and use the list of names to populate the real dictionary?

This works because I think the only time the 'Name' node
is used is to get a top-level name from the current namespace.
Eg, a.b uses Getattr(Name('a'), 'b')

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list