From adefa07f699de37ae1ac40c08dd9bc5a171b27fd Mon Sep 17 00:00:00 2001 From: Sebastian Rittau Date: Tue, 13 May 2025 13:33:27 +0200 Subject: [PATCH 1/2] Add some exceptions when commenting Any --- docs/guides/writing_stubs.rst | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/docs/guides/writing_stubs.rst b/docs/guides/writing_stubs.rst index 47f48b40a..534df53af 100644 --- a/docs/guides/writing_stubs.rst +++ b/docs/guides/writing_stubs.rst @@ -772,18 +772,26 @@ all type checkers:: Using ``Any`` and ``object`` ---------------------------- -When adding type hints, avoid using the ``Any`` type when possible. Reserve -the use of ``Any`` for when: +When adding type hints, avoid using the :ref:`Any` type when possible. Reserve +the use of :ref:`Any` for when: * the correct type cannot be expressed in the current type system; and * to avoid union returns (see above). -Note that ``Any`` is not the correct type to use if you want to indicate +Note that :ref:`Any` is not the correct type to use if you want to indicate that some function can accept literally anything: in those cases use -``object`` instead. - -When using ``Any``, document the reason for using it in a comment. Ideally, -document what types could be used. +:class:`object` instead. + +When using :ref:`Any`, document the reason for using it in a comment, unless the +reason is obvious. Ideally, document what types could be used. Obvious +reasons can include: + +* Using :ref:`Any` as a type argument for a generic to say "any object of this + type is allowed", e.g. ``type[Any]``. +* Using ``dict[str, Any]`` or ``Mapping[str, Any]`` when the value types + depends on the keys. But consider using :ref:`TypedDict` or + ``dict[str, Incomplete]`` (temporarily) when the keys of the dictionary are + fixed. The ``Any`` Trick ----------------- From 624954f698dd0caf52d1927833aba7f28b5b7164 Mon Sep 17 00:00:00 2001 From: Sebastian Rittau Date: Tue, 13 May 2025 18:12:46 +0200 Subject: [PATCH 2/2] Use Future[Any] instead of type[Any] --- docs/guides/writing_stubs.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guides/writing_stubs.rst b/docs/guides/writing_stubs.rst index 534df53af..605750d08 100644 --- a/docs/guides/writing_stubs.rst +++ b/docs/guides/writing_stubs.rst @@ -786,8 +786,8 @@ When using :ref:`Any`, document the reason for using it in a comment, unless the reason is obvious. Ideally, document what types could be used. Obvious reasons can include: -* Using :ref:`Any` as a type argument for a generic to say "any object of this - type is allowed", e.g. ``type[Any]``. +* Using :ref:`Any` as a type argument for a generic with invariant type variables + to say "any object of this type is allowed", e.g. ``Future[Any]``. * Using ``dict[str, Any]`` or ``Mapping[str, Any]`` when the value types depends on the keys. But consider using :ref:`TypedDict` or ``dict[str, Incomplete]`` (temporarily) when the keys of the dictionary are