5

Python 如何将上下文管理器中的段落执行多次?

 2 years ago
source link: https://www.v2ex.com/t/814044
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Python

Python 如何将上下文管理器中的段落执行多次?

  LeeReamond · 9 小时 30 分钟前 · 458 次点击
# 提前声明一个上下文管理器
class timer:
    ...
   
# 调用这个管理器时实现如下效果:
import timer
with timer(100):
    x = 12 * 12

# 计算一百次 x=12*12 计算消耗的时间,等同于 for range(100)
10 条回复    2021-11-09 16:29:08 +08:00

Contextualist

Contextualist   8 小时 53 分钟前

上下文管理器是(在字节码层面)被设计为必须将段落内容执行且只执行一次的。你这个需求可能得写个装饰器,然后把需要计时的片段放在一个被装饰的函数里。

SmiteChow

SmiteChow   8 小时 50 分钟前

```
with timer(100) as runner:
def inner():
x = 12 * 12
runner(inner)

```

LeeReamond

LeeReamond   8 小时 25 分钟前

@SmiteChow 如果要多写一行 runner(inner)我感觉直接写 for _ in range(100)也一样了。。

SmiteChow

SmiteChow   8 小时 21 分钟前

@LeeReamond 你需求不是指明了要用 context 做吗?你要写 for 就写,就别考虑 context 了。

Vegetable

Vegetable   8 小时 19 分钟前

这个应该是实现不了的,不过你知道你在重新实现 timeit 吗...

jaredyam

jaredyam   8 小时 15 分钟前

个人认为怎么都会多此一举。class 上下文管理主要靠 with 的传参,__enter__、__exit__方法控制,你这真要真么搞也就是在__enter__里加个 for range 。

jaredyam

jaredyam   8 小时 11 分钟前

不对,你这种需要应该不是用 class ,而是用装饰器,当然,也逃不掉 for range

LeeReamond

LeeReamond   6 小时 45 分钟前

@Vegetable 我知道,我觉得 timeit 不好用

vanton

vanton   2 小时 34 分钟前

timeit 很好用啊,自己包装下不就得了。
不晓得你怎么用的。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK