Is there a general naming convention for classes or functions that are meant to be used in with
block such as
with CreateSomeContext() as x:
...
? Something that signals that the class or the result of a function should be used with with
?
In the respective PEP 0343, there is a mention of two conventions:
The tense used in the names of the example contexts is not arbitrary. Past tense ("-ed") is used when the name refers to an action which is done in the
__enter__
method and undone in the__exit__
method. Progressive tense ("-ing") is used when the name refers to an action which is to be done in the__exit__
method.
There's no naming convention (open
, socket.create_connection
, urllib.request.urlopen
all return context managers which can be used with with
) but context managers will have the __enter__
and __exit__
methods.
Note: in the case of open("file", "w")
, the return value (the file object) is the context manager, not open
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With