Draft typing spec chapter for constructors

Creating type stubs for a library is a tall ask for 99% of pylance’s 12M+ users. I don’t think that’s an acceptable answer.

There is precedent for this. Type checkers treat unannotated class and function decorators as having no effect on the decorated function. That makes sense because it’s a reasonable (and correct) assumption the vast majority of the time. Treating unannotated decorators as though they return Any and asking users to “write your own stubs if you want this to work” would be a big step backward in terms of usability. I see the metaclass __call__ case as similar. If a library author is going to do something extremely nonstandard, let’s put the onus on them to provide a non-Any return type annotation.

2 Likes

I feel like my ideal behavior (for both __call__ and __new__) would look something like:

  • no return type annotation: assume an instance of the class is returned
  • if annotated to return anything other than an instance of the class (including Any): something special is being done, don’t evaluate subsequent constructor methods

I agree with Eric’s point that this isn’t the time to try to introduce a full-blown Unknown type, but what about specifically special-casing constructor methods to have an assumed return type annotation when they’re left unannotated?

3 Likes

Thanks @rchen152, I think your suggestion strikes a good balance. I’m OK with carving out that special case for __call__ and __new__.

@Jelle, what do you think?

I’m fine with special-casing just unannotated methods. That also aligns with pyright’s behavior with class decorators (Pyright Playground).

I’ve updated the proposed spec to incorporate @rchen152’s suggestion. Please review and add comments if you think it’s unclear or I missed any important points.

Added draft chapter to typing spec for constructors. by erictraut · Pull Request #1667 · python/typing (github.com)

The typing council has signed off on this change, and it has been incorporated into the typing spec.

Thanks to everyone who contributed to the discussion!

2 Likes