推荐学习书目
› 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 · Nov 9, 2021 · 2899 views
    This topic created in 1780 days ago, the information mentioned may be changed or developed.

    需求:

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

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

    然后在 timer.__exit__ 里面 inspect 出需要的作用域然后调用 100 次 __timed__
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   987 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 753ms · UTC 18:27 · PVG 02:27 · LAX 11:27 · JFK 14:27
    ♥ Do have faith in what you're doing.