Replacing the β€œnew” module

I have a code that contains the following two lines: -

instanceMethod = new.instancemethod(testFunc, None, TestCase) setattr(TestCase, testName, instanceMethod) 

How can it be rewritten without using the "new" module? I'm sure the new style classes provide some workaround for this, but I'm not sure how to do this.

+6
python
source share
5 answers

There is a discussion that this is not required in python 3. The same thing works in Python 2.6

Cm:

 >>> class C: pass ... >>> c=C() >>> def f(self): pass ... >>> cf = f.__get__(c, C) >>> cf <bound method Cf of <__main__.C instance at 0x10042efc8>> >>> cf <unbound method Cf> >>> 

Repeating the question for every benefit, including mine.

Is there a replacement in Python3 for new.instancemethod? That is, given an arbitrary instance (and not its class), how can I add a new corresponding function as a method for it?

The following is enough:

 TestCase.testFunc = testFunc.__get__(None, TestCase) 
+9
source share

You can replace "new.instancemethod" with "types.MethodType":

 from types import MethodType as instancemethod class Foo: def __init__(self): print 'I am ', id(self) def bar(self): print 'hi', id(self) foo = Foo() # prints 'I am <instance id>' mm = instancemethod(bar, foo) # automatically uses foo.__class__ mm() # prints 'I have been bound to <same instance id>' foo.mm # traceback because no 'field' created in foo to hold ref to mm foo.mm = mm # create ref to bound method in foo foo.mm() # prints 'I have been bound to <same instance id>' 
+3
source share

Check this thread (updated: source site deleted).

+2
source share

This will do the same:

 >>> Testcase.testName = testFunc 

Yes, it really is that simple.

Your line

 >>> instanceMethod = new.instancemethod(testFunc, None, TestCase) 

Is in practice (albeit not theoretically) noop. :) You could just as well

 >>> instanceMethod = testFunc 

In fact, in Python 3, I’m sure it will be the same in theory, but the new module has disappeared, so I can’t test it in practice.

+1
source share

To confirm that you don't need to use new.instancemthod () at all, starting with Python v2.4, here's an example of replacing an instance method. Also no need to use descriptors (although this works).

 class Ham(object): def spam(self): pass h = Ham() def fake_spam(): h._spam = True h.spam = fake_spam h.spam() # h._spam should be True now. 

Convenient for unit testing.

0
source share

All Articles