Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Inconsistencies between __init__ and __new__ #6905

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

Closed
erictraut opened this issue Jan 12, 2022 · 3 comments · Fixed by #8072
Closed

Inconsistencies between __init__ and __new__ #6905

erictraut opened this issue Jan 12, 2022 · 3 comments · Fixed by #8072

Comments

@erictraut
Copy link
Contributor

I just implemented a new check in pyright called reportInconsistentConstructor that detects inconsistencies between the __init__ and __new__ methods. It's disabled by default but can be enabled in the configuration. It's in pyright 1.1.207, which I just published.

The check is pretty conservative, but it does identify three places in typeshed that look like legitimate problems.

  1. The class WeakMethod in weakref.pyi defines a __new__ that is incompatible with the __init__ declared in its parent class ReferenceType.
  2. The class _TokenType in pygments/token.pyi defines an __init__ that is incompatible with the __new__ in tuple[str].
  3. The class CascadeOptions in SQLAlchemy/sqlalchemy/orm/util.pyi defines a __new__ that is incompatible with the __init__ in its parent class frozenset[Any].

If/when these are addressed, we might want to update pyright to 1.1.207 and enable the new diagnostic check to prevent future inconsistencies from being introduced.

@Akuli
Copy link
Collaborator

Akuli commented Jan 13, 2022

For problem 2, I think we should just delete _TokenType.__init__. You aren't supposed to instantiate _TokenType yourself anyway.

The implementation is:

class _TokenType(tuple):
    ...
    def __init__(self, *args):
        # no need to call super.__init__
        self.subtypes = set()

@srittau
Copy link
Collaborator

srittau commented Jan 14, 2022

Sounds like a good plan.

@AlexWaygood
Copy link
Member

Relatedly (but slightly tangentially), can anybody explain to me why classmethod.__new__ and classmethod.__init__ have different signatures in builtins? I've never really understood why, and there's no comment clarifying it:

def __init__(self: staticmethod[_R], __f: Callable[..., _R]) -> None: ...
def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ...

(Same issue for staticmethod.)

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 a pull request may close this issue.

4 participants