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

stubtest: get better signatures for __init__ of C classes #18259

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

tungol
Copy link
Contributor

@tungol tungol commented Dec 6, 2024

When an __init__ method has the generic C-class signature, check the underlying class for a better signature.

I was looking at asyncio.futures.Future.__init__ and wanted to take advantage of the better __text_signature__ on asyncio.futures.Future.

The upside is that this clears several allowlist entries and surfaced several other cases where typeshed is currently incorrect, with no false positives.

When an __init__ method has the generic C-class signature,
check the underlying class for a better signature.
mypy/stubtest.py Outdated Show resolved Hide resolved
@tungol
Copy link
Contributor Author

tungol commented Dec 6, 2024

Now handles when runtime.__objclass__ is object instead of skipping those, which clears a couple more allowlist entries in typeshed but didn't surface any new problems to fix.

Technically the implementation of the lookup makes the assumption that the class name is only one element in the object_path list, and will fail for a nested class like modulename.class1.class2.__init__. Those are tricky to look up, and unlikely for something that looks like a C implementation anyway.

@tungol tungol marked this pull request as draft December 6, 2024 23:08
@tungol
Copy link
Contributor Author

tungol commented Dec 7, 2024

While investigating what to do about __new__, I found this issue: python/typeshed#8632

The meaning of which is that this check should not attempt to get a better signature by working around getting passed object.__init__ or object.__new__. Having __init__ in the stubs when we should have __new__ results in this passing type check but being incorrect at runtime:

from __future__ import annotations
from zoneinfo import ZoneInfo

KEY = "America/Los_Angeles"

class Foo(ZoneInfo):
    def __init__(self) -> None:
        super().__init__(KEY)

    def __new__(cls) -> Foo:
        return super().__new__(cls)

Foo()
Traceback (most recent call last):
  File "temp.py", line 13, in <module>
    Foo()
    ~~~^^
  File "temp.py", line 11, in __new__
    return super().__new__(cls)
           ~~~~~~~~~~~~~~~^^^^^
TypeError: ZoneInfo() missing required argument 'key' (pos 1)

While this is correct at runtime but fails type check:

from __future__ import annotations
from zoneinfo import ZoneInfo

KEY = "America/Los_Angeles"

class Foo(ZoneInfo):
    def __init__(self) -> None:
        super().__init__()  # error: Missing positional argument "key" in call to "__init__" of "ZoneInfo"  [call-arg]

    def __new__(cls) -> Foo:
        return super().__new__(cls, KEY)  # error: Too many arguments for "__new__" of "object"  [call-arg]

Foo()

This is good, actually, because it means that this check is a lot simpler, and I don't have to worry about duplicating __init__ and __new__; I just need to follow the runtime.

@tungol
Copy link
Contributor Author

tungol commented Dec 7, 2024

I'm working through the errors flagged this way. A couple things that are coming up:

  • Some classes have both a __init__ and a __new__ that are custom to that class. Without additional work, this check will prompt both to be created in the stubs - I think that's probably okay.

  • Overloads and positionals

a function like def (arg, /) -> None errors if you try to add self to the start and it's POSITIONAL_OR_KEYWORD, so I check for "first argument is positional only") and add self as positional only if that's the case. However, a bunch of these have overload stubs like:

@overload
def __init__(self) -> None: ...
@overload
def __init__(self, arg, /) -> None: ...

And it's causing stubtest to prompt to make the first overload positional-only, and normally typeshed wouldn't do that.

  • More complicated overloads

We also have overloads where the runtime definition is def __init__(self, *args) -> None: ...
and the stub makes an overload that breaks this out into a bunch individually typed parameters. itertools.product and builtins.zip are the gnarliest ones. These want a positional-only self or cls as well, since the stubs end up positional-only. Those two are also producing overload stub signatures that are also just hot nonsense.

This is from builtins.zip.__new__:

Inferred signature: def (cls: type[builtins.zip[_T_co`1]] = ..., cls: type[builtins.zip[_T_co`1]] = ..., iter1: Union[typing.Iterable[_T1`-1], typing.Iterable[_T1`-1], typing.Iterable[_T1`-1], typing.Iterable[_T1`-1], typing.Iterable[_T1`-1], typing.Iterable[Any]] = ..., iter2: Union[typing.Iterable[_T2`-2], typing.Iterable[_T2`-2], typing.Iterable[_T2`-2], typing.Iterable[_T2`-2], typing.Iterable[Any]] = ..., iter3: Union[typing.Iterable[_T3`-3], typing.Iterable[_T3`-3], typing.Iterable[_T3`-3], typing.Iterable[Any]] = ..., iter4: Union[typing.Iterable[_T4`-4], typing.Iterable[_T4`-4], typing.Iterable[Any]] = ..., iter5: Union[typing.Iterable[_T5`-5], typing.Iterable[Any]] = ..., iter6: typing.Iterable[Any] = ..., *iterables, strict: builtins.bool = ...)
Runtime:
def (cls, /, *iterables, strict=False)

Inferred signature with multiple copies of cls, cls with default values, etc. It's real bad, and that's not code that I've touched in this MR, it's just that we never actually ran a comparison between it and runtime before.

@tungol
Copy link
Contributor Author

tungol commented Dec 7, 2024

I worked out the issues. "self" was special cased in two places, and I needed to add special-casing in the same way for "cls" to deal with the sudden glut of complicated overloaded __new__ methods. Once I did that, all the troublesome bits went away.

I pushed up the fixes that this MR surfaced to python/typeshed#13211 but pyright is unhappy with some of them, so I need to work through that still.

@tungol
Copy link
Contributor Author

tungol commented Dec 7, 2024

I think this is basically good now. See python/typeshed#13211 for the changes that this suggests for the stdlib stubs. Some tests would be good still.

@tungol tungol marked this pull request as ready for review December 7, 2024 12:43
@tungol
Copy link
Contributor Author

tungol commented Dec 8, 2024

Having looked at how stubtest tests are run, I'm not sure if I can create a test for this? I can't see a way to mimic a C-implemented class as a test case in teststubtest.py.

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