Skip to content

Commit

Permalink
Make type stubs generated on Python 3.13 backwards compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
freider committed Oct 31, 2024
1 parent 41c59b1 commit 03f5201
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
5 changes: 5 additions & 0 deletions src/synchronicity/type_stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -733,10 +733,15 @@ def _formatannotation(self, annotation, base_module=None) -> str:
# e.g. first argument to typing.Callable
subargs = ",".join([self._formatannotation(arg) for arg in annotation])
return f"[{subargs}]"

return repr(annotation)

# generic:
origin_name = get_specific_generic_name(annotation)
if origin is contextlib.AbstractAsyncContextManager:
# python 3.13 adds a second optional exit arg, we only want to emit the first one
# to be backwards compatible
args = args[:1]

if (safe_get_module(annotation), origin_name) == ("typing", "Optional"):
# typing.Optional adds a None argument that we shouldn't include when formatting
Expand Down
9 changes: 3 additions & 6 deletions test/type_stub_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,12 +283,9 @@ async def _get_foo(foo: _Foo) -> typing.AsyncContextManager[_Foo]:
print(src)
assert "class __get_foo_spec(typing_extensions.Protocol):" in src
assert " def __call__(self, foo: Foo) -> synchronicity.combined_types.AsyncAndBlockingContextManager[Foo]" in src
if sys.version_info < (3, 13):
expected_original_repr = "typing.AsyncContextManager[Foo]"
else:
# python 3.13 has an exit type generic argument to context managers
expected_original_repr = "typing.AsyncContextManager[Foo, bool | None]"
assert f" async def aio(self, foo: Foo) -> {expected_original_repr}" in src
# python 3.13 has an exit type generic argument, e.g. typing.AsyncContextManager[Foo, bool | None]
# but we want the type stubs to work on older versions of python too (without conditionals everywhere):
assert " async def aio(self, foo: Foo) -> typing.AsyncContextManager[Foo]" in src
assert "get_foo: __get_foo_spec"


Expand Down

0 comments on commit 03f5201

Please sign in to comment.