Is there a way to get __thismodule__?

Peter Otten __peter__ at web.de
Wed Mar 19 05:50:52 EDT 2008


benhoyt wrote:

> Is there a way to get __thismodule__ in Python? That is, the current
> module you're in. Or isn't that known until the end of the module?
> 
> For instance, if I'm writing a module of message types/classes, like
> so:
> 
> class SetupMessage(Message):
>     number = 1
> 
> class ResetMessage(Message):
>     number = 2
> 
> class OtherMessage(Message):
>     number = 255
> 
> nmap = {  # maps message numbers to message classes
>     1: SetupMessage,
>     2: ResetMessage,
>     255: OtherMessage,
> }
> 
> Or something similar. But adding each message class manually to the
> dict at the end feels like repeating myself, and is error-prone. It'd
> be nice if I could just create the dict automatically, something like
> so:
> 
> nmap = {}
> for name in dir(__thismodule__):
>     attr = getattr(__thismodule__, name)
>     if isinstance(attr, Message):
>         nmap[attr.number] = attr
> 
> Or something similar. Any ideas?

Use globals():

def is_true_subclass(a, b):
    try:
        return issubclass(a, b) and a is not b
    except TypeError:
        return False

nmap = dict((m.number, m) for m in globals().itervalues()
            if is_true_subclass(m, Message))
print nmap

You may also rely on duck-typing, assuming that everything that has a number
attribute is a Message subclass:

nmap = dict((m.number, m) for m in globals().itervalues()
            if hasattr(m, "number"))

Peter



More information about the Python-list mailing list