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

86 Views Asked by At

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

There are 1 best solutions below

1
AKX On

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.)