【问题标题】:How can I type a function argument as native function如何将函数参数键入为本机函数
【发布时间】:2018-09-05 01:28:55
【问题描述】:

我在 python repl 中使用了一个辅助函数来将变量移动到全局以便于调试。但是有一个mypy错误:

class stepin(object):  # pylint: disable=R0903
    def __init__(self, func: Callable) -> None:
        self.func = func
        self.args = func.__code__.co_varnames
        if hasattr(func, "__defaults__") and func.__defaults__:
            self.defaults = dict(zip(reversed(self.args), reversed(func.__defaults__)))
        else:
            self.defaults = None

    def __call__(self, *args, **kwargs):
        result_dict = {x: None for x in self.args}
        if self.defaults:
            result_dict.update(self.defaults)
        result_dict.update(dict(zip(self.args, args)))
        result_dict.update(kwargs)
        for x in result_dict.keys():
            if result_dict[x] is None:
                raise ValueError('Missing args: ', self.func.__qualname__, x)
        globals().update(result_dict)

现在,一行

if hasattr(func, "__defaults__") and func.__defaults__:
    self.defaults = dict(zip(reversed(self.args), reversed(func.__defaults__)))

引发一个 mypy 错误,指出 func 没有 __defaults__ 现在我知道 BDFL 说他鄙视“hasattr”检查,所以它可能不会在 mypy 中解决;那么我的问题是,有没有办法更改 __init__ 键入签名以消除错误?

我尝试了什么:Callable 不起作用,可以理解:并非所有 Callables 都有 __defaults__。 但是类型“函数”在哪里?如果我键入()一个函数,它说“函数”,但“函数”不在序言或“打字”中。我看到有些人提到“FunctionType”,但也没有在“打字”中。

【问题讨论】:

    标签: python-3.6 type-hinting mypy type-annotation


    【解决方案1】:

    函数的类型是types.FunctionType(在types 模块中)。

    如果您将func 的注解从Callable 修改为types.FunctionType,mypy 将不再抱怨__defaults__

    【讨论】:

      猜你喜欢
      • 2019-10-07
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 2021-07-10
      相关资源
      最近更新 更多