473,396 Members | 1,938 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Generators and Decorators doing my head in ..

Hi Can someone please help me understand this (i shouldn't have tried
to learn decorators and generators at the same time..).

Im trying to create a decorator that counts the number of times a
function is run. Somthing like:

def FunctionCounter():
n=0
while 1:
yield n
n=n+1

def logFunctionCalls(function):
print "Entering function:", function.__name__, ec.next()
return function

@logFunctionCalls
def doWork():
print "Doing Work"
doWork()

Where "ec" is a generator that is created inside logFunctionCalls if it
doesnt already exist.
Im thinking this has somthing to do with anonymous generators, but im
not sure how you create or access these..

Apologies in advance if this is moronic.

Sep 6 '05 #1
5 1031
Compare this to your original:

def logFunctionCalls(function):
ec = FunctionCounter()
def decoratedFunction(*args,**kwargs):
print "Entering function:", function.__name__, ec.next()
function(*args,**kwargs)
return decoratedFunction

@logFunctionCalls
def doWork():
print "Doing Work"

doWork()
doWork()

(This is a quick-and-dirty example, but it works. A proper iterator
would do more to preserve the identity, docstring, etc. of the
underlying doWork() function. See the decorator library page on the
Python Wiki, at http://wiki.python.org/moin/PythonDecoratorLibrary.)

Also, look into the treasure trove that is itertools, especially
itertools.count.

-- Paul

Sep 6 '05 #2
si*****@gmail.com wrote:
Im trying to create a decorator that counts the number of times a
function is run.


Your code doesn't work because decorators are run at function creation
time, not at function run time. Try this instead:
from itertools import count

def logFunctionCalls(function):
times = count()
def newfunction(*args, **kwargs):
print "Entering function:", function.__name__, times.next()
return function(*args, **kwargs)
newfunction.__doc__ = function.__doc__
newfunction.__name__ = function.__name__
return newfunction

@logFunctionCalls
def doWork():
print "Doing work..."
Sep 6 '05 #3
Paul McGuire wrote:
(snip)
(This is a quick-and-dirty example, but it works. A proper iterator


s/iterator/decorator/

(snip)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Sep 6 '05 #4
Fantastic, thanks Leif and Paul, My problem is that i thought the
decorator worked at the function runtime, not when the function gets
created.

Sep 6 '05 #5
I usually point out my decorator module
(http://www.phyast.pitt.edu/~micheles.../decorator.zip) to simplify
decorator usage. In this case you would use it as follows:

from decorator import decorator

@decorator # convert logFunctionCalls into a decorator
def logFunctionCalls(function, *args, **kwargs):
try: # increment the counter
function.counter += 1
except AttributeError: # first call, there is no counter attribute
function.counter = 1
print "Entering function:", function.__name__, function.counter
return function(*args, **kwargs)

@logFunctionCalls
def f():
pass

f()
f()
f()

help(f)

The whole point of the decorator module is that the signature of
the original function is left unchanged (i.e. in this case the
decorated f is still a thunk, not a generic function f(*args, **kw)).
HTH,

Michele Simionato

Sep 7 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: fishboy | last post by:
Howdy, I'm in middle of a personal project. Eventually it will download multipart binary attachments and look for missing parts on other servers. And so far I've got it to walk a newsgroup and...
0
by: fishboy | last post by:
Howdy, Sorry if this is a double post. First try seemed to go into hyperspace. I'm working on a personal project. It's going to be a multipart binary attachment downloader that will search...
4
by: Michael Sparks | last post by:
Anyway... At Europython Guido discussed with everyone the outstanding issue with decorators and there was a clear majority in favour of having them, which was good. From where I was sitting it...
12
by: Colin J. Williams | last post by:
Christopher T. King suggested that "we're trying to kill too many birds with one stone". ...
8
by: Timothy Fitz | last post by:
It seems to me that in python, generators are not truly coroutines. I do not understand why. What I see is that generators are used almost exclusively for generation of lists just-in-time. Side...
0
by: Anthony Baxter | last post by:
To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. PEP: 318 Title: Decorators for Functions and...
6
by: Talin | last post by:
I've been using generators to implement backtracking search for a while now. Unfortunately, my code is large and complex enough (doing unification on math expressions) that its hard to post a...
10
by: Jerry | last post by:
I have just started to do some semi-serious programming (not one-off specialized scripts) and am loving Python. I just seem to get most of the concepts, the structure, and the classes (something I...
0
by: Scott SA | last post by:
Hi, I've been trying to wrap my head around decorators and in my trails found avery recent article on Linux Mag's website. I didn't see a post here regarding this article and feel it is worth...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.