== Two Python _import_ tricks Here's an extreme example of _import_ and namespace trickery, drawn from the standard Python _ftplib_ module: > try: > import SOCKS > socket = SOCKS > del SOCKS > from socket import getfqdn > socket.getfqdn = getfqdn > del getfqdn > except ImportError: > import socket (linebreaks added for clarity) Modules are objects in Python, so a module's name binding can be manipulated like anything else. This leads to the two things that _ftplib_ is doing here. First, the _ftplib_ module would like to use the _SOCKS_ module if it exists and otherwise use the standard _socket_ module. Rather than sprinkle conditionals throughout its own code, it just imports _SOCKS_ and renames it to _socket_, counting on _SOCKS_ to have all the socket routines it needs under the same names as _socket_ does. Second, _SOCKS_ is apparently missing the _getfqdn_ function. So _ftplib_ yanks a reference to it out of the real _socket_ module and stuffs it into the _SOCKS_ module (that _ftplib_ knows as '_socket_'). This lets its code can just call _socket.getfqdn_ without having to worry about whether _socket_ is the real thing or _SOCKS_. This works because of bonus trickery: unlike other operations, both '_import_' and '_from import ..._' take the names *without* looking them up in the current namespace. So even though the name '_socket_' points to the _SOCKS_ module at this point, '_from socket import getfqdn_' goes off to the real _socket_ module, instead of trying to find _getfqdn_ in the _SOCKS_ module. Because modules are global, the side effect of this is that _ftplib_ has changed _SOCKS_'s namespace for everyone that's imported it. If somewhere in the program another module has also imported _SOCKS_, they can refer to '_SOCKS.getfqdn_' and it will work. (There are actually practical uses of altering other modules' namespaces. I may cover some of them in a later entry.)