Skip to content

How to use return type changed in decorator? #143

@MisLink

Description

@MisLink

I have a function like this:

@change_return_annotation(str)
def my_function(x: int, y: int) -> int:
    return x + y

The decorator change the return annotation:

def change_return_annotation(new_return_annotation):
    def decorator(func):
        func.__annotations__['return'] = new_return_annotation
        @functools.wrap(func)
        def wrapper(*args, **kwargs):
            return str(func((args, **kwargs))
        return func
    return decorator

I'd like to show the changed return type in mkdocs. It seems that I need to use InspectorExtension to let griffe import the code. Then I try to create one:

class Inspect(InspectorExtension):
    def inspect_function(self, node: ObjectNode) -> None:
        function: Function = self.inspector.current.members[node.name]  # type: ignore
        for decorator in function.decorators:
            ret = node.obj.__annotations__["return"]
            # not work
            # function.returns = ret


class HybridExtension(hybrid.HybridExtension):
    def __init__(self) -> None:
        super().__init__([Inspect()])


Extension = HybridExtension

Here I'm stuck. How to get an AST node for ret, or do I totally do the wrong thing?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions