Skip to content

PLR1711, RET501 should exempt annotated function where return type isn’t -> None #3704

@andersk

Description

@andersk

Ruff flags PLR1711 useless-return and RET501 unnecessary-return-none in this code:

class BaseCache:
    def get(self, key: str) -> str | None:
        print(f"{key} not found")
        return None
test.py:4:9: RET501 [*] Do not explicitly `return None` in function if it is the only possible return value
test.py:4:9: PLR1711 [*] Useless `return` statement at end of function

But mypy complains if return None is removed:

test.py:2: error: Missing return statement  [return]

or if return None is changed to return:

test.py:4: error: Return value expected  [return-value]

mypy can be appeased by changing the return type annotation to -> None, and that’s okay in many cases (e.g. Callable[..., None] covariantly coerces to Callable[..., str | None), but it’s not without problems—for example, it prevents a derived class from overriding the method to return a str.

So I think RET501 and PLR1711 should exempt annotated functions with a return type other than -> None.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions