473,569 Members | 2,400 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1998
"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 "fishinghol e"
-- e.g.,

----< spam.py >-------------------------------
"""spam.py module doc string"""
class Spam(object):
def fish(self, whatfor):
return self.fishinghol e[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.k eys() ['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.k eys() ['__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
6312
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 def foo(self, data): self.attr1=data self.attr2.append(data) The initialization of attr1 is obviously OK, all instances of Father redefine it in the...
1
2108
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 { public:
2
3020
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' priviledged methods also. Do you know if this is possible ? In the following example, I create an ObjectA (variable a), an ObjectB which inherits...
38
2021
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 syntax return old-style class, same as "class C:", and not the new style "class C(object):" ?
6
1745
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, 12:41:11) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = object() >>> a.data = 1
11
1815
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 inspecting instances to find out what capabilities they have. At the moment, I'm leaning towards a superclass (Exposed) that defines a static method...
7
13643
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
2682
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 module does the same as a class but cannot herite or be herited. 1)Is that right? 2) So i guess this module does exactly the same as the class?
1
1096
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 name of the class that contains the Borg class. I've played a bit with inspect and _getframe from the sys module but get inconsistent results. ...
0
7926
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7983
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6287
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3657
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1228
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
946
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.