0
root
    - Module_1
        - utils.py
    - Module_2 
        - basic.py

I have a couple of functions in utils.py which I want to use in basic.py, I tried every possible option but not able to do it, I referred many answers, I don't want to use sys path. Is it possible, thank u in advance (:

If I have to add __init__.py, where all should I add it??

gelonida
  • 5,327
  • 2
  • 23
  • 41
Josh Demail
  • 101
  • 1
  • 6
  • what would be interesting to know to give the best answer. Are module_1 and module_2 part of the same project? are your files under version control do you want to create a real python package of module_1, that can be installed with pip? – gelonida Jun 12 '20 at 10:15

3 Answers3

1

In fact there's multiple ways.

I personally would suggest a way, where you do not have to mess with the environment variable PYTHONPATH and where you do not have to change sys.path

The simplest suggestion and preferred if possible in your context

If you can, then just move Module_2/basic.py one level up, so that it is located in the parent directory of Module_1 and Module_2. create an empty file Module_1/__init__.py and use following import in basic.py

from Module_1.utils import function

My second preferred suggestion:

I'd suggest to create two empty files.

Module_1/__init__.py
Module_2/__init__.py

By the way I hope, that the real directory names do not contain any uppercase characters. This is strongly discouraged. compared to python2 python 3 contains no (or almost no) module with uppercase letters anymore. So I'd try to keep the same spirit.

then in basic just write

from Module_1.utils import function

!!! But:

Instead of typing

python Module_2/basic.py

you had to be in the parent directory of Module_1 and Module_2

python -m Module_2.basic

or if under a unix like operation system you could also type

PYTHONPATH="/path/to/parent_of_Mdule_1" python Module_2/basic.py

My not so preferred suggestion:

It looks simpler but is a little more magic and might not be desired with bigger projects in a bigger contents.

It seems simpler, but for bigger projects you might get lost and when you start using coding style checkers like flake8 you will get coding style warnings

Just add at the beginning of Module_2/basic.py following lines.

import os
import sys
TOPDIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, TOPDIR)

and import then the same way as in my first solution

from Module_1.utils import function
gelonida
  • 5,327
  • 2
  • 23
  • 41
0

If you want to make a custom package importable the, put __init__.py in that dir. In your case, __init__.py should be in Module_1 dir. Similarly, if you want utilise the code of basic.py somewhere else then put __init__.py in Module_2 dir.

borz
  • 313
  • 4
  • 10
0

try add __init__.py in Module_1 folder and import in basic.py like this: from Module_1.utils import func

gcdsss
  • 357
  • 3
  • 14