0

There is a note in os.access function's documentation which says:

Note Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use 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 PermissionError:
   return "some default data"
else:
   with fp:
       return fp.read()

I'm aware why EAFP is generally considered the better approach. I just don't understand the bolded text. Can you show me an example?

In both cases whether we check the user's permission in advance or not, It's going to fail when open() is encountered and Python raises exception. Am I misinterpreting the paragraph?

S.B
  • 13,077
  • 10
  • 22
  • 49

0 Answers0