Enthought traits.api traitlist()似乎支持item_validator
在某些应用中,我发现 inthought traits.api 支持Python中的静态变量类型。
我正在尝试使用 item_validator
关键字,但是使用item_validator
关键字引发了一个错误...我尝试了此问题...
from traits.api import HasTraits, HasRequiredTraits, TraitList, TraitError
from traits.api import Regex, Enum
def garage_item_validator(item):
"""Validate item adjectives and reject pink or floral items"""
try:
if isinstance(item, Tool):
if item.adjective!="pink" or item.adjective!="floral":
return item
else:
raise ValueError()
except ValueError():
raise TraitError(f"Cannot put {item} in the Garage()")
class Tool(HasRequiredTraits):
name = Regex(regex=r"[Ww]rench|[Ll]awnmower", required=True)
adjective = Enum(*["brown", "rusty", "pink", "floral"], required=True)
def __init__(self, name, adjective):
self.name = name
self.adjective = adjective
def __repr__(self):
return """<Tool: {}>""".format(self.name)
class Garage(HasTraits):
things = TraitList(Tool, item_validator=garage_item_validator) # <---- TraitList() doesn't work
def __init__(self):
self.things = list()
if __name__=="__main__":
my_garage = Garage()
my_garage.things.append(Tool("Lawnmower", "brown"))
my_garage.things.append(Tool("wrench", "pink"))
print(my_garage)
type> type> typeerror:__init_________init__ ()获得了一个意外的关键字参数'item_validator'
,尽管特征清单文档明确表示item_validator
受支持。
我还尝试使用 traits.api code> code> list list()
/a>,但它只是默默地忽略item_validator
关键字。
我应该用什么来验证特征列表的内容?
In some applications, I've found that Enthought Traits.api is a helpful addition to support static variable types in python.
I'm trying to use the TraitList()
item_validator
keyword, but using the item_validator
keyword threw an error... I tried this...
from traits.api import HasTraits, HasRequiredTraits, TraitList, TraitError
from traits.api import Regex, Enum
def garage_item_validator(item):
"""Validate item adjectives and reject pink or floral items"""
try:
if isinstance(item, Tool):
if item.adjective!="pink" or item.adjective!="floral":
return item
else:
raise ValueError()
except ValueError():
raise TraitError(f"Cannot put {item} in the Garage()")
class Tool(HasRequiredTraits):
name = Regex(regex=r"[Ww]rench|[Ll]awnmower", required=True)
adjective = Enum(*["brown", "rusty", "pink", "floral"], required=True)
def __init__(self, name, adjective):
self.name = name
self.adjective = adjective
def __repr__(self):
return """<Tool: {}>""".format(self.name)
class Garage(HasTraits):
things = TraitList(Tool, item_validator=garage_item_validator) # <---- TraitList() doesn't work
def __init__(self):
self.things = list()
if __name__=="__main__":
my_garage = Garage()
my_garage.things.append(Tool("Lawnmower", "brown"))
my_garage.things.append(Tool("wrench", "pink"))
print(my_garage)
This throws: TypeError: __init__() got an unexpected keyword argument 'item_validator'
although the TraitList docs clearly say item_validator
is supported.
I also tried to use a traits.api List()
, but it just silently ignores the item_validator
keyword.
What should I use to validate the contents of a traits list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
TraitList
不是Trait
,而是执行验证和触发事件的list
的子类。它由List
特征在内部使用:并且它获取由
List
特征设置的item_validator
:因此,尽管没有钩子可以更改此设置验证器,它确实使用来自 Trait 的验证器,用作
List
的trait
参数(在上面的示例中为Int
,因此列表只会保存整数项)。因此,您可以通过编写验证您想要的方式的自定义特征来实现您的目标。
在您的示例中,您希望这些项目是具有形容词某些属性的
Tool
实例,因此 Instance 特征是一个很好的起点:它会根据需要给出错误:
TraitList
isn't aTrait
, but rather a subclass oflist
that performs validation and fires events. It is used internally by theList
trait:and it gets its
item_validator
set by theList
trait:So although there is no hook to change this validator, it does use the validator from the Trait used as the
trait
argument theList
(Int
in the above example, so the list will only hold integer items).So you can achieve your goal by writing a custom trait that validates the way that you want.
In your example you want the items to be instances of
Tool
with certain properties for theadjective
, so an Instance trait is a good starting point:which gives an error as desired:
我在以前的尝试中犯了一个错误...
这是错误的...
工具
应该是tool()
...这是正确的...
此外,我发现我可以手动分配
self.things.item_validator
初始化garage()
这也正确运行...
I made a mistake in my previous attempts...
This is wrong...
Tool
should beTool()
...This is correct...
Additionally, I found that I can manually assign
self.things.item_validator
after initializing theGarage()
This also runs correctly...