Django’s post_save
signal sends a model class argument – sender
– along with the actual instance being saved – instance
.
Is there a way to differentiate between the two in type hints?
Example
We have a model User
and would like to create a post_save
signal:
JavaScript
x
9
1
# …
2
@receiver([post_save], sender=User)
3
def send_activation_email(
4
sender: User,
5
instance: User,
6
# …
7
) -> None:
8
# …
9
As you can see, I have given both sender
and instance
the same type hint – User
. But they are not the same type. The first is a class, and the second is an object. So, is there a way to differentiate the two?
Advertisement
Answer
What you are looking for is typing.Type
.
JavaScript
1
10
10
1
from typing import Type
2
# …
3
@receiver([post_save], sender=User)
4
def send_activation_email(
5
sender: Type[User],
6
instance: User,
7
# …
8
) -> None:
9
# …
10
This answer was posted for the clarity and readability thanks to a comment by @Michael0x2a.