GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Believe more __new__ return types by hauntsaninja · Pull Request #16020 · python/mypy

Conversation

@hauntsaninja

@hauntsaninja hauntsaninja commented Sep 2, 2023 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Collaborator

Fixes #1020 (comment) Surprisingly popular comment on a closed issue.

We still issue the warning, but we do trust the return type instead of overruling it.

Fixes #14471. Fixes #8330.
We avoid fixing #15182 for now.

Co-authored-by: ikonst

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

stinodego, Viicos, wahuneke, brycedrennan, Hnasar, gschaffner, hoodmane, Avasam, and randolf-scholz reacted with thumbs up emoji fofoni, Avasam, and randolf-scholz reacted with hooray emoji
All reactions
  • 👍 9 reactions
  • 🎉 3 reactions
@hauntsaninja
Believe arbitrary __new__ return types
4616fa2
Fixes python#1020 (comment)
Surprisingly popular comment on a closed issue.

We still issue the warning, but we do trust the return type instead of
overruling it.

Maybe fixes python#16012
@github-actions

This comment has been minimized.

Sign in to view
hauntsaninja added 2 commits September 2, 2023 02:46
@hauntsaninja
changes
e2d3a5e
@hauntsaninja
more changes
2bd91d5
@hauntsaninja hauntsaninja changed the title Believe arbitrary __new__ return types Believe more __new__ return types Sep 2, 2023
@github-actions

This comment has been minimized.

Sign in to view
@hauntsaninja

hauntsaninja commented Sep 2, 2023

Copy link
Copy Markdown
Collaborator Author

There's an issue where we turn TypeType's into CallableType, but the type_obj of CallableType just looks at the return type of the constructor. So this doesn't work as expected:

class A:
    def __new__(cls) -> int: raise

class B(A):
    @classmethod
    def foo(cls) -> int: raise

reveal_type(B.foo())
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@hauntsaninja
hauntsaninja force-pushed the abide-by-new branch from 61b6476 to 25c9ef0 Compare September 4, 2023 01:13
@github-actions

This comment has been minimized.

Sign in to view
@hauntsaninja
hauntsaninja force-pushed the abide-by-new branch from 25c9ef0 to 5b791f7 Compare September 4, 2023 01:36
@hauntsaninja
hacks
393b303
@hauntsaninja
hauntsaninja force-pushed the abide-by-new branch from 5b791f7 to 393b303 Compare September 4, 2023 01:49
@hauntsaninja
fix instantiate
7b7d76d
@github-actions

This comment has been minimized.

Sign in to view
@hauntsaninja
hauntsaninja marked this pull request as ready for review September 4, 2023 02:44
@Viicos

Viicos commented Sep 4, 2023

Copy link
Copy Markdown
Contributor

Thanks so much @hauntsaninja, couldn't get this far due to limited knowledge of the mypy internals

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@hauntsaninja
clarify comment
aa5df74
@github-actions

This comment has been minimized.

Sign in to view
@hauntsaninja
hauntsaninja requested a review from ilevkivskyi September 5, 2023 00:10
ikonst
ikonst reviewed Sep 5, 2023
View reviewed changes
Comment thread mypy/checkmember.py Outdated
# The following is a hack. mypy often represents types as CallableType, where the signature of
# CallableType is determined by __new__ or __init__ of the type (this logic is in
# type_object_type). Then if we ever need the TypeInfo or an instance of the type, we fish
# around for the return type in CallableType.type_object. Unfortunately, this is incorrect if

@ikonst ikonst Sep 5, 2023

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

we fish around for the return type in CallableType.type_object

Where do we do this? This function certainly didn't, going for simple .ret_type

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@hauntsaninja hauntsaninja Sep 5, 2023

Copy link
Copy Markdown
Collaborator Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

I clarified the comment a little bit. type_object also just uses ret_type. Also, thanks for the suggestion to use bound_args, I added you as a co-author of this PR!

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@hauntsaninja
clarify comment
59a5aee
@github-actions

This comment has been minimized.

