Dave Liu
Dave Liu

Reputation: 1142

`from typing` vs. `from collections.abc` for standard primitive type annotation?

I'm looking at the standard library documentation, and I see that from typing import Sequence is just calling collections.abc under the hood.

Now originally, there was a deprecation warning/error and migration from the collections package to collections.abc for some abstract classes. See here. However, now that the abstractions have settled in a new location, is it fine to use either? I see from collections.abc import [etc] in the codebase, and I wonder if it would be more practical to just import from typing when trying to do type annotations?

Cython source code: Sequence = _alias(collections.abc.Sequence, 1)

Upvotes: 4

Views: 561

Answers (1)

S.B
S.B

Reputation: 16526

However, now that the abstractions have settled in a new location, is it fine to use either?

It's better not to do so. The documentation specifically says:

class typing.Sequence(Reversible[T_co], Collection[T_co])

Deprecated alias to collections.abc.Sequence.

Deprecated since version 3.9: collections.abc.Sequence now supports subscripting ([])

If it's deprecated, it may be removed in the next versions of Python. So go with collections.abc generic classes.

Upvotes: 5

Related Questions