user3124181
user3124181

Reputation: 863

Can I enforce lambda in the arguments of a function in python?

I have a simple timing function like this:

    def time_it(fn):
        start_time = datetime.now()
        fn()
        time_elapsed = datetime.now() - start_time
        return time_elapsed

Which can be used like this:

    time_it(lambda: time.sleep(5))

Problem is my team is likely to use the function without lambda which will not work at runtime, but the IDE won't complain about usage and even worse they won't find out it fails for hours after they deploy. (don't ask)

What I want to know is, is there a way such as using python typing to require lambda be used in the function so that when they're writing in Pycharm, for example, they will be alerted that they're misusing the function time_it and that they need to preface it with lambda?

I know I could write the function differently in that I could just pass the function, args & kwargs separately then this wouldn't be an issue, but I want to write this in a way that will be simplified for them.

Upvotes: 1

Views: 77

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45826

Yes, Python has type hints for this; although they rely entirely on the environment you're writing in to enforce.

In your case here, you'd use something like:

from typing import Callable

def time_it(fn: Callable[[], None]):
    . . .

Callable[[], None] indicates a function that takes no arguments and returns nothing. You can change this as required.

Upvotes: 2

Related Questions