Importing a class without knowing the module

Alex Martelli aleax at mail.comcast.net
Fri Nov 18 18:02:18 CET 2005


Mike Meyer <mwm at mired.org> wrote:
   ...
> A classes __module__ attribute doesn't always tell you the name of the
> module - or at least, not a name that would be usefull for the the OPs
> use case. That's the case where you don't have the module name.  The

How do you arrange a module so that its classes' __module__ attributes
don't tell you the name of the module "that would be useful", yet the
module's __file__ DOES give you information that you can usefully
process, heuristically I assume, to infer a module name that IS useful?

I just don't see it, which of course doesn't mean it can't be done, with
sufficient evil ingenuity.  But since you're the one arguing that this
case is important enough to be worth dwelling on, I'd rather see some
specific examples from you, to understand whether my gut reaction "if
possible at all, this has gotta be such a totally CORNER, ARTIFICIAL
case, that it's absurd to bend over backwards to cover it" is justified,
or whether I'm misjudging instead.

> reference to a classes __file__ attribute was meant to be to the
> modules __file__ attribute - I'm surprised that no one picked up on
> that. Again, assuming that the module has an __file__ attribute at
> all. Getting the __file__ attribute to a module you don't know the
> name of is a bit tricky, but possible.

If you have the module object, getting its __file__ isn't hard -- but
then, neither is getting its module name... m.__file__ and m.__name__
are just about as accessible as each other.  Of the two, the one more
likely to be useless would be the __file__ -- import hooks (zipimport or
more deviously sophisticated ones) might mean that string is not a file
path at all; __name__ is supposed to be the string key of that module
object within sys.modules, and it is, I think, far less likely that any
tricks will have been played wrt that -- plus, you can easily
doublecheck by scouring sys.modules.

I just cannot see ANY case where I would want to try heuristics on some
__file__ attribute (hopefully but not necessarily a filename) to try and
recover a __name__ that appears to be missing, mangled, or incorrect; my
instinct would be to raise exceptions informing the user that what
they're trying to marshal is too weird and strange for their own good,
and let them deal with the situation.  But as I said, that may depend on
a failure of the imagination -- if you can show me compelling use cases
in which heuristics on __file__ prove perfectly satisfactory where just
dealing with __name__ wouldn't, I'm quite ready to learn!


Alex



More information about the Python-list mailing list