Skip to content

try-except-in-loop (PERF203) possibly false-positives with continue/pass in except block #12805

@Avasam

Description

@Avasam
  • List of keywords you searched for before creating this issue. Write them down here so that others can find this issue more easily and help provide feedback.
    try-except, continue, pass, PERF203, try-except-in-loop

  • A minimal code snippet that reproduces the bug.
    Here's a few examples taken directly from setuptools. I don't see a better way of writing them, nor does the doc at make any mention of such cases. Where the iteration must complete and ignore certain errors https://docs.astral.sh/ruff/rules/try-except-in-loop/

def test_process_template_line_invalid(self):
    # invalid lines
    file_list = FileList()
    for action in (
        'include',
        'exclude',
        'global-include',
        'global-exclude',
        'recursive-include',
        'recursive-exclude',
        'graft',
        'prune',
        'blarg',
    ):
        try:
            file_list.process_template_line(action)
        except DistutilsTemplateError:  # raises PERF203
            pass
        except Exception:
            assert False, "Incorrect error thrown"
        else:
            assert False, "Should have thrown an error"

###

def filesys_decode(path):
    """
    Ensure that the given path is decoded,
    ``None`` when no expected encoding works
    """

    if isinstance(path, str):
        return path

    fs_enc = sys.getfilesystemencoding() or 'utf-8'
    candidates = fs_enc, 'utf-8'

    for enc in candidates:
        try:
            return path.decode(enc)
        except UnicodeDecodeError:  # raises PERF203
            continue

    return None

###

def process_index(self, url, page):
    """Process the contents of a PyPI page"""

    # process an index page into the package-page index
    for match in HREF.finditer(page):
        try:
            self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))
        except ValueError:  # raises PERF203
            pass
    ...
  • The command you invoked (e.g., ruff /path/to/file.py --fix), ideally including the --isolated flag.
    ruff check . --isolated --preview --select=PERF203

  • The current Ruff settings (any relevant sections from your pyproject.toml).
    N/A

  • The current Ruff version (ruff --version).
    ruff 0.5.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    previewRelated to preview mode featuresruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions