Skip to content

Commit 67a9b12

Browse files
committed
python typing / improve Collection and Sequence
1 parent 576e358 commit 67a9b12

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

docs/posts/2025/2025-02-01-python-type-hints.md

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -144,19 +144,22 @@ Some types like: `typing.Any`, `typing.Generic`, `typing.TypeVar`, etc. are stil
144144

145145
## Sequence & Collection
146146

147-
- `collections.abc.Sequence` is a type of ordered collection. Sequence does not include `append` and `extend` methods.
148-
- `collections.abc.Collection` is a type of unordered collection.
149-
150-
| Type | Sequence | Collection |
151-
| ------------------------------- | -------- | ---------- |
152-
| str | Yes | No |
153-
| tuple | Yes | Yes |
154-
| list | Yes | Yes |
155-
| set | No | Yes |
156-
| dict | No | Yes |
157-
| order | Yes | No |
158-
| indexing (e.g., `seq[0]`) | Yes | No |
159-
| Membership Checks (`x in data`) | Yes | Yes |
147+
- `collections.abc.Collection` is a type of unordered collection. Collections supports only `__len__`, `__iter__`, `__contains__` operators, and does not support indexing or slicing.
148+
- `collections.abc.Sequence` is **subclass** of `Collection`, is a type of ordered, indexable collection. Sequence supports `__getitem__()`, `__reversed__` in addition to the methods of `Collection`. Sequences can be sliced and indexed.
149+
150+
See [Collections Abstract Base Classes](https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes) to check all the methods available for each type.
151+
152+
| Type | Sequence | Collection |
153+
| ------------------------------------------------- | -------- | ---------- |
154+
| str |||
155+
| tuple |||
156+
| list |||
157+
| range |||
158+
| set |||
159+
| dict |||
160+
| order |||
161+
| indexing (having `__getitem__()`)(e.g., `seq[0]`) |||
162+
| Membership Checks (`x in data`) |||
160163

161164
## Type aliases
162165

@@ -451,7 +454,7 @@ In [7]: process("2")
451454
Runtime type is 'str'
452455
```
453456

454-
!!! note "Don't use TypeGuard, it works only in if branch, not else branch. TypeIs works for both if and else branch."
457+
!!! warning "Don't use TypeGuard, it works only in if branch, not else branch. TypeIs works for both if and else branch."
455458

456459
### When to use TypeIs over isinstance()
457460

0 commit comments

Comments
 (0)