Skip to content

fix: prevent ValueError in break_up_import when \r in source shifts line numbers - #355

Open
koteshyelamati wants to merge 1 commit into
PyCQA:mainfrom
koteshyelamati:patch-1
Open

fix: prevent ValueError in break_up_import when \r in source shifts line numbers#355
koteshyelamati wants to merge 1 commit into
PyCQA:mainfrom
koteshyelamati:patch-1

Conversation

@koteshyelamati

Copy link
Copy Markdown

Fixes #326

Problem

fix_code() raises ValueError: not enough values to unpack (expected 2, got 1) in break_up_import when the source contains a bare \r character (e.g. a Windows CR without LF, or a CR mid-line):

import autoflake
s = """
from t import (
\r  a,
    b,
)
"""
autoflake.fix_code(s)  # ValueError: not enough values to unpack (expected 2, got 1)

Root cause

io.StringIO.readlines() does not treat \r alone as a line separator, but Python's tokenizer (and str.splitlines()) does. When pyflakes analyses the source, it uses splitlines(), so a bare \r is counted as an extra line. This causes the line numbers that pyflakes marks as import lines to be offset from the lines that filter_code sees via readlines(). As a result, break_up_import is sometimes called with a continuation line that contains no import keyword, causing the re.split() to return a 1-element list and the tuple unpacking to fail.

Fix

Add a guard in break_up_import: if re.split does not produce exactly 2 parts (i.e. no import keyword was found), return the line unchanged rather than crashing. This is a minimal, defensive fix at the point of failure.

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.

ValueError: not enough values to unpack (expected 2, got 1) in break_up_import

1 participant