Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Last active June 30, 2022 11:57
Show Gist options
  • Save AndrewIngram/1fa94101dd7f8702247c60b570e1d0b7 to your computer and use it in GitHub Desktop.
Save AndrewIngram/1fa94101dd7f8702247c60b570e1d0b7 to your computer and use it in GitHub Desktop.
Python Entity or ID Pattern
def my_fun(user_or_id: UserOrId):
user = get_user(user_or_id)
# Do something with user
# These both do the same thing (but the first avoids the extra db hit)
my_fun(user)
my_fun(user.id)
from typing import cast, overload
from uuid import UUID
@overload
def get_user(user_or_id: User) -> User:
...
@overload
def get_user(user_or_id: UUID) -> User:
...
UserOrId = User | UUID
def get_user(user_or_id):
if isinstance(user_or_id, User):
return user_or_id
return cast(User, User.objects.get(id=user_or_id))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment