Friday, October 17, 2008

Nicely Wrapping API Definitions in Python

I was doing a project in which I needed a good way to create an API for the code.inspect fuction. I wanted to have some "globally accessible" variables for the API only, but I didn't want to screw around with having to modify the module's namespace, or running into the problem of from module import *. So, after some pondering, and some playing around and learning about decorators, I came up with the following solution, which I kind of like:

"""
The following code will take a class with static methods
and create a module API from it to use with the code.inspect
(or other) functions.
"""
import inspect
import code

class Singleton(object):
""" A Pythonic Singleton """
def __new__(cls, *args, **kwargs):
if '_inst' not in vars(cls):
cls._inst = object.__new__(cls, *args, **kwargs)
return cls._inst


class MyApi(Singleton):
"""This is a Singleton so that the identifying object and other attributes
don't get overwritten, which could lead to things like race conditions.
"""
_api = {}
def __init__(self):
for f in dir(self):
if inspect.isfunction(getattr(self,f)):
self._api[f] = getattr(self, f)

@staticmethod
def func1():
pass

@staticmethod
def func2():
pass

if __name__ == "__main__":
m = MyApi()
code.interact(local=m._api)


All of this will provide your interactive shell with a list of commands defined in this class. Since they're all static methods, you don't need to know who self is or anything of the like. This should probably be a

No comments: