]> granicus.if.org Git - python/commitdiff
add example for not using access
authorBenjamin Peterson <benjamin@python.org>
Fri, 20 May 2011 16:41:13 +0000 (11:41 -0500)
committerBenjamin Peterson <benjamin@python.org>
Fri, 20 May 2011 16:41:13 +0000 (11:41 -0500)
Doc/library/os.rst

index 3f6d69d1493a4b29bbde44df5ff811ee75b9ab92..e6bafced8f2220a3d7aae213891f2486b510f84f 100644 (file)
@@ -772,7 +772,26 @@ Files and Directories
       Using :func:`access` to check if a user is authorized to e.g. open a file
       before actually doing so using :func:`open` creates a security hole,
       because the user might exploit the short time interval between checking
-      and opening the file to manipulate it.
+      and opening the file to manipulate it. It's preferable to use :term:`EAFP`
+      techniques. For example::
+
+         if os.access("myfile", os.R_OK):
+             with open("myfile") as fp:
+                 return fp.read()
+         return "some default data"
+
+      is better written as::
+
+         try:
+             fp = open("myfile")
+         except OSError as e:
+             if e.errno == errno.EACCESS:
+                 return "some default data"
+             # Not a permission error.
+             raise
+         else:
+             with fp:
+                 return fp.read()
 
    .. note::