Skip to content

Checking if file exists before reading can cause problem in case of race conditions. #731

@mohitanand001

Description

@mohitanand001

if os.path.exists(config_file):
with open(config_file) as fd:

The above snippet of code can cause problem in case of race condition, where file might be present at the time of if os.path.exists(path) but might not exist when we try to read the file and result in exception. The python EAFP(Easy to Ask for Forgiveness than Permission) philosophy suggests that we use a try catch block to avoid this problem. Suggested changes.
You can read this stackoverflow answer to understand the problem more
Can this issue be assigned to me?
The above snippets can be replaced by the following.

try:
    f = open(config_file)
except IOError as e:
    print("File can't be accessed")
else:
      with f:
        config = py3compat.ConfigParser()
        config.read_file(fd)
        if config.has_section('yapf'):
          return config_file```
@gwelymernans 
@sergiogiro 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions