Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify class type in function annotations

Tags:

python

So I have a function that takes a class as a parameter (not a class instance!).

How can I specify this in the function annotation

What I mean is:

def add(a: int, b: int):

But I can't do this:

def my_func(cls: class):

Since class is a reserved word for class definition. How can I solve this?

like image 535
Desiigner Avatar asked Oct 28 '25 14:10

Desiigner


1 Answers

You can use cls: type.

Just like every integer is an instance of int, every class is an instance of type.

Demo:

>>> class Foo: pass
>>> 
>>> isinstance(Foo, type)
>>> True
>>> isinstance(Foo(), type)
>>> False

You can also use Type from the typing module, which, as per the docs, is

A special construct usable to annotate class objects.

Using typing.Type is more flexible than cls:type.

For example, if you wanted to hint that the argument can be any class object, you simply use cls:Type.

If the argument should be any class object that is a subclass of the class Foo (or Foo itself), you can write cls: Type[Foo].

Read the docs for more info.

Responding to the comments:

it's like in your example. Class object is an instance of type, but class instance isn't. So that's why it complains: going func(Person) is alright but func(Person('Steve', 22)) is not.

In the second case, you are doing what you explicitly said you don't want to do: pass an instance of Person, not the class Person. So your IDE rightfully complains if you annotated type or Type.

like image 166
timgeb Avatar answered Oct 30 '25 05:10

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!