0

I have python script in following directory structure

common/
    log.py
    file.py
    __init__.py
     conf/
        myconf.py
       
        __init__.py

here is my myconf.py

from common import file

data = file.myfunction()
print (data )

here is file.py

import log

myfunction():

return "dummy"



when i run my myconf.py i get below error

ModuleNotFoundError: No module named 'log

how to handle import log in my myconf.py?

0

2 Answers 2

4

One solution is to add common to your PYTHONPATH and run everything from there. This is the best practice and the best solution in my opinion to handle the imports.

To do so:

  1. In terminal, cd to the directory where common directory is there.
  2. Run export PYTHONPATH=${PWD}
  3. Change your imports to start from common, for example:
from common import log
from common import file
from common.conf.myconf import something
  1. If you want to run a file, run it from the root:
python common/conf/myconf.py

This way you will never have any import error and all your imports are extremely clear and readable cause they all start from common

Sign up to request clarification or add additional context in comments.

2 Comments

How is it don't work in a long run? You rarely rebuild a whole project structure deep in. That's how I organize imports in every python project I work on. You usually have a root source directory, set it to PYTHONPATH and then all imports are related to the root. Btw you can run your code python -m common.conf.myconf and you then don't need to use PYTHONPATH
I meant to put this comment on the solution below this. Made a mistake and actually commented on my own answer :)) I'll delete it.
-1

If you want to run myconf.py as the entry point from anywhere without caring about PYTHONPATH you can add the parent folder of common to sys.path.

myconf.py

if __name__ == '__main__':
    import sys; from os.path import dirname
    sys.path.append(dirname(dirname(dirname(__file__))))

from common import file

data = file.myfunction()
print(data)

log.py

from common import log

def myfunction():
    return "dummy"

1 Comment

Manipulating sys.path is not a good practice: stackoverflow.com/questions/51146723/…...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.