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

Closures in python

Having played with Smalltalk for the past month, I'm getting used to
passing code as arguments to methods... how easy is it to do this in
python? I haven't seen any recent postings on this subject here...

\kasper
Jul 18 '05 #1
11 3790
Try this.

def f(n):
return n*2

def t(fnc_prm, n):
return fnc_prm(n)

t(f, 2)

I hope it helps.

Károly

"Kasper B. Graversen" <kb******@it-c.dk> az alábbiakat írta a következo
hírüzenetben: 9c**************************@posting.google.com...
Having played with Smalltalk for the past month, I'm getting used to
passing code as arguments to methods... how easy is it to do this in
python? I haven't seen any recent postings on this subject here...

\kasper

Jul 18 '05 #2
kb******@it-c.dk (Kasper B. Graversen) writes:
Having played with Smalltalk for the past month, I'm getting used to
passing code as arguments to methods... how easy is it to do this in
python? I haven't seen any recent postings on this subject here...


It is fairly straightforward:

import sys

def funcThatTakesCallable(aCallable):
aCallable('SomeString')

class MyClass:
def myFunc():
def myCallable(arg):
print arg
funcThatTakesCallable(myCallable)
funcThatTakesCallable(self.anotherCallable)
funcThatTakesCallable(lambda arg: sys.stdout.write('%s\n' % arg))

def anotherCallable(self, arg):
print 'another', arg
The major difference is that the anonymous form of a function (lambda)
isn't allowed to contain statements, only an expression. This is
rather crippling for Smalltalk/Ruby style coding and seems to lead to
warts like list comprehensions instead of having simple methods in the
collection interface that takes a block/lambda and calls this for each
element of the collection.

Example:

newCollection = [each for each in collection if each != 'Sausage']

newCollection = collection.select(lambda each: each != 'Sausage')
Jul 18 '05 #3
Kasper B. Graversen wrote:
Having played with Smalltalk for the past month, I'm getting used to
passing code as arguments to methods... how easy is it to do this in
python? I haven't seen any recent postings on this subject here...


There is no direct equivalent of code blocks in Python. Use Callables
instead. Callables are

- functions
def mywrite (text):
sys.stdout.write (text)
variable = mywrite
variable ('printed text')

- bound methods, a method bound to a specific object
variable = sys.stdout.write
variable ('printed text')

- lambda, unnamed functions, which can contain only one expression
variable = lambda text: sys.stdout.write (text)
variable ('printed text')

- classes implementing the __call__ method
class Writer:
def __call__ (self, text):
sys.stdout.write (text)
variable = Writer ()
variable ('printed text')

Daniel

Jul 18 '05 #4
'closure' is a much-abused word.
This is a closure over foo's x variable:

def foo():
x = 3
def bar():
x += 1
return x
return bar

f = foo()
print f() # print 4
g = foo()
print f() # print 5
print g() # print 4

....or it would be, if it worked.

--
Hallvard
Jul 18 '05 #5
Try this.

def f(n):
return n*2

def t(fnc_prm, n):
return fnc_prm(n)

t(f, 2)

I hope it helps.

Károly
"Kasper B. Graversen" <kb******@it-c.dk> az alábbiakat írta a következo
hírüzenetben: 9c**************************@posting.google.com...
Having played with Smalltalk for the past month, I'm getting used to
passing code as arguments to methods... how easy is it to do this in
python? I haven't seen any recent postings on this subject here...

\kasper

Jul 18 '05 #6
Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote:
'closure' is a much-abused word.
This is a closure over foo's x variable:
How about namespaces?
def foo():
x = 3
def bar():
x += 1
return x
return bar

f = foo()
print f() # print 4
g = foo()
print f() # print 5
print g() # print 4

...or it would be, if it worked.


This works:

def foo():
class ns:pass
ns.x = 3
def bar():
ns.x += 1
return ns.x
return bar

Anton

Jul 18 '05 #7
JCM
Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote:
'closure' is a much-abused word.
This is a closure over foo's x variable: def foo():
x = 3
def bar():
x += 1
return x
return bar f = foo()
print f() # print 4
g = foo()
print f() # print 5
print g() # print 4 ...or it would be, if it worked.


