473,386 Members | 1,795 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,386 software developers and data experts.

Adding functions to an existing instance

I need a way to add a method to an existing instance, but be as close as
possible to normal instance methods. Using 'new' module or such code as
'def addfunc(...): def helper(...) .. setattr(...)' causes a cyclic
reference which requires using 'gc.collect' to release the object. Also
'new' is deprecated. I also made a helper that uses weakref, but the
problem is when the object is gone, existing instance method object
would not work:
f = myobject.function
myobject = None
f() <--- would not work if it holds weak ref to myobject
The best I can come up with is to create a parent class and try to
simulate as best as possible. The code below works with no cyclic
references that would be cause by 'new.instancemethod' etc, and without
the weakref as well. Is there a simpler way of achieving the same
without cyclic references? I know this is 'monkey patching' but for a
small project I'm working on it is useful to be able to add functions
dynamically to one instance without adding it to another instance of the
same class, etc.
class InstanceFunctionHelper(object):
class FunctionCaller(object):
def __init__(self, instance, func):
self.__instance = instance
self.__func = func

def __call__(self, *args, **kwargs):
return self.__func(self.__instance, *args, **kwargs)

def add_instance_function(self, func, name = None):
if name is None:
name = func.__name__

if hasattr(self, name):
delattr(self, name)

try:
self._instance_funcs[name] = func
except AttributeError:
self._instance_funcs = {name: func}

def __setattr__(self, name, value):
funcs = getattr(self, '_instance_funcs', None)
if funcs and name in funcs:
del funcs[name]

object.__setattr__(self, name, value)

def __delattr__(self, name):
funcs = getattr(self, '_instance_funcs', None)
if funcs and name in funcs:
del funcs[name]
else:
object.__delattr__(self, name)

def __getattr__(self, name):
if name == '_instance_funcs':
raise AttributeError

funcs = object.__getattribute__(self, '_instance_funcs')

if name in funcs:
return InstanceFunctionHelper.FunctionCaller(self, funcs[name])

raise AttributeError

x = 0
class Blah(InstanceFunctionHelper):
def __init__(self):
global x
x += 1
def __del__(self):
global x
x -= 1

def Action(self, value):
print self
print value

a = Blah()
a.add_instance_function(Action)
a.Action(5)
a = None
print x

Jun 27 '08 #1
1 1703
On 26 juin, 17:18, Allen <brian_vanderbu...@yahoo.comwrote:
I need a way to add a method to an existing instance, but be as close as
possible to normal instance methods.
def set_method(obj, func, name=None):
if not name:
name = func.__name__
setattr(obj, name, func.__get__(obj, type(obj)))

class Toto(object):
pass

toto = Toto()

def titi(self):
print self

set_method(toto, titi)

Jun 27 '08 #2

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

Similar topics

0
by: Anthony Baxter | last post by:
To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. PEP: 318 Title: Decorators for Functions and...
4
by: Rhamphoryncus | last post by:
First a bit about myself. I've been programming in python several years now, and I've got several more years before that with C. I've got a lot of interest in the more theoretical stuff (language...
8
by: Kevin Little | last post by:
#!/usr/bin/env python ''' I want to dynamically add or replace bound methods in a class. I want the modifications to be immediately effective across all instances, whether created before or...
2
by: laredotornado | last post by:
Hello, I am looking for a cross-browser way (Firefox 1+, IE 5.5+) to have my Javascript function execute from the BODY's "onload" method, but if there is already an onload method defined, I would...
11
by: Steven D'Aprano | last post by:
Suppose I create a class with some methods: py> class C: .... def spam(self, x): .... print "spam " * x .... def ham(self, x): .... print "ham * %s" % x .......
6
by: Rudy | last post by:
Hi all, I know this is easy, just can't seem to get it. I have a windows form, and a text box, with a value already in it. I need to add that value to a table. It's just one value, so the entire...
47
by: Albert | last post by:
So structures are useful to group variables, so you can to refer to a collection as a single entity. Wouldn't it be useful to also have the ability to collect variable and functions? Ask K&R...
3
by: jjk1407 | last post by:
hello, i am a newbie to vb.net. i met a problem with vb on adding function to an existing class. when i was trying to add a function, say myfunc, to a class, myclass,
7
by: Maximus Decimus | last post by:
HI all, I am using python v2.5 and I am an amateur working on python. I am extending python for my research work and would like some help and guidance w.r.t this matter from you experienced...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
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
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...
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...

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.