Python imported the package, and the properties reported an error
I’m new to Python and I want to understand how package and import statements work.
I made this package, located on my desktop :
package/
__ init __.py
module2.py
subpackage1/
__ init __.py
module1.py
This is the contents of __ init __ .py in the package folder:
__ all __ =["module2"]
import os
os.chdir("C:/Users/Leo--/Desktop/Package")
import subpackage1.module1
os.chdir("C:/Users/Leo--/Desktop")
In __ init __ .py in the subpackage1 folder:
__ all __ =["module1"]
I just want to import module1.py and module2.py by writing
import package
After entering the above command in the interpreter, I can access any function of module1.py without any problem by writing
it
package.subpackage1.module1.mod1()
where mod1() is the function defined in module1.py.
But when I type
package.module2.mod2()
I get “AttributeError: module ‘package’ does not have attribute ‘module2′” (mod2() is a function defined in module2.py).
Why is that?
Thanks in advance!
Solution
You receive AttributeError
because you have not imported module2
in the __init__.py
file.
You should not execute os.chdir()
in __init__.py
to import submodules.
I’ll do it :
__ init __.py
in the package
directory.
from . import module2
from . import subpackage
__ init __.py
in the subpackage1
directory.
from . import module1