B
benhoyt
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?
(A friend suggested class decorators, which is a good idea, except
that they're not here until Python 2.6 or Python 3000.)
Cheers,
Ben.
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?
(A friend suggested class decorators, which is a good idea, except
that they're not here until Python 2.6 or Python 3000.)
Cheers,
Ben.