Importing a class without knowing the module

Mike Meyer mwm at
Fri Nov 18 05:27:45 CET 2005

aleax at (Alex Martelli) writes:
> Mike Meyer <mwm at> wrote:
>> >> 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.
> I disagree with the last sentence.  From a filepath of
> '/zip/zap/zop/', it's VERY hard to say whether the module name is
> to be zup, zop.zup, or zap.zop.zup -- it depends on which directories
> are on sys.path and which have, which is impossible to tell
> at unmarshaling time.  If you use Foo.__module__, you should get the
> *module* name correctly, independently from sys.path or's,
> or .pth files for that matter -- so, I do NOT agree that using __file__
> is "about the best you can do" for this use case.

You should read the next-to-last sentence, which says to use the
module name if you have it. The last sentence starts "If not" -
meaning you don't have the module name. *That's* the case for which
the file name is about the best you can do.

Mike Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list