Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming convention for context-manager classes ("with" blocks)

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?

like image 304
Petr Avatar asked Nov 13 '13 08:11

Petr


2 Answers

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.

like image 88
glglgl Avatar answered Oct 15 '22 03:10

glglgl


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.

like image 28
Ramchandra Apte Avatar answered Oct 15 '22 03:10

Ramchandra Apte