0

I have the following directory structure:

├── DynamicProgramming
│   ├── 0-1_kp_problem.py
│   ├── b.py
│   ├── largest_contigous_subarray.py
│   ├── longest_common_substring.py
│   ├── min_change_for_given_money.py
│   ├── optimal_matrix_chain.py
│   ├── Readme.md
│   └── wis.py
├── helper
│   ├── a.py
│   └── __init__.py
└── Readme.md

The helper directory contains the library functions which will be used all over the code. How can I import the helper package from the scripts inside DynamicProgramming without adding it to the path?

Edit=>

I cannot move helper directory inside dynamicProgramming because there can be more than one directories using it.

2 Answers 2

3

You could use something like:

from ..helper import a

See python docs on packages.

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

2 Comments

Yeah but I can only do that if the file I am using it in is a package itself
It sounds like helper directory contains some common functionality that will be used from other places besides DynamicProgramming. In that case perhaps you should think about adding 'helper' directory to PYTHONPATH. If you are using virtual environments you could easily add/remove the helper directory to PYTHONPATH when the virtual environment is activated/deactivated. Then you could simply use an absolute path in your import.
2

If you run your code from project root folder, you are likely to succeed with import helper or import helper.a. If not, you would have to add current directory to PYTHONPATH:

$ export PYTHONPATH="."

better use project setup.py

Instead of playing with PYTHONPATH (what can be tricky business sometime), you shall create your project as python package.

You add setup.py into your project root, specify attributes of that package and build it from it.

setup.py can define multiple packages at once, but generally it is more often using only one. For this purpose it would be better moving the helper package into DynamicProgramming structure and import it from there.

Search for setup.py python packaging tutorials, it requires some study, but it will pay back.

Comments

Your Answer

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.