如何将 contextlib.contextmanager 与类方法一起使用?

Int*_*rer 5 python class-method contextmanager

请参阅下面的 Python 3.10 代码片段:

import contextlib

class Foo:
    @contextlib.contextmanager
    @classmethod
    def state(cls):
        try:
            yield
        finally:
            pass

with Foo.state():
    pass
Run Code Online (Sandbox Code Playgroud)

它抛出一个TypeError

Traceback (most recent call last):
  File "/path/to/code/play/quick_play.py", line 12, in <module>
    with Foo.state():
  File "/path/to/.pyenv/versions/3.10.5/lib/python3.10/contextlib.py", line 281, in helper
    return _GeneratorContextManager(func, args, kwds)
  File "/path/to/.pyenv/versions/3.10.5/lib/python3.10/contextlib.py", line 103, in __init__
    self.gen = func(*args, **kwds)
TypeError: 'classmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)

可以用classmethod来装饰吗contextlib.contextmanager?如果是的话,该怎么做?

Alb*_*ert 7

这应该有效:

import contextlib

class Foo:
    @classmethod
    @contextlib.contextmanager
    def state(cls):
        try:
            print("A")
            yield
            print("C")
        finally:
            pass

with Foo.state():
    print("B")
Run Code Online (Sandbox Code Playgroud)

这将打印 AB C。