Handling import errors

Guillaume Martel-Genest guillaumemg at gmail.com
Wed Jun 22 21:52:56 EDT 2011


I did not think about using a global variable, and the top-level
try...except solution is interesting. After further thinking, I have
to reformulate my initial question:

How do I manage to run code before my imports?

For example, I want to make sure that I can use the logging module in
the case an import fails, so I want to call logging.basicConfig()
before this particular import. Likewise, I could want to import a
module whose path is relative to an environment variable, and would
want to test if this variable is set before doing so.

I have come up with 2 solution templates :

>>> import logging
>>>
>>> main()
>>>
>>> def pre_import():
...     logging.basicConfig(format='%(message)s')
>>>
>>> def import():
...     global foo
...     import foo
>>>
>>> def main():
...     pre_import()
...     import()

>>> import logging
>>> logging.basicConfig(format='%(message)s')
>>> import foo
>>>
>>> main()
>>>
>>> def main():
...     pass

To me, the latter looks better, but I could be missing something. In
any case, surrounding the entire program with try...except would look
like the following?

>>> try:
...     import logging
...     logging.basicConfig(format='%(message)s')
...     import foo
...
...     main()
>>> except Exception:
...     # Display simple error message
>>>
>>> def main():
...     pass



More information about the Python-list mailing list