How do I catch an exception for a module that I've not fully imported?

20,860

Solution 1

If you do not want to import the full module you can simply import the exception aswell. PEP8 states that you are allowed to do.

from socket import gethostbyname, gaierror

http://www.python.org/dev/peps/pep-0008/#imports

Solution 2

In this case you should use : from socket import gethostbyname,gaierror and then try:

except gaierror:
    print('oops')

that's because from socket import gethostbyname is equivalent to:

import socket
gethostbyname=socket.gethostbyname
del socket

so socket is removed from from the namespace and you get that NameError.

Share:
20,860
user1814016
Author by

user1814016

Updated on July 17, 2022

Comments

  • user1814016
    user1814016 almost 2 years

    Normally, if I imported socket, I would be able to easily catch exceptions:

    >>> import socket
    >>> try:
    ...     socket.gethostbyname('hello')
    ... except socket.gaierror:
    ...     print('oops')
    ...
    oops
    

    But if I just import socket.gethostbyname, it won't work:

    >>> from socket import gethostbyname
    >>> try:
    ...     gethostbyname('hello')
    ... except socket.gaierror:
    ...     print('oops')
    ...
    Traceback (most recent call last):
      File "<stdin>", line 3, in <module>
    NameError: name 'socket' is not defined
    

    I also get a NameError if I try to catch gaierror.

    Is there any workaround for this? Is it not possible to catch an exception with a string (eg. except 'socket.gaierror':)?