opening a file using a relative path from a subclass in a package

Heiko Wundram modelnine at bit-bukket.org
Wed Dec 7 16:44:48 EST 2005


spike grobstein wrote:
> so, since python supports module packages like it does, you'd think
> that it would have ways of making add-on or extension modules to be
> more self contained.

Errm... You're not quite understanding what the problem is about. A class is
just an object. A class object may appear in many modules (namespaces),
even in non-module namespaces (function namespaces). It's part of the
debugging system that a class is bound to a module (by the __module__
member of the class object), which helps in finding the source for a class
if you're the debugger.

The method I wrote to you won't work if you import the class from some file
and want to get the file where the class is imported, not where it's
defined. So, the following won't do what you think:

a.py
====

import c

class x:
    __metaclass__ = c.superclass
    pass

b.py
====

from a import x

c.py
====

class superclass(type):
    def __init__(cls,name,bases,dct):
        print cls.__module__

d.py
====

import b

python d.py

will print
"a"

and not
"b"

what you might have expected.

So, actually this is quite fragile stuff, and is something that's better
left alone if you care for portable code. Why do you desperately need
access to the source file of the extension class? Isn't it enough that you
import the extension class and rely on the fact that its module object has
a member which is a class object which defines a certain interface? Can't
you use the class name if you need a unique identifier for the class in
your system? (self.__class__.__name__)

Think about it...

--- Heiko.



More information about the Python-list mailing list