How to properly do importing during development of a python package? -
this question has answer here:
i first year computer science student working on small project save dropbox school.
i apologize in advance potentially trivial question. having little no experience , after trying debugging techniques have been taught, im stuck!
it has following file structure
school_project/ __init__.py #(empty) main_functions/ __init__.py #(empty) render.py filter.py helper_functions/ __init__.py #(empty) string.py utility.py
currently, need use functions founded in utility.py
in file render.py
. first attempt @ solving problem import ..helper_functions.utility
in file render.py
.
unfortunately, met following error message.
import ..helper_functions.utility ^ syntaxerror: invalid syntax
first off, have no idea why relative import not working.
secondly, should use absolute import instead? in form import school_project.helper_functions.utility
? if so, need add directory school_project/
in pythonpath? how this?
would modify computer's path , pythonpath adapt accordingly? or separate entities , process bit more involved? ive looked @ other threads seem modify pythonpath @ run time in python script itself, see giant potential origin of bugs in future.
this way should it:
..helper_functions import utility
this not work if run python program due relative imports.
this way supposed run it:
python3 -m helper_functions.utility
but it's verbose, , doesn't mix shebang line #!/usr/bin/env python3.
although it's not unique. package structure more complex. you'll need include directory containing package directory in pythonpath, , this.
from mypackage.mymodule import as_int
you can this. not recommanded beginners. frob pythonpath in code first this...
import sys import os package_parent = '..' script_dir = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(script_dir, package_parent))) mypackage.mymodule import as_int
Comments
Post a Comment