Last active
September 19, 2019 14:26
-
-
Save ultrafunkamsterdam/019b0dd7f80137812ac4de463b728bf6 to your computer and use it in GitHub Desktop.
MagicBuiltins - define methods on built-in types in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ctypes as c | |
class PyObject_HEAD(c.Structure): | |
_fields_ = [ | |
('HEAD', c.c_ubyte * (object.__basicsize__ - | |
c.sizeof(c.c_void_p))), | |
('ob_type', c.c_void_p) | |
] | |
_get_dict = c.pythonapi._PyObject_GetDictPtr | |
_get_dict.restype = c.POINTER(c.py_object) | |
_get_dict.argtypes = [c.py_object] | |
def get_dict(object): | |
return _get_dict(object).contents.value | |
def setattr_builtin(builtin, method_name, func): | |
# don't forget func needs to be defined and must have self as first arg | |
get_dict(builtin)[method_name] = func | |
# usage | |
def add100(self): | |
return self + 100 | |
setattr_builtin(int, 'add100', add100) | |
>>>i = 10 | |
>>>i.add100() | |
>>>110 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment