ACEGL ACEGL - 2 months ago 7
Python Question

Which is faster in Python: if or try

Please consider the following code:

def readPath(path):
content = None
if os.path.isfile(path):
f = open(path,"rb")
content = f.read()
f.close()
return content


versus this one:

def readPath(path):
content = None
try:
f = open(path,"rb")
content = f.read()
f.close()
except:
pass
return content


Given that the def is called many (hundreds to thousands times) in succession, mostly with valid paths (that represent actual files on the file system) but sometimes with non existent paths, which version is more efficient? Is checking a condition prior to opening the file is slower than setting a try block?

Answer

Performance considerations shouldn't be the reason for choosing the os.path.isfile approach: using isfile because it makes your code prone to race conditions. Suppose someone removes the file just after you called isfile and before you actually opened it. There have been countless of security bugs because of this. isfile also amounts to an extra system call and that in itself is more expensive than catching an exception.

Additionally your code possibly leaks an open file and is unnecessarily complicated. Using the with block, this becomes much cleaner:

def read_path(path):
    try:
        with open(path, "rb") as f:
           return f.read()
    except IOError:
        return None