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

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Nov 29 03:35:41 EST 2008


En Mon, 24 Nov 2008 02:11:49 -0200, Rafe <rafesacks at gmail.com> escribió:

> 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"]

3) using the bare name:
whatever

1) and 2) are useful when the desired name is variable, not a constant
like "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__".

(note that it works even with __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 don't completely understand your use case. In the expression:
    getattr(some_module, attribute_name)
you may use any module as the first argument (the current module, or any  
other).

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

Perhaps if you explain in more detail your use case, somebody else may  
have further comments...
I don't have the need to use globals()[name] very often.

-- 
Gabriel Genellina




More information about the Python-list mailing list