1

I have the following package structure:

mypkg
├── mymodule
│   ├── __init__.py
│   └── ...
├── mylib.py
└── script.py

In script.py I can do from .mymodule import X and from .mylib import Y and works fine for both Python 2 and Python 3.

In Python 2, I can do import mymodule and import mylib and it works fine and then later I can do mymodule.X or mylib.Y.

In Python 3, I cannot do import .mymodule nor import .mylib (syntax error) and if I remove the leading dot I get: ModuleNotFoundError: No module named 'mymodule' and ModuleNotFoundError: No module named 'mylib'.

After reading this question I understand that I need the leading dot but why am I getting a syntax error? How can I get these imports working for both Python 2 and 3?

Update: For future reference, my package structure now is:

mypkg
├── __init__.py
├── mymodule
│   ├── __init__.py
│   └── ...
├── mylib.py
└── script.py
Josep Valls
  • 5,483
  • 2
  • 33
  • 67

1 Answers1

1

You need

from . import mymodule

and

from . import mylib

Explicit relative imports must use from syntax. The design intent is that whatever comes after the import in import ... or from ... import ... is a valid expression to access the imported thing after the import, and .mymodule is not a valid expression.

user2357112
  • 260,549
  • 28
  • 431
  • 505