简体   繁体   中英

Python type hinting: when to use MutableSequence vs List

I have been reading about typing.Sequence and typing.MutableSequence . There isn't a ton of "light reading" out there on either of the two, everything goes straight into details.

From this answer to Can you specify variance in a Python type annotation?

Sequence is the read-only version of List

So that leads me to wonder, what is the difference between MutableSequence , and just a plain List ?


More Details

The best source I could find was the The standard type hierarchy section of the Python Data model.

From reading the section Mutable sequences , it seems like MutableSequence might be a "parent" of List ?

In other words, one can use them interchangeably, just MutableSequence is a bit less restrictive?

MutableSequence represents arbitrary mutable sequences. For example, an instance of array.array satisfies MutableSequence .

List is specifically just lists. If an object is not a list, it doesn't satisfy List .

Use MutableSequence when you want to express "mutable sequence". Use List when you want to express "list".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM