1

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.

2
  • 2
    Look at Callable type hinting. docs.python.org/3/library/typing.html#callable Commented Oct 1, 2020 at 19:20
  • If your team forgets to use the lambda, the above code will fail. Your code will sleep for five seconds, but then will call time_it(None), which will call None() which will throw an exception. I'm not sure if that's any consolation or not. Commented Oct 1, 2020 at 19:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That does indeed work. Thanks. Follow up question though, the IDE complains about the misuse but doesn't actually consider it a bug. Is there a way to essentially declare it a bug unless they actually give a callable argument?
@user3124181 In the settings of Pycharm, you can change type warnings to be treated as actual errors. I don't think it gives very fine control though, so all type warnings will be errors. There is no such option for Python interpreters though afaik.
@user3124181 Actually no, that apparently doesn't prevent execution (I thought I had tested that previously). I don't know of a way to enforce it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.