特定代码行的类似于装饰器的语法 [英] Decorator-like syntax for a specific line of code

查看:41
本文介绍了特定代码行的类似于装饰器的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接的主题(但不是重复的主题):

Linked topic (but not duplicate): Decorator to time specific lines of the code instead of whole method?

我知道Python函数通常使用装饰器.

I know how decorators are usually used for Python functions.

单行代码是否有类似的概念/语法?

示例:使用

def measuretime(lineofcode):
    start = time.time()
    lineofcode()
    print time.time() - start

然后

@measuretime
im = Image.open(BytesIO(base64.b64decode(data)))

将被解释为

start = time.time()
im = Image.open(BytesIO(base64.b64decode(data)))
print time.time() - start

注意:

  • I know measuring execution time like this is not optimal, it's better to use timeit, etc. but it's just a random example to show what I'm looking for (decorators for single lines of code)

我正在寻找1或2行代码的解决方案(当然是+函数的定义).如果解决方案需要两行以上的代码(即,比 @measuretime 之类的代码要多),那么最好放弃并照常做:

I'm looking for a 1 or 2 lines of code solution (+ definition of the function of course). If the solution takes more than 2 lines of code (i.e. more than something like @measuretime), then it's probably better to give up and just do the normal:

  start = time.time()
  im = Image.open(BytesIO(base64.b64decode(data)))
  print time.time() - start

推荐答案

如果要在一行代码之前和之后进行操作,请

If you want to do stuff before and after a line of code, a context manager would be appropriate:

from contextlib import contextmanager
import time

@contextmanager
def measuretime():
    start = time.time()
    try:
        yield
    finally:
        print(time.time() - start)

with measuretime():
    do_stuff()

这篇关于特定代码行的类似于装饰器的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