Python Try-Except vs If-Else performance

Viewed 265

Someone recently said to me "In Python it is better to try and ask for forgiveness later instead of begging for permission" which I found quite funny but also relates to my question

I'm creating a personal assistant of sorts called Ada and was being pedantic about performance. From what I gather, using a try statement is faster when it works then checking and then executing. E.G: (The second one being slower if the directory DOESNT EXIST???)

import os

try:
    os.makedirs("Test")
except FileExistsError:
    pass

# VS

if not os.path.exists("Test"):
    os.makedirs("Test")

So when creating coding, you need to weigh up whats more likely. In my example it would be the file is more likely to NOT exist so I should use a try block which yields better performance then an If-Else

I was wondering if this is of any benefit to try (pun intended) this method of the default If-Else?

P.S (This question isn't a duplicate of Python if vs try-except since that's not specifying about comparing the probabilities of the try: code block)

My current code if anyone's interested: (Created a folder in AppData called Ada where a Config.ini file is made)

import os

AppDataDirectory = os.getenv("AppData")
AdaDirectory = AppDataDirectory + "\Ada"
ConfigFile = AdaDirectory + "\CONFIG.ini"

try:
    File = open(ConfigFile, "r")
except FileNotFoundError:
    try:
        os.makedirs(AdaDirectory)
    except FileExistsError:
        print("Config File Missing")
    # Setup Config File
1 Answers

The performance of try vs. if-else depends.

Generally, it is considered more pythonic to use try blocks because:

  1. You do an action
  2. If it fails then do something else

The benefit here is that if the action fails you can specify an exact error and react accordingly or keep the exception at the Base Exception class.

Using if-else isn't necessarily non-pythonic but with them python (this gets longer if there are elif statements),

  1. Checks the boolean value of a statement
  2. If boolean value is desired, then perform another action
  3. If boolean value is not desired then do something else

Ultimately try blocks are recommended because you do something and specify an exact response if the action fails as opposed to setting up a variety of conditions.

Related