Make staticmethod objects callable?

Murali maha.murali at gmail.com
Wed Mar 1 00:31:05 EST 2006


You have a text-database, each record has some "header info" and some
data (text-blob). e.g.

--------------------
<HEADER>
name = "Tom"
phone = "312-996-XXXX"
</HEADER>
I last met tom in 1998. He was still single then.
blah
blah
<HEADER>
name = "John"
birthday = "1976-Mar-12"
</HEADER>
I need to ask him his email when I see him next.
------------------

I use this format for a file to keep track of tit bits of information.
Lets say the file has several hundred records. I know want to say
generate a birthday list of people and their birthdays. Ofcourse along
with that I also need the "text-blob" (because I dont want to send a
birthday card to a person I dont like). In order to do this I execute a
script

./filter --input=database.txt --condn='similar(name,"tom")'.

The way it is implemented is simple. Have a class which has dict as its
base class. For each record the text between <hEADER> and </HEADER> is
executed with the class instance as "locals()". Now that I have a list
of class instances, I just exec the condition and those instances where
it evaluates True comprise the output text file.

To make the user, not have to know too much python, one would like to
define "functions" which can be used. For eg. similar would have the
following definition

@staticmethod
def similar(regexp,str):
   return re.match("(?i)^.*%s.*$" % regexp, str) != None

This way the "locals()" dictionary in the exec'ed environment has
access to the function similar (if similar was callable). At the same
time, I can enclose all these functions in their own name space (as
static methods of a class).

Right now, I declare all these "helper" functions in a different
module, and "attach" the "helper" functions as keys into the
dictionary. If only staticmethods were callable. For some reason (I
dont recall why) the idea of converting the staticmethod into a
callable still did not work, e.g.

class Callable:
   def __init__(self,method):
        self.__call__ = method

class Record(dict):

   @staticmethod
   def similar(regexp,string):
        ....

   self['similar'] = Callable(similar)

The above did not work. The error message was still related to a
staticmethod not being a callable.

- Murali




More information about the Python-list mailing list