referencing the module a piece of code is in

Dan Hitt hitt at eskimo.com
Wed Sep 12 22:53:37 CEST 2001


Hi Sean,

Thanks for your mail.

You are absolutely right.

I was looking for an expression that i could use anywhere
in a file/module and get a reference to the module,
and __name__ (or more exactly, sys.modules[__name__]) does it.

I was inexcusably confused by the fact that functions and classes also
have a __name__ attribute.  But indeed inside the scope
of a class, an unqualified __name__ means the name of the module,
not the name of the class.

I still wonder if the sys.modules[] part can be dropped (i.e., if
there's some expression like __this_module__ which directly evaluates
to the module it's in) but that's getting more unreasonable to ask for
since the __name__'s are in one-to-one correspondence with the
modules.

Thanks again Sean.

dan


|   On 12-Sep-2001 Dan Hitt wrote:
|   > I'd like to be able to get a reference to a module a piece of
|   > code is in.
|   > 
|
|   you have seen this before:
|
|   if __name__ == '__main__':
|	   # do work
|
|   there is the answer -- __name__ refers to the name of the module.





More information about the Python-list mailing list