I would disagree with the accepted answer above, since the validation is actually not done in the NamedTuple class itself, but in external class with extra call, and so it is still possible to do invalid initialisation of Version instance with default constructor:
from typing import NamedTuple
import enum
class AppType(enum.Enum):
desktop = 0
web = 1
class Version(NamedTuple):
app: AppType
>>> v=Version(42)
>>> print(v)
Version(app=42)
>>> v2=Version('whatever you want')
>>> print(v2)
Version(app='whatever you want')
I haven't found a way to overload or at least to disable the default NamedTuple constructor, to prevent invalid initialisation((
The workaround I'm using - creating an alternative constructor(s), which implement validation. but again nothing prevents 'user' to create invalid object using default NamedTuple constructor:
class Version2(NamedTuple):
app_type : str
@classmethod
def new(cls, app_value: str):
assert app_value in ('desktop', 'web')
return cls(app_value)
>>> Version2.new('web')
Version2(app_type='web')
>>> Version2.new('tablet')
Traceback (most recent call last):
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<input>", line 6, in new
AssertionError
>>> Version2('whatever you want')
Version2(app_type='whatever you want')