First, you are not asking if something is “acceptable,” you are asking if it is a “context manager." *
, , (, 3.1, 3.3):
Lock, RLock, Condition, Semaphore BoundedSemaphore with.
, , :
if hasattr(x, '__exit__'):
print('x is a context manager')
try:
with x:
pass
except AttributeError:
pass
else:
print('x is a context manager')
:
help(open)...
, , open , , , . 3.3 ; 2.7, (a file), help , , help , , , __exit__.
, , , EAFTP , . - with. , , , , , . ( AttributeError __exit__, , , with, .) , , , , , /etc/. ( stdlib, , - .)
: , close, , contextlib.closing :
with closing(legacy_file_like_object):
...
with closing(legacy_file_like_object_producer()) as f:
, contextlib. @contextmanager , nested , 2.7/3.x 2.5, closing ( @contextmanager), stdlib .
* -, , . help('with') , " " " ". , with foo(bar) as baz, qux as quux:, foo(bar) qux - . (, , - .)