Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PEP8: Never use equality operators to compare to singletons #158

Merged
merged 1 commit into from
Feb 28, 2025

Conversation

cclauss
Copy link
Contributor

@cclauss cclauss commented Dec 13, 2024

https://peps.python.org/pep-0008/#programming-recommendations

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

% ruff rule E712

true-false-comparison (E712)

Derived from the pycodestyle linter.

Fix is always available.

What it does

Checks for equality comparisons to boolean literals.

Why is this bad?

PEP 8 recommends against using the equality operators == and != to
compare values to True or False.

Instead, use if cond: or if not cond: to check for truth values.

If you intend to check if a value is the boolean literal True or False,
consider using is or is not to check for identity instead.

Example

if foo == True:
    ...

if bar == False:
    ...

Use instead:

if foo:
    ...

if not bar:
    ...

Fix safety

This rule's fix is marked as unsafe, as it may alter runtime behavior when
used with libraries that override the ==/__eq__ or !=/__ne__ operators.
In these cases, is/is not may not be equivalent to ==/!=. For more
information, see this issue.

https://peps.python.org/pep-0008/#programming-recommendations
> Comparisons to singletons like None should always be done with `is` or `is not`, never the equality operators.
@cclauss cclauss changed the title PEP8: Never equality operators to compare to singletons PEP8: Never use equality operators to compare to singletons Dec 14, 2024
@darrenburns darrenburns merged commit fb9407e into darrenburns:main Feb 28, 2025
@cclauss cclauss deleted the patch-1 branch March 1, 2025 08:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants