在 YARD 中使用多种方法记录鸭子类型
YARD 允许我指定方法参数和返回值的类型。因为我真的很喜欢鸭子类型,所以很高兴看到 YARD 还支持通过指定类型必须支持的方法来定义类型。
正如您在此处所看到的,表达式如下
#first_method, #second_methodare interpreted as a logical disjunctions. This means an object needs to support #first_method or #second_method or both. This is not what I need.
我希望能够指定一个对象需要支持我的参数的#first_method 和#second_method。有没有办法指定这一点?
YARD allows me to specify types for method parameters and return values. As I really like to duck type it is nice to see that YARD also supports defining types by specifying methods they must support.
As you can see here, expressions like
#first_method, #second_method
are interpreted as a logical disjunctions. This means an object needs to support #first_method or #second_method or both. This is not what I need.
I would like to be able to specify that an object is required to support both #first_method and #second_method for my parameter. Is there a way to specify this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有用于指定复合鸭子类型接口的惯用语法。也就是说,请注意,所有类型规范实际上只是自由格式文本;问题中给出的 YARD 类型解析器链接只是一组用于指定通用接口的常规或惯用语法。如果您想到一种聪明的方法来指定这些类型(并且对您的用户有意义),您可以随意这样做。也许诸如
#first#second
之类的东西可能会起作用,或者#first&#second
。然而,我的建议是创建一个具体的类型来包装这个临时接口。即使您实际上没有在运行时使用该类型,它也会作为域中的对象向用户解释接口。例如,通过使用
#first
和#second
两个方法创建class Foo
,然后记录这两个方法,您现在可以使用Foo
作为您的类型。您可以在 Foo 类文档中解释它从未在代码中实际使用,而只是作为“接口”存在(如果是这样的话)。您还可以将 Foo 设为“模块”,以表示它更多的是“接口”(或“协议”,如果您更喜欢该语言)而不是具体类型。There is no idiomatic syntax for specifying a compound duck-type interface. That said, note that all type specifications are really just free-form text; the YARD types parser link given in the question is simply a set of conventional or idiomatic syntaxes for specifying common interfaces. If you think of a smart way to specify these types (and it makes sense to your users), you are free to do so. Perhaps something like
#first#second
might work, or#first&#second
.My recommendation, however, would be to create a concrete type to wrap this ad-hoc interface. Even if you don't actually use the type in your runtime, it would serve as object in your domain to explain the interface to your users. For example, by creating a
class Foo
with the two methods#first
and#second
, and then documenting those two methods, you could now useFoo
as your type. You could explain in the Foo class documentation that it is never actually used in code and just exists as an "interface", if that's the case. You could also make Foo a "module" to denote that it is more of an "interface" (or "protocol", if you prefer that language) than a concrete type.