How to find the package a module belongs to ?
Gordon McMillan
gmcm at hypernet.com
Fri Jun 1 22:31:51 EDT 2001
Siggy Brentrup wrote:
>gmcm at hypernet.com (Gordon McMillan) writes:
>
>> Jeff Sandys wrote:
>> ...
>> [Sasa Zivkov]
>> >> I have a package containing several modules.
>> >> Is is possible, within a module,
>> >> to say "give me the package I belong to" ?
>>
>> Strictly speaking, no, not automatically, because module x within
>> package p may be loaded as p.x or just as x.
[Siggy]
>Just use the module's __name__ attribute, in both cases it's 'p.x'.
>A module is part of a package iff it's __name__ attribute contains a
>'.'.
>
>>>> import xml.dom.html as H
>>>> H.__name__
>'xml.dom.html'
>>>> import socket as S
>>>> S.__name__
>'socket'
Given
/test
__init__.py
a.py
b.py
Then:
C:\tmp\test>python a.py
I'm b. My __name__ is b
C:\tmp\test>cd ..
C:\tmp>python test/a.py
I'm b. My __name__ is b
C:\tmp>python
Python 1.5.42+ (#0, Mar 28 2000, 20:39:47) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> from test import a
I'm b. My __name__ is test.b
ignoring-the-case-of-my-__name__-is-__main__ly y'rs
- Gordon
More information about the Python-list
mailing list