473,397 Members | 1,961 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,397 software developers and data experts.

Useful decorator

In the course of writing a bunch of generator-oriented code I kept
wanting to temporarily truncate the output of generators for debugging,
i.e. I might have a function like

def generate_bazillion_items():
for line in bazillion_line_file:
yield itemify(line)

where I wanted to test the program on just the first 20 lines of the
file. After a number of rounds of editing the program to wrap an
xrange(20) loop I went to using islice(bazillion_line_file, 20), but
even more handy was to write this decorator:

def truncate(n):
from itertools import islice
def trunc(gen): # truncate generator to n items
return lambda *a,**kw: islice(gen(*a,**kw), n)
return trunc

Then to chop bazillion_items to 20 items, I just write:

@truncate(20)
def generate_bazillion_items():
for line in bazillion_line_file:
yield itemify(line)

When I want to run the whole file, I comment out the @truncate line,
and if I want to debug again, I just uncomment it.
Apr 14 '07 #1
4 1104
Paul Rubin wrote:
In the course of writing a bunch of generator-oriented code I kept
wanting to temporarily truncate the output of generators for debugging,
i.e. I might have a function like

def generate_bazillion_items():
for line in bazillion_line_file:
yield itemify(line)

where I wanted to test the program on just the first 20 lines of the
file. After a number of rounds of editing the program to wrap an
xrange(20) loop I went to using islice(bazillion_line_file, 20), but
even more handy was to write this decorator:

def truncate(n):
from itertools import islice
def trunc(gen): # truncate generator to n items
return lambda *a,**kw: islice(gen(*a,**kw), n)
return trunc

Then to chop bazillion_items to 20 items, I just write:

@truncate(20)
def generate_bazillion_items():
for line in bazillion_line_file:
yield itemify(line)

When I want to run the whole file, I comment out the @truncate line,
and if I want to debug again, I just uncomment it.
Thes may be overkill, but how about allowing None as a parameter to
truncate, to allow for programmatic truncation?

# top of module
if DEBUG:
FILETRUNC = 20
else:
FILETRUNC = None

# imported, etc.
def truncate(n):
if n is None:
return lambda gen: gen
from itertools import islice
def trunc(gen): # truncate generator to n items
return lambda *a,**kw: islice(gen(*a,**kw), n)
return trunc

# in the body somewhere
@truncate(FILETRUNC)
def generate_bazillion_items():
# etc.

James
Apr 14 '07 #2
On Apr 14, 5:03 pm, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
In the course of writing a bunch of generator-oriented code I kept
wanting to temporarily truncate the output of generators for debugging,
i.e. I might have a function like

def generate_bazillion_items():
for line in bazillion_line_file:
yield itemify(line)

where I wanted to test the program on just the first 20 lines of the
file. After a number of rounds of editing the program to wrap an
xrange(20) loop I went to using islice(bazillion_line_file, 20), but
even more handy was to write this decorator:

def truncate(n):
from itertools import islice
def trunc(gen): # truncate generator to n items
return lambda *a,**kw: islice(gen(*a,**kw), n)
return trunc

Then to chop bazillion_items to 20 items, I just write:

@truncate(20)
def generate_bazillion_items():
for line in bazillion_line_file:
yield itemify(line)

When I want to run the whole file, I comment out the @truncate line,
and if I want to debug again, I just uncomment it.
You should add this to the Python Wiki at http://wiki.python.org/moin/PythonDecoratorLibrary

-- Paul

Apr 14 '07 #3
On Sat, 14 Apr 2007 15:03:00 -0700, Paul Rubin wrote:
Then to chop bazillion_items to 20 items, I just write:

@truncate(20)
def generate_bazillion_items():
for line in bazillion_line_file:
yield itemify(line)

When I want to run the whole file, I comment out the @truncate line,
and if I want to debug again, I just uncomment it.

By All-Father Wodan's one good eye! Why not do something like this?

if __debug__:
generate_bazillion_items = truncate(20)(generate_bazillion_items)

Now you don't have to comment/uncomment dozens of lines all over your
application, but only set a single global.

--
Steven.

Apr 15 '07 #4
Steven D'Aprano <st***@REMOVE.THIS.cybersource.com.auwrites:
if __debug__:
generate_bazillion_items = truncate(20)(generate_bazillion_items)

Now you don't have to comment/uncomment dozens of lines all over your
application, but only set a single global.
The cool thing about organizing the program as a generator pipeline is
you only have to comment or uncomment one line ;).
Apr 15 '07 #5

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

Similar topics

41
by: John Marshall | last post by:
How about the following, which I am almost positive has not been suggested: ----- class Klass: def __init__(self, name): self.name = name deco meth0: staticmethod def meth0(x):
17
by: Jim Jewett | last post by:
Guido has said that he is open to considering *one* alternative decorator syntax. At the moment, (Phillip Eby's suggestion) J4 <URL: http://www.python.org/moin/PythonDecorators > (section 5.21...
3
by: Diez B. Roggisch | last post by:
Hi, I just wrote my first decorator example - and I already love them. However I've encountered one peculiarity that strikes me odd: When one writes a decorated function like this: ...
30
by: Ron_Adam | last post by:
I was having some difficulty figuring out just what was going on with decorators. So after a considerable amount of experimenting I was able to take one apart in a way. It required me to take a...
22
by: Ron_Adam | last post by:
Hi, Thanks again for all the helping me understand the details of decorators. I put together a class to create decorators that could make them a lot easier to use. It still has a few glitches...
3
by: Ron_Adam | last post by:
Ok... it's works! :) So what do you think? Look at the last stacked example, it process the preprocess's first in forward order, then does the postprocess's in reverse order. Which might be...
6
by: Michele Simionato | last post by:
could ildg wrote: > I think decorator is a function which return a function, is this right? > e.g. The decorator below if from http://www.python.org/peps/pep-0318.html#id1. > > def...
5
by: Doug | last post by:
I am looking at using the decorator pattern to create a rudimentary stored proc generator but am unsure about something. For each class that identifies a part of the stored proc, what if I want to...
4
by: thomas.karolski | last post by:
Hi, I would like to create a Decorator metaclass, which automatically turns a class which inherits from the "Decorator" type into a decorator. A decorator in this case, is simply a class which...
8
by: Chris Forone | last post by:
hello group, is there a possibility to implement the decorator-pattern without new/delete (nor smartpt)? if not, how to ensure correct deletion of the objects? thanks & hand, chris
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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:
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.