| 1 |
|
| 2 |
|
| 3 |
> |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
from __future__ import unicode_literals |
| 19 |
|
| 20 |
import platform |
| 21 |
|
| 22 |
is_cpython = ( |
| 23 |
hasattr(platform, 'python_implementation') |
| 24 |
and platform.python_implementation().lower() == 'cpython') |
| 25 |
|
| 26 |
if is_cpython: |
| 27 |
|
| 28 |
import ctypes |
| 29 |
DictProxyType = type(object.__dict__) |
| 30 |
|
| 31 |
Py_ssize_t = \ |
| 32 |
hasattr(ctypes.pythonapi, 'Py_InitModule4_64') \ |
| 33 |
and ctypes.c_int64 or ctypes.c_int |
| 34 |
|
| 35 |
class PyObject(ctypes.Structure): |
| 36 |
pass |
| 37 |
|
| 38 |
PyObject._fields_ = [ |
| 39 |
('ob_refcnt', Py_ssize_t), |
| 40 |
('ob_type', ctypes.POINTER(PyObject)), |
| 41 |
] |
| 42 |
|
| 43 |
class SlotsProxy(PyObject): |
| 44 |
_fields_ = [('dict', ctypes.POINTER(PyObject))] |
| 45 |
|
| 46 |
def patchable_builtin(klass): |
| 47 |
name = klass.__name__ |
| 48 |
target = getattr(klass, '__dict__', name) |
| 49 |
|
| 50 |
if not isinstance(target, DictProxyType): |
| 51 |
return target |
| 52 |
|
| 53 |
proxy_dict = SlotsProxy.from_address(id(target)) |
| 54 |
namespace = {} |
| 55 |
|
| 56 |
ctypes.pythonapi.PyDict_SetItem( |
| 57 |
ctypes.py_object(namespace), |
| 58 |
ctypes.py_object(name), |
| 59 |
proxy_dict.dict, |
| 60 |
) |
| 61 |
|
| 62 |
return namespace[name] |
| 63 |
else: |
| 64 |
patchable_builtin = lambda *args, **kw: None |