Description
Coming out of #227 was a discussion on using constants to specify ports, pins, modes, etc for configuring GPIO and peripherals. For example:
GPIO_PinA4 = 4
GPIO_OutputMode = 0x40
p = pyb.Gpio(GPIO_PinA4, GPIO_OutputMode)
This is not very efficient because the first 2 lines store into the module namespace the 2 constants, taking up RAM. The above could be optimised by the compiler remembering the value of the constants and substituting the value whenever they are used. But this would break general Python semantics (since the globals can be written to elsewhere in the code), and not all global numbers are constants. To fix this one could wrap the number in a special function which declares it as a constant:
GPIO_PinA4 = constant(4)
GPIO_OutputMode = constant(0x40)
Okay, but what about sharing such definitions over multiple Python files? They would need to be put in a separate file (say pyb.py) and imported:
import pyb
p = pyb.Gpio(pyb.GPIO_PinA4, pyb.GPIO_OutputMode)
That can't be optimised because pyb may be assigned to something else during the course of execution. Thus we require something like:
import pyb.constant
and the compiler would recognise this as saying that pyb will not change and so it can lookup constants inside this import. But that requires the compiler having in RAM a very large hash table with all these constants.