How do I set temporary function calls in Python?

I have a read function in a module.

If I run this function at the same time, I need to timestamp it.

How to do it?

-1


source to share


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


#!/usr/bin/env python

import datetime

def timestampit(func):
    def decorate(*args, **kwargs):
        print datetime.datetime.now()
        return func(*args, **kwargs)
    return decorate

@timestampit
def hello():
    print 'hello'

hello()

# Output:
# $ python test.py 
# 2009-01-09 11:50:48.704584
# hello

      



+2


source


If you're interested, there is a wealth of information on decorators on the python wiki .

0


source


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







All Articles