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
?
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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.