Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

python - How can I access T from a Generic[T] instance early in its lifecycle?

Oh, it feels so contrived to ask now that I've resigned myself to an alternative approach, but Python's typing module has me mystified.

I know I can do this:

import typing

T = typing.TypeVar("T")

class MyGenericClass(Generic[T]):
    def a_method(self):
        print(self.__orig_class__)

MyOtherGeneric[SomeBaseClass]().a_method()

to print SomeBaseClass. Probably, I will just stick with that ability to achieve what I am ultimately trying to do (modify functionality based on T), but I am now stuck wondering how all of this even works.

Originally, I wanted to access the base type information (the value of T) from inside the class at the time the object is being instantiated, or soon thereafter, rather than later in its lifecycle.

As a concrete example, in the code below, I wanted something to replace any of ?n? so I could get the value SomeOtherBaseClass early in the object's lifecycle. Maybe there's some code that needs to go above one of those lines, as well.

import typing

T = typing.TypeVar("T")

class MyOtherGenericClass(Generic[T]):
    def __init__(self, *args, **kwargs):
        print(?1?)

    def __new__(klass, *args, **kwargs):
        print(?2?)

MyOtherGenericClass[SomeOtherBaseClass]()

I was trying to set some instance variables at the time of instantiation (or, somehow, soon after it) based on the value of T. I'm rethinking my approach given that the typing module and, specifically, this stuff with generics, still seems to be in an unstable period of development.

So… Is that possible? A user pointed out that, at least in 3.8, __orig_class__ gets set during typing._GenericAlias.__call__, but how does that __call__ method get invoked? When does that happen?

Related reading:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...