Skip to content

Commit b93992e

Browse files
committed
Create asking_for_permission_instead_of_forgiveness_when_working_with_files.rst.
1 parent 35934ff commit b93992e

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
Asking for permission instead of forgiveness when working with files
2+
====================================================================
3+
4+
Summary
5+
-------
6+
7+
When working with files in Python, it's better to ask for forgiveness than for permission. Assume that you have access and permission to use the file, and catch any problems as exceptions. Don't use a lot of ``if`` statements to check that you are allowed to use a file.
8+
9+
Description
10+
-----------
11+
12+
The Python community uses an EAFP (easier to ask for forgiveness than permission) coding style. This coding style assumes that needed variables, files, etc. exist. Any problems are caught as exceptions. This results in a generally clean and concise style containing a lot of ``try`` and ``except`` statements.
13+
14+
Examples
15+
----------
16+
17+
Checking if file exists
18+
.......................
19+
20+
The module below uses an ``if`` statement to check if a file exists before attempting to use the file. This is not the preferred coding style in the Python community. The community prefers to assume that a file exists and you have access to it, and catch any problems as exceptions.
21+
22+
.. warning:: The code below is an example of an error. Using this code will create bugs in your programs!
23+
24+
.. code:: python
25+
26+
import os
27+
28+
if os.path.exists("file.txt"): # violates EAFP coding style
29+
os.unlink("file.txt")
30+
31+
Solutions
32+
---------
33+
34+
Assume the file can be used and catch problems as exceptions
35+
.............................................................
36+
37+
The updated module below is a demonstration of the EAFP coding style, which is the preferred style in the Python community. Unlike the original module, the modified module 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.
38+
39+
.. code:: python
40+
41+
import os
42+
43+
try:
44+
os.unlink("file.txt")
45+
except OSError: # raised when file does not exist
46+
pass
47+
48+
References
49+
----------
50+
- `Python 2.7.8 - Glossary <https://docs.python.org/2/glossary.html>`_

0 commit comments

Comments
 (0)