notalentgeek
notalentgeek

Reputation: 5779

How can I know what kind value will a function returns without executing the function itself?

This is my decorator. I want any function that has this decorator to be checked if _kwargs["_dir_abs"] is an absolute path or not. If not I want to fault the _function by returning False if the decorated _function returns bool. And returning None if the _function returns anything other than bool.

The thing is _function is a folder operation (deleting, moving, naming, ...) hence I cannot just try it to see what it returns.

def check_abs_dec(_function):
    def wrapper(*_args, **_kwargs):
        if not check_abs(_kwargs["_dir_abs"]):
            napw()
            """`return False` if the `_function` return `bool`. `return None`
            if the `_function` return anything other than `bool`.
            """

        return _function(*_args, **_kwargs)
    return wrapper

Is there anyway I can check what value _function will be returned without actually executing it? Is there any workaround?

Upvotes: 0

Views: 52

Answers (2)

Franz Wexler
Franz Wexler

Reputation: 1252

You can try annotating your function with return type.

def do_not_call() -> bool:  # Note the `-> bool` part
    raise Exception("Do not call, may have side effects")

Now you can get return type using __annotations__ attribute.

print(do_not_call.__annotations__['return'] == bool)  # True
print(do_not_call.__annotations__['return'] == int)  # False

def mysterious():  # Return type is not annotated...
    raise Exception("Do not call this either")
print(mysterious.__annotations__['return'])  # ...so this raises KeyError

This does however require you to annotate return type of all functions which return type you want to check.

To be honest, I also don't know when it was added to Python, but it works for me with Python 3.5.

If you are hardcore programmer who has plenty of time, I think you can use ast module to check bytecode of function for return statements and guess types. I don't recommend it though.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599590

No, you cannot do this by definition. This is how dynamic languages work; you cannot know what type will be returned until you execute the function.

Upvotes: 1

Related Questions