Search code examples
pythonpython-modulepython-packaging

Import File in Python Package


How would I go about importing another file in a python package. I install the package with

pip install .

so I can then run it using

python3 -m pkg

Here's the file structure:
.
├── pkg
│⠀⠀├── cli.py
│⠀⠀├── __init__.py
│⠀⠀├── __main__.py
├── README.md
└── setup.py

I try to import a function from cli.py in __main__.py by using

import .cli as clifunc

but it results in an error

root@localhost:~# python3 -m pkg
import .cli as clifunc
       ^
SyntaxError: invalid syntax

How do I import the file? Other methods I've tried resulted in the error being that the file isn't a module!?! How can I just import the file?


Solution

  • So apparently when using the explicit relative imports (using dots like .cli), you can't just use import .module (not sure quite why though, maybe someone else does)

    You instead need to use from . import module

    So from . import cli as clifunc should work.