Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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':)?

like image 408
user1814016 Avatar asked Nov 16 '12 08:11

user1814016


2 Answers

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

like image 117
Tuim Avatar answered Nov 01 '22 04:11

Tuim


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.

like image 40
Ashwini Chaudhary Avatar answered Nov 01 '22 03:11

Ashwini Chaudhary