When we use from package.subpackage import module
, how can we access the package and subpackage init file variables from the calling module?
Assuming varname
is name of variable in the __init__ file
from both the package
and package.subpackage
, how can we access them in the calling module? Example:
package.varname
package.subpackage.varname
I know that if we had used 'import package.subpackage.module' then the above is possible but I am getting name is not defined error when I try to do the same using the from pkg.subpkg import mod
approach since the package is not in the local namespace (only module is).
If a variable named varname
is defined in the __init__.py
module of a package named package
, then we can access varname
like this:
from package import varname
print(varname)
Similarly, if a variable named varname
is defined in the __init__.py
module of the subpackage named subpackage
of a package named package
, then we can access varname
like this:
from package.subpackage import varname
print(varname)
To access both of them at the same time we should take care of the naming conflict like this:
from package import varname as package_varname
from package.subpackage import varname as package_subpackage_varname
print(package_varname)
print(package_subpackage_varname)
Also, __init__.py
allows us to define any variable at the package level. Doing so is often convenient if a module defines something that will be imported frequently. This pattern promotes adherence to the Pythonic flat is better than nested
philosophy.
An example:
Suppose our project structure looks like:
/project
- __init__.py
- file1.py
And our file1.py
looks like:
message = 'hi there'
Then we can access it like:
from project.file1 import message
print(message)
Now to make it accessible like:
from project import message
In the __init__.py
we can do:
from .file1 import message
__all__ = ['message']
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.