1

Scenario

I am trying to understand how python packages work and I have one doubt. I have the following structure:

root
├── src
│   ├── main_pkg
|   |   ├─ __init__.py
|   |   ├─ letter.py
│   |   └─ main.py
|   └── numbers
|       ├─ __init__.py
|       └─ number.py       
├── pyproject.toml
└── setup.py
    

And the following files:

# main.py
from letters import letter_1
from numbers_pkg.numbers import number_1


def main():
    print(f"Letter is {letter_1}")

def number():
    print(f"Number is {number_1}")

if __name__ == "__main__":
    main()

# setup.py
from setuptools import setup
setup()
# pyproject.toml
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "imp"
version = "1.0.0"

[project.scripts]
letter = "main_pkg.main:main"
number = "main_pkg.main:number"

Error

If I run python src/main_pkg/main.py, the execution is successful.

But if I install the package with pip install -e ., and then I write letter on the console, I receive the following error: ModuleNotFoundError: No module named 'letters'. (the package is isntalled in a virtual env)

Solution

I have found one solution to run letter and solve the import error, change the first line of main.py:

from letters import letter_1 --> from main_pkg.letters import letter_1

Question

Is this how it should be done correctly? I understand that if I am importing modules from another package, I have to specify it, but if it is a module within the same package, isn't it redundant?

fullfine
  • 1,371
  • 1
  • 4
  • 11
  • A few good questions with excellent answers; recommended reading: https://stackoverflow.com/q/4209641/7976758 , https://stackoverflow.com/q/20706335/7976758 , https://stackoverflow.com/q/48716943/7976758 – phd Aug 03 '22 at 19:49

0 Answers0