How to find the package a module belongs to ?

Siggy Brentrup bsb at winnegan.de
Fri Jun 1 23:57:21 CEST 2001


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.

> [Jeff]
> >It would sure be nice to pull this information from some 
> >secret variable without having to explicitly name them.    
> 
> But every module has a __file__ attribute that will tell you (whether the 
> module is loaded as x or p.x) that it came from some/path/p/x.py.
> 

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'

Regards
  Siggy

-- 
Siggy Brentrup - bsb at winnegan.de - http://www.winnegan.de/
****** ceterum censeo javascriptum esse restrictam *******





More information about the Python-list mailing list