2

I am trying to understand relative imports in python (python3), and the following simple piece of code does not work. I would like to know what's missing in my understanding of relative imports.

I have a directory structure like this:

example/
   a.py
   b.py

a.py has the following code:

def test_print():
   print("test")

and b.py has the following code:

from . import a

a.test_print()

When I run b.py, I get an ImportError: cannot import name 'a'. However, if I go one level above (cd ..), and run python -m example.b, it runs without any errors.

Spot
  • 83
  • 1
  • 7
  • 4
    The folder `example` doesn't seem to be a package. Try putting an empty `__init__.py` file in there – rdas Aug 20 '19 at 12:55
  • 3
    You can just use `import a` as it is within the same directory. Further, `from .` will not work as `example` is not a package. – Anoop R Desai Aug 20 '19 at 12:55
  • @rdas, you don't need that from python3.3 https://stackoverflow.com/questions/37139786/is-init-py-not-required-for-packages-in-python-3-3 – Shubham Sharma Aug 20 '19 at 12:57
  • @ShubhamSharma Agreed, however, the `from ... import ...` statement needs an `__init__.py` file as described [here](https://stackoverflow.com/a/56301295/1898437). – Anoop R Desai Aug 20 '19 at 13:27

0 Answers0