Open elsamuko opened 4 months ago
Hellopaca, @elsamuko!
I'd suggest importing things into your __init__.py
file. You may want to make use of __main__.py
to create a runnable module instead as well. When floof
is defined in your files it gets name-spaced like this:
what_import/__init__.py
→ what_import.floof
what_import/lib.py
→ what_import.lib.floof
what_import/main.py
→ what_import.main.floof
You can re-export things at the top module level by importing them into the init file.
Have a fluffy evening!
Hello Joakim,
thanks for your suggestions, when running main.py is started directly, it's not reading the __init__.py
as it seems, and it still complains when the import is from what_import import lib
.
What I found, what works:
__name__
-dependent:
if __name__ == "__main__":
import lib
else:
from what_import import lib
python3 -m what_import.main
main.py
in the root folder, which calls then the main.py from the what_import
folderpip install -e .
, which makes the whole module availableHave a fluffy evening yourself!
One could also modify sys.path
directly. But I must admit that this feels kinda hacky:
import sys
import os
# Add the parent directory of main.py to the Python path
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
# Now you can import foo from what_import
from my_module import foo
# ...
How about something like this?
Do you have the same problem there?
If the lib is not installed, then yes:
samuel@xeon:~/projects/wutlib (main)$ python3 wutlib/__main__.py
Traceback (most recent call last):
File "/home/samuel/projects/wutlib/wutlib/__main__.py", line 2, in <module>
from wutlib.cli import cli
ModuleNotFoundError: No module named 'wutlib'
The Python version is 3.10.12
Btw the explanation here is, that this is not possible in Python: https://stackoverflow.com/questions/16981921/relative-imports-in-python-3
Relative imports do break in __main__.py
if I do that, but they work fine across the rest of the modules. I can reproduce the issue if I use a container, but not on my local machine for whatever reason. I suppose running it as a module or having an executable outside of the module makes sense then!
EDIT: My PYTHONPATH
contained an empty item (due to a missing variable), which included my current directory.
@JockeTF @M0r13n
How to solve this in the most pythonic way?