Providing backwards compatibility for serialized objects

Jason Mobarak jason at __nospam__mobarak.name
Fri Jul 2 20:03:03 EDT 2004


Greetings!

Say that it's desirable to provide backwards compatibility for methods 
of an object, consider the case where...

class Foo:
     def bar (self, a, b):
         pass

...is a defined class that can be serialized and later be deserialized. 
This object is later changed so that it's defined as...

class Foo:
     def bar (self, a, b, c): # note the different argument spec
         pass

...old versions of Foo can still be deserialized but the new code relies 
on the fact that new version has one more argument in the spec. In the 
case were you wanted to provide backwards compatibility as general 
solution you could do...

try:
     fooObject.bar(a, b, c)

except TypeError:

     import sys

     if sys.exc_traceback.tb_next is not None:

         # Don't capture the exception if the traceback object
         # has more than one level, this *should* handle the case
         # were there is a TypeError inside of the .bar method

         raise

     # else call it with the old signature
     fooObject.bar(a, b)

...what are the draw backs of using this approach? Are there any cases 
were this would break?

The better approach is just to break backwards compatibility or provide 
a new method with a different name or another version of the class -- 
but consider the case were you don't have the luxury of proper design 
decisions up front.

TIA,
Jason



More information about the Python-list mailing list