monkeypatching

Is it possible to override __getitem__ at instance level in Python?

橙三吉。 提交于 2019-12-04 02:47:14
With the following code : import types class Foo(): def __getitem__(self, x): return x def new_get(self, x): return x + 1 x = Foo() x.__getitem__ = types.MethodType(new_get, x) x.__getitem__(42) will return 43, but x[42] will return 42. Is there a way to override __getitem__ at instance level in Python? This is unfortunately, and quite surprisingly, not allowed: For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. Source: https://docs.python.org/3/reference/datamodel.html

Adding base class to existing object in python

▼魔方 西西 提交于 2019-12-04 01:20:53
问题 I have several objects of different kinds (different function names, different signatures) and I monkey patch them to have a common way to access them from different functions. Briefly, there is a dispatcher that takes the objects that I want to patch and depending on the object type it calls different patcher. A patcher will add methods to the object: def patcher_of_some_type(object): def target(self, value): # do something and call self methods object.target = types.MethodType(target,

Why python's monkeypatch doesn't work when importing a class instead of a module?

耗尽温柔 提交于 2019-12-03 23:23:09
I was having issues while using the code of the accepted answer here . The code works depending on how I do the import of datetime. Why is that? Is it possible to mock it so it works both ways? I am using Python 3.4 . The following code illustrates the problem: import pytest from datetime import datetime mockdate = datetime(2000, 1, 1, 0, 0, 0) @pytest.fixture(autouse=True) def patch_datetime_now(monkeypatch): class mydatetime: @classmethod def now(cls): return mockdate monkeypatch.setattr('datetime.datetime', mydatetime) def test_doesnt_work(): assert datetime.now() == mockdate def test_works

Duck punching in a property in python

佐手、 提交于 2019-12-03 16:22:12
I'd like to be able to add a property http://docs.python.org/library/functions.html#property to an object (a specific instance of a class). Is this possible? Some other questions about duck punching/monkey patching in python: Adding a Method to an Existing Object Instance Python: changing methods and attributes at runtime UPDATE: Answered by delnan in the comments Dynamically adding @property in python Following code works : #!/usr/bin/python class C(object): def __init__(self): self._x = None def getx(self): print "getting" return self._x def setx(self, value): print "setting" self._x = value

Dynamically add a property or method to an object in groovy

和自甴很熟 提交于 2019-12-03 14:27:40
问题 Is it possible to add a property or a method to an object dynamically in Groovy? This is what I have tried so far: class Greet { def name Greet(who) { name = who[0].toUpperCase() + [1..-1] } def salute() { println "Hello $name!" } } g = new Greet('world') // create object g.salute() // Output "Hello World!" g.bye = { println "Goodbye, $name" } g.bye() But I get the following exception: Hello World! Caught: groovy.lang.MissingPropertyException: No such property: bye for class: Greet Possible

How to monkey patch a `__call__` method?

南笙酒味 提交于 2019-12-03 12:50:13
I don't seem to be able to monkey patch a __call__ method of class instance (and yes, I want to patch just single instances, not all of them). The following code: class A(object): def test(self): return "TEST" def __call__(self): return "EXAMPLE" a = A() print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) a.__call__ = lambda : "example" a.test = lambda : "test" print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) print(a()) print("Explicit call: {0}".format(a.__call__())) print(a.test()) Outputs this: call method: <bound method

If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?

我的未来我决定 提交于 2019-12-03 11:39:59
问题 In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. Why this distinction? Does Python include different types of safeguards to minimize the risks of this feature? 回答1: As a Python programmer who has had a taste of Ruby (and likes it), I

Monkey patching a @property

烂漫一生 提交于 2019-12-03 08:08:58
问题 Is it at all possible to monkey patch the value of a @property of an instance of a class that I do not control? class Foo: @property def bar(self): return here().be['dragons'] f = Foo() print(f.bar) # baz f.bar = 42 # MAGIC! print(f.bar) # 42 Obviously the above would produce an error when trying to assign to f.bar . Is # MAGIC! possible in any way? The implementation details of the @property are a black box and not indirectly monkey-patchable. The entire method call needs to be replaced. It

Where is the best place to add methods to the Integer class in Rails?

牧云@^-^@ 提交于 2019-12-03 08:02:15
Where is the best place to add a method to the integer class in Rails? I'd like to add a to_meters and to_miles methods. If you have your heart set on mucking with the Numeric (or integer, etc) class to get unit conversion, then at least do it logically and with some real value. First, create a Unit class that stores the unit type (meters,feet, cubits, etc.) and the value on creation. Then add a bunch of methods to Numeric that correspond to the valid values unit can have: these methods will return a Unit object with it's type recorded as the method name. The Unit class would support a bunch

Dynamically add a property or method to an object in groovy

一笑奈何 提交于 2019-12-03 04:15:14
Is it possible to add a property or a method to an object dynamically in Groovy? This is what I have tried so far: class Greet { def name Greet(who) { name = who[0].toUpperCase() + [1..-1] } def salute() { println "Hello $name!" } } g = new Greet('world') // create object g.salute() // Output "Hello World!" g.bye = { println "Goodbye, $name" } g.bye() But I get the following exception: Hello World! Caught: groovy.lang.MissingPropertyException: No such property: bye for class: Greet Possible solutions: name at test.run(greet.groovy:11) If you just want to add the bye() method to the single