如何验证 namedtuple 值?
How to validate namedtuple values?
我有 namedtuple 变量,它代表应用程序的版本(它的编号和类型)。但我想要对值进行一些限制:
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
我现在的解决方案是原始的 class,没有任何方法:
class Version:
def __init__(self, app_type, number):
assert app_type in ('desktop', 'web')
self.app_type = app_type
self.number = number
是pythonic吗?是不是矫枉过正了?
您可以使用 enum.Enum
和 typing.NamedTuple
而不是 collections.namedtuple
:
也许是这样的:
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>)
一个未定义的AppType
引发了一个AttributeError
:
v2 = Version(app=AppType.deskpoop)
输出:
AttributeError: deskpoop
我有 namedtuple 变量,它代表应用程序的版本(它的编号和类型)。但我想要对值进行一些限制:
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
我现在的解决方案是原始的 class,没有任何方法:
class Version:
def __init__(self, app_type, number):
assert app_type in ('desktop', 'web')
self.app_type = app_type
self.number = number
是pythonic吗?是不是矫枉过正了?
您可以使用 enum.Enum
和 typing.NamedTuple
而不是 collections.namedtuple
:
也许是这样的:
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>)
一个未定义的AppType
引发了一个AttributeError
:
v2 = Version(app=AppType.deskpoop)
输出:
AttributeError: deskpoop