Using try / except or if / else when copying files

I have two methods to copy the file, which is the most pythonic / best version?

While working through the object oriented tutorial, I was told (to paraphrase here) that it is best to avoid checking and handling "exceptions" when they occur. Is the way I used try

/ except

in the second version valid?

First version using if

/ else

:

if os.path.exists(dest):
    print("\nCopying zipfile to {}".format(dest))
    shutil.copy(self.backup_zipfile_name, dest)
else:
    print("Cannot find {}.".format(dest))

      

Second version using try

/ except

:

try:
    shutil.copy(self.back_zipfile_name, dest)
except FileNotFoundError:
    print("{!r} could not be found".format(dest))

      

+3


source to share


2 answers


Definitely the second.

It's easy to think of your program steps as sequential actions with nothing happening in between. But that's not how computers work (at least modern non-embedded ones).

In between checking that the path exists and actually trying to write to it, some other program might come up and uninstall it, resulting in an excluded runtime being thrown. This is a common concurrency error.



Therefore, always use try/catch

(or in the case of Python, try/except

) when dealing with the filesystem, network, or any other external resource that you do not have full control over.

Here is a good resource with a more detailed explanation.

+2


source


Edit: I think @ Jared Smiths answer is more appropriate for a specific use case (file system access).


This is for you like everyone else, but here is what it says in the python docs for your reference.

LBYL



Take a look before jumping. This coding style explicitly checks for preconditions before making calls or searches. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.

In a multithreaded environment, the LBYL approach can compromise the appearance of a race condition between "look" and "jump". For example, code if the key in the mapping is: return mapping [key] may fail if another thread removes the key from the mapping after a test, but before searching. This problem can be solved with blocking or using an EAFP approach.

ESPC

It's easier to ask for forgiveness than permission. This general Python coding style assumes that there are valid keys or attributes and throws exceptions if the assumption turns out to be false. This clean and fast style is characterized by many attempts and exceptions. This technique contrasts with the LBYL standard, which is common to many other languages ​​such as C.

https://docs.python.org/2/glossary.html

+2


source







All Articles