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

There should be an inverse of Type #8103

Open
samuelbryant opened this issue Dec 8, 2019 · 4 comments
Open

There should be an inverse of Type #8103

samuelbryant opened this issue Dec 8, 2019 · 4 comments
Labels

Comments

@samuelbryant
Copy link

Specifically, it would be nice if there was a keyword Instance such that Instance[Type[_T]] is equivalent to _T

I'm thinking about this mostly in the context of working with metaclasses.

Suppose I have a class with a class method that creates an instance of the class written so it can be reused by subclasses. This can be typed in the following way:

_ThingInstance = TypeVar('_ThingInstance', bound='Thing')

class Thing():

    @classmethod
    def make_new(cls: Type[_ThingInstance]) -> _ThingInstance:
        return cls()

And this is automatically usable by subclasses.

What I want is an Instance type such that I can correctly type the same logic defined within a metaclass like so:

_ThingClass = TypeVar('_ThingClass', bound='MetaThing')

class MetaThing(type):

  def make_new(cls: _ThingClass) -> Instance[_ThingClass]:
      return cls()

As far as I can tell, there's no way to correctly annotate this

@samuelbryant
Copy link
Author

err... this might be a limitation imposed by PEP itself. Sorry if I posted in the wrong place

@msullivan
Copy link
Collaborator

I think it is debatable where the best place to discuss this is. It could be done at https://github.com/python/typing/issues but it is plausible to do it here since it could start as an extension?

@Congee
Copy link

Congee commented Jun 30, 2020

This feature is desirable because, as far as I know, there's no way to have a union of instances easily.

class A: ...
class B: ...
TypeOfTypes: Union[A, B]  # -> Type[A] | Type[B]
# how do I get a union of instances without instantiate classes?
TypeOfInstances: Union[A(), B()]  # -> A | B

To solve the above problem, we have to figure out if an instance is unique value type. I.e. is Union[A(), A()] == Union[A()]?

@JelleZijlstra
Copy link
Member

@Congee Union[A, B] in fact means an instance of either A or B.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants