Created
October 16, 2024 11:15
-
-
Save olamigokayphils/b929e6c1e8920f89feca0377b6574a77 to your computer and use it in GitHub Desktop.
Python Type annotation example[.]py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import requests | |
from typing import Final, TypedDict | |
MAX_VALUE: Final = 10_000 | |
""" | |
Special typing construct to indicate final names to type checkers. | |
A final name cannot be re-assigned or overridden in a subclass. | |
""" | |
class Coordinates(TypedDict): | |
""" | |
when you want to define a structured type for nested dictionaries, | |
it's a good practice to define each nested structure as its own TypedDict class. | |
This makes your types more explicit, reusable, and maintainable. | |
""" | |
latitude: float | |
longitude: float | |
asset_on_scale: bool | |
editable: bool | |
timestamp: datetime | |
battery_history: list[float] | |
class APIResponse(TypedDict): | |
status: str | |
message: str | |
data: Coordinates | |
try: | |
fetch_data = requests.get("", headers={"authorization": "Bearer XXXY"}) | |
fetch_data : APIResponse = fetch_data.json() | |
# Calcuations | |
# ... | |
except Exception as e: | |
# LOG | |
print(f"Error with request: {e}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
lgtm