Fix Python – Type hints with user defined classes

Question

Asked By – hhprogram

Couldn’t seem to find a definitive answer. I want to do a type hint for a function and the type being some custom class that I have defined, called it CustomClass().

And then let’s say in some function, call it FuncA(arg), I have one argument named arg. Would the correct way to type hint FuncA be:

def FuncA(arg: CustomClass):

Or would it be:

from typing import Type

def FuncA(Arg:Type[CustomClass]):

Now we will see solution for issue: Type hints with user defined classes


Answer

The former is correct, if arg accepts an instance of CustomClass:

def FuncA(arg: CustomClass):
    #     ^ instance of CustomClass

In case you want the class CustomClass itself (or a subtype), then you should write:

from typing import Type  # you have to import Type

def FuncA(arg: Type[CustomClass]):
    #     ^ CustomClass (class object) itself

Like it is written in the documentation about Typing:

class typing.Type(Generic[CT_co])

A variable annotated with C may accept a value of type C. In
contrast, a variable annotated with Type[C] may accept values that
are classes themselves
– specifically, it will accept the class
object of C
.

The documentation includes an example with the int class:

a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'

This question is answered By – Willem Van Onsem

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0