realpython/reader

How to make imports that works locally and once the package is installed?

Closed this issue · 3 comments

Hello,

I wanted to publish my package so I found this article along with this example repository. I consider running my program locally for development purpose then publish it but I have an issue with the import statements. Either the import will be good to run it during development and break once the package is installed using $ pip install (ModuleNotFoundError: No module named 'xxx') or the other way around (using relative path).

Is there a way or should I rename each import before packaging?


Using this repository example, what would be the way to run it directly locally? $ python reader/__main__.py throws ModuleNotFoundError: No module named 'reader'. Let's imagine that someone wants to extend the code, they would have to run the code locally along during the programming stage, is it possible?

Thank you.

I found the solution here: I should call it with $ python -m reader.

My bad.

Hi @bidetaggle ,

sorry for the slightly late response. I'm glad you found a solution.

My preference is to install packages that I work on in development mode. Typically I do this by opening the base directory (the one containing setup.py and similar files) in my terminal. Then I can install it using the -e (editable) flag with pip:

$ python -m pip install -e .

The dot at the end is necessary and tells pip to install the current directory.

Once, you've done this, the reader module will be available for your code and all absolute imports should work. Using -e also makes sure that any updates you do to your code are taken into account when you run the code. Without -e the code will be "frozen", and later changes will not be reflected.

We also discuss this a little bit in a different tutorial: https://realpython.com/python-import/#create-and-install-a-local-package

Definitely a good piece of information, thank you!