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:

  1. how python find packages in file structure (this isn't django app, regular folder)? appending sys.path unnecessary?

  2. 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:

  1. using import mappings empty init causes nameerror: name 'mappings' not defined

  2. using import mappings import mapping in init causes same nameerror: name 'mappings' not defined

  3. using import mappings in init not in get_models.py , attempting call mappings.process_model in get_models yields: nameerror: global name 'mappings' not defined


Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -