Plz help, I have followed the exact same step from YouTube and websites, but why this one still does not work!!!!!! Using python3, and this gives error 'attempted relative import with no known parent package'.
This is the a.py script
Plz help, I have followed the exact same step from YouTube and websites, but why this one still does not work!!!!!! Using python3, and this gives error 'attempted relative import with no known parent package'.
This is the a.py script
This is a rather confusing point for beginners in Python: are we in a package?
The general rule is that Python can only import modules from the current directory for from a directory contained in sys.path
. But as having multiple related modules to build a large thing is common (small is beautiful is a general rule in programming...), Python has a notion of package. A (non namespace) package is a subtree with 2 conditions:
sys.path
)__init__
file.When both conditions are met, the directory becomes a (non namespace) package and the modules it contains can be accessed (or imported) using dotted expressions.
And relative imports using dotted expressions are only valid in a module that was loaded as a member of a package. Being in a folder containing a __init__.py
file is not enough.
If we have this folder:
top
|- __init__.py
|- a.py
|- b.py
if the current directory is the parent directory of top, and is a.py
contains from . import b
Then you can successfully run python -m top.a
because a.py
is loaded as a member of the top
package.
But python top/a.py
will raise an import error.
Namespace package are a more advanced concept that allows a package to be scattered in different places. Refere to the official documentation for more...
Do you have any module that is named "."? Probably not. Refering to the module with "." only works, if you're inside the module "."
What you probably want to do is:
import sys
sys.path.append('/.../testimports/package1')
import b
b.run()
Here is a guide on python modules