Slide 1

Slide 1 text

Opening CPython Built-in Classes JESUS ESPINO GARCIA, DEVELOPER #007000

Slide 2

Slide 2 text

What’s the problem?

Slide 3

Slide 3 text

Closed built-in classes >>> int.x = 3 Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'int'

Slide 4

Slide 4 text

The solution

Slide 5

Slide 5 text

Master Key >>> import masterkey >>> masterkey.open_class(int) >>> int.x = 3 >>> (10).x 3

Slide 6

Slide 6 text

Application

Slide 7

Slide 7 text

Fix broken float comparisons >>> assert 1.3332 == 1.3333 Traceback (most recent call last): File "", line 1, in AssertionError >>> float.__eq__ = lambda self, other: abs(abs(self) - abs(other)) < 0.1 >>> 1.3332 == 1.3333 True >>> 1.7 == 1.1 False

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

Close your own classes >>> class MyClass: ... pass >>> masterkey.close_class(MyClass) >>> MyClass.x = 3 Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'MyClass'

Slide 12

Slide 12 text

Of course, this is a joke

Slide 13

Slide 13 text

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)

Slide 14

Slide 14 text

The code http://www.github.com/jespino/python-master-key