Skip to content

Switch to typing_extensions.Self for __new__ implementations#259

Open
bigfootjon wants to merge 1 commit intographql-python:mainfrom
bigfootjon:fix-self-type
Open

Switch to typing_extensions.Self for __new__ implementations#259
bigfootjon wants to merge 1 commit intographql-python:mainfrom
bigfootjon:fix-self-type

Conversation

@bigfootjon
Copy link

@bigfootjon bigfootjon commented Feb 28, 2026

I noticed that when running with https://pyrefly.org/ I get type errors on things like:

from graphql import GraphQLEnumType

def get_enum() -> GraphQLEnumType:
  return GraphQLEnumType()

This occurs because the __new__ function for GraphQLNamedType returns GraphQLNamedType (i.e. that exact class) instead of Self which automatically infers the actual class (e.g. GraphQLEnumType in this case).

I used the typing_extensions version because AIUI this project supports versions of python from before Self was introduced, and I also fixed the other __new__ function that returns a type while I was fixing the problem I was seeing.

@bigfootjon bigfootjon requested a review from Cito as a code owner February 28, 2026 19:56
@leszekhanusz
Copy link

leszekhanusz commented Feb 28, 2026

In gql, we are importing Self like this:

import sys
if sys.version_info >= (3, 11):
    from typing import Self  # pragma: no cover
else:
    from typing_extensions import Self  # pragma: no cover

I think it makes it easier for the maintainer to know when we can avoid using typing_extensions when we remove the support for an old Python version.

Copy link
Member

@Cito Cito left a comment

Choose a reason for hiding this comment

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

Thank you @bigfootjon, this makes sense.

As @leszekhanusz said, this should be only imported conditionally, and the import should go to the TYPE_CHECKING block.

Usually I don't even check the sys.version, but just try to import from typing and then from type extensions if that fails - like here. But I add the Python version as comment, so that it can be searched and removed when no longer needed.

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 this pull request may close these issues.

3 participants