[libre-riscv-dev] static typing in python
Luke Kenneth Casson Leighton
lkcl at lkcl.net
Tue Mar 12 04:13:36 GMT 2019
On Tue, Mar 12, 2019 at 3:41 AM Jacob Lifshay <programmerjake at gmail.com> wrote:
>
> apparently python 3 supports static typing:
> https://www.python.org/dev/peps/pep-0484/
well it's about damn time!
> I think we should use it in the code we write using nmigen as it should
> help catch errors.
funnily enough, i don't believe that it will be a significant
difference. at least not the style of code i'm writing. parameters
are passed in such as "bitwidth" and "size of array", it's pretty
immediately obvious, if you pass in a string instead of an int, for i
in range("hello") will go badly.
[unit tests - which should be run immediately on saving of the (very
small, incremental) modifications as part of a day-to-day side-by-side
synergistic development practice where the code *and* the unit test
are always, *always* developed *together* - will pick up errors].
the reason is that the majority of code written uses nmigen, and it's
nmigen that is not using static typing. however if nmigen *itself*
were to have static typing added, that would be very useful.
also, it doesn't really help when passing in e.g. a Signal into a
function, to declare its type as "Signal", because it's going into an
object for assignment (or other purposes) where it's nmigen that will
do the checking at runtime.
if however there was a class Signal32 which was *derived* from Signal
and made its width fixed to 32-bit, *now* we have something useful.
like this:
class Signal32(Signal):
def __init__(self):
Signal.__init__(self, 32)
that's a useful class to use as a static typecheck. Signal itself is
not. it's just going to be... a bit weird to create classes named
Signal1, Signal2, Signal3, Signal4.... Signal66 and Signal1Unsigned,
Signal2Unsigned..... Signal78Unsigned.
doing that should however catch errors where an assignment is made
between two different-sized bitwidths.
however i cannot emphasise or stress enough just how absolutely
essential it is when writing python to make writing unit tests *at the
same time as the code* a routine and normal part of the development:
not just the debugging process. using static typing is not going to
be a substitute for that, it's an augmentation.
l.
More information about the libre-riscv-dev
mailing list