-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!

1
  • 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. Commented Nov 10, 2017 at 19:14

2 Answers 2

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. 
Sign up to request clarification or add additional context in comments.

Comments

0

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

from ..basics import class1, function2, # or a wildcard like * 

1 Comment

relative imports are icky. I'd rather see the folder containing basics.py added to PYTHONPATH and get an __init__.py

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.