473,326 Members | 2,136 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,326 software developers and data experts.

Singleton generators as code blocks

Hey all,

I was just reflecting upon the old code block debate, and the thought
occurred to me that Python really does have a form of code blocks in its
implementation of generators. It was a pretty natural conclusion, and I'm
not sure why I didn't think of it before. For instance, compare Python's
generator-style iteration versus Ruby's codeblock-style iteration:

Python:
for item in seq:
print item

Ruby:
seq.each { |item|
puts item
}

Now, aside from the difference in mechanics, these two methods basically
accomplish the same thing. "seq" could be a regular list, or it could be a
lazy sequence. The syntax remains the same.

One of the simplest arguments in favor of codeblocks (or macros, but I'm not
going to go there <grin>) was the ability to write a function like
"with_open_file" that would open a file, perform some action on the file,
and then close the file automatically. I'm going to use this as an example
because of its simplicity, not because I think that there is an overwhelming
need for such a function.

In Python, I was able to implement a generator version quite simply. It
seemed so obvious that I thought maybe there was a thread in the past where
this was already mentioned; if so, forgive me for stating the obvious:

def open_file(filename, mode='r'):
f = file(filename, mode)
yield f
print 'closing...'
f.close()

for f in open_file('input.txt'):
print f.read()

The above code prints the conntents of the file "input.txt", then the string
"closing...", and then closes the file.

This seems to illustrate that generators and codeblock-accepting functions
are really very similar, and that maybe codeblocks wouldn't really add much
of anything to Python after all. I still have to wonder if maybe I'm missing
something here...

Has anyone used this sort of "singleton generator" technique?

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #1
3 1890
On Sat, Nov 22, 2003 at 12:12:10AM -0000, Dave Benjamin wrote:
Hey all,

[snip]

In Python, I was able to implement a generator version quite simply. It
seemed so obvious that I thought maybe there was a thread in the past where
this was already mentioned; if so, forgive me for stating the obvious:

def open_file(filename, mode='r'):
f = file(filename, mode)
yield f
print 'closing...'
f.close()

for f in open_file('input.txt'):
print f.read()

The above code prints the conntents of the file "input.txt", then the string
"closing...", and then closes the file.

This seems to illustrate that generators and codeblock-accepting functions
are really very similar, and that maybe codeblocks wouldn't really add much
of anything to Python after all. I still have to wonder if maybe I'm missing
something here...

Has anyone used this sort of "singleton generator" technique?


This is a pretty nifty approach, but it seems to have (at least?) one serious
drawback. If the body of the loop raises an exception, the generator is
never resume, and the cleanup (or whatever) is never run.

A way to reformulate the above without losing its conciseness eludes me
currently.

Jp

Jul 18 '05 #2
In article <ma************************************@python.org >, Jp Calderone wrote:
Has anyone used this sort of "singleton generator" technique?
This is a pretty nifty approach, but it seems to have (at least?) one serious
drawback. If the body of the loop raises an exception, the generator is
never resume, and the cleanup (or whatever) is never run.


Yeah, that is indeed a problem. That was in the back of my mind when I wrote
that disclaimer (that it's just an example), but you summed it up very well.
A way to reformulate the above without losing its conciseness eludes me
currently.


Me too. The obvious solution would be to wrap the body in a try/finally, but
then, I guess we're right back where we started. ;)

Thanks for the feedback.

--
..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
Jul 18 '05 #3
Jp Calderone wrote:
This is a pretty nifty approach, but it seems to have (at least?) one serious
drawback. If the body of the loop raises an exception, the generator is
never resume, and the cleanup (or whatever) is never run.


If open_file were implemented as a class rather than a
generator, maybe the cleanup could be implemented with its
__del__ method.

Or maybe the iterator protocol should include a __cleanup__
or __finally__ method that the for-loop invokes before leaving
via a break or exception?

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg

Jul 18 '05 #4

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

Similar topics

23
by: Francis Avila | last post by:
Below is an implementation a 'flattening' recursive generator (take a nested iterator and remove all its nesting). Is this possibly general and useful enough to be included in itertools? (I know...
9
by: Francis Avila | last post by:
A little annoyed one day that I couldn't use the statefulness of generators as "resumable functions", I came across Hettinger's PEP 288 (http://www.python.org/peps/pep-0288.html, still listed as...
3
by: Michael Sparks | last post by:
Hi, I'm posting a link to this since I hope it's of interest to people here :) I've written up the talk I gave at ACCU Python UK on the Kamaelia Framework, and it's been published as a BBC...
9
by: Sudesh Sawant | last post by:
Hello, We have an application which communicates using remoting. There is a server which is a Windows Service. The server exposes an object which is a singleton. The client is a Web Application...
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...
4
by: Sergei Shelukhin | last post by:
Suppose I want to supply a singleton class object that will sit between my intranet asp.net app and MS SQL database, doing al the chemistry with connections etc inside of it. The problem is that...
8
by: Ronald S. Cook | last post by:
On a new project, my management thought it would be a good idea to utilize a 3rd party tool to generate the database, and middle-tier classes. We chose DeKlarit and I went to work. While...
3
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That...
0
by: Dustin J. Mitchell | last post by:
This question was first brought up in October of 2005, and was included in the "Unresolved Issues" section of my microthreading PEP, which I have quietly withdrawn from consideration due to lack of...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.