Warning in conditional sentence

1

I have a variable save to store the directory that indicates where to save a graph or, otherwise and by default, it has the value False .

Next, the following sentence:

if save != False:
    plt.savefig(save + "/" + title + ".png")

So if save has a directory, the condition is met and the image is saved in the indicated place and if not, the image is not saved and the execution of the program runs its course.

But I get warning (use Spider):

  

comparison to False should be 'if cond is not False' or 'if cond:'

Is there a better way to solve the problem?

    
asked by Zhisi 05.01.2018 в 11:29
source

1 answer

1

We go by parties. What you get is a warning, which is given by Spyder , probably because it automatically verifies your code against PEP 8 - Style Guide for Python Code which is the official document of coding styles which comments:

  

Comparisons to singletons like None should always be done with is or   is not, never the equality operators. Also, beware of writing if x   when you really mean if x is not None - e.g. when testing whether to   variable or argument that defaults to None was set to some other   value The other value might have a type (such as a container) that   could be false in a boolean context!

Free translation:

  

Comparisons between singletons such as "None" should always be made with   "is" or "is not", never with equality operators. Also, have   Be careful when writing "if x" when you really want to say "if not x" -   for example, when you test whether a variable or argument is by default   is "None" has another value. The other value could have a type (for   example, a container) that could be false in a Boolean context!

Your construction if save != False: is syntactically valid but it is not the "pythonico" style, the recommended way to write this statement would be: if not save: .

The other problem you have is that you are reusing the same variable ( save ) to save in one case a str , the directory you mention and otherwise a bool , the value False if you do not have said directory. It is not advisable to do so, however if this were the case, the simplest thing is to verify if the data type of save is a string, in which case we have security that the variable has the directory, for example:

if isinstance(save, str):
   print("save tiene el directorio")

But there is a much more elegant way to solve it: first, we must initialize the variable save as None , and we must not change the value in case of not having a folder as you are doing now:

save = None
save = "Carpeta" # Proba comentar esta linea

if save is not None:
    plt.savefig(save + "/" + title + ".png")

Note: Another way is to initialize save with a blank string and ask for if save != ""

    
answered by 05.01.2018 / 15:11
source