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

mypy wrongly resolves super(...).__new__ as object.__new__ #6061

Closed
DarwinAwardWinner opened this issue Dec 12, 2018 · 2 comments
Closed

mypy wrongly resolves super(...).__new__ as object.__new__ #6061

DarwinAwardWinner opened this issue Dec 12, 2018 · 2 comments

Comments

@DarwinAwardWinner
Copy link

In my code I am subclassing int to add an extra attribute, using something like this code:

from typing import Any

class MyInt(int):
    '''Subclass of int with an extra attribute'''
    def __new__(cls: type, value: int, extra_attr: Any) -> 'MyInt':
        # Offending line
        newval = super(MyInt, cls).__new__(cls, value)
        newval.extra_attr = extra_attr
        return newval

    def __repr__(self) -> str:
        return 'MyInt(value={value!r}, extra_attr={extra_attr!r})'.format(
            value=int(self),
            extra_attr=self.extra_attr,
        )

# MyInt should work like an int
x = MyInt(5, "hello")
print(repr(x))
x == 5
x * 2
x + 1

However, mypy doesn't like the call to super(...).__new__:

$ mypy ~/temp/test_mypy.py
temp/test_mypy.py:7: error: Argument 2 for "super" not an instance of argument 1
temp/test_mypy.py:7: error: Too many arguments for "__new__" of "object"
temp/test_mypy.py:14: error: "MyInt" has no attribute "extra_attr"
$ mypy --version
pmypy 0.650
$ python --version
Python 3.7.1

As far as I know, this is the correct way to implement MyInt.__new__, and if I understand correctly, super(MyInt, cls).__new__ should be resolving to int.__new__, not object.__new__.

I believe this is the same bug that was mentioned here and suggested to be reported as a separate issue: #794 (comment)

@JelleZijlstra
Copy link
Member

This is probably a typeshed bug, fixable by adding an implementation of __new__ on the stub for int.

@DarwinAwardWinner
Copy link
Author

Ok, I reported the issue here: python/typeshed#2686

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

2 participants