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

overloading __new__ #421

Closed
Rouslan opened this issue May 2, 2017 · 2 comments
Closed

overloading __new__ #421

Rouslan opened this issue May 2, 2017 · 2 comments

Comments

@Rouslan
Copy link

Rouslan commented May 2, 2017

I propose allowing the use of @overload on __new__ to specify the return type. E.g.:

T = TypeVar('T')

class MyClass(Generic[T]):
    @overload
    def __new__(cls,val: str) -> 'MyClass[int]':
        pass
    @overload
    def __new__(cls,val: int) -> int:
        pass
           
    def __new__(cls,val):
        if isinstance(val,int):
            return val
        r = super().__init__(cls)
        if isinstance(val,str):
            r.val = int(val)
        r.val = val
        return r

This is useful on its own, but if @overload is allowed to have return types that only differ by the generic type argument (e.g. MyClass[int] vs MyClass[str]), then this would also supersede issue #307 and allow more complicated type argument deduction.

@gvanrossum
Copy link
Member

This sounds like something to be filed in the mypy tracker. What's a realistic use case for allowing __new__ to return something that's not an instance of the containing class?

@ilevkivskyi
Copy link
Member

What's a realistic use case for allowing __new__ to return something that's not an instance of the containing class?

To be fair typing uses this few times :-) but I agree this is quite esoteric, and this feature proposal belongs to https://github.com/python/mypy/issues

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

No branches or pull requests

3 participants