7
def __init__(self, content):
10
return '<pre class="python">%s</pre>' % (self.content,)
13
"Changing the Type of Literals",
14
Slide("New-style classes",
15
Bullet("In 2.2+, built-in types can be subclassed"),
16
Bullet("These can be created explicitly by using their name", SubBullet(
17
Bullet("For example, an int subclass that displays itself in roman numerals"),
18
Bullet("print RomanNumeral(13) -> XIII"),
21
Slide("Literals are less accessable",
22
Bullet("When you write [] or 7, the list or int type is instantiated"),
23
Bullet("This behavior seems inaccessable"),
24
Bullet("While this makes for more readable code, it limits the scope of possible evil"),
26
Slide("Throw in an extension module...",
27
Bullet("intrinsics.so exposes one function, 'replace'"),
28
Bullet("It takes two arguments", SubBullet(
29
Bullet("A type object to replace"),
30
Bullet("The type object with which to replace it"),
32
Bullet("Magic is performed, and the new type is now used whenever the old one would have been"),
36
class RomanNumeral(int):
38
# Regular code for formatting roman numerals
40
old_int = intrinsics.replace(int, RomanNumeral)
44
Bullet("The output is simply the roman numerals XIII"),
46
Slide("intrinsics.c - The replacement",
49
intrinsics_replace(PyObject* self, PyObject* args) {
50
static PyTypeObject* const types[] = {
51
&PyInt_Type, &PyLong_Type, &PyFloat_Type, &PyComplex_Type,
52
&PyBool_Type, &PyBaseObject_Type, &PyDict_Type, &PyTuple_Type,
53
&PyBuffer_Type, &PyClassMethod_Type, &PyEnum_Type, &PyProperty_Type,
54
&PyList_Type, &PyStaticMethod_Type, &PySlice_Type, &PySuper_Type,
55
&PyType_Type, &PyRange_Type, &PyFile_Type, &PyUnicode_Type,
64
if (!PyArg_ParseTuple(args, "OO:replace", &old, &new))
69
Slide("intrinsics.c - The actual replacement",
72
if (types[i] == (PyTypeObject*)old) {
73
space = PyObject_New(PyTypeObject, &PyType_Type);
75
*(types[i]) = *(PyTypeObject*)new;
81
PyErr_SetString(replace_error, "unknown type");
86
return (PyObject*)space;
91
Slide("This is the wrong answer",
92
Bullet("The right answer is to add more flexibility to the Python compiler"),
93
Bullet("This is a lot less code, though"),
97
lecture.renderHTML(".", "intrinsics-lightning-%d.html", css="stylesheet.css")