Skip to content

B006 (MutableArgumentDefault) should exempt parameters with immutable type annotations #572

@andersk

Description

@andersk

B006 aims to prevent bugs that arise from mutating the default value of a function’s parameter, with unintended effects on all future calls to that function. But for a parameter that’s annotated with an immutable abstract type such as Sequence[int], mypy already prevents the value from being mutated. So such parameters should be exempt from B006. For example:

from typing import Sequence

def f(a: Sequence[int] = [1, 2, 3]):  # should not raise B006
    for x in a:
        print(x)

This was suggested at PyCQA/flake8-bugbear#137 (comment), but wasn’t implemented due to flake8-bugbear lacking the machinery to accurately track typing imports. Since ruff has that now (#533), perhaps this is easy to implement in ruff.

Types that should be considered immutable:

object
collections.abc.Container[T]
collections.abc.Iterable[T]
collections.abc.Reversible[T]
collections.abc.Sized
collections.abc.Collection[T]
collections.abc.Sequence[T]
collections.abc.Set[T]
collections.abc.Mapping[K, V]
typing.Container[T]
typing.Iterable[T]
typing.Reversible[T]
typing.Sized
typing.Collection[T]
typing.Sequence[T]
typing.AbstractSet[T]  # not typing.Set[T]
typing.Mapping[K, V]
typing.Optional[I]  # where I is any of the above
I | None  # where I is any of the above
typing.Annotated[I, …]  # where I is any of the above

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