-2

I have python code with the directory structure -

main.py
basics.py
component1
  file1.py
  file2.py
component2
  file1.py
  file2.py

I want the code in the directories component1 and component2 to use code from basics.py. What is the most pythonic way of doing this?

Thanks!

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • 1
    You may choose to use relative imports OR from within the code update sys.path to add location of basics.py. I'd prefer creating another directory called lib or utils, move basics.py there, add __init__.py, update PYTHONPATH to the parent dir and then imports. The imports will look clean and consistent from lib.basics import foo, from component1.file1 import bar, etc. – Sharad Nov 10 '17 at 19:14

2 Answers2

1

Considering application as the root directory for your python project, create an empty __init__.py file in application folder. Then in your target filename.py (ex., component1/file1.py) file, make changes as follows to get the definition of func_name:

import sys
sys.path.insert(0, r'/from/root/directory/')

from application.basic import func_name ## use '*' wildcard to import all the functions in basic.py file.
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
0

At the top of files inside component1, component2, etc.

from ..basics import class1, function2,    # or a wildcard like *
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
  • relative imports are icky. I'd rather see the folder containing `basics.py` added to PYTHONPATH and get an `__init__.py` – Adam Smith Nov 10 '17 at 19:12