简体   繁体   中英

Python type hint for (any) class

I want to type hint the following function:

def get_obj_class(self) -> *class*:
  return self.o.__class__

self.o could be of any type, it's determined at runtime.

*class* obviously is not the answer here, because it's invalid syntax. But what is the right answer? I could not find any documentation on this, any help is appreciated.


On a similar note, if I have a function f(cls: *class*) which returns an instance of cls , is there a way to type hint the return value appropriately?

I'd recommend using a combination of TypeVar , to indicate that your self.o value could be any arbitrary type, and Type , in the following way:

from typing import TypeVar, Type

T = TypeVar('T')

class MyObj:
    def __init__(self, o: T) -> None:
        self.o = o

    def get_obj_class(self) -> Type[T]:
        return type(self.o)

def accept_int_class(x: Type[int]) -> None:
    pass

i = MyObj(3)
foo = i.get_obj_class()
accept_int_class(foo)    # Passes

s = MyObj("foo")
bar = s.get_obj_class()
accept_int_class(bar)    # Fails

If you want the type of o to be even more dynamic, you could explicitly or implicitly give it a type of Any .


Regarding your latter question, you'd do:

def f(cls: Type[T]) -> T:
    return cls()

Note that you need to be careful when instantiating your class -- I don't remember what Pycharm does here, but I do know that mypy currently does not check to make sure you're calling your __init__ function correctly/with the right number of params.

(This is because T could be anything, but there's no way to hint what the constructor ought to look like, so performing this check would end up being either impossibly or highly difficult.)

I think this would do the work:

def get_obj_class(self) -> type
    return self.o.__class__

What about typing.Type?

https://docs.python.org/3/library/typing.html#typing.Type

That seems to fit - since __class_ should always return a type

Yes, this works (even Pycharm does not complain:

import typing


def test(t: object) -> typing.Type:
    return t.__class__

class Dummy(object):
    pass

test(Dummy())

To your second question: That should be an generic: https://docs.python.org/3/library/typing.html#user-defined-generic-types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM