0

I created a module named myutils. This is the file structure I use:

./mypackages
./mypackages/myutils
./mypackages/myutils/util1.py
./mypackages/myutils/util2.py
./myexecs
./myexecs/user_executable1.py

I correctly set PYTHONPATH=./

in ./myexecs/user_executable1.py I can easily use the utils:

from my_packages import myutils
myutils.util1.func1()

In util1.py I can use util2.py:

from . import util2
util2.func2() 

The problem arises when I wish to use util1.py directly as a main entrypoint. It has a

if __name__ == "__main__": main()

entry point, but if I just execute it directly, it fails to import util2 (from . import util1 fails).

It does succeed if I execute it using python -m mypackages.myutils.util1

Any idea how can I make util1 import its' sibilings using from . import ... and yet being able to execute it directly from the cmd without executing it as a module?

asked Dec 28, 2018 at 15:25

1 Answer 1

1

Just use abolute import everywhere in your code (from . import util2 will be from mypackages.myutils import util2) and run your exec with python -m myexecs.user_executable1 and you will be good

answered Dec 28, 2018 at 15:46
Sign up to request clarification or add additional context in comments.

2 Comments

I think that either solution by itself will work. But both are illogical. The first makes the package unmovable. It works only in this current directory. The second is just annoying and makes uncomfortable to work with a script. Do you think differently?
I feel like using absolute imports everywhere and run modules with python -m is the more logical. When you make a script /tmp/foo.py you need to import your package, sometimes from another folder, but that's pure Python - the only thing to fix is "how to import this module in a clean way" (I would say: setup.py + venv + pip install). For me you are trying to fix something on the wrong level, this should not be fixed in your code, but in your setup. (well i think..)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.