magic.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. # <sure - utility belt for automated testing in python>
  3. # Copyright (C) <2012> Gabriel Falcão <gabriel@nacaolivre.org>
  4. # Copyright (C) <2012> Lincoln Clarete <lincoln@comum.org>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. from __future__ import unicode_literals
  19. import platform
  20. is_cpython = (
  21. hasattr(platform, 'python_implementation')
  22. and platform.python_implementation().lower() == 'cpython')
  23. if is_cpython:
  24. import ctypes
  25. DictProxyType = type(object.__dict__)
  26. Py_ssize_t = \
  27. hasattr(ctypes.pythonapi, 'Py_InitModule4_64') \
  28. and ctypes.c_int64 or ctypes.c_int
  29. class PyObject(ctypes.Structure):
  30. pass
  31. PyObject._fields_ = [
  32. ('ob_refcnt', Py_ssize_t),
  33. ('ob_type', ctypes.POINTER(PyObject)),
  34. ]
  35. class SlotsProxy(PyObject):
  36. _fields_ = [('dict', ctypes.POINTER(PyObject))]
  37. def patchable_builtin(klass):
  38. name = klass.__name__
  39. target = getattr(klass, '__dict__', name)
  40. if not isinstance(target, DictProxyType):
  41. return target
  42. proxy_dict = SlotsProxy.from_address(id(target))
  43. namespace = {}
  44. ctypes.pythonapi.PyDict_SetItem(
  45. ctypes.py_object(namespace),
  46. ctypes.py_object(name),
  47. proxy_dict.dict,
  48. )
  49. return namespace[name]
  50. else:
  51. patchable_builtin = lambda *args, **kw: None