Sign in to view
ikonst
ikonst reviewed Sep 5, 2023
View reviewed changes
Comment thread mypy/checkmember.py
# see e.g. testGenericClassMethodUnboundOnClass. So just copy them over to our type.
# This does the wrong thing with custom __new__, see testNewReturnType15, but is
# no worse than previous behaviour.
ret_type = bound_arg.copy_modified(args=ret_type.args)

@ikonst ikonst Sep 5, 2023 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

Maybe you can

Suggested change
ret_type = bound_arg.copy_modified(args=ret_type.args)
ret_type = bound_arg.copy_modified()

if you change checkexpr.py's apply_generic_arguments to expand bound_args (not sure if it's correct to do...):

 return callable.copy_modified(
     ret_type=expand_type(callable.ret_type, id_to_type),
+    bound_args=[
+        expand_type(ba, id_to_type) if ba is not None else None
+        for ba in callable.bound_args
+    ],
     variables=remaining_tvars,
     type_guard=type_guard,
 )

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@hauntsaninja hauntsaninja mentioned this pull request Sep 5, 2023
Remove pathlib.PurePath.__eq__ python/typeshed#10662
Merged
ilevkivskyi
ilevkivskyi reviewed Sep 6, 2023
View reviewed changes

@ilevkivskyi ilevkivskyi left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

TBH I don't like this. This introduces some hack(s) that can backfire unexpectedly in "regular" cases to support a truly weird (even if somewhat common) use case.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@hauntsaninja

hauntsaninja commented Sep 6, 2023 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Collaborator Author

Yeah, it's a little icky :-( I'm curious what "regular" cases you think this makes problematic? I do think it's something we should support, so would like to find a way forward. E.g. it came up again yesterday in python/typeshed#10662 (comment)

I'd also definitely be open to removing this back compat hack https://github.com/python/mypy/pull/16020/files#diff-1dce7e2a19559e2ff4e08fd46877b87c9cfec3cb5e6d465157788542948e11e4R206-R208 . It does result in a few mypy_primer hits, but they're technically correct.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ilevkivskyi

ilevkivskyi commented Sep 6, 2023

Copy link
Copy Markdown
Member

I'm curious what "regular" cases you think this makes problematic?

I think various operations with class objects, like type applications, subtyping/inference against them, member access on them etc. Also TBH I don't even remember why do we need bound_args, but I will not be surprised if various default visitors don't handle them correctly (because they are so rarely used). So relying on some important information being stored there if quite dangerous.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@ikonst

ikonst commented Sep 6, 2023 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

I'd also rather have the type in a specialized attribute than bound_args[0]. Maintenance-wise it's cheaper to add another attribute than to add semantics to bound_args[0].

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@Viicos Viicos mentioned this pull request Sep 11, 2023
Fix typing of reversed python/typeshed#10655
Merged
@Daverball Daverball mentioned this pull request Sep 23, 2023
Add stubs for WTForms python/typeshed#10557
Merged
@Viicos Viicos mentioned this pull request Oct 12, 2023
feat: Add basic typing support FactoryBoy/factory_boy#903
Closed
@Viicos

Viicos commented Oct 13, 2023 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Do you think the following use case with generics will be supported?

from typing import Generic, TypeVar

T = TypeVar("T")

class A(Generic[T]):
   # Having `T` returned at runtime would only be possible with a metaclass.
   # This is a hack that should most probably be in an `if TYPE_CHECKING` block
   # To describe the runtime behaviour of the metaclass' `__call__` method for example.  
    def __new__(cls, *args, **kwargs) -> T:
        ...

class Model:
    pass

reveal_type(A[Model]())  # Type of "A[Model]()" is "Model"

class B(A[Model]):
    pass

reveal_type(B())  # Type of "B()" is "Model"

This is a workaround for FactoryBoy/factory_boy#903 (comment), and could probably be used for any situation where we want to take into account the return type of __call__ (#14122).

pyright supports it.

insilications, finite-state-machine, and sveinugu reacted with heart emoji
All reactions
  • ❤️ 3 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

JukkaL
JukkaL reviewed Oct 24, 2023
View reviewed changes
Comment thread mypy/checkmember.py
# if __new__ returns an unrelated type, but we can kind of salvage things here using
# CallableType.bound_args
self_type: Type = typ
if len(item.bound_args) == 1 and item.bound_args[0]:

