Python Forum
Decorator for a function with argument(s)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Decorator for a function with argument(s)
#1
Hello everyone,

considering the code I've written here, please tell me:
1. Is this done correctly? (Although I get the correct output, someone told me for functions that take inputs, I need a wrapper within another wrapper!) Liar
2. How can I do it differently? (two wrappers?! two decorators?!)

import time


def elapsed_time(function):
    def wrapper(*args):
        t1 = time.time()
        function(*args)
        t2 = time.time()
        print(f'Elapsed time: {(t2 - t1) * 1000:.2f} ms')
    return wrapper


@elapsed_time
def sleep(seconds):  # a function that DOES take argument(s)
    time.sleep(seconds)


sleep(0.5)
Output:
Elapsed time: 514.42 ms
Special thanks to the contributors.
Reply
#2
It is correct. You could improve it a little
import functools
import time
 
def elapsed_time(function):
    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        t1 = time.time()
        rv = function(*args, **kwarg)
        t2 = time.time()
        print(f'Elapsed time: {(t2 - t1) * 1000:.2f} ms')
        return rv
    return wrapper
 
banidjamali likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  function-decorator , which is checking an access according to USERNAME Liki 6 549 Feb-17-2024, 03:36 AM
Last Post: deanhystad
  i got a decorator question yosef 3 2,568 Aug-25-2020, 04:14 PM
Last Post: DeaD_EyE
  Decorator is using in class,but not working mbilalshafiq 2 2,111 Jul-04-2020, 08:53 PM
Last Post: mbilalshafiq
  function vs argument millpond 2 2,142 Aug-26-2019, 05:48 AM
Last Post: ndc85430
  Decorator and namespace. JayIvhen 2 2,766 Oct-26-2018, 03:56 PM
Last Post: nilamo
  python decorator alfredocabrera 0 3,132 Feb-22-2017, 07:04 AM
Last Post: alfredocabrera

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020