Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update optional #28435

Merged
merged 2 commits into from
Mar 24, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions doc/dev/static_type_checking_cheat_sheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,24 @@ def foo(
...
```

- Do use `Optional` if a parameter can be typed as `Any` or `None`. `Optional[Any]`, or `Union[Any, None]`, is __not__ equal to `Any`.

```python
from typing import Optional, Any

# Yes
def foo(
bar: Optional[Any] = None,
) -> None:
bar.append(1) # error caught at type checking time: Item "None" of "Optional[Any]" has no attribute "append"

# No
def foo(
bar: Any = None,
) -> None:
bar.append(1) # error caught at runtime: AttributeError: 'NoneType' object has no attribute 'append'
```

### Collections

- Do familiarize yourself with the supported operations of various abstract collections in the [collections.abc](https://docs.python.org/3/library/collections.abc.html#collections-abstract-base-classes) docs.
Expand Down