Home > Blockchain >  How to import sibling file within a package?
How to import sibling file within a package?

Time:01-04

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?

CodePudding user response:

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.

  •  Tags:  
  • Related