使用functools.wraps来免费获取签名和类型提示?

huangapple go评论55阅读模式
英文:

Using functools.wraps to get signature and type hints for free?

问题

我最近发现自己在使用functools.wraps以便免费获取签名和参数类型提示。

例如,我有一个包含一些渲染功能的类,我通过functools.wraps来“借用”了builtins.open的签名,像这样:

import functools
from typing import Callable

class Cls:

    def render(self, call: Callable) -> None:
        ...

    @functools.wraps(open)
    def render_to_file(self, *args, mode="w", **kwargs) -> None:
        with open(*args, mode=mode, **kwargs) as f:
            self.render(f.write)

我是否忽略了一些潜在问题,还是可以继续像这样使用functools.wraps

英文:

I recently found myself using functools.wraps in order to get a signature and parameter type hints for free.

E.g. I have a class that features some rendering functionality and I 'borrow' the signature of builtins.open via functools.wraps like so:

import functools
from typing import Callable

class Cls:

    def render(self, call: Callable) -> None:
        ...

    @functools.wraps(open)
    def render_to_file(self, *args, mode="w", **kwargs) -> None:
        with open(*args, mode=mode, **kwargs) as f:
            self.render(f.write)

Has this some caveats I am missing or can I continue to use functools.wraps like this?

答案1

得分: 1

我不会说有任何其他注意事项,除了任何类型检查器都需要知道如何解析 @wraps(...) 而不仅仅是查看静态写出的类型注释。(如果你说你在那里免费获得提示,那么你的IDE显然知道如何做到这一点。)

英文:

I wouldn't say there are any other caveats than that any type checker you'll use needs to know how to resolve @wraps(...) instead of just looking at the statically written-out type annotations. (Your IDE evidently does, if you say you're getting the hints for free there.)

huangapple
  • 本文由 发表于 2023年7月13日 15:38:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76676986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定