Importing a class without knowing the module

Alex Martelli aleax at mail.comcast.net
Thu Nov 17 22:41:41 EST 2005


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.


Alex



More information about the Python-list mailing list