Skip to content

Commit d88697d

Browse files
authored
Merge pull request #144 from kwi-dk/master
readability/EAFP: update to Py 3, use specific exception, add race condition note
2 parents 18e309e + d054ac5 commit d88697d

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)