I am new to python (3.6.2 is the version I am using).
I am currently porting (trying to port) a DSL implementation from Scala to python for some projet in which python is imposed.
So I am looking for a way to efficiently write immutable class hierarchies to represent ADTs in a way that supports type-checking with mypy.
I first came across macropy which replicates scala case classes and pattern matching in python but is only python 2.7.x compatible (and would not work with mypy anyway).
I did some more research and came by typing.NamedTuple and abc.ABC. So now I am trying to find a way to combine the benefits of typing.NamedTuple with abc.ABC to be able to add mixins to namedtuples.
I would like to be able to write this sort of code:
from typing import *
from abc import ABC, abstractmethod
class M(ABC):
@abstractmethod
def m1(self, it: Iterable[str]) -> str:
pass
class NT(NamedTuple):
attr1: str
attr2: Union[bool, float]
class C1(NT,M):
def m(self, it: Iterable[str]) -> str:
return attr1.join(it)
class C2(NT,M):
pass
c1 = C1('foo',12)
c1.m([str(i) for in in range(10)]) # would work
c2 = C2('bar',12.0)
c2.m([str(i) for in in range(10)]) # would fail because abstractmethod not implemented
The code above runs typechecks with mypy but fails to fail on the C2.m call (the method call just returns None).
So I searched further and came by this recipe for collections.namedtuple + Mix-In : abc.namedtuple
I tried to adapt the recipe from collections.namedtuple to typing.NamedTuple but cannot wrap my head around the fairly complex and fragile python machinery involved in the recipe. Is there any obvious way to make this work ?