Python does have closures; the trouble is you can't rebind variables
defined in arbitrary scopes--you can only rebind locals and globals.
So you need some indirection for it to work:
def foo(): ... x = [3]
... def bar():
... x[0] += 1
... return x[0]
... return bar
... f = foo()
f() 4 g = foo()
f() 5 g()

4

This is actually one of my biggest complaints about Python. I'd like
syntactic disambiguation between definition and assignment in order to
have control over which scope you're assigning into.
Jul 18 '05 #8
Anton Vredegoor wrote:
Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote:
'closure' is a much-abused word.
This is a closure over foo's x variable:


How about namespaces?
(...)


Nice! Being a Python newbie I needed JCM's explanation to figure out
how it worked, though. Nothing magic about classes at all...

--
Hallvard
Jul 18 '05 #9
JCM wrote:
>>> def foo():

... x = [3]
... def bar():
... x[0] += 1
(...)

This is actually one of my biggest complaints about Python. I'd like
syntactic disambiguation between definition and assignment in order to
have control over which scope you're assigning into.


Maybe Python could be changed to let 'foo.x' inside function foo mean
the x variable in foo?

--
Hallvard
Jul 18 '05 #10
nospam wrote:
JCM wrote:
>>> def foo():

... x = [3]
... def bar():
... x[0] += 1
(...)

This is actually one of my biggest complaints about Python. I'd like
syntactic disambiguation between definition and assignment in order to
have control over which scope you're assigning into.


Maybe Python could be changed to let 'foo.x' inside function foo mean
the x variable in foo?


That would be backwards-incompatible, since foo.x already means
something -- the attribute x of object foo (yep, functions are objects
and can have attributes), which has no connection whatsoever with
the local variable x inside (some of the potentially many currently
active instances of) functions named foo.
Alex

Jul 18 '05 #11
In article <HB*************@bombur.uio.no>,
Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote:
JCM wrote:
>>> def foo():

... x = [3]
... def bar():
... x[0] += 1
(...)

This is actually one of my biggest complaints about Python. I'd like
syntactic disambiguation between definition and assignment in order to
have control over which scope you're assigning into.


Maybe Python could be changed to let 'foo.x' inside function foo mean
the x variable in foo?


But the x variable does not live on the foo function object, it lives on
the stack frame created by the current call to foo.

So something more indirect, like scope(foo).x, would make more sense,
where scope() inspects the call stack looking for calls to foo and
returns an object with appropriate __getattr__ and __setattr__ methods.
This may be implementable now, by someone who knows more about python
introspection than I do. I tried doing it with inspect.stack, but it
doesn't work -- I can find the right frame and get it's f_locals
dictionary, but this gives read-only access to the true frame's locals.

--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
Jul 18 '05 #12

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...
76
by: Nick Coghlan | last post by:
GvR has commented that he want to get rid of the lambda keyword for Python 3.0. Getting rid of lambda seems like a worthy goal, but I'd prefer to see it dropped in favour of a different syntax,...
53
by: Stelios Xanthakis | last post by:
Hi. pyvm is a program which can run python 2.4 bytecode (the .pyc files). A demo pre-release is available at: http://students.ceid.upatras.gr/~sxanth/pyvm/ Facts about pyvm: - It's FAST....
22
by: Francois | last post by:
I discovered Python a few months ago and soon decided to invest time in learning it well. While surfing the net for Python, I also saw the hype over Ruby and tried to find out more about it, before...
17
by: hanumizzle | last post by:
I have used Perl for a long time, but I am something of an experimental person and mean to try something new. Most of my 'work' with Vector Linux entails the use of Perl (a bit of a misnomer as it...
267
by: Xah Lee | last post by:
Python, Lambda, and Guido van Rossum Xah Lee, 2006-05-05 In this post, i'd like to deconstruct one of Guido's recent blog about lambda in Python. In Guido's blog written in 2006-02-10 at...
26
by: brenocon | last post by:
Hi all -- Compared to the Python I know and love, Ruby isn't quite the same. However, it has at least one terrific feature: "blocks". Whereas in Python a "block" is just several lines of...
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...
4
by: MartinRinehart | last post by:
I've written a short article explaining closures in JavaScript. It's at: http://www.martinrinehart.com/articles/javascript-closures.html I think I've understood. I look forward to your...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...

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.