Friday, May 29, 2009

Tail recursion in Python

Problem: When marshalling an object to be able to transmit to or from an XMLRPC server and the xmlrpc lib is insufficient to the task because the objects within the main object do not implement a marshal method.

Admittedly the datetime, mxDateTime and None objects should just know what to do if asked by the xmlrpclib to marshal themselves, but in this case, I want to do this myself.

Answer: Here is a tail recursive way to perform this task. This should not use any stack space, but I cannot confirm this since I am not sure what is going on in the interpreter.


def __convertNonMarshalables(self, obj):
  if type(obj) == type({}):
    for key, value in obj.items():
       if value is None:
        obj[key] = ""
      elif type(value) is type(mx.DateTime.now()) or type(value) is type(datetime.datetime.now()):
        obj[key] = value.strftime('%Y-%m-%d')
      elif type(value) == type([]) or type(value) == type({}):
        value = self.__convertNonMarshalables(value)
  elif type(obj) == type([]):
    for value in obj:
      if value is None:
        value = ""
      elif type(value) is type(mx.DateTime.now()) or type(value) is type(datetime.datetime.now()):
        value = value.strftime('%Y-%m-%d')
      elif type(value) == type([]) or type(value) == type({}):
        value = self.__convertNonMarshalables(value)
  else:
    if obj is None:
      obj = ""
  return obj

No comments: