1 Micropython: A minimal implementation of Python for constrained devices
2
3 * Python provides a rich programming environment
4 * CPython enforces the "official" language version
5 * CPython, Jython, etc. expose the full strength language
6
7 Motivations
8
9 * Run Python programs in "small" devices
10 * Small programs
11 * Few executed instructions
12
13 Python's flexibility comes at a cost
14
15 * Modules, classes, instances are all objects
16 * Freedom to modify most objects at any time
17 * Difficult to predict eventual behaviour before execution
18 * Difficult to generate optimisations when compiling
19
20 Attribute access
21
22 * Must do a full lookup every time:
23 * Check instance dictionary
24 * Check class, superclasses
25 * Potentially lots of code
26 * Lots of executed instructions
27
28 Other costly operations
29
30 * Keyword parameter resolution
31 * Binary operators
32 * Comparisons
33
34 Examples of rarely used/unnecessary flexibility
35
36 * Can subclass dynamically:
37
38 for cls in A, B:
39 class C(cls):
40 pass
41
42 * Yet most people would relate to "class C"
43 * Not "the class currently known as C"
44
45 Examples of occasionally used flexibility
46
47 * Can evaluate classes and functions in dynamic contexts:
48
49 if platform == 'posix':
50 class C:
51 ...
52 else:
53 class C:
54 ...
55
56 * Seen quite often in the standard library with functions
57 * Dynamism used for configuration purposes
58
59 Distinguish between "good" and "bad" dynamism
60
61 * Dynamic class preparation
62 * Run-time choice of classes
63 * Assigning attributes to modules
64
65 Run-time configuration
66
67 * The source of a lot of "bad" dynamism
68 * Comparable to, but more robust than...
69 * Class loading tricks in Java
70 * Dynamic library loading magic in C/C++
71 * Has a place, but perhaps not in compiled, embedded programs
72
73 Micropython modules
74
75 * Modules contain attributes as with normal Python
76 * Inside the module:
77 * Attributes can be accessed and set as globals
78 * Classes and functions define module attributes
79 * Outside the module:
80 * Attributes can be accessed but not set
81 * Definition from within means more predictable content
82
83 Micropython classes
84
85 * Classes contain attributes and expose superclass attributes
86 * Inside the class:
87 * Attributes can be accessed and set in the class scope
88 * Functions define methods
89 * Outside the class:
90 * Attributes can be accessed but not set
91 * Definition from within means more predictable content
92
93 Micropython instances
94
95 * Instances contain attributes and expose class attributes
96 * Instance attributes must not shadow class attributes
97 * The set of attributes is detected by scanning the __init__ method
98
99 Rationale for restrictions
100
101 * Construct efficient run-time representations
102 * Predictable content means that access can be optimised
103 * No shadowing means that only a single lookup is necessary