[Chicago] Question about the with statement in Python 2.5

Kumar McMillan kumar.mcmillan at gmail.com
Wed Nov 14 21:20:46 CET 2007


On Nov 14, 2007 1:59 PM, Feihong Hsu <hsu.feihong at yahoo.com> wrote:
> Just checking to make sure there's not something I'm missing here, but
> Python 2.5's with statement cannot be used to define anonymous callback
> functions, right? For example, the following could not be made to work:
>
> ============================================
>
> btn = Button(label="Click me!")
> with btn.click:
>     print "You pressed the button!"
>
> ============================================
>
> I have tried writing my own context manager, but have not found a way to
> defer the execution of the code inside the with-block.

hmm, you probably want a decorator instead (thus, the original code you posted):

btn = Button(label="Click me!")
@btn.click
def onclick(target):
    print "You clicked", target.label


The with statement is more designed to ease the try/finally pattern.
For example:

class ezfile(file):
    def __enter__(self):
        pass
    def __exit__(self):
        self.close()

with ezfile('/tmp/fooz.txt', 'w') as f:
    f.write("stuff')


If you want to do with statement stuff in python 2.4 this is a pretty
good solution: http://oakwinter.com/code/context_tools/
For example:

@context_tools.decorate_with(my_manager())
def foo(context, y, z):
  ...

is equivalent to

def foo(y, z):
  with my_manager() as context:
    ...


More information about the Chicago mailing list