Что-то вроде:
Код: Выделить всё
if needs_with():
with get_stuff() as gs:
# do nearly the same large block of stuff,
# involving gs or not, depending on needs_with()
Первоначальные эксперименты, конечно, дают ошибки в отступах..
Подробнее здесь: https://stackoverflow.com/questions/278 ... -in-python