I currently have a couple of classes following the pattern described in the code below:
from typing import NamedTuple
class Data(NamedTuple):
name: str,
value: float
def json(self):
return {'name': self.name, 'value': self.value}
Instead of defining a json
method in every new class that I create, I would like to extend typing.NamedTuple
, so that I can extend from my new class without having to define the json method in the subclasses. typing.NamedTuple
already provides the _asdict
method, but this method is not sufficient because it is not recursive (Nested namedtuples will not be converted to dict objects).
I have tried to attempt this in the code below:
class JsonNamedTuple(NamedTuple):
def json(self):
# some slightly complex recursive code here
class Data(JsonNamedTuple):
name: str,
value: float
a = Data('asdf', 0.5)
I get this error:
TypeError: <lambda>() takes 1 positional argument but 3 were given
Is there a way to extend typing.NamedTuple
without getting this error?