Debian Codegraph @

forbiddenfruit/__init__.py

raw symbols SCIP
1 # forbiddenfruit - Patch built-in python objects
2 #
3 # Copyright (c) 2013-2020 Lincoln de Sousa <[email protected]>
4 #
5 # This program is dual licensed under GPLv3 and MIT.
6 #
7 # GPLv3
8 # -----
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #
22 # MIT
23 # ---
24 # Permission is hereby granted, free of charge, to any person obtaining a copy
25 # of this software and associated documentation files (the "Software"), to deal
26 # in the Software without restriction, including without limitation the rights
27 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
28 # copies of the Software, and to permit persons to whom the Software is
29 # furnished to do so, subject to the following conditions:
30 #
31 # The above copyright notice and this permission notice shall be
32 # included in all copies or substantial portions of the Software.
33 #
34 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
35 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
36 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
37 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
38 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
39 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
40 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
41 # SOFTWARE.
42
43 import gc
44 import sys
45 from types import FunctionType
46 import ctypes
47 import inspect
48 from functools import wraps
49 from collections import defaultdict
50 from contextlib import contextmanager
51
52 try:
53 import __builtin__
54 except ImportError:
55 # Python 3 support
56 import builtins as __builtin__
57
58 __version__ = '0.1.4'
59
60 __all__ = 'curse', 'curses', 'reverse'
61
62
63 Py_ssize_t = ctypes.c_int64 if ctypes.sizeof(ctypes.c_void_p) == 8 else ctypes.c_int32
64
65
66 # dictionary holding references to the allocated function resolution
67 # arrays to type objects
68 tp_as_dict = {}
69 # container to cfunc callbacks
70 tp_func_dict = {}
71
72
73 class PyObject(ctypes.Structure):
74 def incref(self):
75 self.ob_refcnt += 1
76
77 def decref(self):
78 self.ob_refcnt -= 1
79
80 class PyFile(ctypes.Structure):
81 pass
82
83 PyObject_p = ctypes.py_object
84 Inquiry_p = ctypes.CFUNCTYPE(ctypes.c_int, PyObject_p)
85 # return type is void* to allow ctypes to convert python integers to
86 # plain PyObject*
87 UnaryFunc_p = ctypes.CFUNCTYPE(ctypes.py_object, PyObject_p)
88 BinaryFunc_p = ctypes.CFUNCTYPE(ctypes.py_object, PyObject_p, PyObject_p)
89 TernaryFunc_p = ctypes.CFUNCTYPE(ctypes.py_object, PyObject_p, PyObject_p, PyObject_p)
90 LenFunc_p = ctypes.CFUNCTYPE(Py_ssize_t, PyObject_p)
91 SSizeArgFunc_p = ctypes.CFUNCTYPE(ctypes.py_object, PyObject_p, Py_ssize_t)
92 SSizeObjArgProc_p = ctypes.CFUNCTYPE(ctypes.c_int, PyObject_p, Py_ssize_t, PyObject_p)
93 ObjObjProc_p = ctypes.CFUNCTYPE(ctypes.c_int, PyObject_p, PyObject_p)
94
95 FILE_p = ctypes.POINTER(PyFile)
96
97
98 def get_not_implemented():
99 namespace = {}
100 name = "_Py_NotImplmented"
101 not_implemented = ctypes.cast(
102 ctypes.pythonapi._Py_NotImplementedStruct, ctypes.py_object)
103
104 ctypes.pythonapi.PyDict_SetItem(
105 ctypes.py_object(namespace),
106 ctypes.py_object(name),
107 not_implemented
108 )
109 return namespace[name]
110
111
112 # address of the _Py_NotImplementedStruct singleton
113 NotImplementedRet = get_not_implemented()
114
115 class PyNumberMethods(ctypes.Structure):
116 _fields_ = [
117 ('nb_add', BinaryFunc_p),
118 ('nb_subtract', BinaryFunc_p),
119 ('nb_multiply', BinaryFunc_p),
120 ('nb_remainder', BinaryFunc_p),
121 ('nb_divmod', BinaryFunc_p),
122 ('nb_power', BinaryFunc_p),
123 ('nb_negative', UnaryFunc_p),
124 ('nb_positive', UnaryFunc_p),
125 ('nb_absolute', UnaryFunc_p),
126 ('nb_bool', Inquiry_p),
127 ('nb_invert', UnaryFunc_p),
128 ('nb_lshift', BinaryFunc_p),
129 ('nb_rshift', BinaryFunc_p),
130 ('nb_and', BinaryFunc_p),
131 ('nb_xor', BinaryFunc_p),
132 ('nb_or', BinaryFunc_p),
133 ('nb_int', UnaryFunc_p),
134 ('nb_reserved', ctypes.c_void_p),
135 ('nb_float', UnaryFunc_p),
136
137 ('nb_inplace_add', BinaryFunc_p),
138 ('nb_inplace_subtract', BinaryFunc_p),
139 ('nb_inplace_multiply', BinaryFunc_p),
140 ('nb_inplace_remainder', BinaryFunc_p),
141 ('nb_inplace_power', TernaryFunc_p),
142 ('nb_inplace_lshift', BinaryFunc_p),
143 ('nb_inplace_rshift', BinaryFunc_p),
144 ('nb_inplace_and', BinaryFunc_p),
145 ('nb_inplace_xor', BinaryFunc_p),
146 ('nb_inplace_or', BinaryFunc_p),
147
148 ('nb_floor_divide', BinaryFunc_p),
149 ('nb_true_divide', BinaryFunc_p),
150 ('nb_inplace_floor_divide', BinaryFunc_p),
151 ('nb_inplace_true_divide', BinaryFunc_p),
152
153 ('nb_index', BinaryFunc_p),
154
155 ('nb_matrix_multiply', BinaryFunc_p),
156 ('nb_inplace_matrix_multiply', BinaryFunc_p),
157 ]
158
159 class PySequenceMethods(ctypes.Structure):
160 _fields_ = [
161 ('sq_length', LenFunc_p),
162 ('sq_concat', BinaryFunc_p),
163 ('sq_repeat', SSizeArgFunc_p),
164 ('sq_item', SSizeArgFunc_p),
165 ('was_sq_slice', ctypes.c_void_p),
166 ('sq_ass_item', SSizeObjArgProc_p),
167 ('was_sq_ass_slice', ctypes.c_void_p),
168 ('sq_contains', ObjObjProc_p),
169 ('sq_inplace_concat', BinaryFunc_p),
170 ('sq_inplace_repeat', SSizeArgFunc_p),
171 ]
172
173 class PyMappingMethods(ctypes.Structure):
174 pass
175
176 class PyTypeObject(ctypes.Structure):
177 pass
178
179 class PyAsyncMethods(ctypes.Structure):
180 pass
181
182
183 PyObject._fields_ = [
184 ('ob_refcnt', Py_ssize_t),
185 ('ob_type', ctypes.POINTER(PyTypeObject)),
186 ]
187
188 PyTypeObject._fields_ = [
189 # varhead
190 ('ob_base', PyObject),
191 ('ob_size', Py_ssize_t),
192 # declaration
193 ('tp_name', ctypes.c_char_p),
194 ('tp_basicsize', Py_ssize_t),
195 ('tp_itemsize', Py_ssize_t),
196 ('tp_dealloc', ctypes.CFUNCTYPE(None, PyObject_p)),
197 ('printfunc', ctypes.CFUNCTYPE(ctypes.c_int, PyObject_p, FILE_p, ctypes.c_int)),
198 ('getattrfunc', ctypes.CFUNCTYPE(PyObject_p, PyObject_p, ctypes.c_char_p)),
199 ('setattrfunc', ctypes.CFUNCTYPE(ctypes.c_int, PyObject_p, ctypes.c_char_p, PyObject_p)),
200 ('tp_as_async', ctypes.CFUNCTYPE(PyAsyncMethods)),
201 ('tp_repr', ctypes.CFUNCTYPE(PyObject_p, PyObject_p)),
202 ('tp_as_number', ctypes.POINTER(PyNumberMethods)),
203 ('tp_as_sequence', ctypes.POINTER(PySequenceMethods)),
204 ('tp_as_mapping', ctypes.POINTER(PyMappingMethods)),
205 ('tp_hash', ctypes.CFUNCTYPE(ctypes.c_int64, PyObject_p)),
206 ('tp_call', ctypes.CFUNCTYPE(PyObject_p, PyObject_p, PyObject_p, PyObject_p)),
207 ('tp_str', ctypes.CFUNCTYPE(PyObject_p, PyObject_p)),
208 # ...
209 ]
210
211
212 # redundant dict of pointee types, because ctypes doesn't allow us
213 # to extract the pointee type from the pointer
214 PyTypeObject_as_types_dict = {
215 'tp_as_async': PyAsyncMethods,
216 'tp_as_number': PyNumberMethods,
217 'tp_as_sequence': PySequenceMethods,
218 'tp_as_mapping': PyMappingMethods,
219 }
220
221
222 def patchable_builtin(klass):
223 refs = gc.get_referents(klass.__dict__)
224 assert len(refs) == 1
225 return refs[0]
226
227
228 @wraps(__builtin__.dir)
229 def __filtered_dir__(obj=None):
230 name = hasattr(obj, '__name__') and obj.__name__ or obj.__class__.__name__
231 if obj is None:
232 # Return names from the local scope of the calling frame,
233 # taking into account indirection added by __filtered_dir__
234 calling_frame = inspect.currentframe().f_back
235 return sorted(calling_frame.f_locals.keys())
236 return sorted(set(__dir__(obj)).difference(__hidden_elements__[name]))
237
238 # Switching to the custom dir impl declared above
239 __hidden_elements__ = defaultdict(list)
240 __dir__ = dir
241 __builtin__.dir = __filtered_dir__
242
243 # build override infomation for dunder methods
244 as_number = ('tp_as_number', [
245 ("add", "nb_add"),
246 ("sub", "nb_subtract"),
247 ("mul", "nb_multiply"),
248 ("mod", "nb_remainder"),
249 ("pow", "nb_power"),
250 ("neg", "nb_negative"),
251 ("pos", "nb_positive"),
252 ("abs", "nb_absolute"),
253 ("bool", "nb_bool"),
254 ("inv", "nb_invert"),
255 ("invert", "nb_invert"),
256 ("lshift", "nb_lshift"),
257 ("rshift", "nb_rshift"),
258 ("and", "nb_and"),
259 ("xor", "nb_xor"),
260 ("or", "nb_or"),
261 ("int", "nb_int"),
262 ("float", "nb_float"),
263 ("iadd", "nb_inplace_add"),
264 ("isub", "nb_inplace_subtract"),
265 ("imul", "nb_inplace_multiply"),
266 ("imod", "nb_inplace_remainder"),
267 ("ipow", "nb_inplace_power"),
268 ("ilshift", "nb_inplace_lshift"),
269 ("irshift", "nb_inplace_rshift"),
270 ("iadd", "nb_inplace_and"),
271 ("ixor", "nb_inplace_xor"),
272 ("ior", "nb_inplace_or"),
273 ("floordiv", "nb_floor_divide"),
274 ("div", "nb_true_divide"),
275 ("ifloordiv", "nb_inplace_floor_divide"),
276 ("idiv", "nb_inplace_true_divide"),
277 ("index", "nb_index"),
278 ("matmul", "nb_matrix_multiply"),
279 ("imatmul", "nb_inplace_matrix_multiply"),
280 ])
281
282 as_sequence = ("tp_as_sequence", [
283 ("len", "sq_length"),
284 ("concat", "sq_concat"),
285 ("repeat", "sq_repeat"),
286 ("getitem", "sq_item"),
287 ("setitem", "sq_ass_item"),
288 ("contains", "sq_contains"),
289 ("iconcat", "sq_inplace_concat"),
290 ("irepeat", "sq_inplace_repeat"),
291 ])
292
293 as_async = ("tp_as_async", [
294 ("await", "am_await"),
295 ("aiter", "am_aiter"),
296 ("anext", "am_anext"),
297 ])
298
299 override_dict = {}
300 for override in [as_number, as_sequence, as_async]:
301 tp_as_name = override[0]
302 for dunder, impl_method in override[1]:
303 override_dict["__{}__".format(dunder)] = (tp_as_name, impl_method)
304
305 # divmod isn't a dunder, still make it overridable
306 override_dict['divmod()'] = ('tp_as_number', "nb_divmod")
307 override_dict['__str__'] = ('tp_str', "tp_str")
308
309
310 def _is_dunder(func_name):
311 return func_name.startswith("__") and func_name.endswith("__")
312
313
314 def _curse_special(klass, attr, func):
315 """
316 Curse one of the "dunder" methods, i.e. methods beginning with __ which have a
317 precial resolution code path
318 """
319 assert callable(func)
320
321 @wraps(func)
322 def wrapper(*args, **kwargs):
323 """
324 This wrapper returns the address of the resulting object as a
325 python integer which is then converted to a pointer by ctypes
326 """
327 try:
328 return func(*args, **kwargs)
329 except NotImplementedError:
330 return NotImplementedRet
331
332 tp_as_name, impl_method = override_dict[attr]
333
334 # get the pointer to the correct tp_as_* structure
335 # or create it if it doesn't exist
336 tyobj = PyTypeObject.from_address(id(klass))
337 if tp_as_name in PyTypeObject_as_types_dict:
338 struct_ty = PyTypeObject_as_types_dict[tp_as_name]
339 tp_as_ptr = getattr(tyobj, tp_as_name)
340 if not tp_as_ptr:
341 # allocate new array
342 tp_as_obj = struct_ty()
343 tp_as_dict[(klass, attr)] = tp_as_obj
344 tp_as_new_ptr = ctypes.cast(ctypes.addressof(tp_as_obj),
345 ctypes.POINTER(struct_ty))
346
347 setattr(tyobj, tp_as_name, tp_as_new_ptr)
348 tp_as = tp_as_ptr[0]
349
350 # find the C function type
351 for fname, ftype in struct_ty._fields_:
352 if fname == impl_method:
353 cfunc_t = ftype
354
355 cfunc = cfunc_t(wrapper)
356 tp_func_dict[(klass, attr)] = cfunc
357
358 setattr(tp_as, impl_method, cfunc)
359 else:
360 # find the C function type
361 for fname, ftype in PyTypeObject._fields_:
362 if fname == impl_method:
363 cfunc_t = ftype
364
365 if not (klass, attr) in tp_as_dict:
366 tp_as_dict[(klass, attr)] = ctypes.cast(getattr(tyobj, impl_method), cfunc_t)
367
368 # override function call
369 cfunc = cfunc_t(wrapper)
370 tp_func_dict[(klass, attr)] = cfunc
371 setattr(tyobj, impl_method, cfunc)
372
373 def _revert_special(klass, attr):
374 tp_as_name, impl_method = override_dict[attr]
375 tyobj = PyTypeObject.from_address(id(klass))
376 tp_as_ptr = getattr(tyobj, tp_as_name)
377 if tp_as_ptr:
378 if tp_as_name in PyTypeObject_as_types_dict:
379 tp_as = tp_as_ptr[0]
380
381 struct_ty = PyTypeObject_as_types_dict[tp_as_name]
382 for fname, ftype in struct_ty._fields_:
383 if fname == impl_method:
384 cfunc_t = ftype
385
386 setattr(tp_as, impl_method,
387 ctypes.cast(ctypes.c_void_p(None), cfunc_t))
388 else:
389 if not (klass, attr) in tp_as_dict:
390 # we didn't save this pointer
391 # most likely never cursed
392 return
393
394 cfunc = tp_as_dict[(klass, attr)]
395 setattr(tyobj, impl_method, cfunc)
396
397
398 def curse(klass, attr, value, hide_from_dir=False):
399 """Curse a built-in `klass` with `attr` set to `value`
400
401 This function monkey-patches the built-in python object `attr` adding a new
402 attribute to it. You can add any kind of argument to the `class`.
403
404 It's possible to attach methods as class methods, just do the following:
405
406 >>> def myclassmethod(cls):
407 ... return cls(1.5)
408 >>> curse(float, "myclassmethod", classmethod(myclassmethod))
409 >>> float.myclassmethod()
410 1.5
411
412 Methods will be automatically bound, so don't forget to add a self
413 parameter to them, like this:
414
415 >>> def hello(self):
416 ... return self * 2
417 >>> curse(str, "hello", hello)
418 >>> "yo".hello()
419 "yoyo"
420 """
421 if _is_dunder(attr):
422 if sys.version_info < (3, 3):
423 raise NotImplementedError(
424 "Dunder overloading is only supported on Python >= 3.3")
425 _curse_special(klass, attr, value)
426 return
427
428 dikt = patchable_builtin(klass)
429
430 old_value = dikt.get(attr, None)
431 old_name = '_c_%s' % attr # do not use .format here, it breaks py2.{5,6}
432
433 # Patch the thing
434 dikt[attr] = value
435
436 if old_value:
437 hide_from_dir = False # It was already in dir
438 dikt[old_name] = old_value
439
440 try:
441 dikt[attr].__name__ = old_value.__name__
442 except (AttributeError, TypeError): # py2.5 will raise `TypeError`
443 pass
444 try:
445 dikt[attr].__qualname__ = old_value.__qualname__
446 except AttributeError:
447 pass
448
449 ctypes.pythonapi.PyType_Modified(ctypes.py_object(klass))
450
451 if hide_from_dir:
452 __hidden_elements__[klass.__name__].append(attr)
453
454
455 def reverse(klass, attr):
456 """Reverse a curse in a built-in object
457
458 This function removes *new* attributes. It's actually possible to remove
459 any kind of attribute from any built-in class, but just DON'T DO IT :)
460
461 Good:
462
463 >>> curse(str, "blah", "bleh")
464 >>> assert "blah" in dir(str)
465 >>> reverse(str, "blah")
466 >>> assert "blah" not in dir(str)
467
468 Bad:
469
470 >>> reverse(str, "strip")
471 >>> " blah ".strip()
472 Traceback (most recent call last):
473 File "<stdin>", line 1, in <module>
474 AttributeError: 'str' object has no attribute 'strip'
475
476 """
477 if _is_dunder(attr):
478 _revert_special(klass, attr)
479 return
480
481 dikt = patchable_builtin(klass)
482 del dikt[attr]
483
484 ctypes.pythonapi.PyType_Modified(ctypes.py_object(klass))
485
486
487 def curses(klass, name):
488 """Decorator to add decorated method named `name` the class `klass`
489
490 So you can use it like this:
491
492 >>> @curses(dict, 'banner')
493 ... def dict_banner(self):
494 ... l = len(self)
495 ... print('This dict has {0} element{1}'.format(
496 ... l, l is 1 and '' or 's')
497 >>> {'a': 1, 'b': 2}.banner()
498 'This dict has 2 elements'
499 """
500 def wrapper(func):
501 curse(klass, name, func)
502 return func
503 return wrapper
504
505
506 @contextmanager
507 def cursed(obj, attr, val, hide_from_dir=False):
508 curse(obj, attr, val, hide_from_dir)
509 try:
510 yield
511 finally:
512 reverse(obj, attr)