Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lightning Talk "Opening CPython Built-in Classes" (Europython)

Lightning Talk "Opening CPython Built-in Classes" (Europython)

Jesús Espino

July 24, 2015
Tweet

More Decks by Jesús Espino

Other Decks in Programming

Transcript

  1. Closed built-in classes >>> int.x = 3 Traceback (most recent

    call last): File "<stdin>", line 1, in <module> TypeError: can't set attributes of built-in/extension type 'int'
  2. Fix broken float comparisons >>> assert 1.3332 == 1.3333 Traceback

    (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> float.__eq__ = lambda self, other: abs(abs(self) - abs(other)) < 0.1 >>> 1.3332 == 1.3333 True >>> 1.7 == 1.1 False
  3. Add sense to the << operator >>> 5 << 1

    10 >>> 5 << 2 20 >>> int.__lshift__ = lambda self, other: self * (10 ** other) >>> 5 << 1 50 >>> 5 << 2 500
  4. More semantic bool __repr__ >>> True == True True >>>

    True == False False >>> bool.__repr__ = lambda x: ‘Yes’ if True else ‘No’ >>> True == True Yes >>> True == False No
  5. Be more rubyist >>> from masterkey import rubint >>> (3).times(print)

    0 1 2 >>> (3).upto(5, print) 4 5 >>> (3).downto(1, print) 2 1
  6. Close your own classes >>> class MyClass: ... pass >>>

    masterkey.close_class(MyClass) >>> MyClass.x = 3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't set attributes of built-in/extension type 'MyClass'
  7. The black magic import ctypes from operator import xor longsize

    = ctypes.sizeof(ctypes.c_long) def open_class(klass): int_flags = ctypes.c_long.from_address(id(klass) + longsize * 21) int_flags.value |= 1 << 9 def close_class(klass): int_flags = ctypes.c_long.from_address(id(klass) + longsize * 21) int_flags.value = xor(int_flags.value, 1 << 9)