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':
)?
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With