@JukkaL JukkaL Oct 24, 2023

Copy link
Copy Markdown
Collaborator

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

I agree with other comments that using bound_args doesn't look like something we want to do. I think storing the real self type in a new attribute might be a better approach. All type operations should be updated to do something reasonable with the attribute.

It seems like the above should also fix the issue that no error is currently reported here, and perhaps other related issues:

class C:
    def __new__(self) -> D:
        return D()

class D(C):
    x: int

C.x  # No Error, but fails at runtime

We'd use use the new attribute when looking up class attributes.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@hauntsaninja hauntsaninja mentioned this pull request Nov 12, 2023
Meta issue tracker, pt 2 #16472
Open
@Viicos Viicos mentioned this pull request Dec 20, 2023
Honor return type of __new__ even if not a subclass #15182
Closed
@willwill2will54

willwill2will54 commented May 30, 2024

Copy link
Copy Markdown

I appreciate this PR. It helps correctly type the dominate library, which currently cannot be correctly typed for some of it's API.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@JelleZijlstra
Merge branch 'master' into abide-by-new
cdccffa
@github-actions

github-actions Bot commented Jul 5, 2024

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

dd-trace-py (https://github.com/DataDog/dd-trace-py)
+ ddtrace/propagation/http.py:1059: error: Unused "type: ignore" comment  [unused-ignore]
+ ddtrace/propagation/http.py:1061: error: Argument 2 to "_attach_baggage_to_context" has incompatible type "None"; expected "Context"  [arg-type]
+ ddtrace/propagation/http.py:1062: error: Incompatible return value type (got "None", expected "Context")  [return-value]

steam.py (https://github.com/Gobot1234/steam.py)
- steam/client.py:1321: error: Invalid self argument "type[TradeOffer[Any, Any, Any]]" to attribute function "_from_history" with type "Callable[[type[TradeOffer[MovedItem[UserT], MovedItem[ClientUser], UserT]], ConnectionState, TradeOfferHistoryTrade, Sequence[Description]], TradeOffer[MovedItem[UserT], MovedItem[ClientUser], UserT]]"  [misc]
+ steam/client.py:1321: error: Invalid self argument "type[TradeOffer[ReceivingAssetT, SendingAssetT, UserT]]" to attribute function "_from_history" with type "Callable[[type[TradeOffer[MovedItem[UserT], MovedItem[ClientUser], UserT]], ConnectionState, TradeOfferHistoryTrade, Sequence[Description]], TradeOffer[MovedItem[UserT], MovedItem[ClientUser], UserT]]"  [misc]

pandera (https://github.com/pandera-dev/pandera)
+ pandera/api/dataframe/model.py:395: error: "type[DataFrameBase[Any]]" has no attribute "Config"  [attr-defined]
+ tests/strategies/test_strategies.py:996: error: Need type annotation for "sample_data"  [var-annotated]
+ tests/dask/test_dask.py:30: error: Need type annotation for "ddf"  [var-annotated]
+ tests/dask/test_dask.py:30: note: Error code "var-annotated" not covered by "type: ignore" comment
+ tests/dask/test_dask.py:33: error: Need type annotation for "ddf"  [var-annotated]
+ tests/dask/test_dask.py:33: note: Error code "var-annotated" not covered by "type: ignore" comment
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jorenham

jorenham commented Jul 8, 2024

Copy link
Copy Markdown
Contributor

@hauntsaninja Perhaps you're already aware, but the official typing specs have a section on the __new__ method nowadays.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@Viicos

Viicos commented Jul 8, 2024

Copy link
Copy Markdown
Contributor

This new spec chapter is pretty complex, I don't know how much of it is being already implemented in mypy (e.g. #14122 is not). Perhaps this PR could be considered as a quick win?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jorenham

jorenham commented Jul 8, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

I agree @Viicos; all progress towards compatibility with the typing spec is a win.

The reason I mentioned it is that if one is unaware of it; there's a chance of deviating away from it.
But don't get me wrong; I'm not suggesting that that's necessarily the case here, as I'm not too familiar with the mypy codebase (or its current state w.r.t. the typing spec).

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@JelleZijlstra

JelleZijlstra commented Jul 8, 2024

Copy link
Copy Markdown
Member

You can be assured that @hauntsaninja is aware of the spec change; he signed off on it after all (python/typing-council#25) :)

Fully implementing that spec change in mypy will be more work but this PR seems like a step in the right direction, so hopefully we'll be able to get it ready to merge soon.

jorenham and Hnasar reacted with thumbs up emoji
All reactions
  • 👍 2 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@randolf-scholz randolf-scholz mentioned this pull request Nov 1, 2024
[Experiment] Add more precise overloads for bool.__new__. python/typeshed#12940
Closed
@alessiamarcolini

alessiamarcolini commented Nov 18, 2024

Copy link
Copy Markdown

Hi @JelleZijlstra is there an update on the status of this PR? 🙏

PedroPerpetua reacted with heart emoji
All reactions
  • ❤️ 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@Viicos Viicos mentioned this pull request Apr 1, 2025
Incompatible type with many=True typeddjango/djangorestframework-stubs#260
Open
@randolf-scholz randolf-scholz mentioned this pull request Oct 28, 2025
added type annotation to _NoParamDecoratorContextManager.__new__ pytorch/pytorch#166414
Closed
@ilevkivskyi ilevkivskyi mentioned this pull request May 8, 2026
Respect explicit return type of __new__() #21441
Merged
@ilevkivskyi ilevkivskyi closed this in #21441 May 27, 2026
pull Bot pushed a commit to LadyK-21/mypy that referenced this pull request May 27, 2026
@ilevkivskyi
Respect explicit return type of __new__() (python#21441)
938dbe2
Fixes python#8330
Fixes python#15182
Closes python#16020
Closes python#14471
Fixes python#13824
Fixes python#14502

With this PR will still give an error if the explicit return `__new__()`
is not a subtype of current class, but now we will actually use it.
There are _two exceptions_ (to preserve backwards compatibility):
* If the return type is `Any` with still use current class as the return
type.
* If the explicit return type comes from a superclass and is a supertype
of implicit return type.

```python
class A:
    def __new__(cls): ...
reveal_type(A())  # still __main__.A

class B:
    def __new__(cls) -> B:
        return cls()
class C(B): ...
reveal_type(C())  # still __main__.C
```

This uses a more principled implementation than some earlier attempts:
adding a new dedicated attribute to `CallableType` for this purpose.
Some comments:
* This PR has a bit for boilerplate, but this is expected. When adding a
new attribute to a type, one needs to update most visitors.
* While doing the above I noticed that `CallableType.type_guard` and
`CallableType.type_is` were not handled in dependency visitors (neither
coarse-grained nor fine-grained). IMO they definitely should be handled
there, so I now handle them.
* I try to reduce the size of `CallableType` a bit to compensate for new
attribute by removing (rarely used) `min_args` attribute. I also use
compact flags serialization.
* I skimmed the code base and updated all places where we "casually" use
`CallableType.ret_type` for various type object edge cases.
* Note that I don't assert that `instance_type` is set when
`is_type_obj()` returns `True`. This is mostly to avoid breaking 3rd
party plugins.
* I didn't add a test case for each edge case, but I added (improved)
test cases from python#16020 plus some
more. Suggestions for more test cases are welcome.
* It looks like this exposes a pre-existing bug where we leaked type
variables in `type[T]`. It is relatively niche edge case, but it looks
important for NumPy stubs, so I am trying to fix it here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@JukkaL JukkaL JukkaL left review comments
@ilevkivskyi ilevkivskyi ilevkivskyi left review comments
+1 more reviewer
@ikonst ikonst ikonst left review comments
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Respecting return type of __new__ does not extend to derived classes Honor return type of __new__

Uh oh!

There was an error while loading. Please reload this page.

9 participants

@hauntsaninja @Viicos @ilevkivskyi @ikonst @willwill2will54 @jorenham @JelleZijlstra @alessiamarcolini @JukkaL
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.