0

enter image description here

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

FrankData
  • 21
  • 2
  • Which file are you showing on the right? The `from . import` construct only works if you are inside a package, so if another file did `import package1`. Since you don't have any `__init__.py` files, you haven't set these up as a package. Did you perhaps mean `from .b import run`? The `from .xxx import ...` thing is different from `from . import xxx`. – Tim Roberts Dec 21 '21 at 07:16
  • dear sir, thank you for answering , this script is a.py. It just does not work – FrankData Dec 21 '21 at 07:18
  • Right, because when you run `a.py` it's not part of a package. If you are just running `a.py`, you should be able to say `import b`. If you are going to build these into a module, then the rules change. This is helpful. https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time – Tim Roberts Dec 21 '21 at 07:28

2 Answers2

1

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:

  • the top level folder is directly accessible (ie is a subdir of the current folder or of a folder from sys.path)
  • the top level folder contains a __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...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

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

eDonkey
  • 606
  • 2
  • 7
  • 25