Here is simple ST plugin. Is there a difference between commented lines? Personally, I don't see any difference in how they work, just a difference in visual appearance.
However, some plugin developers prefer second version (== 1
), which looks just useless and ugly for me. Probably there are some reasons to prefer it?
import sublime_plugin
class ExpandUnexpandTabsCommand(sublime_plugin.EventListener):
def on_pre_save(self, view):
# if view.settings().get("translate_tabs_to_spaces"):
# if view.settings().get("translate_tabs_to_spaces") == 1:
# if view.settings().get("translate_tabs_to_spaces") == True:
view.run_command("expand_tabs")
else:
view.run_command("unexpand_tabs")
It depends on what the possible values are.
0
or 1
in it, anything else is an error, and you're reading it as an int, then you probably want == 1
.True
or no entry at all, and you're using get(…)
instead of []
so you get back None
whenever it's not True
, then you want to just test the truthiness. (Or maybe is not None
, but definitely not == True
or == 1
.)The rule is pretty simple: when writing a test, write what you mean to test.
Different tests mean different things:
if spam:
: passes if spam
is anything truthy. That means anything besides None
, False
, numeric zero, or empty containers.
if spam == 1:
: passes if spam
is the number 1
.
if spam is True:
: passes only if spam
is the special constant True
. If you want to make sure other truthy values fail, and only True
counts, use is
. You rarely want this.
if spam == True:
: passes if spam
is the special constant True
, or some object equal to it. If you've gone out of your way to write a class whose __eq__
tests for True
or something, then you might want this test, but it's hard to imagine why you would otherwise.
It happens to be true that 1 == True
. But writing == True
when you want to test for the number 1
, or == 1
when you want to test for True
but not other truthy values, is misleading to anyone who understands idiomatic Python, and mildly confusing to anyone who doesn't, and there's no benefit to anyone. So don't do it.
And writing either of those when you want to test for anything truthy isn't just misleading, it's wrong.