Closures in python
Daniel Dittmar
daniel.dittmar at sap.com
Thu Sep 18 07:41:51 EDT 2003
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
More information about the Python-list
mailing list