Reputation: 653
I was trying to do some coding practice with python. And here's my structure
mydir/
template.py
problem1/
solution.py
problem2/
solution.py
I'd like to write some general-used staff in template.py and import them in solution.py in both problem1 and problem2 and maybe the problems afterwards.
What should I do to make this possible. I was once trying to do this in solution.py
from .. import template
but it failed.
Upvotes: 1
Views: 73
Reputation: 10897
This is kind of a touchy thing for Python. What you are trying to do with template.py is more apt for a second package for common stuff. Just put MyDev on your PYTHONPATH.
So I think you would have a better time with:
MyDev/
common/
myutils.py
solutions/
solution1.py
solution2.py
And in solution1:
from common.myutils import awesome_func
And this may explain as to why it is not working for you:
How to do relative imports in Python?
PEP8 also has some good style guidelines for using imports. Basically, in my own words, unless you are developing a large package for the community where complexity is neccesesary and imports start to get overly verbose absolute imports are the way to go.
A good example of a code base that does use relative imports is SQLAlchemy.
Upvotes: 1
Reputation: 23
You might do the following:
import sys
and then: sys.path.append('../')
If you import template
now, it should work.
Upvotes: 0