472,992 Members | 3,271 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Closures / Blocks in Python

Does anyone know a way to use closures or blocks in python like those
used in Ruby? Particularly those used in the { } braces.

Jul 24 '07 #1
10 1255
On Tue, 2007-07-24 at 14:58 +0000, treble54 wrote:
Does anyone know a way to use closures or blocks in python like those
used in Ruby? Particularly those used in the { } braces.
Please describe the problem you're trying to solve. Even if Python had a
direct equivalent of "Ruby closures or blocks", which I don't think it
does, it may not be the best solution to your problem.

--
Carsten Haese
http://informixdb.sourceforge.net
Jul 24 '07 #2
On 2007-07-24, treble54 <tr******@gmail.comwrote:
Does anyone know a way to use closures or blocks in python like
those used in Ruby? Particularly those used in the { } braces.
Python's nameless functions are week. So it supports iterators
and generators using protocols, comprehensions and a few simple
statements, rather than promoting the use of nameless functions.

Ruby's

some_list.each do |item|
puts item
end

if I understood it correctly, In Python would be:

for item in some_list:
print item

That works for any object that supports the iterator protocol.

--
Neil Cerutti
Jul 24 '07 #3
On Jul 24, 8:58 am, treble54 <trebl...@gmail.comwrote:
Does anyone know a way to use closures or blocks in python like those
used in Ruby? Particularly those used in the { } braces.
Python isn't Ruby. Python has a lambda function for creating
anonymous functions, but many of the common use cases expired with the
introduction of iterators and comprehensions. Python's functions are
first class objects, and can be passed around, bound to names, and
used like any other object. (I don't know whether Ruby's functions
are first class objects.) Python's function objects are callable, but
so are classes (calling them creates a class instance) and some
instances (those that define the __call__ special method).

If you can't find a way of doing what you want with iterators,
comprehensions, or lambda, consider writing a little function. Heck,
you can even nest functions in Python or pass a function as a
parameter.

For example, removing all names that start with a 'J' from a list of
names:
newListOfNames = [ name for name in nameList if not
name.startswith('J') ] # List comprehension
newListOfNames = filter(lambda name: not name.startswith('J'),
nameList) # Filter with lambda

# Explicit for-loop
newListOfNames = []
for name in nameList:
if not name.startswith('J'): newListOfNames.append(name)
Take a look at "http://ivan.truemesh.com/archives/000392.html" for a
comparison between some simple Ruby code and Python. Hope this helps.

--Jason

Jul 24 '07 #4
treble54 a écrit :
Does anyone know a way to use closures or blocks in python like those
used in Ruby? Particularly those used in the { } braces.
Instead of looking for what you think is the solution, you'd be better
explaining your concrete problem.
Jul 24 '07 #5
In article <11**********************@n60g2000hse.googlegroups .com>,
Jason <te***********@gmail.comwrote:
Jul 25 '07 #6
You can create a lexical closure using a Python generator function,
which allows iteration using a block of code while maintaining
internal state. A generator is a regular function which uses yield
(like Ruby) to define the point at which the function should return an
expression to the calling code. For example:

# Generic counter
def counter(min=None, max):
if not min:
min = 0
for i in xrange(min, max):
yield i
i = i + 1

When called, this function will yield the value of i and remember its
state. The next time it's called, it will increment i, then continue
on another iteration of the loop, yielding the new value of i.

For example:

my_counter = counter(0, 10)
my_counter() # <-- 0
my_counter() # <-- 1
for i in my_counter():
print i
# Prints 2-10 (the remaining numbers in xrange(min, max))

Jul 25 '07 #7
Jeff wrote:
# Generic counter
def counter(min=None, max):
if not min:
min = 0
for i in xrange(min, max):
yield i
i = i + 1
Just for the record:
>># Generic counter
.... def counter(min=None, max):
.... if not min:
.... min = 0
.... for i in xrange(min, max):
.... yield i
.... i = i + 1
....
File "<stdin>", line 2
SyntaxError: non-default argument follows default argument
You'd have to add a little more parameter-checking for this to work like
you intend.
/W
Jul 25 '07 #8
True, and I should have known better than to not have thoroughly
tested code I post to Usenet :). That being said, it was intended as
a fast example of how a generator operates for someone coming from
Ruby.

Jul 25 '07 #9
On Jul 24, 7:58 am, treble54 <trebl...@gmail.comwrote:
Does anyone know a way to use closures or blocks in python like those
used in Ruby? Particularly those used in the { } braces.
Inner functions allow you to define closures and (named) blocks
anywhere). Anonymous blocks must consist of a single expression.

-Mike

Jul 25 '07 #10
En Wed, 25 Jul 2007 11:45:00 -0300, Jeff <je******@gmail.comescribió:
You can create a lexical closure using a Python generator function,
which allows iteration using a block of code while maintaining
internal state. A generator is a regular function which uses yield
(like Ruby) to define the point at which the function should return an
expression to the calling code. For example:

# Generic counter
def counter(min=None, max):
if not min:
min = 0
for i in xrange(min, max):
yield i
i = i + 1

When called, this function will yield the value of i and remember its
state. The next time it's called, it will increment i, then continue
on another iteration of the loop, yielding the new value of i.

For example:

my_counter = counter(0, 10)
my_counter() # <-- 0
my_counter() # <-- 1
for i in my_counter():
print i
# Prints 2-10 (the remaining numbers in xrange(min, max))
Uhmm, I think this won't win the Best Python Code Of The Week Award :)
Apart from the already noted syntax error in the function definition, the
`i = i + 1` is useless because `i` gets reassigned right on the next loop.
And you don't "call" a generator, you have to iterate over it;
my_counter() will raise an error. This would be the right way:

my_counter = counter(0, 10)
my_counter.next() <-- 0
my_counter.next() <-- 1
for value in my_counter:
print value <-- 2 to 9

--
Gabriel Genellina

Jul 26 '07 #11

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

Similar topics

5
by: paolo veronelli | last post by:
I've a vague idea of the differences,I don't know scheme anyway. I'd like to see an example to show what is missing in python about closures and possibly understand if ruby is better in this...
2
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is...
4
by: king kikapu | last post by:
Hi, i am trying, to no avail yet, to take a C#'s overloaded functions skeleton and rewrite it in Python by using closures. I read somewhere on the net (http://dirtsimple.org/2004/12/python-is-...
2
by: Jon Harrop | last post by:
Just debating somewhere else whether or not Python might be considered a functional programming language. Lua, Ruby and Perl all seem to provide first class lexical closures. What is the current...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

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.