Importing a class without knowing the module

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Franck PEREZ

    #1

    Importing a class without knowing the module

    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.du mps(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
Working...