I have the following package structure:
package_name/
__init__.py
some_module.py
another_module.py
# other classes
I'm using this package from another Python file, in which I would like to do the following:
declare an alias for package_name
import package_name as pn
and refer to classes inside some_module.py
, another_module.py
, etc. as follows:
instance = pn.SomeClass(pn.AnotherClass(x, y))
ie omitting the module name and instead using only the package name alias.
Something like this:
import package_name as pn
from package_name import some_module to pn
Is this, or anything equivalent, possible?
I can do this:
from package_name.some_module import SomeClass
from package_name.another_module import AnotherClass
instance = SomeClass(AnotherClass(x, y))
and this:
import package_name.some_module
import package_name.another_module
instance = pn.some_module.SomeClass(pn.some_module.AnotherClass(x, y))
but this doesn't work
import package_name.some_module as pn
import package_name.another_module as pn
instance = pn.SomeClass(pn.AnotherClass(x, y))
because the second as pn
overrides the first one.
The syntax to import a single module from the package is:
from package_name import some_module as pn
To have access from package_name
to the classes defined inside the other modules, the right thing to do is to import these classes, explictly or using some tool, to the __init__.py
file inside package_name:
package_name/__init__.py
:
from .some_module import a_class
from .another_module import another_class
And that will allow you to simply do:
import package_name as pn
pn.a_class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.