Is there a way to get __thismodule__?
Duncan Booth
duncan.booth at invalid.invalid
Wed Mar 19 06:29:10 EDT 2008
benhoyt <benhoyt at gmail.com> wrote:
> 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.)
>
Why not just use your base class?
class Message(object):
@staticmethod
def getmap():
return dict((cls.number, cls)
for cls in Message.__subclasses__())
class SetupMessage(Message):
number = 1
class ResetMessage(Message):
number = 2
class OtherMessage(Message):
number = 255
nmap = Message.getmap()
More information about the Python-list
mailing list