docs: Add an example for read-only types.

Signed-off-by: Zixuan James Li <p359101898@gmail.com>
This commit is contained in:
Zixuan James Li 2022-10-05 23:52:08 -04:00 committed by Tim Abbott
parent a0c4e077d6
commit 8e472402fe
1 changed files with 15 additions and 0 deletions

View File

@ -381,6 +381,21 @@ types might be appropriate. (But dont use `Iterable` for a value
that might be iterated multiple times, since a one-use iterator is
`Iterable` too.)
For example, if a function gets called with either a `list` or a `QuerySet`,
and it only iterates the object once, the parameter can be typed as `Iterable`.
```python
def f(items: Iterable[Realm]) -> None:
for item in items:
...
realms_list: List[Realm] = [zulip, analytics]
realms_queryset: QuerySet[Realm] = Realm.objects.all()
f(realms_list) # OK
f(realms_queryset) # Also OK
```
A function's return type can be mutable if the return value is always
a freshly created collection, since the caller ends up with the only
reference to the value and can freely mutate it without risk of