Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Python error numbers associated with IOError stable?

I want to move a file, but in the case it is not found I should just ignore it. In all other cases the exception should be propagated. I have the following piece of Python code:

try:
    shutil.move(old_path, new_path)
except IOError as e:
    if e.errno != 2: raise e

errno == 2 is the one, that has 'No such file or directory' description. I wonder if this is stable across Python versions and platforms, and etc.

like image 760
Anton Daneyko Avatar asked Sep 05 '12 14:09

Anton Daneyko


1 Answers

It is better to use values from the errno module instead of hardcoding the value 2:

try:
    shutil.move(old_path, new_path)
except IOError as e:
    if e.errno != errno.ENOENT: raise e

This makes your code less likely to break in case the integer error value changes (although that is unlikely to occur).

like image 94
Simeon Visser Avatar answered Nov 11 '22 14:11

Simeon Visser