pythonsublimetextsublime-text-plugin

"if" condition for boolean settings: == 1, == True or just omit?


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")

Solution

  • It depends on what the possible values are.

    The rule is pretty simple: when writing a test, write what you mean to test.

    Different tests mean different things:

    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.