Tuesday, July 18, 2006

Overriding IronPython's built-in modules

For those who haven't used IronPython, batteries are not included. After installing IronPython, you need to copy, symbolic link or update sys.path with the CPython standard libs if you want to do more than script .NET/Mono classes. As the various beta's of IronPython have been released, some of the standard library modules are being coded in C# and included in the IronPython Assembly. The socket module is one of these. But as of Beta 9, the socket module does not implement the getaddrinfo function. Many Python network modules expect this function and I was having trouble with a script I was trying to port because of it. But I knew that Seo Sanghyeon had written a IronPython socket module prior to it being included as a built-in and it had getaddrinfo. Since the calls to socket were in other third party python modules, I couldn't just rename socket.py and import it the new name. I needed to override the built-in but how? Then I remembered a post by Fuzzyman about including Python code in an assembly. So by using the code in the top of my script I was able to use the python version of socket.

import imp
import sys

moduleName = 'socket'
moduleSource = './Lib.ip/socket.py'
newModule = imp.new_module(moduleName)
execfile(moduleSource, newModule.__dict__)
sys.modules[moduleName] = newModule

import socket

Of course, there may be a better way.

No comments: