I had namedtuple variable which represents version of application (its number and type). But i want and some restriction to values:
Version = namedtuple("Version", ["app_type", "number"])
version = Version("desktop") # i want only "desktop" and "web" are valid app types
version = Version("deskpop") # i want to protect from such mistakes
My solution for now is primitive class with no methods:
class Version:
def __init__(self, app_type, number):
assert app_type in ('desktop', 'web')
self.app_type = app_type
self.number = number
Is it pythonic? Is it overkill?
From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.
@Antimony: pickle handles namedtuple classes just fine; classes defined in a function local namespace not so much.
Tuples are immutable, whether named or not. namedtuple only makes the access more convenient, by using names instead of indices. You can only use valid identifiers for namedtuple , it doesn't perform any hashing — it generates a new type instead.
Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field.
You could use enum.Enum
, and typing.NamedTuple
instead of collections.namedtuple
:
Maybe something like this:
from typing import NamedTuple
import enum
class AppType(enum.Enum):
desktop = 0
web = 1
class Version(NamedTuple):
app: AppType
v0 = Version(app=AppType.desktop)
v1 = Version(app=AppType.web)
print(v0, v1)
Version(app=<AppType.desktop: 0>) Version(app=<AppType.web: 1>)
A undefined AppType
raises an AttributeError
:
v2 = Version(app=AppType.deskpoop)
AttributeError: deskpoop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With