Skip to content

EM101 fix rebinds or shadows a variable named msg #24335

@dscorbett

Description

@dscorbett

Summary

The fix for raw-string-in-exception (EM101) can change the program’s behavior when a variable named msg is already in scope. The function fresh_binding_name added in #24316 may help.

Example of rebinding:

$ cat >em101_1.py <<'# EOF'
def f():
    msg = "."
    try:
        raise RuntimeError("!")
    except RuntimeError:
        return msg
print(f())
# EOF

$ python em101_1.py
.

$ ruff --isolated check em101_1.py --select EM101 --unsafe-fixes --fix
Found 1 error (1 fixed, 0 remaining).

$ cat em101_1.py
def f():
    msg = "."
    try:
        msg = "!"
        raise RuntimeError(msg)
    except RuntimeError:
        return msg
print(f())

$ python em101_1.py
!

Example of shadowing:

$ cat >em101_2.py <<'# EOF'
msg = "."
def f():
    try:
        raise RuntimeError("!")
    except RuntimeError:
        return msg
print(f())
# EOF

$ python em101_2.py
.

$ ruff --isolated check em101_2.py --select EM101 --unsafe-fixes --fix
Found 1 error (1 fixed, 0 remaining).

$ cat em101_2.py
msg = "."
def f():
    try:
        msg = "!"
        raise RuntimeError(msg)
    except RuntimeError:
        return msg
print(f())

$ python em101_2.py
!

Version

ruff 0.15.8 (c2a8815 2026-03-26)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions