How do I set temporary function calls in Python?
4 answers
I suggest a slightly different approach:
import time
def timestampit(func):
def decorate(*args, **kwargs):
decorate.timestamp = time.time()
return func(*args, **kwargs)
return decorate
@timestampit
def hello():
print 'hello'
hello()
print hello.timestamp
time.sleep(1)
hello()
print hello.timestamp
Differences from Swaroop example:
- I am using time.time () and not datetime.now () for the timestamp because it is more suitable for performance testing.
- I am attaching the timestamp as an attribute of the decorated function. This way you can reference and store it whenever you want.
+6
source to share
If you're interested, there is a wealth of information on decorators on the python wiki .
0
source to share
In some example, the code of Terik Ziad
(a more polished version using the timeit module can be found in his recent book Expert Python Programming)
0
source to share