python - clean name space and __init__.py -
i designing python package following directory structure
package\ __init__.py subpackage1\ __init__.py module1.py module2.py subpackage2\ __init__.py module3.py
i users able explore clean name space reflects directory structure using tab completion when importing package in ipython.
for example, after doing
import package pkg
i want tab completion on pkg. show pkg.subpackage1 pkg.subpackage2
, tab completion on pkg.subpackage1
. show pkg.subpackage1.module1 pgk.subpackage1.module2
. of these modules depend on each other, , include import statements
.
for example in module1.py
have,
from ..subpackage2 import module3
however, don't want able tab complete following pkg.subpackage1.module1.module3
if they've done import pkg.subpackage1.module1
.
in addition, when people import pkg.subpackage1.module1
don't want tab completion on pkg.subpackage1.module1
. show things internal exception classes , fact imported numpy np in module1. in other words, i'd usage of module3 in module1 hidden user usage of numpy np. using things import numpy _np
, from ..subpackage2 import module3 _module3
best way this?
do have prepend underscore don't want them see?
to clarify, can see in scipy source code file scipy.integrate.quadrature has line import numpy np
in it, when import scipy
in ipython can tab complete out scipy.integrate.quadrature , not see np
in package/__init__.py
, include:
import subpackage1 import subpackage2
this makes sure anytime package
imported, imports subpackagex
, package.subpackagex
.
in subpackagex/__init__.py
don't include anything. in order package.subpackagex.modulex
defined, 1 have import explicitly (e.g. from package.subpackage1 import module1
)
note if take underscores approach, in ipython, 1 still tab-complete names prefixed underscores, if doing package.subpackage1._<tab>
.
edit:
other alternatives:
- in
subpackage1/__init__.py
, import names want expose, e.g.from .module1 import x,y
. make them definedpackage.subpackage1.x
, notpackage.subpackage1.module1.x
- define names using
__all__
directive. not affect tab-completion, declarative way of saying importer should of interest. way, canfrom package.subpackage1 import *
.
Comments
Post a Comment