Naming convention for context-manager classes (“with” blocks)

荒凉一梦 提交于 2019-12-14 04:17:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!