python - Use with statement in a class that wraps a resource -
if have class wraps resource, e.g., sqlite
database connection or file, there way can use with
statement close resource when object goes out of scope or gcollected?
to clarify mean, want avoid this:
class x: def __init__(self): # open resource def close(self): # or __del__, worst # close resource
but make in such way resource freed in
with open('foo') f: # use resource
you need provide __enter__
, __exit__
methods. see pep 343.
this pep adds new statement "with" python language make possible factor out standard uses of try/finally statements.
in pep, context managers provide
__enter__()
,__exit__()
methods invoked on entry , exit body of statement.
Comments
Post a Comment