问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/19948457/naming-convention-for-context-manager-classes-with-blocks