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

Rule to force var = <default> if value is None else value instead of var = value or <default> for value: int | None = None #16107

Open
adriangb opened this issue Feb 11, 2025 · 0 comments
Labels
needs-decision Awaiting a decision from a maintainer rule Implementing or modifying a lint rule type-inference Requires more advanced type inference.

Comments

@adriangb
Copy link
Contributor

Description

I often see the pattern of a function taking a parameter such as value: int | None = None and then having an internal default by doing var = value or 1. This is problematic because 0 and None are both falsy:

def f(value: int | None) -> int:
    return value or 1

f(0)  # returns 1

I guess one might do this intentionally, but unless you are explicit the meaning is unclear. I would rather see one of:

def f(value: int | None) -> int:
    return 1 if value is None else value

def f(value: int | None) -> int:
    return 1 if value is None or value == 0 else value

Arguably in these simple cases just making the parameter value: int = 1 would be better, but I believe there are use cases for this pattern or it is at least a pattern that exists

@MichaReiser MichaReiser added rule Implementing or modifying a lint rule needs-decision Awaiting a decision from a maintainer type-inference Requires more advanced type inference. labels Feb 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-decision Awaiting a decision from a maintainer rule Implementing or modifying a lint rule type-inference Requires more advanced type inference.
Projects
None yet
Development

No branches or pull requests

2 participants