Source From Here
Question
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:
Or would it be:
HowTo
The former is correct, if arg accepts an instance of CustomClass:
In case you want the class CustomClass itself (or a subtype), then you should write:
Like it is written in the documentation about Typing:
The documentation includes an example with the int class:
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):
- def FuncA(Arg:Type[CustomClass]):
The former is correct, if arg accepts an instance of CustomClass:
- def FuncA(arg: CustomClass):
- # ^ instance of CustomClass
- from typing import Type # you have to import Type
- def FuncA(arg: Type[CustomClass]):
- # ^ CustomClass (class object) itself
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]'
沒有留言:
張貼留言