Python type hint for (any) class

I want to enter hint the following function:

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

self.o can be of any type defined at runtime.

*class*obviously is not the answer here because it is an invalid syntax. But what is the correct answer? I could not find any documentation about this, any help is appreciated.


In a similar note, if I have a function f(cls: *class*)that returns an instance cls, is there a way to correctly type the return value?

+4
source share
3 answers

TypeVar, , self.o , Type :

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

, o , Any.


, :

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

, - , Pycharm, , mypy , __init__ .

( , T , , , , ).

+3

, :

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

typing.Type?

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

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

Yes, it works (even Peacharm doesn't complain:

import typing


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

class Dummy(object):
    pass

test(Dummy())

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

0
source

Source: https://habr.com/ru/post/1678400/


All Articles