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

Add Doc from PEP 727: https://peps.python.org/pep-0727/ #277

Merged
merged 18 commits into from Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
@@ -1,5 +1,7 @@
# Release 4.8.0 (???)

- Add `typing_extensions.doc`, as proposed by PEP 727. Patch by
tiangolo marked this conversation as resolved.
Show resolved Hide resolved
Sebastián Ramírez.
- Drop support for Python 3.7 (including PyPy-3.7). Patch by Alex Waygood.
- Fix bug where `get_original_bases()` would return incorrect results when
called on a concrete subclass of a generic class. Patch by Alex Waygood
Expand Down
46 changes: 46 additions & 0 deletions doc/index.rst
Expand Up @@ -616,6 +616,29 @@ Functions

.. versionadded:: 4.2.0

.. function:: doc(documentation)

Define the documentation of a type annotation using :data:`Annotated`, to be
used in class attributes, function and method parameters, return values,
and variables.

The value should be a string literal to allow static tools like editors
to use it.

This complements docstrings.

It returns a :class:`DocInfo` instance containing the documentation value in
the ``documentation`` attribute.

Example::

>>> from typing_extensions import doc, Annotated
>>> def hi(to: Annotated[str, doc("Who to say hi to")]) -> None: ...

.. versionadded:: 4.8.0

See :pep:`727`.

tiangolo marked this conversation as resolved.
Show resolved Hide resolved
.. function:: get_args(tp)

See :py:func:`typing.get_args`. In ``typing`` since 3.8.
Expand Down Expand Up @@ -721,6 +744,29 @@ Functions

.. versionadded:: 4.1.0


Helper classes
tiangolo marked this conversation as resolved.
Show resolved Hide resolved
~~~~~~~~~~~~~~

.. class:: DocInfo(documentation)

Container for documentation information as returned by :func:`doc`.

It is expected this class wouldn't be manually created but instead returned
by :func:`doc` inside of type annotations using :data:`Annotated`.

The ``documentation`` attribute contains the documentation string passed
to :func:`doc`.

.. versionadded:: 4.8.0

See :pep:`727`.

.. attribute:: documentation

The documentation string passed to :func:`doc`.
tiangolo marked this conversation as resolved.
Show resolved Hide resolved


Pure aliases
~~~~~~~~~~~~

Expand Down
36 changes: 36 additions & 0 deletions src/test_typing_extensions.py
Expand Up @@ -38,6 +38,7 @@
from typing_extensions import clear_overloads, get_overloads, overload
from typing_extensions import NamedTuple
from typing_extensions import override, deprecated, Buffer, TypeAliasType, TypeVar, get_protocol_members, is_protocol
from typing_extensions import doc, DocInfo
from _typed_dict_test_helper import Foo, FooGeneric, VeryAnnotated

# Flags used to mark tests that only apply after a specific
Expand Down Expand Up @@ -5895,5 +5896,40 @@ class MyAlias(TypeAliasType):
pass


class DocTests(BaseTestCase):
def test_annotation(self):

def hi(to: Annotated[str, doc("Who to say hi to")]) -> None: pass

hints = get_type_hints(hi, include_extras=True)
doc_info = hints["to"].__metadata__[0]
self.assertEqual(doc_info.documentation, "Who to say hi to")
self.assertIsInstance(doc_info, DocInfo)

def test_repr(self):
doc_info = doc("Who to say hi to")
self.assertEqual(repr(doc_info), "DocInfo('Who to say hi to')")

def test_hashability(self):
doc_info = doc("Who to say hi to")
self.assertIsInstance(hash(doc_info), int)
self.assertNotEqual(hash(doc_info), hash(doc("Who not to say hi to")))

def test_equality(self):
doc_info = doc("Who to say hi to")
# Equal to itself
self.assertEqual(doc_info, doc_info)
# Equal to another instance with the same string
self.assertEqual(doc_info, doc("Who to say hi to"))
# Not equial to another instance with a different string
self.assertNotEqual(doc_info, doc("Who not to say hi to"))

def test_pickle(self):
doc_info = doc("Who to say hi to")
for proto in range(pickle.HIGHEST_PROTOCOL):
pickled = pickle.dumps(doc_info, protocol=proto)
self.assertEqual(doc_info, pickle.loads(pickled))


if __name__ == '__main__':
main()
52 changes: 52 additions & 0 deletions src/typing_extensions.py
Expand Up @@ -60,6 +60,8 @@
'clear_overloads',
'dataclass_transform',
'deprecated',
'doc',
'DocInfo',
'get_overloads',
'final',
'get_args',
Expand Down Expand Up @@ -2810,6 +2812,56 @@ def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]:
return frozenset(_get_protocol_attrs(tp))


if hasattr(typing, "DocInfo"):
DocInfo = typing.DocInfo
else:
class DocInfo:
"""Container for documentation information as returned by ``doc()``.

It is expected this class wouldn't be manually created but instead returned
by ``doc()`` inside of type annotations using ``Annotated``.

The ``documentation`` attribute contains the documentation string passed
to ``doc()``.
"""
def __init__(self, documentation: str) -> None:
self.documentation = documentation

def __repr__(self) -> str:
return f"DocInfo({self.documentation!r})"
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
tiangolo marked this conversation as resolved.
Show resolved Hide resolved

def __hash__(self) -> int:
return hash(self.documentation)

def __eq__(self, other: object) -> bool:
if not isinstance(other, DocInfo):
return NotImplemented
return self.documentation == other.documentation


if hasattr(typing, "doc"):
doc = typing.doc
else:
def doc(documentation: str) -> DocInfo:
"""Define the documentation of a type annotation using ``Annotated``, to be
used in class attributes, function and method parameters, return values,
and variables.

The value should be a string literal to allow static tools like editors
to use it.

This complements docstrings.

It returns a class ``DocInfo`` instance containing the documentation value in
the ``documentation`` attribute.

Example::

>>> from typing_extensions import doc, Annotated
>>> def hi(to: Annotated[str, doc("Who to say hi to")]) -> None: ...
"""
return DocInfo(documentation)
tiangolo marked this conversation as resolved.
Show resolved Hide resolved

# Aliases for items that have always been in typing.
# Explicitly assign these (rather than using `from typing import *` at the top),
# so that we get a CI error if one of these is deleted from typing.py
Expand Down