У нас есть код, который вызывает переменное количество менеджеров контекста в зависимости от параметров времени выполнения:
from contextlib import nested, contextmanager
@contextmanager
def my_context(arg):
print("entering", arg)
try:
yield arg
finally:
print("exiting", arg)
def my_fn(items):
with nested(*(my_context(arg) for arg in items)) as managers:
print("processing under", managers)
my_fn(range(3))
Однако contextlib.nested
устарел с Python 2.7:
DeprecationWarning: With-statements now directly support multiple context managers
Ответы на Несколько переменных в Python с инструкцией " указывают на то, что contextlib.nested
имеет некоторые" запутывающие ошибки, связанные с ошибками", но предложенная альтернатива использования множественного числа -manager with
не будет работать для переменного количества менеджеров контекста (а также нарушает обратную совместимость).
Есть ли альтернативы contextlib.nested
, которые не устарели и (желательно) не имеют одинаковых ошибок?
Или я должен продолжать использовать contextlib.nested
и игнорировать предупреждение? Если да, должен ли я планировать удаление contextlib.nested
в будущем?