V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
LeeReamond
V2EX  ›  Python

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

  •  
  •   LeeReamond · 2021-11-09 09:32:47 +08:00 · 1957 次点击
    这是一个创建于 870 天前的主题,其中的信息可能已经有所发展或是发生改变。

    需求:

    # 提前声明一个上下文管理器
    class timer:
        ...
       
    # 调用这个管理器时实现如下效果:
    import timer
    with timer(100):
        x = 12 * 12
    
    # 计算一百次 x=12*12 计算消耗的时间,等同于 for range(100)
    
    11 条回复    2021-11-10 09:29:43 +08:00
    Contextualist
        1
    Contextualist  
       2021-11-09 10:09:24 +08:00
    上下文管理器是(在字节码层面)被设计为必须将段落内容执行且只执行一次的。你这个需求可能得写个装饰器,然后把需要计时的片段放在一个被装饰的函数里。
    SmiteChow
        2
    SmiteChow  
       2021-11-09 10:12:47 +08:00
    ```
    with timer(100) as runner:
    def inner():
    x = 12 * 12
    runner(inner)

    ```
    LeeReamond
        3
    LeeReamond  
    OP
       2021-11-09 10:37:02 +08:00
    @SmiteChow 这个感觉好丑陋啊
    LeeReamond
        4
    LeeReamond  
    OP
       2021-11-09 10:37:29 +08:00
    @SmiteChow 如果要多写一行 runner(inner)我感觉直接写 for _ in range(100)也一样了。。
    SmiteChow
        5
    SmiteChow  
       2021-11-09 10:41:21 +08:00
    @LeeReamond 你需求不是指明了要用 context 做吗?你要写 for 就写,就别考虑 context 了。
    Vegetable
        6
    Vegetable  
       2021-11-09 10:43:54 +08:00
    这个应该是实现不了的,不过你知道你在重新实现 timeit 吗...
    jaredyam
        7
    jaredyam  
       2021-11-09 10:47:13 +08:00
    个人认为怎么都会多此一举。class 上下文管理主要靠 with 的传参,__enter__、__exit__方法控制,你这真要真么搞也就是在__enter__里加个 for range 。
    jaredyam
        8
    jaredyam  
       2021-11-09 10:51:55 +08:00
    不对,你这种需要应该不是用 class ,而是用装饰器,当然,也逃不掉 for range
    LeeReamond
        9
    LeeReamond  
    OP
       2021-11-09 12:17:41 +08:00
    @Vegetable 我知道,我觉得 timeit 不好用
    vanton
        10
    vanton  
       2021-11-09 16:29:08 +08:00
    timeit 很好用啊,自己包装下不就得了。
    不晓得你怎么用的。
    2i2Re2PLMaDnghL
        11
    2i2Re2PLMaDnghL  
       2021-11-10 09:29:43 +08:00
    上下文管理器没有回跳
    不过理论上你可以在 #2 的基础上「约定」一个魔法名字,
    with timer(100):
    def __timed__():
    x=12*12

    然后在 timer.__exit__ 里面 inspect 出需要的作用域然后调用 100 次 __timed__
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   961 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 21:16 · PVG 05:16 · LAX 14:16 · JFK 17:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.