elsamuko / what_import

0 stars 0 forks source link

Running both #1

Open elsamuko opened 4 months ago

elsamuko commented 4 months ago

@JockeTF @M0r13n

How to solve this in the most pythonic way?

JockeTF commented 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:

You can re-export things at the top module level by importing them into the init file.

Have a fluffy evening!

elsamuko commented 4 months ago

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:

Have a fluffy evening yourself!

M0r13n commented 4 months ago

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

# ...
JockeTF commented 4 months ago

How about something like this?

Do you have the same problem there?

elsamuko commented 4 months ago

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

elsamuko commented 4 months ago

Btw the explanation here is, that this is not possible in Python: https://stackoverflow.com/questions/16981921/relative-imports-in-python-3

JockeTF commented 4 months ago

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.