Nested Imports - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Nested Imports (/thread-13947.html) |
Nested Imports - CanadaGuy - Nov-07-2018 I'm trying to create modules for my application that are themselves testable on their own. I would like to have the following directory structure: \application.py \support\module1.py \support\module2.py application.py depends on both module1.py and module2.py. module1.py is also dependent directly on module2.py My way to make this work so far is the following in module1.py if __name__ == "__main__": import module2 else: import support.module2Without that, I get various "module not found" issues. I did a lot of reading on absolute and relative imports, but I can't identify my case among the many examples presented. My alternative plan was to leave everything flat for now (no directories) so that imports are nice and straightforward. But for a larger application, I know this would just make a big mess. Ideas? RE: Nested Imports - Larz60+ - Nov-07-2018 use try except, here's an extreme example from the lxml manual: try: from lxml import etree print("running with lxml.etree") except ImportError: try: # Python 2.5 import xml.etree.cElementTree as etree print("running with cElementTree on Python 2.5+") except ImportError: try: # Python 2.5 import xml.etree.ElementTree as etree print("running with ElementTree on Python 2.5+") except ImportError: try: # normal cElementTree install import cElementTree as etree print("running with cElementTree") except ImportError: try: # normal ElementTree install import elementtree.ElementTree as etree print("running with ElementTree") except ImportError: print("Failed to import ElementTree from any known place") RE: Nested Imports - CanadaGuy - Nov-07-2018 Thanks for the reply. Is try/except a better approach than using an if statement? In this case, I know exactly what statement will work under each condition so try except seems a little less direct. RE: Nested Imports - Larz60+ - Nov-08-2018 'if' statements will not stop error events from crashing system, try/except will RE: Nested Imports - CanadaGuy - Nov-08-2018 (Nov-08-2018, 12:19 AM)Larz60+ Wrote: 'if' statements will not stop error events from crashing system, try/except will True. That gives me something to think about. |