Best way to dynamically get an attribute from a module from within the same module

Rafe rafesacks at gmail.com
Mon Nov 24 05:11:49 CET 2008


What are the pros and cons of these two patterns (and are there any
other)? Which is the best way to dynamically get an attribute from a
module from within the same module?

1) Using the name of the module
    this_module = sys.modules[__name__]
    attr = getattr(this_module, "whatever", None)

2) using globals
    globals()["whatever"]


I have been using #1 for two reasons. First, I will never run this
module directly, so __name__ will always be the module name and not
"__main__". Second, I can use this in a class to decide whether I want
the module where the class came from or, if I make the class a base
for a class in another module, the module where the sub-class is.

I am not familiar with the scope, pros or cons of globals() so I would
love to hear comments on this subject.


Cheers,

- Rafe



More information about the Python-list mailing list