"Reid Priedhorsky" <[EMAIL PROTECTED]> wrote: > Dear group, > > I'd have a class defined in one module, which descends from another class > defined in a different module. I'd like the superclass to be able to > access objects defined in the first module (given an instance of the first > class) without importing it. Example of what I'm looking for: > > <<<file spam.py>>> > > class Spam(object): > def fish(self): > a = self.__module__.Ham() > > <<<file eggs.py>>> > > import spam > > class Eggs(spam.Spam): > pass > > class Ham(object): > pass > > The above doesn't work because __module__ is a string, not a module object: > > >>> import eggs > >>> b = eggs.Eggs() > >>> b.fish() > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "spam.py", line 3, in foo > a = self.__module__.Ham() > AttributeError: 'str' object has no attribute 'Ham' > > (I suppose I could call __import__(self.__module__), but that seems kind > of awkward.) > > Is this possible using Python 2.3? Any better ways to accomplish this?
I don't know if it's "better", but since you know that self.__module__ has already been imported, you can access it through the sys.modules dict: a = sys.modules[self.__module__].Ham() By the way, this seems like an error-prone hack. Are you sure you want to relate two independent classes just by the fact that they rely in the same file ? Remember, explicit is better than implicit. George -- http://mail.python.org/mailman/listinfo/python-list