473,385 Members | 1,333 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Access descendant class's module namespace from superclass

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?

Thanks very much for any help,

Reid
Jul 21 '05 #1
2 1986
"Reid Priedhorsky" <re**@reidster.net> 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

Jul 21 '05 #2
On Mon, 11 Jul 2005 18:45:20 -0500, Reid Priedhorsky <re**@reidster.net> 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?

Thanks very much for any help,

Reid


I think 2.3 will do this. But be careful not to tie your shoelaces together and trip --
I haven't tested this beyond what you see. It was just an idea for the kind of access
you seemed to want ;-)

If each class and subclass whose global environment you want to reach through an instance
provides a property that will return the class or subclass' global dict, then a base class
method can access that via the instance to "fish" for a name in the appropriate "fishinghole"
-- e.g.,

----< spam.py >-------------------------------
"""spam.py module doc string"""
class Spam(object):
def fish(self, whatfor):
return self.fishinghole[whatfor]
fishinghole = property(lambda self:globals()) # spam.py globals if this fishinghole used
----------------------------------------------

----< eggs.py >-------------------------------
"""eggs.py module doc string"""
import spam

class Eggs(spam.Spam):
fishinghole = property(lambda self:globals()) # eggs.py globals if this fishinghole used

class Ham(object):
pass # won't find any fishing hole at all

class Grits(spam.Spam):
pass # no fishing hole, should find spam.py globals if looked for
----------------------------------------------
import eggs
dir(eggs) ['Eggs', 'Grits', 'Ham', '__builtins__', '__doc__', '__file__', '__name__', 'spam'] eggs.__doc__ 'eggs.py module doc string'
e = eggs.Eggs()
e.fish('Ham') <class 'eggs.Ham'> e.fish('__doc__') 'eggs.py module doc string' e.fishinghole.keys() ['Ham', 'spam', '__builtins__', '__file__', '__doc__', 'Grits', '__name__', 'Eggs'] g = eggs.Grits()
g.fish('Spam') <class 'spam.Spam'> g.fish('__doc__') 'spam.py module doc string' g.fishinghole.keys() ['__builtins__', '__name__', '__file__', '__doc__', 'Spam']

You could fish for a class that might be available in both modules by the same name,
and get a different one depending on which instance' fish method or fishinghole you used.
Here Spam is only available in spam.py, but if it were available in eggs.py then e.fish('Spam')
would pick it up just like Ham.
spaminst = g.fish('Spam')()
spaminst.fish('__doc__') 'spam.py module doc string'

Note that the fishinghole property dynamically returns the module dict,
which is mutable, so you can write a really tangled mess if you want to.
This already seems dangerously close ;-)
e.fishinghole['x'] = 'x in eggs module globals'
e.fish('x') 'x in eggs module globals' eggs.x 'x in eggs module globals' g.fishinghole['x'] = 'x in spam module globals'
g.fish('x') 'x in spam module globals' eggs.spam.x 'x in spam module globals'

But we didn't directly import spam (eggs did, that's why eggs.spam was visible) ... spam Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined import spam
spam.x

'x in spam module globals'

Regards,
Bengt Richter
Jul 21 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

50
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong...
1
by: Hans-Christian Stadler | last post by:
Hi, I'm wondering how C++ .NET initializes class members. I have code that looks aproximately like this: _gc class SuperClass; // Factory object creates instances _gc class Factory {...
2
by: stephane | last post by:
Hi all, What I am trying to achieve is an 'inherits' method similar to Douglas Crockford's (http://www.crockford.com/javascript/inheritance.html) but that can enable access to the superclass'...
38
by: looping | last post by:
For Python developers around. >From Python 2.5 doc: The list of base classes in a class definition can now be empty. As an example, this is now legal: class C(): pass nice but why this...
6
by: Pierre Rouleau | last post by:
Hi all, Is there any reason that under Python you cannot instantiate the object class and create any attributes like you would be able for a normal class? Python 2.4.2 (#67, Sep 28 2005,...
11
by: glen.coates.bigworld | last post by:
I'm developing a library at the moment that involves many classes, some of which have "exposed" capabilities. I'm trying to design a nice interface for both exposing those capabilities, and...
7
by: S. Lorétan | last post by:
Hi guys, Sorry for this stupid question, but I don't know why it isn't working. Here is my (example) code: namespace Test { class A { public string Label1; }
13
by: André | last post by:
Hi, i'm developping asp.net applications and therefore i use VB.net. I have some questions about best practises. According what i read about class and module and if i understand it right, a...
1
by: seanacais | last post by:
I want to create a class derived from a Borg class that can instantiated as part of a script or be contained in other classes. When methods from the Borg class are called, I would like to know the...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.