Skip to content

support defaults for typing.TypeVar and typing.TypeVarTuple#1318

Open
WKarel wants to merge 3 commits into
wjakob:masterfrom
WKarel:typing-typevar-defaults
Open

support defaults for typing.TypeVar and typing.TypeVarTuple#1318
WKarel wants to merge 3 commits into
wjakob:masterfrom
WKarel:typing-typevar-defaults

Conversation

@WKarel
Copy link
Copy Markdown
Contributor

@WKarel WKarel commented Mar 27, 2026

Python-3.13 added optional defaults for typing.TypeVar and typing.TypeVarTuple. This PR makes stubGen.py document the defaults in stub files.

Tests fine with Python-3.14, and with test_typing.cpp containing

m.attr("T4") = nb::type_var("T4", "bound"_a = nb::builtins()["int"], "default"_a = nb::typing().attr("Literal")[1]);
m.attr("T5") = nb::type_var_tuple(
    "T5", "default"_a = nb::typing().attr("Unpack")[nb::builtins()["tuple"][nb::make_tuple(nb::type<Foo>(), nb::ellipsis())]]);

, and test_typing_ext.pyi containing

T4 = TypeVar("T4", bound=int, default=Literal[1])

T5 = TypeVarTuple("T5", default=Unpack[tuple[Foo, ...]])

But the CI runs stub tests on Python-3.10+, and doing the comparisons correctly for versions below 3.13 seems too complicated.

@wjakob
Copy link
Copy Markdown
Owner

wjakob commented Mar 28, 2026

To consider this for merging, it will need some test coverage..

Comment thread tests/test_stubs.py
s_ref.insert(5, "")
s_ref.insert(6, "from typing_extensions import CapsuleType")

if "test_typing_ext" in p_in.name and sys.version_info < (3, 13):
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

This seems quite complicated/fragile

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Depending on the Python version to be tested, up to 2 names less are imported from the typing-module, crossing stubGen.py's threshold for the maximum line length. Hence, the import-statement is either a one-liner, or it spreads across multiple lines (see my initial comment about this being too complicated to be tested). The test code thus copy/pastes stubGen.py's generation of import statements, which is ready for future changes in the number of names imported from the typing-module. But it will break in case of relevant changes of stubGen.py. An alternative would be to hard-code the resp. import-statement for different Python versions, but that seems more fragile to me. Suggestions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants