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
.
Then the following statement:
if save != False:
plt.savefig(save + "/" + title + ".png")
So if it 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 continues.
But I get a warning (I use Spider):
comparison to False should be 'if cond is not False' or 'if cond:'
Is there a better way to solve the problem?
Let's go by parts. What you get is a warning, given by Spyder , probably because it automatically checks your code against PEP 8 -- Style Guide for Python Code , which is the official coding styles document, which comments:
Free translation:
Your construction
if save != False:
is syntactically valid but it is not "pythonic" 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 store in one case astr
, the directory you mention and otherwise abool
, the valueFalse
if you do not have said directory. It is not recommended to do it this way, however if this is the case, the simplest thing is to check if the data type ofsave
is a string, in which case we are sure that the variable has the directory, for example:But there is a much more elegant way to solve it: first of all, we must initialize the variable
save
asNone
, and also we must not modify the value in case we do not have a folder as you are doing now:Note: Another way is to initialize
save
with a blank string and ask forif save != ""