Skip to content

Clarify the relationship of sequences to truthiness. #138066

@randolf-scholz

Description

@randolf-scholz

It's common nowadays to annotate methods with the abstract Sequence[T] rather than list[T] when mutation is not required. However, I noticed that one sometimes encounters / is tempted to write the following pattern:

from collections.abc import Sequence

def test(args: Sequence) -> None:
    if not args:  # <-- potentially dangerous.
         ...
Here are some example found on GitHub

This is inherently unsafe at the moment, since it assumes that bool(...) behaves the same for any subclass of collections.abc.Sequence as it does with builtins.list or builtins.tuple, but nothing stops a custom subtype to implement __bool__ and override this behavior.1

The documentation, both the data model docs and the collections.abc docs, appears silent about any expected behavior for bool(sequence). Given the prevalence of code that uses such patterns, I think one should either:

  1. Make the boolean behavior on list/tuple officially a part of the specification of sequence types in one way or another.2
  2. Clarify and document that sequences need not behave like bool(list) or bool(tuple), so that linter-libraries can justifiably trigger warnings in cases like the code above, and guide the user to use if len(seq) == instead.

Footnotes

  1. In fact, even currently subclasses of list, tuple and str can implement __bool__ if they want to.

  2. In particular, the most important bit seems to be that truthiness implies non-emptiness implies that the 0-th element exists. So if one is to specify any behavior, I believe this is the minimal fragment that should be included. Maybe sequence truthiness generally need not work exactly like in list and tuple, but this principle seems fundamental.

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dirpendingThe issue will be closed if no feedback is provided

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions