Sujet : Re: Any way to "subclass" typing.Annotated?
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 29. Jan 2025, 14:34:51
Autres entêtes
Organisation : Stefan Ram
Message-ID : <Annotated-20250129143428@ram.dialup.fu-berlin.de>
References : 1 2
ram@zedat.fu-berlin.de (Stefan Ram) wrote or quoted:
Alright, so here's the deal: you're right that typing.Annotated
Alright, so here's the deal with "typing.Annotated" in Python.
It's like adding extra toppings to your In-N-Out burger - you're
not just saying what type of meat you want, you're throwing on
some secret sauce too. Imagine you're at a Coachella for coders.
Here's what typing.Annotated brings to the party:
- Type Declaration: You're still telling Python what kind of
data you're working with, like saying "this variable is as
integer as the number of surfers at Huntington Beach."
- Extra Info: But now you can slap on some bonus details,
like how you'd stick a "I climbed Half Dome" sticker on
your Nalgene.
- Flexibility: This extra info can be pretty much anything -
like how you can put literally anything on avocado toast
and Californians will eat it up.
Here's a quick example, as easy as parallel parking on Lombard
Street:
Python
from typing import Annotated
# Plain Jane version
age: int
# Fancy pants version
age: Annotated[int, "How many times you've seen the Hollywood sign"]
Both lines are saying age is an integer, but the Annotated one
is like adding a little note that your hipster friend's artisanal
documentation tool might dig.
Just a heads up, you might need to grab the typing_extensions
module (like picking up some craft IPA from your local microbrewery)
to use Annotated in older Python versions. It's fresher than
the produce at Berkeley Bowl in the newer versions.
Bottom line, typing.Annotated is like the GPS for your code
- it doesn't change where you're going, but it sure makes the
journey clearer for everyone involved. It's especially clutch
when you're working on projects bigger than Silicon Valley egos.