DevRuby
DevRuby

Reputation: 1

How to import sibling file within a package?

NameChanger

  -main.py
  -__init__.py

  ui
    -__init__.py
    -utils.py

  utils
    -__init__.py
    -file.py

I want to import NameChanger/utils/file.py in NameChanger/ui/utils.py.

So I tried from NameChanger.utils import file but this error occurred ModuleNotFoundError: No module named 'NameChanger'.

and I also tried from ...NameChanger.utils import file and this error ValueError: attempted relative import beyond top-level package occurred.

How can I solve this?

Upvotes: 0

Views: 1877

Answers (1)

chepner
chepner

Reputation: 532303

In ui/utils.py, use a relative import.

from . import utils.file

NameChanger itself is likely not in your search path (nor does it need to be). But since NameChanger is a package, the relative import in a module contained in a subpackage of NameChanger should work.


I originally suggested

from .utils import file

which would only work if utils really had file as a module-level attribute, which is generally not the case for a package.

Upvotes: 1

Related Questions