Skip to content

Commit d054ac5

Browse files
committed
readability/EAFP: update to Py 3, use specific exception, add race condition note
Add a note about the non-EAFP example code also having a potential race condition (which is one of the reasons why the EAFP style is preferred). Update best practice code to catch the specific FileNotFoundError (new in Python 3.3), instead of the overly broad OSError. (Add note about using OSError in Python 2, but caution that it may be too broad.) Update glossary link to point to Python 3 docs, for good measure.
1 parent b4b7c23 commit d054ac5

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

docs/readability/asking_for_permission_instead_of_forgiveness_when_working_with_files.rst

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,17 @@ The code below uses an ``if`` statement to check if a file exists before attempt
1616
if os.path.exists("file.txt"):
1717
os.unlink("file.txt")
1818
19+
(Beyond coding style, the above code also has a potential race condition, as another program might delete the file between the ``exists`` and ``unlink`` calls.)
20+
1921
Best practice
2022
-------------
2123

2224
Assume the file can be used and catch problems as exceptions
2325
.............................................................
2426

25-
The updated code below is a demonstration of the EAFP coding style, which is the preferred style in the Python community. Unlike the original code, the modified code below simply assumes that the needed file exists, and catches any problems as exceptions. For example, if the file does not exist, the problem will be caught as an ``OSError`` exception.
27+
The updated code below is a demonstration of the EAFP coding style, which is the preferred style in the Python community. Unlike the original code, the modified code below simply assumes that the needed file exists, and catches any problems as exceptions. For example, if the file does not exist, the problem will be reported as a ``FileNotFoundError`` exception.
28+
29+
In Python 2, a plain ``OSError`` is raised instead (which can also result from other errors, e.g. permission issues).
2630

2731
.. code:: python
2832
@@ -31,12 +35,12 @@ The updated code below is a demonstration of the EAFP coding style, which is the
3135
try:
3236
os.unlink("file.txt")
3337
# raised when file does not exist
34-
except OSError:
38+
except FileNotFoundError: # or OSError, if using Python 2
3539
pass
3640
3741
References
3842
----------
3943

40-
- `Python 2.7.8 - Glossary <https://docs.python.org/2/glossary.html>`_
44+
- `Python 3 - Glossary: EAFP <https://docs.python.org/3/glossary.html#term-eafp>`_
4145

4246

0 commit comments

Comments
 (0)