Skip to content

Add an issequence utility to check for list, tuple, and other compatible objects #26769

@embray

Description

@embray

git grep 'isinstance(.*, *(list, *tuple))' reveals a widespread use of this type check in the Sage library.

Through the transition to Python 3, many standard functions such as range no longer construct lists but return special objects that support the sequence protocol.

This ticket adds an issequence() function that can work as a more generic replacement for isinstance(x, (list, tuple)) but will also work with a broader range of similar types (e.g. xrange, Sage vectors, Numpy arrays, etc). Note issequence(x) is also True for str and bytes. So when using this to replace (list, tuple) care should be taken to make sure other sequence-like types are handled first, in cases where they require separate handling in the first place.

For the very common case of (list, tuple) this is faster than isinstance, but also has the benefit of being more generic, while not quite as generic as the much slower isinstance(x, Sequence).

#24804 demonstrates an example usage which allows the constructor in question to also accept a Python 3 range object (an example which appears in the doctests that did not otherwise work). This will likely be useful elsewhere but we can find those examples as we come to them.

See also:

CC: @fchapoton @jdemeyer @tscrim

Component: misc

Author: Erik Bray

Branch/Commit: u/embray/misc/issequence @ 1d7066c

Issue created by migration from https://trac.sagemath.org/ticket/26769

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions