Importing a class without knowing the module

Franck PEREZ franck.perez at gmail.com
Thu Nov 17 18:49:04 EST 2005


Hello,

I'm developing a small XML marshaller and I'm facing an annoying
issue. Here's some sample code:

########### My test application ############
class Foo(object):
  #The class I'd like to serialize
  pass

import myMarshaller
foo = Foo()
s = myMarshaller.dumps(foo) #works fine, spits something like <object
class = "Foo"...>
another_foo = loads(s) #fails, see below

########### My marshaller (in its own module) ############
def loads(s):
  #First, get class name (here "Foo")
  klass = eval(className) #fails because "Foo" is not in the
marshaller's namespace !

How could I tell the marshaller to locate the Foo class and any other
class I try to deserialize ? I've tried to pass my test application's
globals() to the marshaller, it works but it's dirty IMHO... I've
tried also to locate the class (here "Foo") somewhere in sys.modules
in the "loads" method, but it was heavy and unsuccessful.

Thanks a lot for your help !
Franck



More information about the Python-list mailing list