Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...