3

I was hoping this would work:

class A:
    def __enter__(self, code):
       print code

    def __exit__(..):
       pass

and then:

with A():
   f()
   g()

would print:

f()
g()

Specifically, my intention is to take this code and create a function out of it. So I can do: with runInThreads() or with runManyTimesTillSuccess(),..

4

4 回答 4

6

In a portable, language defined way, no. However, the withhacks module provides several examples of CPython specific hackery that lets you do all sorts of creative things.

That's more for playing around, though - functions and generators are still the only official ways of playing with reusable code blocks in Python.

于 2011-02-08T07:10:21.050 回答
3

Here's how you could use a decorator with an argument:

>>> def manytimes(n):
    def decorate(fn):
        for i in range(n):
            fn()
    return decorate

>>> @manytimes(3)
def _():
    print("hello")


hello
hello
hello
于 2011-02-08T12:25:45.070 回答
1

Why don't you use a decorator?

I just tried (I still have python 2.6.4 here, but it will surely work with newer ones too)

def decorate(fn):
    print "Got", fn
    return "Anything"

def foo():
    @decorate
    def bar(): pass
    print bar

foo()
foo()

and it gives:

Got <function bar at 0x01EAD4B0>
Anything
Got <function bar at 0x01EAD4B0>
Anything

so you can easily do:

any code...
@runInThreads
def _():
    whatever...

You can even define _ any number of times in a function.

PS: I read the link from withhacks, than thought this up and wanted to comment there too only to notice the same technique is already suggested in the comments there.

于 2011-02-08T07:55:19.913 回答
0

Using ncoghlan's advice I went to http://pypi.python.org/pypi/withhacks and got the code off: http://code.google.com/p/ouspg/wiki/AnonymousBlocksInPython?ts=1253546882&updated=AnonymousBlocksInPython

so I can do:

from blocks import takes_block

@takes_block
def manyTimes(block):
   for i in range(5):
      block()


 with manyTimes():
     print 'a'
     print 'b'

which printouts: a b 5 times.

于 2011-02-08T07:51:24.093 回答