Importing a class without knowing the module

Mike Meyer mwm at mired.org
Fri Nov 18 02:59:08 CET 2005


[Format recovered from top posting.]

Franck PEREZ <franck.perez at gmail.com> writes:
> On 11/18/05, Mike Meyer <mwm at mired.org> wrote:
>> Franck PEREZ <franck.perez at gmail.com> writes:
>> > ########### 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 ?
>>
>> How about adding Foo.__file__ to the serialized data?
> I thought about it, but it would make the XML file depend on the
> machine... no more portability...

They already depend on the machine. You can't take them to an arbitary
machine and reconstruct them: it has to have the classes the XML file
depends on somewhere on it. You can use the module name if you have it
available. If not, deriving the module name from the file name is
about the best you can do.

      <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list