Josep Valls
Josep Valls

Reputation: 5560

Explicit relative imports within a package not using the keyword from

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

Upvotes: 1

Views: 67

Answers (1)

user2357112
user2357112

Reputation: 280973

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.

Upvotes: 1

Related Questions