python - Import separate module from relative location in __init__.py -
i know similar question has been answered ad nauseam in these pages, i've read answers , cannot find solution makes nuanced application work. long , short:
i expose external module (that exists in relative path, , cannot update path variable) working module. in each case, recognize import module using sys.path.append()/import. however, import module in __init__.py , expose module there (so have adjust path once, theoretically). have read indicates once have exposed module via import in __init__.py, should able access via call my_module.imported_module. however, not seem work. basic idea share set of functions across multiple modules should independent. example below:
(base module):
__init__.py: import sys sys.path.append('../') # know not ideal, simplicity import core myfile: import base print dir(core)
nameerror: name 'core' not defined
alternatively:
myfile: import base print dir(base.core)
attributeerror: 'module' object has no attribute 'core'
and last:
myfile: import base.core print dir(base.core)
importerror: no module named core
**last, last:
and last:
myfile: import core print dir(core)
importerror: no module named core
any ideas?
you don't have choice here, if it's relative path in directory outside of main module, you're going have manipulate path. should change sys.path manipulation work __file__
instead aren't bound current working directly, i.e.:
import os import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))
however, if other package shares package file use relative import:
parent/ __init__.py core.py base/ __init__.py myfile.py
you can path manipulation in .pythonrc
or ipython settings.
Comments
Post a Comment