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.
http://www.python.org/dev/peps/pep-0008/#imports