Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 249b508

Browse files
committed
add example for not using access
1 parent 261d855 commit 249b508

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

Doc/library/os.rst

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -772,7 +772,26 @@ Files and Directories
772772
Using :func:`access` to check if a user is authorized to e.g. open a file
773773
before actually doing so using :func:`open` creates a security hole,
774774
because the user might exploit the short time interval between checking
775-
and opening the file to manipulate it.
775+
and opening the file to manipulate it. It's preferable to use :term:`EAFP`
776+
techniques. For example::
777+
778+
if os.access("myfile", os.R_OK):
779+
with open("myfile") as fp:
780+
return fp.read()
781+
return "some default data"
782+
783+
is better written as::
784+
785+
try:
786+
fp = open("myfile")
787+
except OSError as e:
788+
if e.errno == errno.EACCESS:
789+
return "some default data"
790+
# Not a permission error.
791+
raise
792+
else:
793+
with fp:
794+
return fp.read()
776795

777796
.. note::
778797

0 commit comments

Comments
 (0)