From e1e6fb3efc7f51919c065e7a0a5077433437bf46 Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Fri, 20 Jan 2023 13:51:11 -0800 Subject: [PATCH 1/2] add optional[any] to cheat sheet --- doc/dev/static_type_checking_cheat_sheet.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/doc/dev/static_type_checking_cheat_sheet.md b/doc/dev/static_type_checking_cheat_sheet.md index 84bf6d9ec553..193ba8732e9b 100644 --- a/doc/dev/static_type_checking_cheat_sheet.md +++ b/doc/dev/static_type_checking_cheat_sheet.md @@ -164,6 +164,24 @@ def foo( ... ``` +- Do use `Optional` if a parameter can be typed as `Any` or `None`. A `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. From 0e5a70819110637bf6dc8027441ac2ee6dbb076e Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Fri, 20 Jan 2023 13:56:21 -0800 Subject: [PATCH 2/2] fix --- doc/dev/static_type_checking_cheat_sheet.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/dev/static_type_checking_cheat_sheet.md b/doc/dev/static_type_checking_cheat_sheet.md index 193ba8732e9b..84bc58f1cb27 100644 --- a/doc/dev/static_type_checking_cheat_sheet.md +++ b/doc/dev/static_type_checking_cheat_sheet.md @@ -164,7 +164,7 @@ def foo( ... ``` -- Do use `Optional` if a parameter can be typed as `Any` or `None`. A `Union[Any, None]` is not equal to `Any`. +- 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