Mass importing of a template based system.. Trouble with name substitutions

Peter Otten __peter__ at web.de
Thu Aug 4 11:07:50 EDT 2005


rh0dium wrote:

> for mod in modules:
>     a = mod.mod()
>     a.run()

Puzzle: If mod.mod did what you expect, what would a.run have to do to
maintain consistency?

There would be no way to determine the name of the module bound to the mod
variable, but fortunately the Python developers foresaw your problem and
stashed it (the name) in the __name__ attribute.
Use getattr(obj, attrname) to look up an attribute whose name is not known
at compile time:

for mod in modules:
    a = getattr(mod, mod.__name__)()
    a.run()
 
Peter




More information about the Python-list mailing list