简体   繁体   中英

Differentiate class and object in Python type hints

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:

# …
@receiver([post_save], sender=User)
def send_activation_email(
    sender: User, 
    instance: User, 
    # …
) -> None:
    # …

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?

What you are looking for is typing.Type .

from typing import Type
# …
@receiver([post_save], sender=User)
def send_activation_email(
    sender: Type[User], 
    instance: User, 
    # …
) -> None:
    # …

This answer was posted for the clarity and readability thanks to a comment by @Michael0x2a.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM