solving circular imports using __init__.py within 1 package python -
i have 2 files in package , convenient pull 1-2 funcs each other. in init.py tried:
from mappings import * get_models import * in mappings.py:
#!/usr/bin/env python import os, sys, re sys.path.append('/home/cchilders/scripts/python/work-tasks/unit_tests_scripts/completed') . import get_model_name_or_none in get_models.py:
#!/usr/bin/env python import os, re, sys sys.path.append('/home/cchilders/scripts/python/work-tasks/unit_tests_scripts/completed') . import process_model and instead of namespace conflict or whatnot, get:
[cchilders@localhost completed]$ ./mappings.py traceback (most recent call last): file "./mappings.py", line 7, in <module> . import get_model_name_or_none valueerror: attempted relative import in non-package this surprised me, paranoid enough package append sys.path. when try import 1 file other, without going through init.py , leaving init blank, import works. wonder:
how python find packages in file structure (this isn't django app, regular folder)? appending sys.path unnecessary?
why can not throw names package namespace , import them in each separate module? tried changing
from mappings import * from get_models import *
to more safe from get_models import get_model_name_or_none , exact same error above
thank you
with init.py empty, , mappings.py:
#!/usr/bin/env python import os, sys, re (init empty, not appending path, not trying imports in mappings, get_model importing function mappings correctly) get:
[cchilders@localhost completed]$ python -m mappings.py *correct output* /usr/bin/python: no module named mappings.py the correct output code running before (as expected), warning no module. weirdly, when uncomment append:
sys.path.append('/home/cchilders/scripts/python/work-tasks/unit_tests_scripts/completed') i still exact same correct output followed warning /usr/bin/python: no module named mappings.py
trying use mappings in get_models difficult:
using
import mappingsempty init causesnameerror: name 'mappings' not definedusing
import mappingsimport mappingin init causes samenameerror: name 'mappings' not definedusing
import mappingsin init not inget_models.py, attempting callmappings.process_modelinget_modelsyields:nameerror: global name 'mappings' not defined
Comments
Post a Comment