473,406 Members | 2,404 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,406 software developers and data experts.

run time linked attributes

I've read a few posts about how to have attributes that are "linked" at
run time. I've created a (simple) Python metaclass that accomplishes
this with some behind-the-scenes __init__ redirection. I'm posting the
code at the end in case anyone is interested.

Problem background:
Object a (an instance of class A) has an attribute that points to
object b (which is an instance of class B). So A's __init__ might look
something like this:
__init__(self):
self.b = B(arg1, arg2, arg3)

The catch is, that instances of B() need to reference other attributes
of A. The traditional way to do this is pass the instance of A as a
parameter to B. So B's __init__ might look something like:
__init__(self, creator, arg1, arg2, arg3):
self.creator = creator;

naturally, A's __init__ would now look something like:
__init__(self):
self.b = B(self, arg1, arg2, arg3)

Essentially this creates two links:
a = A();
a.b --> b
a.b.creator -> a

To hide the passing of the reference to the parent/creator, the
metaclass below adds a method MakeLinkedAttribute.

To hide the handling of the reference to the parent/creator, the
metaclass below redirects B's __init__ when the class object is
created, inserting a call to Meta__init__, which handles the processing
of the parent/creator element. The original __init__ is then called.
See the module's docstring for an example...

I'm curious to hear feedback about the code, especially any dangers
that can occur from redirecting/hijacking __init__.

Cheers!

LinkedAttribute.py:
""" Metaclass for making linked attributes

The LinkedAttribute class allows you to (at run time) have objects
that have references back to the object that created them.

Any class that has LinkedAttribute as it's metaclass will have a
MakedLinkedAttribute() method to make linked attributes.

To accomplish this hackery, we use the metaclass to hijack the
__init__
method, replacing it with our own. The new __init__ method (defined
as
Meta__init__) sets up the _creator attribute (if it was passed in) and
then
calls the original __init__ function. The original __init__ function
gets
renamed to <class name>_old__init__. The reason for including the
class name
in the first part of the redefinition is so that sub classes that call
super(...).__init__ won't enter an infinite loop.
The restriction to using this metaclass is that the classes that you
call
MakeLinkedAttribute on must also have LinkedAttribute as a metaclass.

If you use this metaclass, make sure to give credit where credit is
due :)
(e.g. in a comment or docstring)

There are other ways of solving the same problem (including passing
the
parent to __init__ explicitly).
The software is provided AS IS, use this software at your own risk.
There
is no warranty. By using this software you agree to hold the
author(s)
harmless of any damage whether direct, incidental, consequently and
otherwise. In no event shall the author(s) of this code be liable for
any
damages whatsoever incurred by this code.

(c) 2006 Michael Murr [mmurr at code-x d0t net]
e.g.:
-----

from LinkedAttribute import LinkedAttribute

class a(object):
def __init__(self):
self.linked_b = self.MakeLinkedAttribute(b, "this is a linked b")
self.plain_b = b("this is a plain b")

__metaclass__ = LinkedAttribute

class b(object):
def __init__(self, text):
self.text = text
if hasattr(self, "_creator"):
print "I have a creator!"
else:
print "I am a standalone!"

__metaclass__ = LinkedAttribute

if __name__ == "__main__":
objectA = a()
objectB = b("created directly")

print objectA.linked_b.text
print objectA.plain_b.text
print objectB.text

yields:
-------

I have a creator!
I am a standalone!
I am a standalone!
this is a linked b
this is a plain b
created directly

"""

class LinkedAttribute(type):
def __new__(klass, klassName, klassBases, klassDict):
# Method to make a new linked child
def MakeLinkedAttribute(self, childClass, *args, **kwds):
return(childClass(_creator=self, *args, **kwds))
# MakeLinkedAttribute(self, childClass, *args, **kwds):

# Run time hijacking of __init__ so we can make
# a _creator BEFORE the original __init__ is called
#
# We use klassName + "_hijacked__init__" so sub classes
# who call super(...).__init__ won't enter infinite
# loops
#
# Note: All your __init__ are belong to us :)
def Meta__init__(self, *args, **kwds):
# If we don't have _creator keyword do nothing
if kwds.has_key("_creator"):
self._creator = kwds["_creator"]
del kwds["_creator"]
# kwds.has_key("_creator"):

# If we don't have an old init, do nothing
if hasattr(self, klassName + "_hijacked__init__"):
attr = getattr(self, klassName + "_hijacked__init__")
attr(*args, **kwds)
# hasattr(self, klassName + "_hijacked__init__"):
# Meta__init__(self, *args, **kwds):

# If we have an init, we need to save it
if klassDict.has_key("__init__"): klassDict[klassName +
"_hijacked__init__"] = klassDict["__init__"]

# Hijack (redirect) __init__ for our [evil] purposes :)
klassDict["__init__"] = Meta__init__
instance = super(LinkedAttribute, klass).__new__(klass, klassName,
klassBases, klassDict)
instance.MakeLinkedAttribute = MakeLinkedAttribute

return(instance)
# __new__(klass, klassName, klassBases, klassDict):
# LinkedAttribute(type):

May 28 '06 #1
0 1196

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

Similar topics

1
by: Ross Klatte | last post by:
Okay, so he didn't. So, who cares? The important question is: How do I direct my SPUFI output to a disk file? I did this before, but now I have forgotten it. (And yet, you say Arnold is the...
2
by: Internet Arrow Limited | last post by:
Hi, I have a requirement to write an access application that must run under access97 and access2K. Some users will use Acess2K to access data that will also be accessed by Access97 users. The...
43
by: Mike MacSween | last post by:
Or something to do with Nulls in PK. Which is obviously wrong. OK, after a diversion of having to earn money its back to the free one. The orchestral management system. At the E-R level: An...
5
by: deko | last post by:
How to run action query against linked table? I have an Access 2003 mdb with an Excel 2003 Workbook as a linked table. When I attempt to run an action query against the linked table I get this...
0
by: crypto_solid via AccessMonster.com | last post by:
I have been using a SQL database with a VB5 frontend for about 5 years. Works well. Unfortunately I don't have access to the source code. I was tasked with implementing a "job entry" application...
2
by: Glen | last post by:
I'm working on a custom assembly and I'm trying to figure out the best approach to handling known constraints within the assembly, once compiled, to alert the developer at compile time of a...
2
by: kharless | last post by:
Greetings, If I use a "select into" to clone a table, all attributes are created correctly, however, if I use the same statement across a linked server, my identity column loses its IDENTITY...
0
by: javi_moreno | last post by:
Hello, I am working with calls to remote methods in Jbuilder X with session beans. i have some problems marshaling a complex linked list. This linked list is a list of nodes. Every node has some...
19
by: Dongsheng Ruan | last post by:
with a cell class like this: #!/usr/bin/python import sys class Cell: def __init__( self, data, next=None ): self.data = data
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
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,...

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.