开发者

python: Is there a way to get the code inside the with statement

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 creat开发者_运维技巧e a function out of it. So I can do: with runInThreads() or with runManyTimesTillSuccess(),..


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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