英文:
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.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论