Negroup schrieb: > Hi, first of all sorry for boring you with a such simple request. I'm > using Python since few days, and I like it even if I'm not yet in > confidence. I'd like to organize my programs in hierarchical > structures, thus I thought that packages could be the solution, > however I have some difficulties understanding their utilization (even > after reading chapter 6 of the tutorial, about modules). > > Now an example (silly) to clarify my doubts: > > This is the structure: > main.py > importers/ > __init__.py (empty) > importer1.py > config/ > __init__.py (empty) > parameters.py > > main.py > ======= > from importers import importer1 > print importer1.display() > > importers/importer1.py > ====================== > from config import parameters > def display(): > return '-' * parameters.counter > > config/parameters.py > ==================== > counter = 5 > > > All works fine when I run "python main.py", while I get an error > trying to run "python importers/importer1.py": > > Traceback (most recent call last): > File "importers/importer1.py", line 1, in ? > from config import parameters > ImportError: No module named config > > Can you explain why does that happen? It prevents me to test > importer1.py alone. > > TIA, > negroup
mainpackage/ main.py importers/ __init__.py (empty) importer1.py config/ __init__.py (empty) parameters.py If this is the package structure and you run 'python main.py' from mainpackage the config package is already in the search path. Therefore importing config in subsequent modules succeeds. If you run importer1.py on the level of importers config may not be in the PYTHONPATH and the import fails. Solution: reference config in the import statement so that the package can be found. from mainpackage.config import parameters should be suffient if mainpackage is in the PYTHONPATH. But note that you have to be consistent with your import statements because the module will be cached in sys. modules using it's import path as key. Doing both from mainpackage.config import parameters and from config import parameters in different modules leads to reimports and different modules. This may cause trouble if you compare objects using class information because the id's of the classes are different. Kay -- http://mail.python.org/mailman/listinfo/python-list