Skip to content

Query regarding try-consider-else documentation #20570

@LilMonk

Description

@LilMonk

Question

In the documentation https://docs.astral.sh/ruff/rules/try-consider-else/ it says to use the pattern

import logging

def reciprocal(n):
    try:
        rec = 1 / n
    except ZeroDivisionError:
        logging.exception("Exception occurred")
    else:
        print(f"reciprocal of {n} is {rec}")
        return rec

when I use it in my code

import logging

class Bar(BaseModel):
    a: int
    b: str

def create_bar(a: int, b: str) -> Bar:
    if a < 0:
        raise ValueError("a must be non-negative")
    return Bar(a=a, b=b)

def foo() -> Bar:
    log = logging.getLogger("foo")
    log.info("Creating Bar instance")
    try:
        bar = create_bar(1, "test")
    except Exception:
        log.exception("Failed to create Bar instance")
    else:
        return bar

But on type checkers like pylance, it gives an error

Function with declared return type "Bar" must return a value on all code paths
  "None" is not assignable to "Bar"

It is only resolved if I have a raise in an except block like this

import logging

class Bar(BaseModel):
    a: int
    b: str

def create_bar(a: int, b: str) -> Bar:
    if a < 0:
        raise ValueError("a must be non-negative")
    return Bar(a=a, b=b)

def foo() -> Bar:
    log = logging.getLogger("foo")
    log.info("Creating Bar instance")
    try:
        bar = create_bar(1, "test")
    except Exception:
        log.exception("Failed to create Bar instance")
        raise
    else:
        return bar

Is my understanding of the documentation wrong, or is there anything else that I'm missing?

Version

ruff 0.12.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions