Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

referencing the module a piece of code is in

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


hitt at eskimo

Sep 12, 2001, 11:31 AM

Post #1 of 3 (268 views)
Permalink
referencing the module a piece of code is in

I'd like to be able to get a reference to a module a piece of
code is in.

I can do something like:
# my_module.py

class dummy:
pass

def my_module():
import sys
return sys.modules[dummy.__module__]

but this feels much too lengthy. I'd prefer something like

# my_desired_module.py

def my_module():
return __nifty_abbreviation_for_module__

Is this possible (and if not, why not?)?

Thanks in advance for any info (including references to the FAQ etc).

dan


shalehperry at home

Sep 12, 2001, 11:50 AM

Post #2 of 3 (250 views)
Permalink
referencing the module a piece of code is in [In reply to]

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.


hitt at eskimo

Sep 12, 2001, 1:53 PM

Post #3 of 3 (247 views)
Permalink
referencing the module a piece of code is in [In reply to]

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.

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact lists@gossamer-threads.com
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.