Introspection at the module level?

Peter Hansen peter at
Sat Mar 6 17:53:27 CET 2004

Roy Smith wrote:

> I've got a module that defines a bunch of constants:
> OP_FOO = 1
> OP_BAR = 2
> OP_BAZ = 37
> and so on.  The values are all unique.  I want to build, at module 
> import time, a reverse map of these constants, i.e. I want to end up 
> with:
> {1: "OP_FOO", 2: "OP_BAR", 37: "OP_BAZ"}
> I can find the appropriate symbols:
> for name in dir():
>    if name.startswith ("OP_"):
>       print name
> But I don't see how to get the values.  Getattr() is sort of what I 
> want, but it works on objects, not modules.  Not to mention that I don't 
> see how to get a handle to the module from inside the module, i.e. 
> there's no "self".
> What am I missing?


That returns a dict which has those constants in it, so you can ask for 
.keys() or .values(), etc.

Think of dir() as just globals().keys() in this case...


More information about the Python-list mailing list