繁体   English   中英

Mypy - 使用可选的 arguments 为 function 创建一个包装器

[英]Mypy - creating a wrapper for function with optional arguments

使用 Mypy,除了调用所有变体并省略每个可选参数之外,还有一种实用的方法如何为带有可选 arguments 的 function 编写包装器?

这是一个示例,我需要在两个变体中调用该方法 - 使用和不使用stopindex参数:

def index_noex(sequence: typing.Sequence, item: typing.Any,
                startindex: int = 0, stopindex: typing.Optional[int] = None
                ) -> int:
    try:
        if stopindex is None:
            index = sequence.index(item, startindex)
        else:
            index = sequence.index(item, startindex, stopindex)
    except ValueError:
        index = -1
    return index

Sequence类型需要 int 作为开始和停止索引的原因是某些序列(如listtuple )的index实现明确禁止将开始或结束索引传递为None

鉴于缺少起始索引的语义是搜索从 0 开始,您可以在调用它时指定它,就像您现在正在做的那样。

缺少结束索引意味着搜索将到达序列的末尾。 并且鉴于搜索将查找stopindex之前的所有元素,您需要将序列的长度作为默认值传递。

因此,以下代码将起作用:

import typing
def index_noex(sequence: Sequence, item: Any,
               startindex: int = 0, stopindex: Optional[int] = None) -> int:
    try:
        if stopindex is None:
            stopindex = len(sequence)
        index = sequence.index(item, startindex, stopindex)
    except ValueError:
        index = -1
    return index

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM