Importing a class without knowing the module
mwm at mired.org
Fri Nov 18 05:27:45 CET 2005
aleax at mail.comcast.net (Alex Martelli) writes:
> Mike Meyer <mwm at mired.org> 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/zup.py', 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 __init__.py, 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 __init__.py'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 mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list