FAQ
What is the pythonic way to handle imports error? What is bugging me
is that the imports can't be inside a function (because I use them in
different places in the script and thus they have to be in the global
scope). I would write something like:

try:

Search Discussions

  • Guillaume Martel-Genest at Jun 21, 2011 at 8:51 pm
    What is the pythonic way to handle imports error? What is bugging me
    is that the imports can't be inside a function (because I use them in
    different places in the script and thus they have to be in the global
    scope). I would write something like:

    try:
    import foo
    except ImportError:
    logging.error('could not import foo')
    sys.exit(1)

    But logging is not configured at this point as my main() have not been
    called yet.

    Should I define a global variable and assign it to my module later? Or
    should I let the exception happen and let the stack trace be the error
    message?
  • Miki Tebeka at Jun 21, 2011 at 9:10 pm

    try:
    import foo
    except ImportError:
    logging.error('could not import foo')
    sys.exit(1)
    Why not just let the exception terminate the program? It will have even more information about the problem that caused foo not to load.
  • Mel at Jun 21, 2011 at 9:12 pm

    Guillaume Martel-Genest wrote:

    What is the pythonic way to handle imports error? What is bugging me
    is that the imports can't be inside a function (because I use them in
    different places in the script and thus they have to be in the global
    scope).
    Actually, you can if you declare them global:

    Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
    [GCC 4.4.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    def f():
    ... global os
    ... import os
    ...
    dir (os)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'os' is not defined
    f()
    dir (os)
    ['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST',
    'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE',
    'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE',
    'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT',
    'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME',
    'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK

    etc.

    Mel.
  • Chris Rebert at Jun 22, 2011 at 5:12 am

    On Tue, Jun 21, 2011 at 1:51 PM, Guillaume Martel-Genest wrote:
    What is the pythonic way to handle imports error? What is bugging me
    is that the imports can't be inside a function (because I use them in
    different places in the script and thus they have to be in the global
    scope). I would write something like:

    try:
    ? ?import foo
    except ImportError:
    ? ?logging.error('could not import foo')
    ? ?sys.exit(1)

    But logging is not configured at this point as my main() have not been
    called yet.

    Should I define a global variable and assign it to my module later? Or
    should I let the exception happen and let the stack trace be the error
    message?
    If your users are technical, the latter, since it's much more
    informative to anyone with programming/sysadmin skills. It's also not
    really the sort of error your program can usefully recover from.
    (Although in some cases, the module being imported may be considered
    truly optional, in which case `try...except ImportError` makes sense;
    but this is fairly uncommon unless a program is intended to have
    extensions/plug-ins.)

    If your users aren't technical, then you should have a top-level
    try...except around almost the entire program that displays a simple
    error message in the event of an unhandled exception, preferably with
    an option to display the gory details (i.e. exception & stack trace).

    Cheers,
    Chris
  • Guillaume Martel-Genest at Jun 23, 2011 at 1:52 am
    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
  • Tim Johnson at Jun 21, 2011 at 9:10 pm

    * Guillaume Martel-Genest [110621 12:53]:
    What is the pythonic way to handle imports error? What is bugging me
    is that the imports can't be inside a function (because I use them in
    different places in the script and thus they have to be in the global
    scope). I would write something like:
    Suppose you do something like this:
    try :
    mod = __import__('mymodulename')
    except ImportError:
    pass ## replace with error handling here

    so `mod' is global if you execute the above code as top-level,
    *but* you can also pass `mod' as an argument like any other
    variable, as far as I know and far as I have done.

    --
    Tim
    tim at johnsons-web dot com or akwebsoft dot com
    http://www.akwebsoft.com

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedJun 21, '11 at 8:41p
activeJun 23, '11 at 1:52a
posts7
users5
websitepython.org

People

Translate

site design / logo © 2022 Grokbase