Extending builtin classes in python

Just subclass the type >>> class X(str): … def my_method(self): … return int(self) … >>> s = X(“Hi Mom”) >>> s.lower() ‘hi mom’ >>> s.my_method() Traceback (most recent call last): File “<stdin>”, line 1, in <module> File “<stdin>”, line 3, in my_method ValueError: invalid literal for int() with base 10: ‘Hi Mom’ >>> z = … Read more

How to monkey patch Django?

put the file monkey_patching.py in any of your apps and import it in app’s __init__.py file. ie: app/monkey_patching.py #app/monkey_patching.py from django.contrib.auth.models import User User.add_to_class(‘openid’, models.CharField(max_length=250,blank=True)) def get_user_name(self): if self.first_name or self.last_name: return self.first_name + ” ” + self.last_name return self.username User.add_to_class(“get_user_name”,get_user_name) app/__init__.py #app/__init__.py import monkey_patching

How does one monkey patch a function in python?

It may help to think of how Python namespaces work: they’re essentially dictionaries. So when you do this: from a_package.baz import do_something_expensive do_something_expensive = lambda: ‘Something really cheap.’ think of it like this: do_something_expensive = a_package.baz[‘do_something_expensive’] do_something_expensive = lambda: ‘Something really cheap.’ Hopefully you can realize why this doesn’t work then 🙂 Once you import … Read more

Patch routine call in delphi

I use the following code: procedure PatchCode(Address: Pointer; const NewCode; Size: Integer); var OldProtect: DWORD; begin if VirtualProtect(Address, Size, PAGE_EXECUTE_READWRITE, OldProtect) then begin Move(NewCode, Address^, Size); FlushInstructionCache(GetCurrentProcess, Address, Size); VirtualProtect(Address, Size, OldProtect, @OldProtect); end; end; type PInstruction = ^TInstruction; TInstruction = packed record Opcode: Byte; Offset: Integer; end; procedure RedirectProcedure(OldAddress, NewAddress: Pointer); var NewCode: TInstruction; … Read more

How can I modify the XMLHttpRequest responsetext received by another function?

Edit: See the second code option below (it is tested and works). The first one has some limitations. Since you can’t modify any of those functions, it appears you have to go after the XMLHttpRequest prototype. Here’s one idea (untested, but you can see the direction): (function() { var open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, … Read more

How to get object itself in custom Object.prototype.xxx function?

Monkey Patching What you want to do is called monkey patching — you mutate a built-in prototype. There are many wrong ways to do it, and it should be avoided entirely, because it has negative Web compatibility impacts. I will, however, demonstrate how this can be done in a way that matches existing prototype features most closely. … Read more