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

Rename TypeExpr to TypeForm #475

Merged
merged 4 commits into from
Sep 28, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Unreleased

- Add `typing_extensions.TypeExpr` from PEP 747. Patch by
- Add `typing_extensions.TypeForm` from PEP 747. Patch by
Jelle Zijlstra.
- Add `typing_extensions.get_annotations`, a backport of
`inspect.get_annotations` that adds features specified
Expand Down
2 changes: 1 addition & 1 deletion doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ Special typing primitives

.. versionadded:: 4.6.0

.. data:: TypeExpr
.. data:: TypeForm

See :pep:`747`. A type hint representing a type expression.

Expand Down
46 changes: 23 additions & 23 deletions src/test_typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
TypeAlias,
TypeAliasType,
TypedDict,
TypeExpr,
TypeForm,
TypeGuard,
TypeIs,
TypeVar,
Expand Down Expand Up @@ -5508,33 +5508,33 @@ def test_no_isinstance(self):
issubclass(int, TypeIs)


class TypeExprTests(BaseTestCase):
class TypeFormTests(BaseTestCase):
def test_basics(self):
TypeExpr[int] # OK
self.assertEqual(TypeExpr[int], TypeExpr[int])
TypeForm[int] # OK
self.assertEqual(TypeForm[int], TypeForm[int])

def foo(arg) -> TypeExpr[int]: ...
self.assertEqual(gth(foo), {'return': TypeExpr[int]})
def foo(arg) -> TypeForm[int]: ...
self.assertEqual(gth(foo), {'return': TypeForm[int]})

def test_repr(self):
if hasattr(typing, 'TypeExpr'):
if hasattr(typing, 'TypeForm'):
mod_name = 'typing'
else:
mod_name = 'typing_extensions'
self.assertEqual(repr(TypeExpr), f'{mod_name}.TypeExpr')
cv = TypeExpr[int]
self.assertEqual(repr(cv), f'{mod_name}.TypeExpr[int]')
cv = TypeExpr[Employee]
self.assertEqual(repr(cv), f'{mod_name}.TypeExpr[{__name__}.Employee]')
cv = TypeExpr[Tuple[int]]
self.assertEqual(repr(cv), f'{mod_name}.TypeExpr[typing.Tuple[int]]')
self.assertEqual(repr(TypeForm), f'{mod_name}.TypeForm')
cv = TypeForm[int]
self.assertEqual(repr(cv), f'{mod_name}.TypeForm[int]')
cv = TypeForm[Employee]
self.assertEqual(repr(cv), f'{mod_name}.TypeForm[{__name__}.Employee]')
cv = TypeForm[Tuple[int]]
self.assertEqual(repr(cv), f'{mod_name}.TypeForm[typing.Tuple[int]]')

def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class C(type(TypeExpr)):
class C(type(TypeForm)):
pass
with self.assertRaises(TypeError):
class D(type(TypeExpr[int])):
class D(type(TypeForm[int])):
pass

def test_call(self):
Expand All @@ -5546,24 +5546,24 @@ def test_call(self):
]
for obj in objs:
with self.subTest(obj=obj):
self.assertIs(TypeExpr(obj), obj)
self.assertIs(TypeForm(obj), obj)

with self.assertRaises(TypeError):
TypeExpr()
TypeForm()
with self.assertRaises(TypeError):
TypeExpr("too", "many")
TypeForm("too", "many")

def test_cannot_init_type(self):
with self.assertRaises(TypeError):
type(TypeExpr)()
type(TypeForm)()
with self.assertRaises(TypeError):
type(TypeExpr[Optional[int]])()
type(TypeForm[Optional[int]])()

def test_no_isinstance(self):
with self.assertRaises(TypeError):
isinstance(1, TypeExpr[int])
isinstance(1, TypeForm[int])
with self.assertRaises(TypeError):
issubclass(int, TypeExpr)
issubclass(int, TypeForm)


class LiteralStringTests(BaseTestCase):
Expand Down
40 changes: 25 additions & 15 deletions src/typing_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
'Text',
'TypeAlias',
'TypeAliasType',
'TypeExpr',
'TypeForm',
'TypeGuard',
'TypeIs',
'TYPE_CHECKING',
Expand Down Expand Up @@ -2047,23 +2047,28 @@ def f(val: Union[int, Awaitable[int]]) -> int:
""")

# 3.14+?
if hasattr(typing, 'TypeExpr'):
TypeExpr = typing.TypeExpr
if hasattr(typing, 'TypeForm'):
TypeForm = typing.TypeForm
# 3.9
elif sys.version_info[:2] >= (3, 9):
class _TypeExprForm(_ExtensionsSpecialForm, _root=True):
# TypeExpr(X) is equivalent to X but indicates to the type checker
# that the object is a TypeExpr.
class _TypeFormForm(_ExtensionsSpecialForm, _root=True):
# TypeForm(X) is equivalent to X but indicates to the type checker
# that the object is a TypeForm.
def __call__(self, obj, /):
return obj

@_TypeExprForm
def TypeExpr(self, parameters):
"""Special typing form used to represent a type expression.
@_TypeFormForm
def TypeForm(self, parameters):
"""A special typing construct to represent valid type expressions.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This phrasing is subtly confusing in the same way that earlier drafts of the PEP were. A TypeForm doesn't represent a type expression. It represents the set of runtime objects that encode the information in a type expression. This is the reason we moved away from the TypeExpr terminology. I recommend using the phrasing from the latest draft of the PEP. I tried hard to make that phrasing as clear as possible to avoid such confusion.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I rewrote the docstring to align with the Specification section of PEP 747.


Expressions are assignable to TypeForm if they represent valid type
expressions. For example, ``int`` is assignable to ``TypeForm`` (because
``int``, as a type, is a valid type expression), but ``1`` is not (because
integers are not valid type expressions).

Usage:

def cast[T](typ: TypeExpr[T], value: Any) -> T: ...
def cast[T](typ: TypeForm[T], value: Any) -> T: ...

reveal_type(cast(int, "x")) # int

Expand All @@ -2073,7 +2078,7 @@ def cast[T](typ: TypeExpr[T], value: Any) -> T: ...
return typing._GenericAlias(self, (item,))
# 3.8
else:
class _TypeExprForm(_ExtensionsSpecialForm, _root=True):
class _TypeFormForm(_ExtensionsSpecialForm, _root=True):
def __getitem__(self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts only a single type')
Expand All @@ -2082,13 +2087,18 @@ def __getitem__(self, parameters):
def __call__(self, obj, /):
return obj

TypeExpr = _TypeExprForm(
'TypeExpr',
doc="""Special typing form used to represent a type expression.
TypeForm = _TypeFormForm(
'TypeForm',
doc="""A special typing construct to represent valid type expressions.

Expressions are assignable to TypeForm if they represent valid type
expressions. For example, ``int`` is assignable to ``TypeForm`` (because
``int``, as a type, is a valid type expression), but ``1`` is not (because
integers are not valid type expressions).

Usage:

def cast[T](typ: TypeExpr[T], value: Any) -> T: ...
def cast[T](typ: TypeForm[T], value: Any) -> T: ...

reveal_type(cast(int, "x")) # int

Expand Down
Loading