Reference current module?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jun 19 22:27:54 EDT 2007


En Tue, 19 Jun 2007 16:34:50 -0300, Steven Bethard  
<steven.bethard at gmail.com> escribió:

> Tobiah wrote:
>>
>> getattr(current_module, 'foo')
>>
>> where 'current_module' is a handle the the one
>> that the code is in?  Just like
>
> You can try __import__() with __name__::
>
>      >>> foo = 42
>      >>> mod = __import__(__name__)
>      >>> getattr(mod, 'foo')
>      42

A simple way would be using sys.modules[__name__].
But I prefer using globals()['foo'] as it is simpler and does not assume  
additional requirements (like __name__ still being the same, or the module  
still available for importing).

-- 
Gabriel Genellina




More information about the Python-list mailing list