how do i get better at typing
None
2020-05-15
<div><div><p>Created with love by Miodec.<br /><a href="#supporters_title">Supported</a> and <a href="#contributors_title">expanded</a> by many awesome people.<br />Launched on 15th of May, 2020.</p><div><p>distribution of time 60 leaderbord results (wpm)</p></div><div><p>about</p><h2>Monkeytype is a minimalistic and customizable typing test. It features many test modes, an account system to save your typing speed history, and user-configurable features such as themes, sounds, a smooth caret, and more. Monkeytype attempts to emulate the experience of natural keyboard typing during a typing test, by unobtrusively presenting the text prompts and displaying typed characters in-place, providing straightforward, real-time feedback on typos, speed, and accuracy.<p>Test yourself in various modes, track your progress and improve your speed.</p></h2></div><div><p>word set</p><p>By default, this website uses the most common 200 words in the English language to generate its tests. You can change to an expanded set (1000 most common words) in the options, or change the language entirely.</p></div><div><p>keybinds</p><p>You can usetabandenter(or justtabif you have quick tab mode enabled) to restart the typing test. Open the command line by pressingctrl/cmd+shift+poresc- there you can access all the functionality you need without touching your mouse</p></div><div><p>stats</p><p>wpm - total amount of characters in the correctly typed words (including spaces), divided by 5 and normalised to 60 seconds.</p><p>raw wpm - calculated just like wpm, but also includes incorrect words.</p><p>acc - percentage of correctly pressed keys.</p><p>char - correct characters / incorrect characters. Calculated after the test has ended.</p><p>consistency - based on the variance of your raw wpm. Closer to 100% is better. Calculated using the coefficient of variation of raw wpm and mapped onto a scale from 0 to 100.</p></div><div><p>results screen</p><p>After completing a test you will be able to see your wpm, raw wpm, accuracy, character stats, test length, leaderboards info and test info. (you can hover over some values to get floating point numbers). You can also see a graph of your wpm and raw over the duration of the test. Remember that the wpm line is a global average, while the raw wpm line is a local, momentary value. (meaning if you stop, the value is 0)</p></div><div><p>bug report or feature request</p><p>If you encounter a bug, or have a feature request - join the Discord server, send me an email, a direct message on Twitter or create an issue on GitHub.</p></div><div><p>support</p><p>Thanks to everyone who has supported this project. It would not be possible without you and your continued support.</p></div><div><p>contact</p><p>If you encounter a bug, have a feature request or just want to say hi - here are the different ways you can contact me directly.</p></div><div><p>credits</p><p><a href="https://www.reddit.com/user/montydrei">Montydrei </a> for the name suggestion</p><p><a href="https://www.reddit.com/r/MechanicalKeyboards/comments/gc6wx3/experimenting_with_a_completely_new_type_of/">Everyone </a> who provided valuable feedback on the original reddit post for the prototype of this website</p><p><a href="#supporters_title">Supporters</a> who helped financially by donating, enabling optional ads or buying merch</p><p><a href="https://github.com/monkeytypegame/monkeytype/graphs/contributors">Contributors </a> on GitHub that have helped with implementing various features, adding themes and more</p></div></div><div><div><p>tip: You can also change all these settings quickly using the command line (</p>ctrl/cmd<p>+</p>shift<p>+</p>p<p>or</p>esc<p>)</p></div><p><i></i> account</p><p><i></i> behavior</p><div><div><p><i></i> test difficulty</p><p>Normal is the classic type test experience. Expert fails the test if you submit (press space) an incorrect word. Master fails if you press a single incorrect key (meaning you have to achieve 100% accuracy).</p></div><div><p><i></i> quick restart</p><div><p>Press</p>tab<p>or</p>esc<p>to quickly restart the test, or to quickly jump to the test page. Both options disable tab navigation on most parts of the website. Using the "esc" option will move opening the commandline to the</p>tab<p>key.</p></div></div><div><p><i></i> repeat quotes</p><p>This setting changes the restarting behavior when typing in quote mode. Changing it to 'typing' will repeat the quote if you restart while typing.</p></div><div><p><i></i> blind mode</p><p>No errors or incorrect words are highlighted. Helps you to focus on raw speed. If enabled, quick end is recommended.</p></div><div><p><i></i> always show words history</p><p>This option will automatically show the words history at the end of the test. Can cause slight lag with a lot of words.</p></div><div><p><i></i> single list command line</p><div><p>When enabled, it will show the command line with all commands in a single list instead of submenu arrangements. Selecting 'manual' will expose all commands only after typing</p>&gt;<p>.</p></div></div><div><p><i></i> min wpm</p><p>Automatically fails a test if your WPM falls below a threshold.</p></div><div><p><i></i> min accuracy</p><p>Automatically fails a test if your accuracy falls below a threshold.</p></div><div><p><i></i> min burst</p><p>Automatically fails a test if your raw for a single word falls below this threshold. Selecting 'flex' allows for this threshold to automatically decrease for longer words.</p></div><div><p><i></i> british english</p><p>When enabled, the website will use the British spelling instead of American. Note that this might not replace all words correctly. If you find any issues, please let us know.</p></div><div><p><i></i> language</p><p>Change in which language you want to type.</p></div><div><p><i></i> funbox</p><p>These are special modes that change the website in some special way (by altering the word generation, behavior of the website or the looks). Give each one of them a try!</p></div><div><p><i></i> custom layoutfluid</p><p>Select which layouts you want the layoutfluid funbox to cycle through.</p></div></div><p><i></i> input</p><div><div><p><i></i> freedom mode</p><p>Allows you to delete any word, even if it was typed correctly.</p></div><div><p><i></i> strict space</p><p>Pressing space at the beginning of a word will insert a space character when this mode is enabled.</p></div><div><p><i></i> opposite shift mode</p><div><p>This mode will force you to use opposite</p>shift<p>keys for shifting. Using an incorrect one will count as an error. This feature ignores keys in locations</p>B<p>,</p>Y<p>, and</p>^<p>because many people use the other hand for those keys. If you're using external software to emulate your layout (including QMK), you should use the "keymap" mode - the standard "on" will not work. This will enforce opposite shift based on the "keymap layout" setting.</p></div></div><div><p><i></i> stop on error</p><p>Letter mode will stop input when pressing any incorrect letters. Word mode will not allow you to continue to the next word until you correct all mistakes.</p></div><div><p><i></i> confidence mode</p><p>When enabled, you will not be able to go back to previous words to fix mistakes. When turned up to the max, you won't be able to backspace at all.</p></div><div><p><i></i> quick end</p><p>This only applies to the words mode - when enabled, the test will end as soon as the last word has been typed, even if it's incorrect. When disabled, you need to manually confirm the last incorrect entry with a space.</p></div><div><p><i></i> indicate typos</p><p>Shows typos that you've made. Below shows what you typed below the letters and replace will replace the letters with the ones you typed.</p></div><div><p><i></i> lazy mode</p><p>Replaces accents / diacritics / special characters with their normal letter equivalents.</p></div><div><p><i></i> layout emulator</p><p>With this setting you can emulate other layouts. This setting is best kept off, as it can break things like dead keys and alt layers.</p></div></div><p><i></i> sound</p><div><div><p><i></i> sound volume</p><p>Change the volume of the sound effects.</p></div><div><p><i></i> play sound on click</p><p>Plays a short sound when you press a key.</p><div><p>off</p><p>click</p><p>beep</p><p>pop</p><p>nk creams</p><p>typewriter</p><p>osu</p><p>hitmarker</p><p>sine</p><p>sawtooth</p><p>square</p><p>triangle</p></div></div><div><p><i></i> play sound on error</p><p>Plays a short sound if you press an incorrect key or press space too early.</p></div></div><p><i></i> caret</p><div><div><p><i></i> smooth caret</p><p>The caret will move smoothly between letters and words.</p></div><div><p><i></i> caret style</p><p>Change the style of the caret during the test.</p></div><div><p><i></i> pace caret</p><p>Displays a second caret that moves at constant speed. The 'average' option averages the speed of last 10 results. The 'daily' option takes the highest speed of the last 24 hours.</p></div><div><p><i></i> repeated pace</p><p>When repeating a test, a pace caret will automatically be enabled for one test with the speed of your previous test. It does not override the pace caret if it's already enabled.</p></div><div><p><i></i> pace caret style</p><p>Change the style of the pace caret during the test.</p></div></div><p><i></i> appearance</p><div><div><p><i></i> timer/progress style</p><p>Change the style of the timer/progress during a timed test.</p></div><div><p><i></i> timer/progress color</p><p>Change the color of the timer/progress number/bar and live wpm number.</p></div><div><p><i></i> timer/progress opacity</p><p>Change the opacity of the timer/progress number/bar and live wpm number.</p></div><div><p><i></i> highlight mode</p><p>Change what is highlighted during the test.</p></div><div><p><i></i> tape mode</p><p>Only shows one line which scrolls horizontally. Setting this to 'word' will make it scroll after every word and 'letter' will scroll after every keypress. Works best with smooth line scroll enabled and a monospace font.</p></div><div><p><i></i> show all lines</p><p>When enabled, the website will show all lines for word, custom and quote mode tests - otherwise the lines will be limited to 3, and will automatically scroll. Using this could cause the timer text and live wpm to not be visible.</p></div><div><div><p>00</p><p>always show decimal places</p></div><p>Always shows decimal places for values on the result page, without the need to hover over the stats.</p></div><div><p><i></i> always show cpm</p><p>Always shows characters per minute calculation instead of the default words per minute calculation.</p></div><div><p><i></i> start graphs at zero</p><p>Force graph axis to always start at zero, no matter what the data is. Turning this off may exaggerate the value changes.</p></div><div><p><i></i> font size</p><p>Change the font size of the test words.</p></div><div><p><i></i> page width</p><p>Control the width of the content.</p></div><div><p><i></i> keymap</p><p>Displays your current layout while taking a test. React shows what you pressed and Next shows what you need to press next.</p></div><div><p><i></i> keymap layout</p><p>Controls which layout is displayed on the keymap.</p></div><div><p><i></i> keymap style</p><div><p>staggered</p><p>alice</p><p>matrix</p><p>split</p><p>split matrix</p></div></div><div><p><i></i> keymap show top row</p><div><p>always</p><p>layout dependent</p><p>never</p></div></div></div><p><i></i> theme</p><div><div><p><i></i> flip test colors</p><p>By default, typed text is brighter than the future text. When enabled, the colors will be flipped and the future text will be brighter than the already typed text.</p></div><div><p><i></i> colorful mode</p><p>When enabled, the test words will use the main color, instead of the text color, making the website more colorful.</p></div><div><p><i></i> custom background</p><p>Set an image url to be a custom background image. Cover fits the image to cover the screen. Contain fits the image to be fully visible. Max fits the image corner to corner.</p></div><div><p><i></i> custom background filter</p><p>Apply various effects to the custom background.</p></div><div><p><i></i> auto switch theme</p><p>Enabling this will automatically switch the theme between light and dark depending on the system theme (this will not override custom theme).</p></div><div><p><i></i> randomize theme</p><p>After completing a test, the theme will be set to a random one. The random themes are not saved to your config. If set to 'favorite' only favorite themes will be randomized. If set to 'light' or 'dark', only presets with light or dark background colors will be randomized, respectively. If set to 'custom', custom themes will be randomized.</p><div><p>off</p><p>on</p><p>favorite</p><p>light</p><p>dark</p><p>custom</p></div></div><div><p><i></i> theme</p><div><p>background</p><p>main</p><p>caret</p><p>sub</p><p>sub alt</p><p>text</p><p> error</p><p>extra error</p><p>colorful mode</p><p>error</p><p>extra error</p><div><p>load from preset</p><p>share</p><p>save as new</p></div></div></div></div><p><i></i> hide elements</p><div><div><p><i></i> live wpm</p><p>Displays a live WPM speed during the test. Updates once every second.</p></div><div><p><i></i> live accuracy</p><p>Displays live accuracy during the test.</p></div><div><p><i></i> live burst</p><p>Displays live burst during the test of the last word you typed.</p></div><div><p><i></i> timer/progress</p><p>Displays a live timer for timed tests and progress for words/custom tests.</p></div><div><p><i></i> key tips</p><p>Shows the keybind tips at the bottom of the page.</p></div><div><p><i></i> out of focus warning</p><p>Shows an out of focus reminder after 1 second of being 'out of focus' (not being able to type).</p></div><div><p><i></i> caps lock warning</p><p>Displays a warning when caps lock is on.</p></div><div><p><i></i> average</p><p>Displays your average wpm and/or accuracy over the last 10 tests.</p></div></div><p><i></i> danger zone</p><div><div><p><i></i> import/export settings</p><p>Import or export the settings as JSON.</p></div><div><p><i></i> ads</p><div><p>You can disable or enable ads at any time. "Result" will show one ad on the result page, "on" will add floating vertical banners, and "sellout" will add multiple ads on every page.</p><p>(changes will take effect after a refresh).</p></div></div><div><p><i></i> update cookie preferences</p><p>If you changed your mind about which cookies you consent to, you can change your preferences here.</p></div><div><p><i></i> reset settings</p><p>Resets settings to the default (but doesn't touch your tags). Warning: you can't undo this action!</p></div></div></div><div><div><p>All-Time English Leaderboards</p></div><div><div><p>filters</p><div><p>all</p><p>current settings</p><p>advanced</p><p>save as preset</p></div></div><div><p>last day</p><p>last week</p><p>last month</p><p>last 3 months</p><p>all time</p></div></div><p>No data found. Check your filters.</p><div><p><i></i> Toggle Accuracy</p><p><i></i> Toggle Chart Style</p></div><div><div><p>average wpm<br />(last 10 tests)</p><p>-</p></div><div><p>average raw wpm<br />(last 10 tests)</p><p>-</p></div><div><p>avg accuracy<br />(last 10 tests)</p><p>-</p></div><div><p>avg consistency<br />(last 10 tests)</p><p>-</p></div></div><div><table><thead><tr><td></td><td>wpm</td><td>raw</td><td>accuracy</td><td>consistency</td><td>chars</td><td>mode</td><td>info</td><td>tags</td><td>date </td></tr></thead><tbody></tbody></table><p>load more</p></div></div><div><p>All-Time English Leaderboards</p></div><div><p>404</p><p>Ooops! Looks like you found a page that doesn't exist.</p><p><a href="/"><i></i> Go Home</a></p></div>||||I||||:( Looks like JavaScript is disabled. Please enable JavaScript in order to use this website. :( It seems like the CSS failed to load. Please try clearing your cache to redownload the styles:
Ctrl / Cmd + Shift + R
You could also try to reinstall the service worker:
Reinstall If that doesn't help contact support ( [email protected] or discord.gg/monkeytype) If the website works for a bit but then this screen comes back, clear your cache again and then on Monkeytype open the command line (esc) and search for "Clear SW cache".
 Close
 Inbox
 Claim all
 Delete all
 Nothing to show
 Announcements
 Nothing to show
 Notifications
 Nothing to show
 If you see this text, that means an extension is blocking a cookie consent popup. This will cause the website to incorrectly assume its still visible and stop you from enjoying Monkeytype. Please disable any extensions that block cookie popups and refresh the page.
 We use cookies by the way
 Cookies enhance your experience and help us improve our website.
 Accept all
 Reject all
 More options
 Security
 We use Cloudflare cookies to improve security and performance of our site.

 They do not store any personal information and are required.
 Analytics
 We use Google Analytics cookies to check how users interact with our website and use this data to improve our site design.
 Advertising
 Our advertising partner may use cookies to deliver ads that are more relevant to you.
 Click to change your preferences on ad related cookies
 Accept selected
 Share test settings
 Mode Time, Words, Quote, Zen, Custom
 Mode2 Test seconds, Test words, Quote Id
 Custom text
 Punctuation
 Numbers
 Language
 Difficulty
 Funbox
 The URL is over 2000 characters long - it might not work
 punctuation
 numbers
 time
 words
 quote
 zen
 custom
 15
 30
 60
 120
 custom
 10
 25
 50
 100
 custom
 all
 short
 medium
 long
 thicc
 search
 change
 words wpm raw difficulty language punctuation lazy mode date
 accuracy consistency 
 
 Practice words
 This will start a new test in custom mode. Words that you mistyped more often or words that you typed much slower will be weighted higher and appear more often.
 Practice missed
 Practice slow
 Practice both
 If you find a grammatical error, think the quote has inappropriate language or feel like it's low quality - don't give it a low rating! Please report it instead. You can do so by closing this popup and clicking the "Flag" icon.
 -
 id
 -
 length
 -
 source
 -
 ratings
 -
 average
 -
 your rating
 import settings
 ok
 Save
 Show saved texts
 Words filter
 A long custom text is currently loaded. Editing the text will disable progress tracking.
 Got it
 Random Randomize the above words, and control how many words are generated.
 Words
 or
 Time
 Remove Fancy Typography Standardises typography symbols (for example “ and ” become ")
 Pipe Delimiter Change how words are separated. Using the pipe delimiter allows you to randomize groups of words.
 Replace new lines with spaces Replace all new line characters with spaces. Can automatically adds periods to the end of lines if you wish.
 no periods
 periods
 ok
 Saved texts
 Saved long texts
 Save custom text
 Long text (book mode) Disables editing this text but allows you to save progress by pressing shift + enter or bailing out. You can then load this text again to continue where you left off.
 save
 language
 min length
 max length
 include
 exclude
 Use the above filters to include and exclude words or characters (separated by spaces)
 "Set" replaces the current custom word list with the filter result, "Add" appends the filter result to the current custom word list
 set
 add
 Account name
 You need to choose a username before continuing
 Sign up
 Word amount
 You can start an infinite test by inputting 0. Then, to stop the test, use the Bail Out feature (esc or ctrl/cmd + shift + p > Bail Out)
 ok
 Test duration
 You can start an infinite test by inputting 0. Then, to stop the test, use the Bail Out feature (esc or ctrl/cmd + shift + p > Bail Out)
 ok
 Quote Search
 Submit a quote
 Approve quotes
 Favorites Only
 No search results
 Submit a Quote
 * Do not include content that contains any libelous or otherwise unlawful, abusive or obscene text.
 * Verify quotes added aren't duplicates of any already present
 * Please do not add extremely short quotes (less than 60 characters)
 * Submitting low quality quotes or misusing this form will cause you to lose access to this feature
 Quote
 -
 Source Language
 Submit
 Ape Keys
 Generate new key
 active name created on modified on last used on 
 
 Report a Quote
 Please report quotes responsibly. Please add comments in English only. Misuse may result in you losing access to this feature.
 quote
 reason Grammatical errorInappropriate contentLow quality contentIncorrect source comment
 -
 Report
 Report a User
 Please report users responsibly. Please add comments in English only. Misuse may result in you losing access to this feature.
 user
 reason Inappropriate nameInappropriate bioInappropriate social linksSuspected cheating comment
 -
 Report
 Approve Quotes
 Refresh list
 Change preset to current settings
 All-Time English Leaderboards
 Next update in: --:--
 Show yesterday
 all-time
 daily
 Time 15
 # name wpm raw date
 accuracy consistency 
 
 Time 60
 # name wpm raw date
 accuracy consistency 
 
 Support Monkeytype
 Thank you so much for thinking about supporting this project. It would not be possible without you and your continued support.
 Enable Ads
 Watch
 a Video Ad
 Donate
 Become
 a Patron
 Buy Merch
 Contact
 Feel free to send an email to [email protected] (the buttons below will open the default mail client).

 Please do not send requests to delete account, update email, update name or clear personal bests - you can do that in the settings page.
 Question
 Feedback
 Bug Report
 Account Help
 Business Inquiry
 Other
 Title
 Add new filter preset
 add
 Edit Profile
 avatar
 To update your avatar make sure your Discord account is linked, then go to Settings > Account > Discord Integration and click "Update Avatar"
 bio
 keyboard
 github

 https://github.com/

 twitter

 https://twitter.com/

 website
 badge
 save

 monkey see
 monkeytype

 1
 5
 ‎
 punctuation
 numbers
 time
 words
 quote
 zen
 custom
 15
 30
 60
 120
 10
 25
 50
 100
 all
 short
 medium
 long
 thicc
 change
 Test Settings
 Caps Lock
 Time left to memorise all words: 0s
 60
 1:00
 60
 100%
 1
 Click here or start typing to focus
 123
 100%%
 1
 wpm
 -
 acc
 -
 test type
 -
 tags
 -
 other
 -
 raw
 -
 characters
 -
 consistency
 2 -
 time
 -
 daily leaderboard
 -
 source
 -
 Sign in to save your result
 input history
 watch replay

 0s

 Retry saving result
 monkeytype.com
 Created with love by Miodec.
 Supported and expanded by many awesome people.
 Launched on 15th of May, 2020.
 total started tests
 -
 -
 total time typing
 -
 -
 total completed tests
 -
 -

 distribution of time 60 leaderbord results (wpm)

 about

 Monkeytype is a minimalistic and customizable typing test. It features many test modes, an account system to save your typing speed history, and user-configurable features such as themes, sounds, a smooth caret, and more. Monkeytype attempts to emulate the experience of natural keyboard typing during a typing test, by unobtrusively presenting the text prompts and displaying typed characters in-place, providing straightforward, real-time feedback on typos, speed, and accuracy.

 Test yourself in various modes, track your progress and improve your speed.

 word set

 By default, this website uses the most common 200 words in the English language to generate its tests. You can change to an expanded set (1000 most common words) in the options, or change the language entirely.

 keybinds

 You can usetabandenter(or justtabif you have quick tab mode enabled) to restart the typing test. Open the command line by pressingctrl/cmd+shift+poresc- there you can access all the functionality you need without touching your mouse

 stats

 wpm - total amount of characters in the correctly typed words (including spaces), divided by 5 and normalised to 60 seconds.

 raw wpm - calculated just like wpm, but also includes incorrect words.

 acc - percentage of correctly pressed keys.

 char - correct characters / incorrect characters. Calculated after the test has ended.

 consistency - based on the variance of your raw wpm. Closer to 100% is better. Calculated using the coefficient of variation of raw wpm and mapped onto a scale from 0 to 100.

 results screen

 After completing a test you will be able to see your wpm, raw wpm, accuracy, character stats, test length, leaderboards info and test info. (you can hover over some values to get floating point numbers). You can also see a graph of your wpm and raw over the duration of the test. Remember that the wpm line is a global average, while the raw wpm line is a local, momentary value. (meaning if you stop, the value is 0)

 bug report or feature request

 If you encounter a bug, or have a feature request - join the Discord server, send me an email, a direct message on Twitter or create an issue on GitHub.

 support

 Thanks to everyone who has supported this project. It would not be possible without you and your continued support.

 Support
 contact

 If you encounter a bug, have a feature request or just want to say hi - here are the different ways you can contact me directly.

 Mail
 Twitter
 Discord
 GitHub
 credits

 Montydrei for the name suggestion

 Everyone who provided valuable feedback on the original reddit post for the prototype of this website

 Supporters who helped financially by donating, enabling optional ads or buying merch

 Contributors on GitHub that have helped with implementing various features, adding themes and more

 supporters
 contributors
 tip: You can also change all these settings quickly using the command line (ctrl/cmd+shift+poresc)
 account behavior input sound caret appearance theme hide elements danger zone
 account
 discord integration
 When you connect your monkeytype account to your Discord account, you will be automatically assigned a new role every time you achieve a new personal best in a 60 second test. If you link your accounts before joining the Discord server, the bot will not give you a role.
 Link with Discord
 Your accounts are linked!
 Update avatar
 Unlink
 tags
 With tags, you can compare how fast you're typing in different situations. You can see your active tags above the test words. They will remain active until you deactivate them, or refresh the page.
 staggered
 presets
 Create settings presets that can be applied with one click. Remember to edit your preset if you make any changes - they don't save on their own.
 staggered
 behavior
 test difficulty
 Normal is the classic type test experience. Expert fails the test if you submit (press space) an incorrect word. Master fails if you press a single incorrect key (meaning you have to achieve 100% accuracy).
 normal
 expert
 master
 quick restart
 Presstaborescto quickly restart the test, or to quickly jump to the test page. Both options disable tab navigation on most parts of the website. Using the "esc" option will move opening the commandline to thetabkey.
 off
 tab
 esc
 repeat quotes
 This setting changes the restarting behavior when typing in quote mode. Changing it to 'typing' will repeat the quote if you restart while typing.
 off
 typing
 blind mode
 No errors or incorrect words are highlighted. Helps you to focus on raw speed. If enabled, quick end is recommended.
 off
 ⠀
 always show words history
 This option will automatically show the words history at the end of the test. Can cause slight lag with a lot of words.
 off
 on
 single list command line
 When enabled, it will show the command line with all commands in a single list instead of submenu arrangements. Selecting 'manual' will expose all commands only after typing>.
 manual
 on
 min wpm
 Automatically fails a test if your WPM falls below a threshold.
 off
 custom
 min accuracy
 Automatically fails a test if your accuracy falls below a threshold.
 off
 custom
 min burst
 Automatically fails a test if your raw for a single word falls below this threshold. Selecting 'flex' allows for this threshold to automatically decrease for longer words.
 off
 fixed
 flex
 british english
 When enabled, the website will use the British spelling instead of American. Note that this might not replace all words correctly. If you find any issues, please let us know.
 off
 on
 language
 Change in which language you want to type.
 funbox
 These are special modes that change the website in some special way (by altering the word generation, behavior of the website or the looks). Give each one of them a try!
 custom layoutfluid
 Select which layouts you want the layoutfluid funbox to cycle through.
 input
 freedom mode
 Allows you to delete any word, even if it was typed correctly.
 off
 on
 strict space
 Pressing space at the beginning of a word will insert a space character when this mode is enabled.
 off
 on
 opposite shift mode
 This mode will force you to use oppositeshiftkeys for shifting. Using an incorrect one will count as an error. This feature ignores keys in locationsB,Y, and^because many people use the other hand for those keys. If you're using external software to emulate your layout (including QMK), you should use the "keymap" mode - the standard "on" will not work. This will enforce opposite shift based on the "keymap layout" setting.
 off
 on
 keymap
 stop on error
 Letter mode will stop input when pressing any incorrect letters. Word mode will not allow you to continue to the next word until you correct all mistakes.
 off
 word
 letter
 confidence mode
 When enabled, you will not be able to go back to previous words to fix mistakes. When turned up to the max, you won't be able to backspace at all.
 off
 on
 max
 quick end
 This only applies to the words mode - when enabled, the test will end as soon as the last word has been typed, even if it's incorrect. When disabled, you need to manually confirm the last incorrect entry with a space.
 off
 on
 indicate typos
 Shows typos that you've made. Below shows what you typed below the letters and replace will replace the letters with the ones you typed.
 off
 below
 replace
 hide extra letters
 Hides extra letters. This will completely avoid words jumping lines (due to changing width), but might feel a bit confusing when you press a key and nothing happens.
 off
 on
 lazy mode
 Replaces accents / diacritics / special characters with their normal letter equivalents.
 off
 on
 layout emulator
 With this setting you can emulate other layouts. This setting is best kept off, as it can break things like dead keys and alt layers.
 sound
 sound volume
 Change the volume of the sound effects.
 quiet
 medium
 loud
 play sound on click
 Plays a short sound when you press a key.
 off
 click
 beep
 pop
 nk creams
 typewriter
 osu
 hitmarker
 sine
 sawtooth
 square
 triangle
 play sound on error
 Plays a short sound if you press an incorrect key or press space too early.
 off
 on
 caret
 smooth caret
 The caret will move smoothly between letters and words.
 off
 on
 caret style
 Change the style of the caret during the test.
 off
 |
 ▮
 ▯
 _
 pace caret
 Displays a second caret that moves at constant speed. The 'average' option averages the speed of last 10 results. The 'daily' option takes the highest speed of the last 24 hours.
 off
 avg
 pb
 last
 daily
 custom
 repeated pace
 When repeating a test, a pace caret will automatically be enabled for one test with the speed of your previous test. It does not override the pace caret if it's already enabled.
 off
 on
 pace caret style
 Change the style of the pace caret during the test.
 off
 |
 ▮
 ▯
 _
 appearance
 timer/progress style
 Change the style of the timer/progress during a timed test.
 bar
 text
 mini
 timer/progress color
 Change the color of the timer/progress number/bar and live wpm number.
 black
 sub
 text
 main
 timer/progress opacity
 Change the opacity of the timer/progress number/bar and live wpm number.
 0.25
 0.5
 0.75
 1
 highlight mode
 Change what is highlighted during the test.
 off
 letter
 word
 tape mode
 Only shows one line which scrolls horizontally. Setting this to 'word' will make it scroll after every word and 'letter' will scroll after every keypress. Works best with smooth line scroll enabled and a monospace font.
 off
 letter
 word
 smooth line scroll
 When enabled, the line transition will be animated.
 off
 on
 show all lines
 When enabled, the website will show all lines for word, custom and quote mode tests - otherwise the lines will be limited to 3, and will automatically scroll. Using this could cause the timer text and live wpm to not be visible.
 off
 on
 00
 always show decimal places
 Always shows decimal places for values on the result page, without the need to hover over the stats.
 off
 on
 always show cpm
 Always shows characters per minute calculation instead of the default words per minute calculation.
 off
 on
 start graphs at zero
 Force graph axis to always start at zero, no matter what the data is. Turning this off may exaggerate the value changes.
 off
 on
 font size
 Change the font size of the test words.
 font family
 page width
 Control the width of the content.
 100%
 125%
 150%
 200%
 max
 keymap
 Displays your current layout while taking a test. React shows what you pressed and Next shows what you need to press next.
 off
 static
 react
 next
 keymap layout
 Controls which layout is displayed on the keymap.
 keymap style
 staggered
 alice
 matrix
 split
 split matrix
 keymap legend style
 lowercase
 uppercase
 blank
 dynamic
 keymap show top row
 always
 layout dependent
 never
 theme
 flip test colors
 By default, typed text is brighter than the future text. When enabled, the colors will be flipped and the future text will be brighter than the already typed text.
 off
 on
 colorful mode
 When enabled, the test words will use the main color, instead of the text color, making the website more colorful.
 off
 on
 custom background
 Set an image url to be a custom background image. Cover fits the image to cover the screen. Contain fits the image to be fully visible. Max fits the image corner to corner.
 cover
 contain
 max
 custom background filter
 Apply various effects to the custom background.
 blur
 brightness
 saturate
 opacity
 auto switch theme
 Enabling this will automatically switch the theme between light and dark depending on the system theme (this will not override custom theme).
 off
 on
 light
 dark
 randomize theme
 After completing a test, the theme will be set to a random one. The random themes are not saved to your config. If set to 'favorite' only favorite themes will be randomized. If set to 'light' or 'dark', only presets with light or dark background colors will be randomized, respectively. If set to 'custom', custom themes will be randomized.
 off
 on
 favorite
 light
 dark
 custom
 theme
 preset
 custom
 background
 main
 caret
 sub
 sub alt
 text
 error
 extra error

 colorful mode

 error
 extra error
 load from preset
 share
 save as new
 hide elements
 live wpm
 Displays a live WPM speed during the test. Updates once every second.
 hide
 show
 live accuracy
 Displays live accuracy during the test.
 hide
 show
 live burst
 Displays live burst during the test of the last word you typed.
 hide
 show
 timer/progress
 Displays a live timer for timed tests and progress for words/custom tests.
 hide
 show
 key tips
 Shows the keybind tips at the bottom of the page.
 hide
 show
 out of focus warning
 Shows an out of focus reminder after 1 second of being 'out of focus' (not being able to type).
 hide
 show
 caps lock warning
 Displays a warning when caps lock is on.
 hide
 show
 average
 Displays your average wpm and/or accuracy over the last 10 tests.
 off
 wpm
 acc
 both
 danger zone
 import/export settings
 Import or export the settings as JSON.
 import
 export
 ads
 You can disable or enable ads at any time. "Result" will show one ad on the result page, "on" will add floating vertical banners, and "sellout" will add multiple ads on every page.

 (changes will take effect after a refresh).
 off
 result
 on
 sellout
 ape keys
 Generate Ape Keys to access certain API endpoints ( documentation ). More endpoints will be added in the future.
 open
 update cookie preferences
 If you changed your mind about which cookies you consent to, you can change your preferences here.
 open
 update account name
 Change the name of your account. You can only do this once every 30 days.
 update name
 password authentication settings
 Add password authentication, update your password or email.
 add password authentication
 update email
 update password
 google authentication settings
 Add or remove Google authentication.
 add google authentication
 remove google authentication
 reset settings
 Resets settings to the default (but doesn't touch your tags). Warning: you can't undo this action!
 reset settings
 reset personal bests
 Resets all your personal bests (but doesn't delete any tests from your history). Warning: you can't undo this action!
 reset personal bests
 reset account
 Completely resets your account to a blank state.
 reset account
 delete account
 Deletes your account and all data connected to it.
 delete account
 register
 Sign Up
 login
 Forgot password?
 Remember me
 Sign In
 or
 Google Sign In
 ‎
 -
 -
 -
 -
 -/-
 tests started
 -
 tests completed
 -
 time typing
 -
 bio
 -
 keyboard
 -
 socials
 -
 All-Time English Leaderboards
 15 seconds
 -
 60 seconds
 -
 10 words
 -
 -
 25 words
 -
 -
 50 words
 -
 -
 100 words
 -
 -
 15 seconds
 -
 -
 30 seconds
 -
 -
 60 seconds
 -
 -
 120 seconds
 -
 -
 filter presets
 filters
 all
 current settings
 advanced
 save as preset

 last day
 last week
 last month
 last 3 months
 all time
 No data found. Check your filters.
 smoothing
 0
 Toggle Accuracy
 Toggle Chart Style
 estimated words typed
 -
 tests started
 -
 tests completed
 -
 -
 time typing
 -
 highest wpm
 -
 average wpm
 -
 average wpm
 (last 10 tests)
 -
 highest raw wpm
 -
 average raw wpm
 -
 average raw wpm
 (last 10 tests)
 -
 highest accuracy
 -
 avg accuracy
 -
 avg accuracy
 (last 10 tests)
 -
 highest consistency
 -
 avg consistency
 -
 avg consistency
 (last 10 tests)
 -
 Export CSV
 wpm raw accuracy consistency chars mode info tags date
 
 load more
 Profile lookup
 -
 -
 -
 -
 -/-
 tests started
 -
 tests completed
 -
 time typing
 -
 bio
 -
 keyboard
 -
 socials
 -
 All-Time English Leaderboards
 15 seconds
 -
 60 seconds
 -
 10 words
 -
 -
 25 words
 -
 -
 50 words
 -
 -
 100 words
 -
 -
 15 seconds
 -
 -
 30 seconds
 -
 -
 60 seconds
 -
 -
 120 seconds
 -
 -
 404
 Ooops! Looks like you found a page that doesn't exist.
 Go Home
 tabandenter- Restart Test
 ctrl/cmd+shift+poresc- Command Line
 Contact
 Support
 GitHub
 Discord
 Twitter
 Terms
 Security
 Privacy
 serika dark
 version
 new
Monkeytype | A minimalistic, customizable typing test
https://monkeytype.com/
None
2023-01-01
<div><div>
 <h2>
 TypeRacer – The Global Typing Competition
 <p>Increase your typing speed while racing against others</p>
 </h2>
 
<div>
 <p>
 </p>
 <p>
 TypeRacer is loading...
 </p>
 
 </div>
 
</div></div>||||I|||| typeracer Pit StopUpdatesDiscordAboutMerch 
 
 

 TypeRacer – The Global Typing Competition

 Increase your typing speed while racing against others





 TypeRacer is loading...









 You must have Javascript enabled in your browser in order to play TypeRacer. It seems that you currently have it turned off.

 Please consult this article for instructions on how to enable Javascript in your browser.

 Also make sure that you are not using any browser plugins (like NoScript for Firefox) that could be blocking Javascript. If you need more assistance, please do not hesitate to contact us.

 typeracer – the global typing competition

 Increase your typing speed while racing against others

 The award-winning online typing competition, TypeRacer, is the best free typing game in the world. It is the first-ever multiplayer typing game, which lets you race against real people typing quotes from books, movies, and songs.

 Your typing speed will improve by at least 10 WPM if you play this free game at least once a week. TypeRacer is much more fun than just a free typing test. It's better to practice typing on typeracer.com than any free typing program or typing tutor. The consensus is clear: among computer typing games, TypeRacer is king!

 Don't wait to get started: the road to becoming a touch typing master is long, but at least TypeRacer makes it fun and easy. To be clear, TypeRacer is not an easy typing game, but it will actually make you a better typist than those easy typing games for kids. It makes you type the same sort of text you would see at typing jobs.

 Don't know how to type yet? Then learn to type! Just grab a free typing tutor or read a free typing tutorial. There are many free typing lessons on the web. You can also just download Mavis Beacon if you prefer.

 Once you've mastered your basic typing skills, use TypeRacer for your first real timed typing test. Then just keep practicing - you will improve your typing speed fast!

 Already know how to type? Then just have fun! TypeRacer is one of the best free online games, so why play any other addicting games which don't improve your typing speed in the process? You can quit those other computer games, flash games, facebook games, and kids games, and get focused on TypeRacer: the game that is actually good for you!

 * Home
 * Terms of Service
 * Privacy Policy
 * Contact
 * Contribute
 * Keyboard Shortcuts
 * FAQ
 © 2008-2023 Addicting Games, Inc.
 Change Theme Addicting Games
 Pit StopUpdatesDiscordAboutMerch
 Skill Level Avg. Speed Races Points
TypeRacer - the global typing competition
https://play.typeracer.com
None
2023-01-01
<div><div>
<section>
<div>
<div>
<ul>
<li>
<p>Aligned to Federal and State Standards</p>
</li>
<li>
<p>Prepares Students for Standardized Testing</p>
</li>
<li>
<p>Powerful District and Classroom Management</p>
</li>
</ul>
</div>
<p>
</p>
</div>
</section>
<div>
<p>
We Proudly Support These Districts &amp; Many More
</p>
<div>
<figure>
<div>
<p></p><blockquote>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
</p>
</blockquote>
<div>
<figcaption>
<p>John K. Sampson</p>
<p>Seattle, WA</p>
</figcaption>
<p>
</p></div>
</div>
</figure>
<figure>
<div>
<p></p><blockquote>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
</p>
</blockquote>
<div>
<figcaption>
<p>John K. Sampson</p>
<p>Seattle, WA</p>
</figcaption>
<p>
</p></div>
</div>
</figure>
<figure>
<div>
<p></p><blockquote>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
</p>
</blockquote>
<div>
<figcaption>
<p>John K. Sampson</p>
<p>Seattle, WA</p>
</figcaption>
<p>
</p></div>
</div>
</figure>
</div>
</div><div>
<figure>
<div>
<p></p><blockquote>
<p>
Typing.com is a comprehensive website that really has it all. 
</p>
</blockquote>
<p>
</p>
</div>
</figure>
<figure>
<div>
<p></p><blockquote>
<p>
Typing.com is the only platform to offer full district support at no cost with no limitations on content or administrative features.
</p>
</blockquote>
<p>
</p>
</div>
</figure>
<figure>
<div>
<p></p><blockquote>
<p>
Typing.com may be free, but it rivals the best paid typing tutor software in features and usability.
</p>
</blockquote>
<p>
</p>
</div>
</figure>
</div><div>
<h2>
Go Beyond Typing with <br />Digital Citizenship, Coding, and Career Prep
</h2>
<div>
<div>
<p>
</p>
<p>
Comprehensive Keyboarding
</p>
</div>
<div>
<p>
</p>
<p>
Computer Basics <br />&amp; Tech Literacy
</p>
</div>
<div>
<p>
</p>
<p>
Online Behavior <br />&amp; Safety
</p>
</div>
<div>
<p>
</p>
<p>
Coding <br />Fundamentals
</p>
</div>
<div>
<p>
</p>
<p>
Career Prep &amp; Professionalism
</p>
</div>
<div>
<p>
</p>
<p>
English, Spanish, <br />&amp; Portuguese
</p>
</div>
</div>
<h2>
A Free Typing Program Built for Teachers
</h2>
<div>
<div>
<p>
</p>
<p>
Engaging Lessons, <br />Tests, &amp; Games
</p>
</div>
<div>
<p>
</p>
<p>
Robust Reporting
</p>
</div>
<div>
<p>
</p>
<p>
Full School &amp; District Administration Tools
</p>
</div>
<div>
<p>
</p>
<p>
SSO and Syncing with Clever, ClassLink, &amp; Google
</p>
</div>
<div>
<p>
</p>
<p>
Customizable Lessons
</p>
</div>
<div>
<p>
</p>
<p>
Standardized Testing <wbr></wbr>Preparation
</p>
</div>
</div>
</div>
<div>
<h4>
We Proudly Support These Districts &amp; Many More
</h4>
</div>
<section>
<h2>
Why You'll Love Typing.com
</h2>
<div>
<div>
<p>
</p>
<div>
<h3>Engaging Curriculum</h3>
<p>Students learn valuable technology fundamentals – designed by experts for students of every skill level.</p>
</div>
</div>
<div>
<p>
</p>
<div>
<h3>Gamified Learning</h3>
<p>Engage students with fun typing games, interactive lessons, and achievements.</p>
</div>
</div>
<div>
<p>
</p>
<div>
<h3>Make it Your Own</h3>
<p>Enhance learning by creating your own lessons for cross-curricular reinforcement.</p>
</div>
</div>
<div>
<p>
</p>
<div>
<h3>Standardized Test Prep Solution</h3>
<p>Prepare your students for standardized testing with free response typing lessons.</p>
</div>
</div>
</div>
</section>
<div>
<p></p><div>
<h2>
Teachers and Administrators, Get Started Today
</h2>
<p>
Grade, track, and report on students' progress in real time. Unlimited students, unlimited classes, unlimited teachers, unlimited schools. Typing.com's teacher portal is FREE!
</p>
</div>
</div>
</div>||||I|||| Skip to Main Navigation Skip to Main Content Skip to Footer
 Support
 |
 Resources
 |
 US English
 * US English
 * UK English
 * Español
 * Português
 |
 Instructor Login › Student Login ›
 Instructors
 * Teachers
 * Schools & Districts
 * Homeschool
 Students

 * Typing Lessons

 * Typing Test

 * Typing Games

 * Digital Literacy

 * Coding Curriculum

 Log In Sign Up Now » Sign Up
 * Home
 * Teachers
 * Schools & Districts
 * Homeschool
 * Premium
 * Typing Lessons
 * 
 * Need some help? Contact Support
 * Instructor Login ›
 Student Login ›
 * 
 * Sign Up Now »

 L
 e
 a
 r
 n

 t
 o

 T
 y
 p
 e

 F
 a
 s
 t
 e
 r
 ,

 E
 a
 s
 i
 e
 r
 ,

 a
 n
 d

 B
 e
 t
 t
 e
 r

 * Aligned to Federal and State Standards

 * Prepares Students for Standardized Testing

 * Powerful District and Classroom Management

 Learn to Type

 Join millions of Typing.com users and learn to type at your own pace with gamified lessons and student-led progression.

 Start Typing Today »

 For Instructors and Admins

 Manage class and student-level settings and meet student needs with timed tests, custom lessons, auto reporting and more.

 Sign Up Now »

 Learn to Type

 Join millions of Typing.com users and learn to type at your own pace with gamified lessons and student-led progression.

 Start Typing Today »

 For Instructors and Admins

 Manage class and student-level settings and meet student needs with timed tests, custom lessons, auto reporting and more.

 Sign Up Now »
 We Proudly Support These Districts & Many More

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
 John K. Sampson
 Seattle, WA

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
 John K. Sampson
 Seattle, WA

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
 John K. Sampson
 Seattle, WA

 Typing.com is a comprehensive website that really has it all.

 Typing.com is the only platform to offer full district support at no cost with no limitations on content or administrative features.

 Typing.com may be free, but it rivals the best paid typing tutor software in features and usability.

 Go Beyond Typing with
 Digital Citizenship, Coding, and Career Prep

 Comprehensive Keyboarding
 Computer Basics
 & Tech Literacy
 Online Behavior
 & Safety
 Coding
 Fundamentals
 Career Prep & Professionalism
 English, Spanish,
 & Portuguese

 A Free Typing Program Built for Teachers

 Engaging Lessons,
 Tests, & Games
 Robust Reporting
 Full School & District Administration Tools
 SSO and Syncing with Clever, ClassLink, & Google
 Customizable Lessons
 Standardized Testing Preparation

 Preparing Students
 for the Future

 38,916,000+ students
 677,000+ teachers
 Tens of thousands of schools rely on us every year.

 Typing.com is a one-stop shop for students to learn to type! The fact that students can progress at their own pace, while tracking accuracy and speed, has been an important benefit.
 Rory Stadt
 Missouri, US

 We Proudly Support These Districts & Many More

 Why You'll Love Typing.com

 Engaging Curriculum

 Students learn valuable technology fundamentals – designed by experts for students of every skill level.

 Gamified Learning

 Engage students with fun typing games, interactive lessons, and achievements.

 Make it Your Own

 Enhance learning by creating your own lessons for cross-curricular reinforcement.

 Standardized Test Prep Solution

 Prepare your students for standardized testing with free response typing lessons.

 Teachers and Administrators, Get Started Today

 Grade, track, and report on students' progress in real time. Unlimited students, unlimited classes, unlimited teachers, unlimited schools. Typing.com's teacher portal is FREE!

 Sign Up Now » Learn More
 * Teachers
 * Schools & Districts
 * Homeschool
 * Premium
 * Students
 * Typing Lessons
 * Typing Test
 * Typing Games
 * Digital Literacy
 * Coding Curriculum
 Powered by:
 2023 © Teaching.com
 |
 * US English
 + US English
 + UK English
 + Español
 + Português
 * |
 Privacy Policy
 * |
 T.O.S.
 * |
 Resources
 * |
 Sitemap
 * |
 Support
 * 
 * 
Learn to Type | Type Better | Type Faster - Typing.com
https://www.typing.com
None
None
<div><div><article><p>Take a typing speed test, learn to type faster and with fewer errors with this free online typing tutor.</p><p>The application is loading, please wait a second...</p></article></div></div>||||I||||Typing Lessons

Take a typing speed test, learn to type faster and with fewer errors with this free online typing tutor.

The application is loading, please wait a second...

This application will not work because JavaScript is disabled in your browser!

 Sign-In
 Practice
 Profile
 Typing Test
 Help
 High Scores
 Multiplayer
 Layouts
 Text Tools
 info@keybr.comDiscordGoogle GroupsTerms of ServicePrivacy Policyde en es fr pl ru
keybr.com - Typing lessons
https://www.keybr.com/
None
2024-08-16T06:09:00Z
<div><section>

<p><span>Added in version 3.5.</span></p>
<p><strong>Source code:</strong> <a href="https://github.com/python/cpython/tree/3.12/Lib/typing.py">Lib/typing.py</a></p>
<div>
<p>Note</p>
<p>The Python runtime does not enforce function and variable type annotations.
They can be used by third party tools such as <a href="https://docs.python.org/3/glossary.html#term-static-type-checker"><span>type checkers</span></a>,
IDEs, linters, etc.</p>
</div>
<hr/>
<p>This module provides runtime support for type hints.</p>
<p>Consider the function below:</p>
<div><pre><span></span><span>def</span> <span>surface_area_of_cube</span><span>(</span><span>edge_length</span><span>:</span> <span>float</span><span>)</span> <span>-&gt;</span> <span>str</span><span>:</span>
    <span>return</span> <span>f</span><span>"The surface area of the cube is </span><span>{</span><span>6</span><span> </span><span>*</span><span> </span><span>edge_length</span><span> </span><span>**</span><span> </span><span>2</span><span>}</span><span>."</span>
</pre></div>
<p>The function <code><span>surface_area_of_cube</span></code> takes an argument expected to
be an instance of <a href="https://docs.python.org/3/library/functions.html#float"><code><span>float</span></code></a>, as indicated by the <a href="https://docs.python.org/3/glossary.html#term-type-hint"><span>type hint</span></a>
<code><span>edge_length:</span> <span>float</span></code>. The function is expected to return an instance
of <a href="https://docs.python.org/3/library/stdtypes.html#str"><code><span>str</span></code></a>, as indicated by the <code><span>-&gt;</span> <span>str</span></code> hint.</p>
<p>While type hints can be simple classes like <a href="https://docs.python.org/3/library/functions.html#float"><code><span>float</span></code></a> or <a href="https://docs.python.org/3/library/stdtypes.html#str"><code><span>str</span></code></a>,
they can also be more complex. The <a href="#module-typing"><code><span>typing</span></code></a> module provides a vocabulary of
more advanced type hints.</p>
<p>New features are frequently added to the <code><span>typing</span></code> module.
The <a href="https://pypi.org/project/typing_extensions/">typing_extensions</a> package
provides backports of these new features to older versions of Python.</p>
<div>
<p>See also</p>
<dl>
<dt><a href="https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html">“Typing cheat sheet”</a></dt><dd><p>A quick overview of type hints (hosted at the mypy docs)</p>
</dd>
<dt>“Type System Reference” section of <a href="https://mypy.readthedocs.io/en/stable/index.html">the mypy docs</a></dt><dd><p>The Python typing system is standardised via PEPs, so this reference
should broadly apply to most Python type checkers. (Some parts may still
be specific to mypy.)</p>
</dd>
<dt><a href="https://typing.readthedocs.io/en/latest/">“Static Typing with Python”</a></dt><dd><p>Type-checker-agnostic documentation written by the community detailing
type system features, useful typing related tools and typing best
practices.</p>
</dd>
</dl>
</div>
<section>
<span></span><h2>Specification for the Python Type System<a href="#specification-for-the-python-type-system">¶</a></h2>
<p>The canonical, up-to-date specification of the Python type system can be
found at <a href="https://typing.readthedocs.io/en/latest/spec/index.html">“Specification for the Python type system”</a>.</p>
</section>
<section>
<span></span><h2>Type aliases<a href="#type-aliases">¶</a></h2>
<p>A type alias is defined using the <a href="https://docs.python.org/3/reference/simple_stmts.html#type"><code><span>type</span></code></a> statement, which creates
an instance of <a href="#typing.TypeAliasType"><code><span>TypeAliasType</span></code></a>. In this example,
<code><span>Vector</span></code> and <code><span>list[float]</span></code> will be treated equivalently by static type
checkers:</p>
<div><pre><span></span><span>type</span> <span>Vector</span> <span>=</span> <span>list</span><span>[</span><span>float</span><span>]</span>

<span>def</span> <span>scale</span><span>(</span><span>scalar</span><span>:</span> <span>float</span><span>,</span> <span>vector</span><span>:</span> <span>Vector</span><span>)</span> <span>-&gt;</span> <span>Vector</span><span>:</span>
    <span>return</span> <span>[</span><span>scalar</span> <span>*</span> <span>num</span> <span>for</span> <span>num</span> <span>in</span> <span>vector</span><span>]</span>

<span># passes type checking; a list of floats qualifies as a Vector.</span>
<span>new_vector</span> <span>=</span> <span>scale</span><span>(</span><span>2.0</span><span>,</span> <span>[</span><span>1.0</span><span>,</span> <span>-</span><span>4.2</span><span>,</span> <span>5.4</span><span>])</span>
</pre></div>
<p>Type aliases are useful for simplifying complex type signatures. For example:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Sequence</span>

<span>type</span> <span>ConnectionOptions</span> <span>=</span> <span>dict</span><span>[</span><span>str</span><span>,</span> <span>str</span><span>]</span>
<span>type</span> <span>Address</span> <span>=</span> <span>tuple</span><span>[</span><span>str</span><span>,</span> <span>int</span><span>]</span>
<span>type</span> <span>Server</span> <span>=</span> <span>tuple</span><span>[</span><span>Address</span><span>,</span> <span>ConnectionOptions</span><span>]</span>

<span>def</span> <span>broadcast_message</span><span>(</span><span>message</span><span>:</span> <span>str</span><span>,</span> <span>servers</span><span>:</span> <span>Sequence</span><span>[</span><span>Server</span><span>])</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>

<span># The static type checker will treat the previous type signature as</span>
<span># being exactly equivalent to this one.</span>
<span>def</span> <span>broadcast_message</span><span>(</span>
    <span>message</span><span>:</span> <span>str</span><span>,</span>
    <span>servers</span><span>:</span> <span>Sequence</span><span>[</span><span>tuple</span><span>[</span><span>tuple</span><span>[</span><span>str</span><span>,</span> <span>int</span><span>],</span> <span>dict</span><span>[</span><span>str</span><span>,</span> <span>str</span><span>]]]</span>
<span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>
</pre></div>
<p>The <a href="https://docs.python.org/3/reference/simple_stmts.html#type"><code><span>type</span></code></a> statement is new in Python 3.12. For backwards
compatibility, type aliases can also be created through simple assignment:</p>

<p>Or marked with <a href="#typing.TypeAlias"><code><span>TypeAlias</span></code></a> to make it explicit that this is a type alias,
not a normal variable assignment:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>TypeAlias</span>

<span>Vector</span><span>:</span> <span>TypeAlias</span> <span>=</span> <span>list</span><span>[</span><span>float</span><span>]</span>
</pre></div>
</section>
<section>
<span></span><h2>NewType<a href="#newtype">¶</a></h2>
<p>Use the <a href="#typing.NewType"><code><span>NewType</span></code></a> helper to create distinct types:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>NewType</span>

<span>UserId</span> <span>=</span> <span>NewType</span><span>(</span><span>'UserId'</span><span>,</span> <span>int</span><span>)</span>
<span>some_id</span> <span>=</span> <span>UserId</span><span>(</span><span>524313</span><span>)</span>
</pre></div>
<p>The static type checker will treat the new type as if it were a subclass
of the original type. This is useful in helping catch logical errors:</p>
<div><pre><span></span><span>def</span> <span>get_user_name</span><span>(</span><span>user_id</span><span>:</span> <span>UserId</span><span>)</span> <span>-&gt;</span> <span>str</span><span>:</span>
    <span>...</span>

<span># passes type checking</span>
<span>user_a</span> <span>=</span> <span>get_user_name</span><span>(</span><span>UserId</span><span>(</span><span>42351</span><span>))</span>

<span># fails type checking; an int is not a UserId</span>
<span>user_b</span> <span>=</span> <span>get_user_name</span><span>(</span><span>-</span><span>1</span><span>)</span>
</pre></div>
<p>You may still perform all <code><span>int</span></code> operations on a variable of type <code><span>UserId</span></code>,
but the result will always be of type <code><span>int</span></code>. This lets you pass in a
<code><span>UserId</span></code> wherever an <code><span>int</span></code> might be expected, but will prevent you from
accidentally creating a <code><span>UserId</span></code> in an invalid way:</p>
<div><pre><span></span><span># 'output' is of type 'int', not 'UserId'</span>
<span>output</span> <span>=</span> <span>UserId</span><span>(</span><span>23413</span><span>)</span> <span>+</span> <span>UserId</span><span>(</span><span>54341</span><span>)</span>
</pre></div>
<p>Note that these checks are enforced only by the static type checker. At runtime,
the statement <code><span>Derived</span> <span>=</span> <span>NewType('Derived',</span> <span>Base)</span></code> will make <code><span>Derived</span></code> a
callable that immediately returns whatever parameter you pass it. That means
the expression <code><span>Derived(some_value)</span></code> does not create a new class or introduce
much overhead beyond that of a regular function call.</p>
<p>More precisely, the expression <code><span>some_value</span> <span>is</span> <span>Derived(some_value)</span></code> is always
true at runtime.</p>
<p>It is invalid to create a subtype of <code><span>Derived</span></code>:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>NewType</span>

<span>UserId</span> <span>=</span> <span>NewType</span><span>(</span><span>'UserId'</span><span>,</span> <span>int</span><span>)</span>

<span># Fails at runtime and does not pass type checking</span>
<span>class</span> <span>AdminUserId</span><span>(</span><span>UserId</span><span>):</span> <span>pass</span>
</pre></div>
<p>However, it is possible to create a <a href="#typing.NewType"><code><span>NewType</span></code></a> based on a ‘derived’ <code><span>NewType</span></code>:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>NewType</span>

<span>UserId</span> <span>=</span> <span>NewType</span><span>(</span><span>'UserId'</span><span>,</span> <span>int</span><span>)</span>

<span>ProUserId</span> <span>=</span> <span>NewType</span><span>(</span><span>'ProUserId'</span><span>,</span> <span>UserId</span><span>)</span>
</pre></div>
<p>and typechecking for <code><span>ProUserId</span></code> will work as expected.</p>
<p>See <span></span><a href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> for more details.</p>
<div>
<p>Note</p>
<p>Recall that the use of a type alias declares two types to be <em>equivalent</em> to
one another. Doing <code><span>type</span> <span>Alias</span> <span>=</span> <span>Original</span></code> will make the static type checker
treat <code><span>Alias</span></code> as being <em>exactly equivalent</em> to <code><span>Original</span></code> in all cases.
This is useful when you want to simplify complex type signatures.</p>
<p>In contrast, <code><span>NewType</span></code> declares one type to be a <em>subtype</em> of another.
Doing <code><span>Derived</span> <span>=</span> <span>NewType('Derived',</span> <span>Original)</span></code> will make the static type
checker treat <code><span>Derived</span></code> as a <em>subclass</em> of <code><span>Original</span></code>, which means a
value of type <code><span>Original</span></code> cannot be used in places where a value of type
<code><span>Derived</span></code> is expected. This is useful when you want to prevent logic
errors with minimal runtime cost.</p>
</div>
<p><span>Added in version 3.5.2.</span></p>
<p><span>Changed in version 3.10: </span><code><span>NewType</span></code> is now a class rather than a function.  As a result, there is
some additional runtime cost when calling <code><span>NewType</span></code> over a regular
function.</p>
<p><span>Changed in version 3.11: </span>The performance of calling <code><span>NewType</span></code> has been restored to its level in
Python 3.9.</p>
</section>
<section>
<span></span><h2>Annotating callable objects<a href="#annotating-callable-objects">¶</a></h2>
<p>Functions – or other <a href="https://docs.python.org/3/glossary.html#term-callable"><span>callable</span></a> objects – can be annotated using
<a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable"><code><span>collections.abc.Callable</span></code></a> or <a href="#typing.Callable"><code><span>typing.Callable</span></code></a>.
<code><span>Callable[[int],</span> <span>str]</span></code> signifies a function that takes a single parameter
of type <a href="https://docs.python.org/3/library/functions.html#int"><code><span>int</span></code></a> and returns a <a href="https://docs.python.org/3/library/stdtypes.html#str"><code><span>str</span></code></a>.</p>
<p>For example:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Callable</span><span>,</span> <span>Awaitable</span>

<span>def</span> <span>feeder</span><span>(</span><span>get_next_item</span><span>:</span> <span>Callable</span><span>[[],</span> <span>str</span><span>])</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>  <span># Body</span>

<span>def</span> <span>async_query</span><span>(</span><span>on_success</span><span>:</span> <span>Callable</span><span>[[</span><span>int</span><span>],</span> <span>None</span><span>],</span>
                <span>on_error</span><span>:</span> <span>Callable</span><span>[[</span><span>int</span><span>,</span> <span>Exception</span><span>],</span> <span>None</span><span>])</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>  <span># Body</span>

<span>async</span> <span>def</span> <span>on_update</span><span>(</span><span>value</span><span>:</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>  <span># Body</span>

<span>callback</span><span>:</span> <span>Callable</span><span>[[</span><span>str</span><span>],</span> <span>Awaitable</span><span>[</span><span>None</span><span>]]</span> <span>=</span> <span>on_update</span>
</pre></div>
<p>The subscription syntax must always be used with exactly two values: the
argument list and the return type.  The argument list must be a list of types,
a <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a>, <a href="#typing.Concatenate"><code><span>Concatenate</span></code></a>, or an ellipsis. The return type must
be a single type.</p>
<p>If a literal ellipsis <code><span>...</span></code> is given as the argument list, it indicates that
a callable with any arbitrary parameter list would be acceptable:</p>
<div><pre><span></span><span>def</span> <span>concat</span><span>(</span><span>x</span><span>:</span> <span>str</span><span>,</span> <span>y</span><span>:</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>str</span><span>:</span>
    <span>return</span> <span>x</span> <span>+</span> <span>y</span>

<span>x</span><span>:</span> <span>Callable</span><span>[</span><span>...</span><span>,</span> <span>str</span><span>]</span>
<span>x</span> <span>=</span> <span>str</span>     <span># OK</span>
<span>x</span> <span>=</span> <span>concat</span>  <span># Also OK</span>
</pre></div>
<p><code><span>Callable</span></code> cannot express complex signatures such as functions that take a
variadic number of arguments, <a href="#overload"><span>overloaded functions</span></a>, or
functions that have keyword-only parameters. However, these signatures can be
expressed by defining a <a href="#typing.Protocol"><code><span>Protocol</span></code></a> class with a
<a href="https://docs.python.org/3/reference/datamodel.html#object.__call__"><code><span>__call__()</span></code></a> method:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Iterable</span>
<span>from</span> <span>typing</span> <span>import</span> <span>Protocol</span>

<span>class</span> <span>Combiner</span><span>(</span><span>Protocol</span><span>):</span>
    <span>def</span> <span>__call__</span><span>(</span><span>self</span><span>,</span> <span>*</span><span>vals</span><span>:</span> <span>bytes</span><span>,</span> <span>maxlen</span><span>:</span> <span>int</span> <span>|</span> <span>None</span> <span>=</span> <span>None</span><span>)</span> <span>-&gt;</span> <span>list</span><span>[</span><span>bytes</span><span>]:</span> <span>...</span>

<span>def</span> <span>batch_proc</span><span>(</span><span>data</span><span>:</span> <span>Iterable</span><span>[</span><span>bytes</span><span>],</span> <span>cb_results</span><span>:</span> <span>Combiner</span><span>)</span> <span>-&gt;</span> <span>bytes</span><span>:</span>
    <span>for</span> <span>item</span> <span>in</span> <span>data</span><span>:</span>
        <span>...</span>

<span>def</span> <span>good_cb</span><span>(</span><span>*</span><span>vals</span><span>:</span> <span>bytes</span><span>,</span> <span>maxlen</span><span>:</span> <span>int</span> <span>|</span> <span>None</span> <span>=</span> <span>None</span><span>)</span> <span>-&gt;</span> <span>list</span><span>[</span><span>bytes</span><span>]:</span>
    <span>...</span>
<span>def</span> <span>bad_cb</span><span>(</span><span>*</span><span>vals</span><span>:</span> <span>bytes</span><span>,</span> <span>maxitems</span><span>:</span> <span>int</span> <span>|</span> <span>None</span><span>)</span> <span>-&gt;</span> <span>list</span><span>[</span><span>bytes</span><span>]:</span>
    <span>...</span>

<span>batch_proc</span><span>([],</span> <span>good_cb</span><span>)</span>  <span># OK</span>
<span>batch_proc</span><span>([],</span> <span>bad_cb</span><span>)</span>   <span># Error! Argument 2 has incompatible type because of</span>
                         <span># different name and kind in the callback</span>
</pre></div>
<p>Callables which take other callables as arguments may indicate that their
parameter types are dependent on each other using <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a>.
Additionally, if that callable adds or removes arguments from other
callables, the <a href="#typing.Concatenate"><code><span>Concatenate</span></code></a> operator may be used.  They
take the form <code><span>Callable[ParamSpecVariable,</span> <span>ReturnType]</span></code> and
<code><span>Callable[Concatenate[Arg1Type,</span> <span>Arg2Type,</span> <span>...,</span> <span>ParamSpecVariable],</span> <span>ReturnType]</span></code>
respectively.</p>
<p><span>Changed in version 3.10: </span><code><span>Callable</span></code> now supports <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> and <a href="#typing.Concatenate"><code><span>Concatenate</span></code></a>.
See <span></span><a href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> for more details.</p>
<div>
<p>See also</p>
<p>The documentation for <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> and <a href="#typing.Concatenate"><code><span>Concatenate</span></code></a> provides
examples of usage in <code><span>Callable</span></code>.</p>
</div>
</section>
<section>
<span></span><h2>Generics<a href="#generics">¶</a></h2>
<p>Since type information about objects kept in containers cannot be statically
inferred in a generic way, many container classes in the standard library support
subscription to denote the expected types of container elements.</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Mapping</span><span>,</span> <span>Sequence</span>

<span>class</span> <span>Employee</span><span>:</span> <span>...</span>

<span># Sequence[Employee] indicates that all elements in the sequence</span>
<span># must be instances of "Employee".</span>
<span># Mapping[str, str] indicates that all keys and all values in the mapping</span>
<span># must be strings.</span>
<span>def</span> <span>notify_by_email</span><span>(</span><span>employees</span><span>:</span> <span>Sequence</span><span>[</span><span>Employee</span><span>],</span>
                    <span>overrides</span><span>:</span> <span>Mapping</span><span>[</span><span>str</span><span>,</span> <span>str</span><span>])</span> <span>-&gt;</span> <span>None</span><span>:</span> <span>...</span>
</pre></div>
<p>Generic functions and classes can be parameterized by using
<a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter syntax</span></a>:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Sequence</span>

<span>def</span> <span>first</span><span>[</span><span>T</span><span>](</span><span>l</span><span>:</span> <span>Sequence</span><span>[</span><span>T</span><span>])</span> <span>-&gt;</span> <span>T</span><span>:</span>  <span># Function is generic over the TypeVar "T"</span>
    <span>return</span> <span>l</span><span>[</span><span>0</span><span>]</span>
</pre></div>
<p>Or by using the <a href="#typing.TypeVar"><code><span>TypeVar</span></code></a> factory directly:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Sequence</span>
<span>from</span> <span>typing</span> <span>import</span> <span>TypeVar</span>

<span>U</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'U'</span><span>)</span>                  <span># Declare type variable "U"</span>

<span>def</span> <span>second</span><span>(</span><span>l</span><span>:</span> <span>Sequence</span><span>[</span><span>U</span><span>])</span> <span>-&gt;</span> <span>U</span><span>:</span>  <span># Function is generic over the TypeVar "U"</span>
    <span>return</span> <span>l</span><span>[</span><span>1</span><span>]</span>
</pre></div>
<p><span>Changed in version 3.12: </span>Syntactic support for generics is new in Python 3.12.</p>
</section>
<section>
<span></span><h2>Annotating tuples<a href="#annotating-tuples">¶</a></h2>
<p>For most containers in Python, the typing system assumes that all elements in
the container will be of the same type. For example:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Mapping</span>

<span># Type checker will infer that all elements in ``x`` are meant to be ints</span>
<span>x</span><span>:</span> <span>list</span><span>[</span><span>int</span><span>]</span> <span>=</span> <span>[]</span>

<span># Type checker error: ``list`` only accepts a single type argument:</span>
<span>y</span><span>:</span> <span>list</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>]</span> <span>=</span> <span>[</span><span>1</span><span>,</span> <span>'foo'</span><span>]</span>

<span># Type checker will infer that all keys in ``z`` are meant to be strings,</span>
<span># and that all values in ``z`` are meant to be either strings or ints</span>
<span>z</span><span>:</span> <span>Mapping</span><span>[</span><span>str</span><span>,</span> <span>str</span> <span>|</span> <span>int</span><span>]</span> <span>=</span> <span>{}</span>
</pre></div>
<p><a href="https://docs.python.org/3/library/stdtypes.html#list"><code><span>list</span></code></a> only accepts one type argument, so a type checker would emit an
error on the <code><span>y</span></code> assignment above. Similarly,
<a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping"><code><span>Mapping</span></code></a> only accepts two type arguments: the first
indicates the type of the keys, and the second indicates the type of the
values.</p>
<p>Unlike most other Python containers, however, it is common in idiomatic Python
code for tuples to have elements which are not all of the same type. For this
reason, tuples are special-cased in Python’s typing system. <a href="https://docs.python.org/3/library/stdtypes.html#tuple"><code><span>tuple</span></code></a>
accepts <em>any number</em> of type arguments:</p>
<div><pre><span></span><span># OK: ``x`` is assigned to a tuple of length 1 where the sole element is an int</span>
<span>x</span><span>:</span> <span>tuple</span><span>[</span><span>int</span><span>]</span> <span>=</span> <span>(</span><span>5</span><span>,)</span>

<span># OK: ``y`` is assigned to a tuple of length 2;</span>
<span># element 1 is an int, element 2 is a str</span>
<span>y</span><span>:</span> <span>tuple</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>]</span> <span>=</span> <span>(</span><span>5</span><span>,</span> <span>"foo"</span><span>)</span>

<span># Error: the type annotation indicates a tuple of length 1,</span>
<span># but ``z`` has been assigned to a tuple of length 3</span>
<span>z</span><span>:</span> <span>tuple</span><span>[</span><span>int</span><span>]</span> <span>=</span> <span>(</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>)</span>
</pre></div>
<p>To denote a tuple which could be of <em>any</em> length, and in which all elements are
of the same type <code><span>T</span></code>, use <code><span>tuple[T,</span> <span>...]</span></code>. To denote an empty tuple, use
<code><span>tuple[()]</span></code>. Using plain <code><span>tuple</span></code> as an annotation is equivalent to using
<code><span>tuple[Any,</span> <span>...]</span></code>:</p>
<div><pre><span></span><span>x</span><span>:</span> <span>tuple</span><span>[</span><span>int</span><span>,</span> <span>...</span><span>]</span> <span>=</span> <span>(</span><span>1</span><span>,</span> <span>2</span><span>)</span>
<span># These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any length</span>
<span>x</span> <span>=</span> <span>(</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>)</span>
<span>x</span> <span>=</span> <span>()</span>
<span># This reassignment is an error: all elements in ``x`` must be ints</span>
<span>x</span> <span>=</span> <span>(</span><span>"foo"</span><span>,</span> <span>"bar"</span><span>)</span>

<span># ``y`` can only ever be assigned to an empty tuple</span>
<span>y</span><span>:</span> <span>tuple</span><span>[()]</span> <span>=</span> <span>()</span>

<span>z</span><span>:</span> <span>tuple</span> <span>=</span> <span>(</span><span>"foo"</span><span>,</span> <span>"bar"</span><span>)</span>
<span># These reassignments are OK: plain ``tuple`` is equivalent to ``tuple[Any, ...]``</span>
<span>z</span> <span>=</span> <span>(</span><span>1</span><span>,</span> <span>2</span><span>,</span> <span>3</span><span>)</span>
<span>z</span> <span>=</span> <span>()</span>
</pre></div>
</section>
<section>
<span></span><h2>The type of class objects<a href="#the-type-of-class-objects">¶</a></h2>
<p>A variable annotated with <code><span>C</span></code> may accept a value of type <code><span>C</span></code>. In
contrast, a variable annotated with <code><span>type[C]</span></code> (or
<a href="#typing.Type"><code><span>typing.Type[C]</span></code></a>) may accept values that are classes
themselves – specifically, it will accept the <em>class object</em> of <code><span>C</span></code>. For
example:</p>
<div><pre><span></span><span>a</span> <span>=</span> <span>3</span>         <span># Has type ``int``</span>
<span>b</span> <span>=</span> <span>int</span>       <span># Has type ``type[int]``</span>
<span>c</span> <span>=</span> <span>type</span><span>(</span><span>a</span><span>)</span>   <span># Also has type ``type[int]``</span>
</pre></div>
<p>Note that <code><span>type[C]</span></code> is covariant:</p>
<div><pre><span></span><span>class</span> <span>User</span><span>:</span> <span>...</span>
<span>class</span> <span>ProUser</span><span>(</span><span>User</span><span>):</span> <span>...</span>
<span>class</span> <span>TeamUser</span><span>(</span><span>User</span><span>):</span> <span>...</span>

<span>def</span> <span>make_new_user</span><span>(</span><span>user_class</span><span>:</span> <span>type</span><span>[</span><span>User</span><span>])</span> <span>-&gt;</span> <span>User</span><span>:</span>
    <span># ...</span>
    <span>return</span> <span>user_class</span><span>()</span>

<span>make_new_user</span><span>(</span><span>User</span><span>)</span>      <span># OK</span>
<span>make_new_user</span><span>(</span><span>ProUser</span><span>)</span>   <span># Also OK: ``type[ProUser]`` is a subtype of ``type[User]``</span>
<span>make_new_user</span><span>(</span><span>TeamUser</span><span>)</span>  <span># Still fine</span>
<span>make_new_user</span><span>(</span><span>User</span><span>())</span>    <span># Error: expected ``type[User]`` but got ``User``</span>
<span>make_new_user</span><span>(</span><span>int</span><span>)</span>       <span># Error: ``type[int]`` is not a subtype of ``type[User]``</span>
</pre></div>
<p>The only legal parameters for <a href="https://docs.python.org/3/library/functions.html#type"><code><span>type</span></code></a> are classes, <a href="#typing.Any"><code><span>Any</span></code></a>,
<a href="#generics"><span>type variables</span></a>, and unions of any of these types.
For example:</p>
<div><pre><span></span><span>def</span> <span>new_non_team_user</span><span>(</span><span>user_class</span><span>:</span> <span>type</span><span>[</span><span>BasicUser</span> <span>|</span> <span>ProUser</span><span>]):</span> <span>...</span>

<span>new_non_team_user</span><span>(</span><span>BasicUser</span><span>)</span>  <span># OK</span>
<span>new_non_team_user</span><span>(</span><span>ProUser</span><span>)</span>    <span># OK</span>
<span>new_non_team_user</span><span>(</span><span>TeamUser</span><span>)</span>   <span># Error: ``type[TeamUser]`` is not a subtype</span>
                              <span># of ``type[BasicUser | ProUser]``</span>
<span>new_non_team_user</span><span>(</span><span>User</span><span>)</span>       <span># Also an error</span>
</pre></div>
<p><code><span>type[Any]</span></code> is equivalent to <a href="https://docs.python.org/3/library/functions.html#type"><code><span>type</span></code></a>, which is the root of Python’s
<a href="https://docs.python.org/3/reference/datamodel.html#metaclasses"><span>metaclass hierarchy</span></a>.</p>
</section>
<section>
<span></span><h2>User-defined generic types<a href="#user-defined-generic-types">¶</a></h2>
<p>A user-defined class can be defined as a generic class.</p>
<div><pre><span></span><span>from</span> <span>logging</span> <span>import</span> <span>Logger</span>

<span>class</span> <span>LoggedVar</span><span>[</span><span>T</span><span>]:</span>
    <span>def</span> <span>__init__</span><span>(</span><span>self</span><span>,</span> <span>value</span><span>:</span> <span>T</span><span>,</span> <span>name</span><span>:</span> <span>str</span><span>,</span> <span>logger</span><span>:</span> <span>Logger</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
        <span>self</span><span>.</span><span>name</span> <span>=</span> <span>name</span>
        <span>self</span><span>.</span><span>logger</span> <span>=</span> <span>logger</span>
        <span>self</span><span>.</span><span>value</span> <span>=</span> <span>value</span>

    <span>def</span> <span>set</span><span>(</span><span>self</span><span>,</span> <span>new</span><span>:</span> <span>T</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
        <span>self</span><span>.</span><span>log</span><span>(</span><span>'Set '</span> <span>+</span> <span>repr</span><span>(</span><span>self</span><span>.</span><span>value</span><span>))</span>
        <span>self</span><span>.</span><span>value</span> <span>=</span> <span>new</span>

    <span>def</span> <span>get</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>T</span><span>:</span>
        <span>self</span><span>.</span><span>log</span><span>(</span><span>'Get '</span> <span>+</span> <span>repr</span><span>(</span><span>self</span><span>.</span><span>value</span><span>))</span>
        <span>return</span> <span>self</span><span>.</span><span>value</span>

    <span>def</span> <span>log</span><span>(</span><span>self</span><span>,</span> <span>message</span><span>:</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
        <span>self</span><span>.</span><span>logger</span><span>.</span><span>info</span><span>(</span><span>'</span><span>%s</span><span>: </span><span>%s</span><span>'</span><span>,</span> <span>self</span><span>.</span><span>name</span><span>,</span> <span>message</span><span>)</span>
</pre></div>
<p>This syntax indicates that the class <code><span>LoggedVar</span></code> is parameterised around a
single <a href="#typevar"><span>type variable</span></a> <code><span>T</span></code> . This also makes <code><span>T</span></code> valid as
a type within the class body.</p>
<p>Generic classes implicitly inherit from <a href="#typing.Generic"><code><span>Generic</span></code></a>. For compatibility
with Python 3.11 and lower, it is also possible to inherit explicitly from
<a href="#typing.Generic"><code><span>Generic</span></code></a> to indicate a generic class:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>TypeVar</span><span>,</span> <span>Generic</span>

<span>T</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'T'</span><span>)</span>

<span>class</span> <span>LoggedVar</span><span>(</span><span>Generic</span><span>[</span><span>T</span><span>]):</span>
    <span>...</span>
</pre></div>
<p>Generic classes have <a href="https://docs.python.org/3/reference/datamodel.html#object.__class_getitem__"><code><span>__class_getitem__()</span></code></a> methods, meaning they
can be parameterised at runtime (e.g. <code><span>LoggedVar[int]</span></code> below):</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Iterable</span>

<span>def</span> <span>zero_all_vars</span><span>(</span><span>vars</span><span>:</span> <span>Iterable</span><span>[</span><span>LoggedVar</span><span>[</span><span>int</span><span>]])</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>for</span> <span>var</span> <span>in</span> <span>vars</span><span>:</span>
        <span>var</span><span>.</span><span>set</span><span>(</span><span>0</span><span>)</span>
</pre></div>
<p>A generic type can have any number of type variables. All varieties of
<a href="#typing.TypeVar"><code><span>TypeVar</span></code></a> are permissible as parameters for a generic type:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>TypeVar</span><span>,</span> <span>Generic</span><span>,</span> <span>Sequence</span>

<span>class</span> <span>WeirdTrio</span><span>[</span><span>T</span><span>,</span> <span>B</span><span>:</span> <span>Sequence</span><span>[</span><span>bytes</span><span>],</span> <span>S</span><span>:</span> <span>(</span><span>int</span><span>,</span> <span>str</span><span>)]:</span>
    <span>...</span>

<span>OldT</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'OldT'</span><span>,</span> <span>contravariant</span><span>=</span><span>True</span><span>)</span>
<span>OldB</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'OldB'</span><span>,</span> <span>bound</span><span>=</span><span>Sequence</span><span>[</span><span>bytes</span><span>],</span> <span>covariant</span><span>=</span><span>True</span><span>)</span>
<span>OldS</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'OldS'</span><span>,</span> <span>int</span><span>,</span> <span>str</span><span>)</span>

<span>class</span> <span>OldWeirdTrio</span><span>(</span><span>Generic</span><span>[</span><span>OldT</span><span>,</span> <span>OldB</span><span>,</span> <span>OldS</span><span>]):</span>
    <span>...</span>
</pre></div>
<p>Each type variable argument to <a href="#typing.Generic"><code><span>Generic</span></code></a> must be distinct.
This is thus invalid:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>TypeVar</span><span>,</span> <span>Generic</span>
<span>...</span>

<span>class</span> <span>Pair</span><span>[</span><span>M</span><span>,</span> <span>M</span><span>]:</span>  <span># SyntaxError</span>
    <span>...</span>

<span>T</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'T'</span><span>)</span>

<span>class</span> <span>Pair</span><span>(</span><span>Generic</span><span>[</span><span>T</span><span>,</span> <span>T</span><span>]):</span>   <span># INVALID</span>
    <span>...</span>
</pre></div>
<p>Generic classes can also inherit from other classes:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Sized</span>

<span>class</span> <span>LinkedList</span><span>[</span><span>T</span><span>](</span><span>Sized</span><span>):</span>
    <span>...</span>
</pre></div>
<p>When inheriting from generic classes, some type parameters could be fixed:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Mapping</span>

<span>class</span> <span>MyDict</span><span>[</span><span>T</span><span>](</span><span>Mapping</span><span>[</span><span>str</span><span>,</span> <span>T</span><span>]):</span>
    <span>...</span>
</pre></div>
<p>In this case <code><span>MyDict</span></code> has a single parameter, <code><span>T</span></code>.</p>
<p>Using a generic class without specifying type parameters assumes
<a href="#typing.Any"><code><span>Any</span></code></a> for each position. In the following example, <code><span>MyIterable</span></code> is
not generic but implicitly inherits from <code><span>Iterable[Any]</span></code>:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Iterable</span>

<span>class</span> <span>MyIterable</span><span>(</span><span>Iterable</span><span>):</span> <span># Same as Iterable[Any]</span>
    <span>...</span>
</pre></div>
<p>User-defined generic type aliases are also supported. Examples:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Iterable</span>

<span>type</span> <span>Response</span><span>[</span><span>S</span><span>]</span> <span>=</span> <span>Iterable</span><span>[</span><span>S</span><span>]</span> <span>|</span> <span>int</span>

<span># Return type here is same as Iterable[str] | int</span>
<span>def</span> <span>response</span><span>(</span><span>query</span><span>:</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>Response</span><span>[</span><span>str</span><span>]:</span>
    <span>...</span>

<span>type</span> <span>Vec</span><span>[</span><span>T</span><span>]</span> <span>=</span> <span>Iterable</span><span>[</span><span>tuple</span><span>[</span><span>T</span><span>,</span> <span>T</span><span>]]</span>

<span>def</span> <span>inproduct</span><span>[</span><span>T</span><span>:</span> <span>(</span><span>int</span><span>,</span> <span>float</span><span>,</span> <span>complex</span><span>)](</span><span>v</span><span>:</span> <span>Vec</span><span>[</span><span>T</span><span>])</span> <span>-&gt;</span> <span>T</span><span>:</span> <span># Same as Iterable[tuple[T, T]]</span>
    <span>return</span> <span>sum</span><span>(</span><span>x</span><span>*</span><span>y</span> <span>for</span> <span>x</span><span>,</span> <span>y</span> <span>in</span> <span>v</span><span>)</span>
</pre></div>
<p>For backward compatibility, generic type aliases can also be created
through a simple assignment:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Iterable</span>
<span>from</span> <span>typing</span> <span>import</span> <span>TypeVar</span>

<span>S</span> <span>=</span> <span>TypeVar</span><span>(</span><span>"S"</span><span>)</span>
<span>Response</span> <span>=</span> <span>Iterable</span><span>[</span><span>S</span><span>]</span> <span>|</span> <span>int</span>
</pre></div>
<p><span>Changed in version 3.7: </span><a href="#typing.Generic"><code><span>Generic</span></code></a> no longer has a custom metaclass.</p>
<p><span>Changed in version 3.12: </span>Syntactic support for generics and type aliases is new in version 3.12.
Previously, generic classes had to explicitly inherit from <a href="#typing.Generic"><code><span>Generic</span></code></a>
or contain a type variable in one of their bases.</p>
<p>User-defined generics for parameter expressions are also supported via parameter
specification variables in the form <code><span>[**P]</span></code>.  The behavior is consistent
with type variables’ described above as parameter specification variables are
treated by the typing module as a specialized type variable.  The one exception
to this is that a list of types can be used to substitute a <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a>:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>class</span> <span>Z</span><span>[</span><span>T</span><span>,</span> <span>**</span><span>P</span><span>]:</span> <span>...</span>  <span># T is a TypeVar; P is a ParamSpec</span>
<span>...</span>
<span>&gt;&gt;&gt; </span><span>Z</span><span>[</span><span>int</span><span>,</span> <span>[</span><span>dict</span><span>,</span> <span>float</span><span>]]</span>
<span>__main__.Z[int, [dict, float]]</span>
</pre></div>
<p>Classes generic over a <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> can also be created using explicit
inheritance from <a href="#typing.Generic"><code><span>Generic</span></code></a>. In this case, <code><span>**</span></code> is not used:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>ParamSpec</span><span>,</span> <span>Generic</span>

<span>P</span> <span>=</span> <span>ParamSpec</span><span>(</span><span>'P'</span><span>)</span>

<span>class</span> <span>Z</span><span>(</span><span>Generic</span><span>[</span><span>P</span><span>]):</span>
    <span>...</span>
</pre></div>
<p>Another difference between <a href="#typing.TypeVar"><code><span>TypeVar</span></code></a> and <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> is that a
generic with only one parameter specification variable will accept
parameter lists in the forms <code><span>X[[Type1,</span> <span>Type2,</span> <span>...]]</span></code> and also
<code><span>X[Type1,</span> <span>Type2,</span> <span>...]</span></code> for aesthetic reasons.  Internally, the latter is converted
to the former, so the following are equivalent:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>class</span> <span>X</span><span>[</span><span>**</span><span>P</span><span>]:</span> <span>...</span>
<span>...</span>
<span>&gt;&gt;&gt; </span><span>X</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>]</span>
<span>__main__.X[[int, str]]</span>
<span>&gt;&gt;&gt; </span><span>X</span><span>[[</span><span>int</span><span>,</span> <span>str</span><span>]]</span>
<span>__main__.X[[int, str]]</span>
</pre></div>
<p>Note that generics with <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> may not have correct
<code><span>__parameters__</span></code> after substitution in some cases because they
are intended primarily for static type checking.</p>
<p><span>Changed in version 3.10: </span><a href="#typing.Generic"><code><span>Generic</span></code></a> can now be parameterized over parameter expressions.
See <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> and <span></span><a href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> for more details.</p>
<p>A user-defined generic class can have ABCs as base classes without a metaclass
conflict. Generic metaclasses are not supported. The outcome of parameterizing
generics is cached, and most types in the typing module are <a href="https://docs.python.org/3/glossary.html#term-hashable"><span>hashable</span></a> and
comparable for equality.</p>
</section>
<section>
<h2>The <a href="#typing.Any"><code><span>Any</span></code></a> type<a href="#the-any-type">¶</a></h2>
<p>A special kind of type is <a href="#typing.Any"><code><span>Any</span></code></a>. A static type checker will treat
every type as being compatible with <a href="#typing.Any"><code><span>Any</span></code></a> and <a href="#typing.Any"><code><span>Any</span></code></a> as being
compatible with every type.</p>
<p>This means that it is possible to perform any operation or method call on a
value of type <a href="#typing.Any"><code><span>Any</span></code></a> and assign it to any variable:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>Any</span>

<span>a</span><span>:</span> <span>Any</span> <span>=</span> <span>None</span>
<span>a</span> <span>=</span> <span>[]</span>          <span># OK</span>
<span>a</span> <span>=</span> <span>2</span>           <span># OK</span>

<span>s</span><span>:</span> <span>str</span> <span>=</span> <span>''</span>
<span>s</span> <span>=</span> <span>a</span>           <span># OK</span>

<span>def</span> <span>foo</span><span>(</span><span>item</span><span>:</span> <span>Any</span><span>)</span> <span>-&gt;</span> <span>int</span><span>:</span>
    <span># Passes type checking; 'item' could be any type,</span>
    <span># and that type might have a 'bar' method</span>
    <span>item</span><span>.</span><span>bar</span><span>()</span>
    <span>...</span>
</pre></div>
<p>Notice that no type checking is performed when assigning a value of type
<a href="#typing.Any"><code><span>Any</span></code></a> to a more precise type. For example, the static type checker did
not report an error when assigning <code><span>a</span></code> to <code><span>s</span></code> even though <code><span>s</span></code> was
declared to be of type <a href="https://docs.python.org/3/library/stdtypes.html#str"><code><span>str</span></code></a> and receives an <a href="https://docs.python.org/3/library/functions.html#int"><code><span>int</span></code></a> value at
runtime!</p>
<p>Furthermore, all functions without a return type or parameter types will
implicitly default to using <a href="#typing.Any"><code><span>Any</span></code></a>:</p>
<div><pre><span></span><span>def</span> <span>legacy_parser</span><span>(</span><span>text</span><span>):</span>
    <span>...</span>
    <span>return</span> <span>data</span>

<span># A static type checker will treat the above</span>
<span># as having the same signature as:</span>
<span>def</span> <span>legacy_parser</span><span>(</span><span>text</span><span>:</span> <span>Any</span><span>)</span> <span>-&gt;</span> <span>Any</span><span>:</span>
    <span>...</span>
    <span>return</span> <span>data</span>
</pre></div>
<p>This behavior allows <a href="#typing.Any"><code><span>Any</span></code></a> to be used as an <em>escape hatch</em> when you
need to mix dynamically and statically typed code.</p>
<p>Contrast the behavior of <a href="#typing.Any"><code><span>Any</span></code></a> with the behavior of <a href="https://docs.python.org/3/library/functions.html#object"><code><span>object</span></code></a>.
Similar to <a href="#typing.Any"><code><span>Any</span></code></a>, every type is a subtype of <a href="https://docs.python.org/3/library/functions.html#object"><code><span>object</span></code></a>. However,
unlike <a href="#typing.Any"><code><span>Any</span></code></a>, the reverse is not true: <a href="https://docs.python.org/3/library/functions.html#object"><code><span>object</span></code></a> is <em>not</em> a
subtype of every other type.</p>
<p>That means when the type of a value is <a href="https://docs.python.org/3/library/functions.html#object"><code><span>object</span></code></a>, a type checker will
reject almost all operations on it, and assigning it to a variable (or using
it as a return value) of a more specialized type is a type error. For example:</p>
<div><pre><span></span><span>def</span> <span>hash_a</span><span>(</span><span>item</span><span>:</span> <span>object</span><span>)</span> <span>-&gt;</span> <span>int</span><span>:</span>
    <span># Fails type checking; an object does not have a 'magic' method.</span>
    <span>item</span><span>.</span><span>magic</span><span>()</span>
    <span>...</span>

<span>def</span> <span>hash_b</span><span>(</span><span>item</span><span>:</span> <span>Any</span><span>)</span> <span>-&gt;</span> <span>int</span><span>:</span>
    <span># Passes type checking</span>
    <span>item</span><span>.</span><span>magic</span><span>()</span>
    <span>...</span>

<span># Passes type checking, since ints and strs are subclasses of object</span>
<span>hash_a</span><span>(</span><span>42</span><span>)</span>
<span>hash_a</span><span>(</span><span>"foo"</span><span>)</span>

<span># Passes type checking, since Any is compatible with all types</span>
<span>hash_b</span><span>(</span><span>42</span><span>)</span>
<span>hash_b</span><span>(</span><span>"foo"</span><span>)</span>
</pre></div>
<p>Use <a href="https://docs.python.org/3/library/functions.html#object"><code><span>object</span></code></a> to indicate that a value could be any type in a typesafe
manner. Use <a href="#typing.Any"><code><span>Any</span></code></a> to indicate that a value is dynamically typed.</p>
</section>
<section>
<h2>Nominal vs structural subtyping<a href="#nominal-vs-structural-subtyping">¶</a></h2>
<p>Initially <span></span><a href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> defined the Python static type system as using
<em>nominal subtyping</em>. This means that a class <code><span>A</span></code> is allowed where
a class <code><span>B</span></code> is expected if and only if <code><span>A</span></code> is a subclass of <code><span>B</span></code>.</p>
<p>This requirement previously also applied to abstract base classes, such as
<a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable"><code><span>Iterable</span></code></a>. The problem with this approach is that a class had
to be explicitly marked to support them, which is unpythonic and unlike
what one would normally do in idiomatic dynamically typed Python code.
For example, this conforms to <span></span><a href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a>:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Sized</span><span>,</span> <span>Iterable</span><span>,</span> <span>Iterator</span>

<span>class</span> <span>Bucket</span><span>(</span><span>Sized</span><span>,</span> <span>Iterable</span><span>[</span><span>int</span><span>]):</span>
    <span>...</span>
    <span>def</span> <span>__len__</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>int</span><span>:</span> <span>...</span>
    <span>def</span> <span>__iter__</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>Iterator</span><span>[</span><span>int</span><span>]:</span> <span>...</span>
</pre></div>
<p><span></span><a href="https://peps.python.org/pep-0544/"><strong>PEP 544</strong></a> allows to solve this problem by allowing users to write
the above code without explicit base classes in the class definition,
allowing <code><span>Bucket</span></code> to be implicitly considered a subtype of both <code><span>Sized</span></code>
and <code><span>Iterable[int]</span></code> by static type checkers. This is known as
<em>structural subtyping</em> (or static duck-typing):</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Iterator</span><span>,</span> <span>Iterable</span>

<span>class</span> <span>Bucket</span><span>:</span>  <span># Note: no base classes</span>
    <span>...</span>
    <span>def</span> <span>__len__</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>int</span><span>:</span> <span>...</span>
    <span>def</span> <span>__iter__</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>Iterator</span><span>[</span><span>int</span><span>]:</span> <span>...</span>

<span>def</span> <span>collect</span><span>(</span><span>items</span><span>:</span> <span>Iterable</span><span>[</span><span>int</span><span>])</span> <span>-&gt;</span> <span>int</span><span>:</span> <span>...</span>
<span>result</span> <span>=</span> <span>collect</span><span>(</span><span>Bucket</span><span>())</span>  <span># Passes type check</span>
</pre></div>
<p>Moreover, by subclassing a special class <a href="#typing.Protocol"><code><span>Protocol</span></code></a>, a user
can define new custom protocols to fully enjoy structural subtyping
(see examples below).</p>
</section>
<section>
<h2>Module contents<a href="#module-contents">¶</a></h2>
<p>The <code><span>typing</span></code> module defines the following classes, functions and decorators.</p>
<section>
<h3>Special typing primitives<a href="#special-typing-primitives">¶</a></h3>
<section>
<h4>Special types<a href="#special-types">¶</a></h4>
<p>These can be used as types in annotations. They do not support subscription
using <code><span>[]</span></code>.</p>
<dl>
<dt>
<span><span>typing.</span></span><span><span>Any</span></span><a href="#typing.Any">¶</a></dt>
<dd><p>Special type indicating an unconstrained type.</p>
<ul>
<li><p>Every type is compatible with <a href="#typing.Any"><code><span>Any</span></code></a>.</p></li>
<li><p><a href="#typing.Any"><code><span>Any</span></code></a> is compatible with every type.</p></li>
</ul>
<p><span>Changed in version 3.11: </span><a href="#typing.Any"><code><span>Any</span></code></a> can now be used as a base class. This can be useful for
avoiding type checker errors with classes that can duck type anywhere or
are highly dynamic.</p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>AnyStr</span></span><a href="#typing.AnyStr">¶</a></dt>
<dd><p>A <a href="#typing-constrained-typevar"><span>constrained type variable</span></a>.</p>
<p>Definition:</p>
<div><pre><span></span><span>AnyStr</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'AnyStr'</span><span>,</span> <span>str</span><span>,</span> <span>bytes</span><span>)</span>
</pre></div>
<p><code><span>AnyStr</span></code> is meant to be used for functions that may accept <a href="https://docs.python.org/3/library/stdtypes.html#str"><code><span>str</span></code></a> or
<a href="https://docs.python.org/3/library/stdtypes.html#bytes"><code><span>bytes</span></code></a> arguments but cannot allow the two to mix.</p>
<p>For example:</p>
<div><pre><span></span><span>def</span> <span>concat</span><span>(</span><span>a</span><span>:</span> <span>AnyStr</span><span>,</span> <span>b</span><span>:</span> <span>AnyStr</span><span>)</span> <span>-&gt;</span> <span>AnyStr</span><span>:</span>
    <span>return</span> <span>a</span> <span>+</span> <span>b</span>

<span>concat</span><span>(</span><span>"foo"</span><span>,</span> <span>"bar"</span><span>)</span>    <span># OK, output has type 'str'</span>
<span>concat</span><span>(</span><span>b</span><span>"foo"</span><span>,</span> <span>b</span><span>"bar"</span><span>)</span>  <span># OK, output has type 'bytes'</span>
<span>concat</span><span>(</span><span>"foo"</span><span>,</span> <span>b</span><span>"bar"</span><span>)</span>   <span># Error, cannot mix str and bytes</span>
</pre></div>
<p>Note that, despite its name, <code><span>AnyStr</span></code> has nothing to do with the
<a href="#typing.Any"><code><span>Any</span></code></a> type, nor does it mean “any string”. In particular, <code><span>AnyStr</span></code>
and <code><span>str</span> <span>|</span> <span>bytes</span></code> are different from each other and have different use
cases:</p>
<div><pre><span></span><span># Invalid use of AnyStr:</span>
<span># The type variable is used only once in the function signature,</span>
<span># so cannot be "solved" by the type checker</span>
<span>def</span> <span>greet_bad</span><span>(</span><span>cond</span><span>:</span> <span>bool</span><span>)</span> <span>-&gt;</span> <span>AnyStr</span><span>:</span>
    <span>return</span> <span>"hi there!"</span> <span>if</span> <span>cond</span> <span>else</span> <span>b</span><span>"greetings!"</span>

<span># The better way of annotating this function:</span>
<span>def</span> <span>greet_proper</span><span>(</span><span>cond</span><span>:</span> <span>bool</span><span>)</span> <span>-&gt;</span> <span>str</span> <span>|</span> <span>bytes</span><span>:</span>
    <span>return</span> <span>"hi there!"</span> <span>if</span> <span>cond</span> <span>else</span> <span>b</span><span>"greetings!"</span>
</pre></div>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>LiteralString</span></span><a href="#typing.LiteralString">¶</a></dt>
<dd><p>Special type that includes only literal strings.</p>
<p>Any string
literal is compatible with <code><span>LiteralString</span></code>, as is another
<code><span>LiteralString</span></code>. However, an object typed as just <code><span>str</span></code> is not.
A string created by composing <code><span>LiteralString</span></code>-typed objects
is also acceptable as a <code><span>LiteralString</span></code>.</p>
<p>Example:</p>
<div><pre><span></span><span>def</span> <span>run_query</span><span>(</span><span>sql</span><span>:</span> <span>LiteralString</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>

<span>def</span> <span>caller</span><span>(</span><span>arbitrary_string</span><span>:</span> <span>str</span><span>,</span> <span>literal_string</span><span>:</span> <span>LiteralString</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>run_query</span><span>(</span><span>"SELECT * FROM students"</span><span>)</span>  <span># OK</span>
    <span>run_query</span><span>(</span><span>literal_string</span><span>)</span>  <span># OK</span>
    <span>run_query</span><span>(</span><span>"SELECT * FROM "</span> <span>+</span> <span>literal_string</span><span>)</span>  <span># OK</span>
    <span>run_query</span><span>(</span><span>arbitrary_string</span><span>)</span>  <span># type checker error</span>
    <span>run_query</span><span>(</span>  <span># type checker error</span>
        <span>f</span><span>"SELECT * FROM students WHERE name = </span><span>{</span><span>arbitrary_string</span><span>}</span><span>"</span>
    <span>)</span>
</pre></div>
<p><code><span>LiteralString</span></code> is useful for sensitive APIs where arbitrary user-generated
strings could generate problems. For example, the two cases above
that generate type checker errors could be vulnerable to an SQL
injection attack.</p>
<p>See <span></span><a href="https://peps.python.org/pep-0675/"><strong>PEP 675</strong></a> for more details.</p>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Never</span></span><a href="#typing.Never">¶</a></dt>
<dt>
<span><span>typing.</span></span><span><span>NoReturn</span></span><a href="#typing.NoReturn">¶</a></dt>
<dd><p><code><span>Never</span></code> and <code><span>NoReturn</span></code> represent the
<a href="https://en.wikipedia.org/wiki/Bottom_type">bottom type</a>,
a type that has no members.</p>
<p>They can be used to indicate that a function never returns,
such as <a href="https://docs.python.org/3/library/sys.html#sys.exit"><code><span>sys.exit()</span></code></a>:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>Never</span>  <span># or NoReturn</span>

<span>def</span> <span>stop</span><span>()</span> <span>-&gt;</span> <span>Never</span><span>:</span>
    <span>raise</span> <span>RuntimeError</span><span>(</span><span>'no way'</span><span>)</span>
</pre></div>
<p>Or to define a function that should never be
called, as there are no valid arguments, such as
<a href="#typing.assert_never"><code><span>assert_never()</span></code></a>:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>Never</span>  <span># or NoReturn</span>

<span>def</span> <span>never_call_me</span><span>(</span><span>arg</span><span>:</span> <span>Never</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>pass</span>

<span>def</span> <span>int_or_str</span><span>(</span><span>arg</span><span>:</span> <span>int</span> <span>|</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>never_call_me</span><span>(</span><span>arg</span><span>)</span>  <span># type checker error</span>
    <span>match</span> <span>arg</span><span>:</span>
        <span>case</span> <span>int</span><span>():</span>
            <span>print</span><span>(</span><span>"It's an int"</span><span>)</span>
        <span>case</span> <span>str</span><span>():</span>
            <span>print</span><span>(</span><span>"It's a str"</span><span>)</span>
        <span>case</span><span> </span><span>_</span><span>:</span>
            <span>never_call_me</span><span>(</span><span>arg</span><span>)</span>  <span># OK, arg is of type Never (or NoReturn)</span>
</pre></div>
<p><code><span>Never</span></code> and <code><span>NoReturn</span></code> have the same meaning in the type system
and static type checkers treat both equivalently.</p>
<p><span>Added in version 3.6.2: </span>Added <a href="#typing.NoReturn"><code><span>NoReturn</span></code></a>.</p>
<p><span>Added in version 3.11: </span>Added <a href="#typing.Never"><code><span>Never</span></code></a>.</p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Self</span></span><a href="#typing.Self">¶</a></dt>
<dd><p>Special type to represent the current enclosed class.</p>
<p>For example:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>Self</span><span>,</span> <span>reveal_type</span>

<span>class</span> <span>Foo</span><span>:</span>
    <span>def</span> <span>return_self</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>Self</span><span>:</span>
        <span>...</span>
        <span>return</span> <span>self</span>

<span>class</span> <span>SubclassOfFoo</span><span>(</span><span>Foo</span><span>):</span> <span>pass</span>

<span>reveal_type</span><span>(</span><span>Foo</span><span>()</span><span>.</span><span>return_self</span><span>())</span>  <span># Revealed type is "Foo"</span>
<span>reveal_type</span><span>(</span><span>SubclassOfFoo</span><span>()</span><span>.</span><span>return_self</span><span>())</span>  <span># Revealed type is "SubclassOfFoo"</span>
</pre></div>
<p>This annotation is semantically equivalent to the following,
albeit in a more succinct fashion:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>TypeVar</span>

<span>Self</span> <span>=</span> <span>TypeVar</span><span>(</span><span>"Self"</span><span>,</span> <span>bound</span><span>=</span><span>"Foo"</span><span>)</span>

<span>class</span> <span>Foo</span><span>:</span>
    <span>def</span> <span>return_self</span><span>(</span><span>self</span><span>:</span> <span>Self</span><span>)</span> <span>-&gt;</span> <span>Self</span><span>:</span>
        <span>...</span>
        <span>return</span> <span>self</span>
</pre></div>
<p>In general, if something returns <code><span>self</span></code>, as in the above examples, you
should use <code><span>Self</span></code> as the return annotation. If <code><span>Foo.return_self</span></code> was
annotated as returning <code><span>"Foo"</span></code>, then the type checker would infer the
object returned from <code><span>SubclassOfFoo.return_self</span></code> as being of type <code><span>Foo</span></code>
rather than <code><span>SubclassOfFoo</span></code>.</p>
<p>Other common use cases include:</p>
<ul>
<li><p><a href="https://docs.python.org/3/library/functions.html#classmethod"><code><span>classmethod</span></code></a>s that are used as alternative constructors and return instances
of the <code><span>cls</span></code> parameter.</p></li>
<li><p>Annotating an <a href="https://docs.python.org/3/reference/datamodel.html#object.__enter__"><code><span>__enter__()</span></code></a> method which returns self.</p></li>
</ul>
<p>You should not use <code><span>Self</span></code> as the return annotation if the method is not
guaranteed to return an instance of a subclass when the class is
subclassed:</p>
<div><pre><span></span><span>class</span> <span>Eggs</span><span>:</span>
    <span># Self would be an incorrect return annotation here,</span>
    <span># as the object returned is always an instance of Eggs,</span>
    <span># even in subclasses</span>
    <span>def</span> <span>returns_eggs</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>"Eggs"</span><span>:</span>
        <span>return</span> <span>Eggs</span><span>()</span>
</pre></div>
<p>See <span></span><a href="https://peps.python.org/pep-0673/"><strong>PEP 673</strong></a> for more details.</p>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>TypeAlias</span></span><a href="#typing.TypeAlias">¶</a></dt>
<dd><p>Special annotation for explicitly declaring a <a href="#type-aliases"><span>type alias</span></a>.</p>
<p>For example:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>TypeAlias</span>

<span>Factors</span><span>:</span> <span>TypeAlias</span> <span>=</span> <span>list</span><span>[</span><span>int</span><span>]</span>
</pre></div>
<p><code><span>TypeAlias</span></code> is particularly useful on older Python versions for annotating
aliases that make use of forward references, as it can be hard for type
checkers to distinguish these from normal variable assignments:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>Generic</span><span>,</span> <span>TypeAlias</span><span>,</span> <span>TypeVar</span>

<span>T</span> <span>=</span> <span>TypeVar</span><span>(</span><span>"T"</span><span>)</span>

<span># "Box" does not exist yet,</span>
<span># so we have to use quotes for the forward reference on Python &lt;3.12.</span>
<span># Using ``TypeAlias`` tells the type checker that this is a type alias declaration,</span>
<span># not a variable assignment to a string.</span>
<span>BoxOfStrings</span><span>:</span> <span>TypeAlias</span> <span>=</span> <span>"Box[str]"</span>

<span>class</span> <span>Box</span><span>(</span><span>Generic</span><span>[</span><span>T</span><span>]):</span>
    <span>@classmethod</span>
    <span>def</span> <span>make_box_of_strings</span><span>(</span><span>cls</span><span>)</span> <span>-&gt;</span> <span>BoxOfStrings</span><span>:</span> <span>...</span>
</pre></div>
<p>See <span></span><a href="https://peps.python.org/pep-0613/"><strong>PEP 613</strong></a> for more details.</p>
<p><span>Added in version 3.10.</span></p>
<p><span>Deprecated since version 3.12: </span><a href="#typing.TypeAlias"><code><span>TypeAlias</span></code></a> is deprecated in favor of the <a href="https://docs.python.org/3/reference/simple_stmts.html#type"><code><span>type</span></code></a> statement,
which creates instances of <a href="#typing.TypeAliasType"><code><span>TypeAliasType</span></code></a>
and which natively supports forward references.
Note that while <a href="#typing.TypeAlias"><code><span>TypeAlias</span></code></a> and <a href="#typing.TypeAliasType"><code><span>TypeAliasType</span></code></a> serve
similar purposes and have similar names, they are distinct and the
latter is not the type of the former.
Removal of <a href="#typing.TypeAlias"><code><span>TypeAlias</span></code></a> is not currently planned, but users
are encouraged to migrate to <a href="https://docs.python.org/3/reference/simple_stmts.html#type"><code><span>type</span></code></a> statements.</p>
</dd></dl>

</section>
<section>
<h4>Special forms<a href="#special-forms">¶</a></h4>
<p>These can be used as types in annotations. They all support subscription using
<code><span>[]</span></code>, but each has a unique syntax.</p>
<dl>
<dt>
<span><span>typing.</span></span><span><span>Union</span></span><a href="#typing.Union">¶</a></dt>
<dd><p>Union type; <code><span>Union[X,</span> <span>Y]</span></code> is equivalent to <code><span>X</span> <span>|</span> <span>Y</span></code> and means either X or Y.</p>
<p>To define a union, use e.g. <code><span>Union[int,</span> <span>str]</span></code> or the shorthand <code><span>int</span> <span>|</span> <span>str</span></code>. Using that shorthand is recommended. Details:</p>
<ul>
<li><p>The arguments must be types and there must be at least one.</p></li>
<li><p>Unions of unions are flattened, e.g.:</p>
<div><pre><span></span><span>Union</span><span>[</span><span>Union</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>],</span> <span>float</span><span>]</span> <span>==</span> <span>Union</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>,</span> <span>float</span><span>]</span>
</pre></div>
</li>
<li><p>Unions of a single argument vanish, e.g.:</p>
<div><pre><span></span><span>Union</span><span>[</span><span>int</span><span>]</span> <span>==</span> <span>int</span>  <span># The constructor actually returns int</span>
</pre></div>
</li>
<li><p>Redundant arguments are skipped, e.g.:</p>
<div><pre><span></span><span>Union</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>,</span> <span>int</span><span>]</span> <span>==</span> <span>Union</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>]</span> <span>==</span> <span>int</span> <span>|</span> <span>str</span>
</pre></div>
</li>
<li><p>When comparing unions, the argument order is ignored, e.g.:</p>
<div><pre><span></span><span>Union</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>]</span> <span>==</span> <span>Union</span><span>[</span><span>str</span><span>,</span> <span>int</span><span>]</span>
</pre></div>
</li>
<li><p>You cannot subclass or instantiate a <code><span>Union</span></code>.</p></li>
<li><p>You cannot write <code><span>Union[X][Y]</span></code>.</p></li>
</ul>
<p><span>Changed in version 3.7: </span>Don’t remove explicit subclasses from unions at runtime.</p>

</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Optional</span></span><a href="#typing.Optional">¶</a></dt>
<dd><p><code><span>Optional[X]</span></code> is equivalent to <code><span>X</span> <span>|</span> <span>None</span></code> (or <code><span>Union[X,</span> <span>None]</span></code>).</p>
<p>Note that this is not the same concept as an optional argument,
which is one that has a default.  An optional argument with a
default does not require the <code><span>Optional</span></code> qualifier on its type
annotation just because it is optional. For example:</p>
<div><pre><span></span><span>def</span> <span>foo</span><span>(</span><span>arg</span><span>:</span> <span>int</span> <span>=</span> <span>0</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>
</pre></div>
<p>On the other hand, if an explicit value of <code><span>None</span></code> is allowed, the
use of <code><span>Optional</span></code> is appropriate, whether the argument is optional
or not. For example:</p>
<div><pre><span></span><span>def</span> <span>foo</span><span>(</span><span>arg</span><span>:</span> <span>Optional</span><span>[</span><span>int</span><span>]</span> <span>=</span> <span>None</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>
</pre></div>
<p><span>Changed in version 3.10: </span>Optional can now be written as <code><span>X</span> <span>|</span> <span>None</span></code>. See
<a href="https://docs.python.org/3/library/stdtypes.html#types-union"><span>union type expressions</span></a>.</p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Concatenate</span></span><a href="#typing.Concatenate">¶</a></dt>
<dd><p>Special form for annotating higher-order functions.</p>
<p><code><span>Concatenate</span></code> can be used in conjunction with <a href="#annotating-callables"><span>Callable</span></a> and
<a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> to annotate a higher-order callable which adds, removes,
or transforms parameters of another
callable.  Usage is in the form
<code><span>Concatenate[Arg1Type,</span> <span>Arg2Type,</span> <span>...,</span> <span>ParamSpecVariable]</span></code>. <code><span>Concatenate</span></code>
is currently only valid when used as the first argument to a <a href="#annotating-callables"><span>Callable</span></a>.
The last parameter to <code><span>Concatenate</span></code> must be a <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> or
ellipsis (<code><span>...</span></code>).</p>
<p>For example, to annotate a decorator <code><span>with_lock</span></code> which provides a
<a href="https://docs.python.org/3/library/threading.html#threading.Lock"><code><span>threading.Lock</span></code></a> to the decorated function,  <code><span>Concatenate</span></code> can be
used to indicate that <code><span>with_lock</span></code> expects a callable which takes in a
<code><span>Lock</span></code> as the first argument, and returns a callable with a different type
signature.  In this case, the <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> indicates that the returned
callable’s parameter types are dependent on the parameter types of the
callable being passed in:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Callable</span>
<span>from</span> <span>threading</span> <span>import</span> <span>Lock</span>
<span>from</span> <span>typing</span> <span>import</span> <span>Concatenate</span>

<span># Use this lock to ensure that only one thread is executing a function</span>
<span># at any time.</span>
<span>my_lock</span> <span>=</span> <span>Lock</span><span>()</span>

<span>def</span> <span>with_lock</span><span>[</span><span>**</span><span>P</span><span>,</span> <span>R</span><span>](</span><span>f</span><span>:</span> <span>Callable</span><span>[</span><span>Concatenate</span><span>[</span><span>Lock</span><span>,</span> <span>P</span><span>],</span> <span>R</span><span>])</span> <span>-&gt;</span> <span>Callable</span><span>[</span><span>P</span><span>,</span> <span>R</span><span>]:</span>
<span>    </span><span>'''A type-safe decorator which provides a lock.'''</span>
    <span>def</span> <span>inner</span><span>(</span><span>*</span><span>args</span><span>:</span> <span>P</span><span>.</span><span>args</span><span>,</span> <span>**</span><span>kwargs</span><span>:</span> <span>P</span><span>.</span><span>kwargs</span><span>)</span> <span>-&gt;</span> <span>R</span><span>:</span>
        <span># Provide the lock as the first argument.</span>
        <span>return</span> <span>f</span><span>(</span><span>my_lock</span><span>,</span> <span>*</span><span>args</span><span>,</span> <span>**</span><span>kwargs</span><span>)</span>
    <span>return</span> <span>inner</span>

<span>@with_lock</span>
<span>def</span> <span>sum_threadsafe</span><span>(</span><span>lock</span><span>:</span> <span>Lock</span><span>,</span> <span>numbers</span><span>:</span> <span>list</span><span>[</span><span>float</span><span>])</span> <span>-&gt;</span> <span>float</span><span>:</span>
<span>    </span><span>'''Add a list of numbers together in a thread-safe manner.'''</span>
    <span>with</span> <span>lock</span><span>:</span>
        <span>return</span> <span>sum</span><span>(</span><span>numbers</span><span>)</span>

<span># We don't need to pass in the lock ourselves thanks to the decorator.</span>
<span>sum_threadsafe</span><span>([</span><span>1.1</span><span>,</span> <span>2.2</span><span>,</span> <span>3.3</span><span>])</span>
</pre></div>
<p><span>Added in version 3.10.</span></p>
<div>
<p>See also</p>
<ul>
<li><p><span></span><a href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> – Parameter Specification Variables (the PEP which introduced
<code><span>ParamSpec</span></code> and <code><span>Concatenate</span></code>)</p></li>
<li><p><a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a></p></li>
<li><p><a href="#annotating-callables"><span>Annotating callable objects</span></a></p></li>
</ul>
</div>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Literal</span></span><a href="#typing.Literal">¶</a></dt>
<dd><p>Special typing form to define “literal types”.</p>
<p><code><span>Literal</span></code> can be used to indicate to type checkers that the
annotated object has a value equivalent to one of the
provided literals.</p>
<p>For example:</p>
<div><pre><span></span><span>def</span> <span>validate_simple</span><span>(</span><span>data</span><span>:</span> <span>Any</span><span>)</span> <span>-&gt;</span> <span>Literal</span><span>[</span><span>True</span><span>]:</span>  <span># always returns True</span>
    <span>...</span>

<span>type</span> <span>Mode</span> <span>=</span> <span>Literal</span><span>[</span><span>'r'</span><span>,</span> <span>'rb'</span><span>,</span> <span>'w'</span><span>,</span> <span>'wb'</span><span>]</span>
<span>def</span> <span>open_helper</span><span>(</span><span>file</span><span>:</span> <span>str</span><span>,</span> <span>mode</span><span>:</span> <span>Mode</span><span>)</span> <span>-&gt;</span> <span>str</span><span>:</span>
    <span>...</span>

<span>open_helper</span><span>(</span><span>'/some/path'</span><span>,</span> <span>'r'</span><span>)</span>      <span># Passes type check</span>
<span>open_helper</span><span>(</span><span>'/other/path'</span><span>,</span> <span>'typo'</span><span>)</span>  <span># Error in type checker</span>
</pre></div>
<p><code><span>Literal[...]</span></code> cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to <code><span>Literal[...]</span></code>, but type checkers may
impose restrictions. See <span></span><a href="https://peps.python.org/pep-0586/"><strong>PEP 586</strong></a> for more details about literal types.</p>
<p><span>Added in version 3.8.</span></p>
<p><span>Changed in version 3.9.1: </span><code><span>Literal</span></code> now de-duplicates parameters.  Equality comparisons of
<code><span>Literal</span></code> objects are no longer order dependent. <code><span>Literal</span></code> objects
will now raise a <a href="https://docs.python.org/3/library/exceptions.html#TypeError"><code><span>TypeError</span></code></a> exception during equality comparisons
if one of their parameters are not <a href="https://docs.python.org/3/glossary.html#term-hashable"><span>hashable</span></a>.</p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>ClassVar</span></span><a href="#typing.ClassVar">¶</a></dt>
<dd><p>Special type construct to mark class variables.</p>
<p>As introduced in <span></span><a href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a>, a variable annotation wrapped in ClassVar
indicates that a given attribute is intended to be used as a class variable
and should not be set on instances of that class. Usage:</p>
<div><pre><span></span><span>class</span> <span>Starship</span><span>:</span>
    <span>stats</span><span>:</span> <span>ClassVar</span><span>[</span><span>dict</span><span>[</span><span>str</span><span>,</span> <span>int</span><span>]]</span> <span>=</span> <span>{}</span> <span># class variable</span>
    <span>damage</span><span>:</span> <span>int</span> <span>=</span> <span>10</span>                     <span># instance variable</span>
</pre></div>
<p><a href="#typing.ClassVar"><code><span>ClassVar</span></code></a> accepts only types and cannot be further subscribed.</p>
<p><a href="#typing.ClassVar"><code><span>ClassVar</span></code></a> is not a class itself, and should not
be used with <a href="https://docs.python.org/3/library/functions.html#isinstance"><code><span>isinstance()</span></code></a> or <a href="https://docs.python.org/3/library/functions.html#issubclass"><code><span>issubclass()</span></code></a>.
<a href="#typing.ClassVar"><code><span>ClassVar</span></code></a> does not change Python runtime behavior, but
it can be used by third-party type checkers. For example, a type checker
might flag the following code as an error:</p>
<div><pre><span></span><span>enterprise_d</span> <span>=</span> <span>Starship</span><span>(</span><span>3000</span><span>)</span>
<span>enterprise_d</span><span>.</span><span>stats</span> <span>=</span> <span>{}</span> <span># Error, setting class variable on instance</span>
<span>Starship</span><span>.</span><span>stats</span> <span>=</span> <span>{}</span>     <span># This is OK</span>
</pre></div>
<p><span>Added in version 3.5.3.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Final</span></span><a href="#typing.Final">¶</a></dt>
<dd><p>Special typing construct to indicate final names to type checkers.</p>
<p>Final names cannot be reassigned in any scope. Final names declared in class
scopes cannot be overridden in subclasses.</p>
<p>For example:</p>
<div><pre><span></span><span>MAX_SIZE</span><span>:</span> <span>Final</span> <span>=</span> <span>9000</span>
<span>MAX_SIZE</span> <span>+=</span> <span>1</span>  <span># Error reported by type checker</span>

<span>class</span> <span>Connection</span><span>:</span>
    <span>TIMEOUT</span><span>:</span> <span>Final</span><span>[</span><span>int</span><span>]</span> <span>=</span> <span>10</span>

<span>class</span> <span>FastConnector</span><span>(</span><span>Connection</span><span>):</span>
    <span>TIMEOUT</span> <span>=</span> <span>1</span>  <span># Error reported by type checker</span>
</pre></div>
<p>There is no runtime checking of these properties. See <span></span><a href="https://peps.python.org/pep-0591/"><strong>PEP 591</strong></a> for
more details.</p>
<p><span>Added in version 3.8.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Required</span></span><a href="#typing.Required">¶</a></dt>
<dd><p>Special typing construct to mark a <a href="#typing.TypedDict"><code><span>TypedDict</span></code></a> key as required.</p>
<p>This is mainly useful for <code><span>total=False</span></code> TypedDicts. See <a href="#typing.TypedDict"><code><span>TypedDict</span></code></a>
and <span></span><a href="https://peps.python.org/pep-0655/"><strong>PEP 655</strong></a> for more details.</p>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>NotRequired</span></span><a href="#typing.NotRequired">¶</a></dt>
<dd><p>Special typing construct to mark a <a href="#typing.TypedDict"><code><span>TypedDict</span></code></a> key as potentially
missing.</p>
<p>See <a href="#typing.TypedDict"><code><span>TypedDict</span></code></a> and <span></span><a href="https://peps.python.org/pep-0655/"><strong>PEP 655</strong></a> for more details.</p>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Annotated</span></span><a href="#typing.Annotated">¶</a></dt>
<dd><p>Special typing form to add context-specific metadata to an annotation.</p>
<p>Add metadata <code><span>x</span></code> to a given type <code><span>T</span></code> by using the annotation
<code><span>Annotated[T,</span> <span>x]</span></code>. Metadata added using <code><span>Annotated</span></code> can be used by
static analysis tools or at runtime. At runtime, the metadata is stored
in a <code><span>__metadata__</span></code> attribute.</p>
<p>If a library or tool encounters an annotation <code><span>Annotated[T,</span> <span>x]</span></code> and has
no special logic for the metadata, it should ignore the metadata and simply
treat the annotation as <code><span>T</span></code>. As such, <code><span>Annotated</span></code> can be useful for code
that wants to use annotations for purposes outside Python’s static typing
system.</p>
<p>Using <code><span>Annotated[T,</span> <span>x]</span></code> as an annotation still allows for static
typechecking of <code><span>T</span></code>, as type checkers will simply ignore the metadata <code><span>x</span></code>.
In this way, <code><span>Annotated</span></code> differs from the
<a href="#typing.no_type_check"><code><span>@no_type_check</span></code></a> decorator, which can also be used for
adding annotations outside the scope of the typing system, but
completely disables typechecking for a function or class.</p>
<p>The responsibility of how to interpret the metadata
lies with the tool or library encountering an
<code><span>Annotated</span></code> annotation. A tool or library encountering an <code><span>Annotated</span></code> type
can scan through the metadata elements to determine if they are of interest
(e.g., using <a href="https://docs.python.org/3/library/functions.html#isinstance"><code><span>isinstance()</span></code></a>).</p>
<dl>
<dt>
<span><span>Annotated[&lt;type&gt;,</span> <span>&lt;metadata&gt;]</span></span></dt>
<dd></dd></dl>

<p>Here is an example of how you might use <code><span>Annotated</span></code> to add metadata to
type annotations if you were doing range analysis:</p>
<div><pre><span></span><span>@dataclass</span>
<span>class</span> <span>ValueRange</span><span>:</span>
    <span>lo</span><span>:</span> <span>int</span>
    <span>hi</span><span>:</span> <span>int</span>

<span>T1</span> <span>=</span> <span>Annotated</span><span>[</span><span>int</span><span>,</span> <span>ValueRange</span><span>(</span><span>-</span><span>10</span><span>,</span> <span>5</span><span>)]</span>
<span>T2</span> <span>=</span> <span>Annotated</span><span>[</span><span>T1</span><span>,</span> <span>ValueRange</span><span>(</span><span>-</span><span>20</span><span>,</span> <span>3</span><span>)]</span>
</pre></div>
<p>Details of the syntax:</p>
<ul>
<li><p>The first argument to <code><span>Annotated</span></code> must be a valid type</p></li>
<li><p>Multiple metadata elements can be supplied (<code><span>Annotated</span></code> supports variadic
arguments):</p>
<div><pre><span></span><span>@dataclass</span>
<span>class</span> <span>ctype</span><span>:</span>
    <span>kind</span><span>:</span> <span>str</span>

<span>Annotated</span><span>[</span><span>int</span><span>,</span> <span>ValueRange</span><span>(</span><span>3</span><span>,</span> <span>10</span><span>),</span> <span>ctype</span><span>(</span><span>"char"</span><span>)]</span>
</pre></div>
<p>It is up to the tool consuming the annotations to decide whether the
client is allowed to add multiple metadata elements to one annotation and how to
merge those annotations.</p>
</li>
<li><p><code><span>Annotated</span></code> must be subscripted with at least two arguments (
<code><span>Annotated[int]</span></code> is not valid)</p></li>
<li><p>The order of the metadata elements is preserved and matters for equality
checks:</p>
<div><pre><span></span><span>assert</span> <span>Annotated</span><span>[</span><span>int</span><span>,</span> <span>ValueRange</span><span>(</span><span>3</span><span>,</span> <span>10</span><span>),</span> <span>ctype</span><span>(</span><span>"char"</span><span>)]</span> <span>!=</span> <span>Annotated</span><span>[</span>
    <span>int</span><span>,</span> <span>ctype</span><span>(</span><span>"char"</span><span>),</span> <span>ValueRange</span><span>(</span><span>3</span><span>,</span> <span>10</span><span>)</span>
<span>]</span>
</pre></div>
</li>
<li><p>Nested <code><span>Annotated</span></code> types are flattened. The order of the metadata elements
starts with the innermost annotation:</p>
<div><pre><span></span><span>assert</span> <span>Annotated</span><span>[</span><span>Annotated</span><span>[</span><span>int</span><span>,</span> <span>ValueRange</span><span>(</span><span>3</span><span>,</span> <span>10</span><span>)],</span> <span>ctype</span><span>(</span><span>"char"</span><span>)]</span> <span>==</span> <span>Annotated</span><span>[</span>
    <span>int</span><span>,</span> <span>ValueRange</span><span>(</span><span>3</span><span>,</span> <span>10</span><span>),</span> <span>ctype</span><span>(</span><span>"char"</span><span>)</span>
<span>]</span>
</pre></div>
</li>
<li><p>Duplicated metadata elements are not removed:</p>
<div><pre><span></span><span>assert</span> <span>Annotated</span><span>[</span><span>int</span><span>,</span> <span>ValueRange</span><span>(</span><span>3</span><span>,</span> <span>10</span><span>)]</span> <span>!=</span> <span>Annotated</span><span>[</span>
    <span>int</span><span>,</span> <span>ValueRange</span><span>(</span><span>3</span><span>,</span> <span>10</span><span>),</span> <span>ValueRange</span><span>(</span><span>3</span><span>,</span> <span>10</span><span>)</span>
<span>]</span>
</pre></div>
</li>
<li><p><code><span>Annotated</span></code> can be used with nested and generic aliases:</p>
<div><pre><span></span><span>@dataclass</span>
<span>class</span> <span>MaxLen</span><span>:</span>
    <span>value</span><span>:</span> <span>int</span>

<span>type</span> <span>Vec</span><span>[</span><span>T</span><span>]</span> <span>=</span> <span>Annotated</span><span>[</span><span>list</span><span>[</span><span>tuple</span><span>[</span><span>T</span><span>,</span> <span>T</span><span>]],</span> <span>MaxLen</span><span>(</span><span>10</span><span>)]</span>

<span># When used in a type annotation, a type checker will treat "V" the same as</span>
<span># ``Annotated[list[tuple[int, int]], MaxLen(10)]``:</span>
<span>type</span> <span>V</span> <span>=</span> <span>Vec</span><span>[</span><span>int</span><span>]</span>
</pre></div>
</li>
<li><p><code><span>Annotated</span></code> cannot be used with an unpacked <a href="#typing.TypeVarTuple"><code><span>TypeVarTuple</span></code></a>:</p>
<div><pre><span></span><span>type</span> <span>Variadic</span><span>[</span><span>*</span><span>Ts</span><span>]</span> <span>=</span> <span>Annotated</span><span>[</span><span>*</span><span>Ts</span><span>,</span> <span>Ann1</span><span>]</span>  <span># NOT valid</span>
</pre></div>
<p>This would be equivalent to:</p>
<div><pre><span></span><span>Annotated</span><span>[</span><span>T1</span><span>,</span> <span>T2</span><span>,</span> <span>T3</span><span>,</span> <span>...</span><span>,</span> <span>Ann1</span><span>]</span>
</pre></div>
<p>where <code><span>T1</span></code>, <code><span>T2</span></code>, etc. are <a href="#typing.TypeVar"><code><span>TypeVars</span></code></a>. This would be
invalid: only one type should be passed to Annotated.</p>
</li>
<li><p>By default, <a href="#typing.get_type_hints"><code><span>get_type_hints()</span></code></a> strips the metadata from annotations.
Pass <code><span>include_extras=True</span></code> to have the metadata preserved:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>from</span> <span>typing</span> <span>import</span> <span>Annotated</span><span>,</span> <span>get_type_hints</span>
<span>&gt;&gt;&gt; </span><span>def</span> <span>func</span><span>(</span><span>x</span><span>:</span> <span>Annotated</span><span>[</span><span>int</span><span>,</span> <span>"metadata"</span><span>])</span> <span>-&gt;</span> <span>None</span><span>:</span> <span>pass</span>
<span>...</span>
<span>&gt;&gt;&gt; </span><span>get_type_hints</span><span>(</span><span>func</span><span>)</span>
<span>{'x': &lt;class 'int'&gt;, 'return': &lt;class 'NoneType'&gt;}</span>
<span>&gt;&gt;&gt; </span><span>get_type_hints</span><span>(</span><span>func</span><span>,</span> <span>include_extras</span><span>=</span><span>True</span><span>)</span>
<span>{'x': typing.Annotated[int, 'metadata'], 'return': &lt;class 'NoneType'&gt;}</span>
</pre></div>
</li>
<li><p>At runtime, the metadata associated with an <code><span>Annotated</span></code> type can be
retrieved via the <code><span>__metadata__</span></code> attribute:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>from</span> <span>typing</span> <span>import</span> <span>Annotated</span>
<span>&gt;&gt;&gt; </span><span>X</span> <span>=</span> <span>Annotated</span><span>[</span><span>int</span><span>,</span> <span>"very"</span><span>,</span> <span>"important"</span><span>,</span> <span>"metadata"</span><span>]</span>
<span>&gt;&gt;&gt; </span><span>X</span>
<span>typing.Annotated[int, 'very', 'important', 'metadata']</span>
<span>&gt;&gt;&gt; </span><span>X</span><span>.</span><span>__metadata__</span>
<span>('very', 'important', 'metadata')</span>
</pre></div>
</li>
</ul>
<div>
<p>See also</p>
<dl>
<dt><span></span><a href="https://peps.python.org/pep-0593/"><strong>PEP 593</strong></a> - Flexible function and variable annotations</dt><dd><p>The PEP introducing <code><span>Annotated</span></code> to the standard library.</p>
</dd>
</dl>
</div>
<p><span>Added in version 3.9.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>TypeGuard</span></span><a href="#typing.TypeGuard">¶</a></dt>
<dd><p>Special typing construct for marking user-defined type guard functions.</p>
<p><code><span>TypeGuard</span></code> can be used to annotate the return type of a user-defined
type guard function.  <code><span>TypeGuard</span></code> only accepts a single type argument.
At runtime, functions marked this way should return a boolean.</p>
<p><code><span>TypeGuard</span></code> aims to benefit <em>type narrowing</em> – a technique used by static
type checkers to determine a more precise type of an expression within a
program’s code flow.  Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code.  The
conditional expression here is sometimes referred to as a “type guard”:</p>
<div><pre><span></span><span>def</span> <span>is_str</span><span>(</span><span>val</span><span>:</span> <span>str</span> <span>|</span> <span>float</span><span>):</span>
    <span># "isinstance" type guard</span>
    <span>if</span> <span>isinstance</span><span>(</span><span>val</span><span>,</span> <span>str</span><span>):</span>
        <span># Type of ``val`` is narrowed to ``str``</span>
        <span>...</span>
    <span>else</span><span>:</span>
        <span># Else, type of ``val`` is narrowed to ``float``.</span>
        <span>...</span>
</pre></div>
<p>Sometimes it would be convenient to use a user-defined boolean function
as a type guard.  Such a function should use <code><span>TypeGuard[...]</span></code> as its
return type to alert static type checkers to this intention.</p>
<p>Using  <code><span>-&gt;</span> <span>TypeGuard</span></code> tells the static type checker that for a given
function:</p>
<ol>
<li><p>The return value is a boolean.</p></li>
<li><p>If the return value is <code><span>True</span></code>, the type of its argument
is the type inside <code><span>TypeGuard</span></code>.</p></li>
</ol>
<p>For example:</p>
<div><pre><span></span><span>def</span> <span>is_str_list</span><span>(</span><span>val</span><span>:</span> <span>list</span><span>[</span><span>object</span><span>])</span> <span>-&gt;</span> <span>TypeGuard</span><span>[</span><span>list</span><span>[</span><span>str</span><span>]]:</span>
<span>    </span><span>'''Determines whether all objects in the list are strings'''</span>
    <span>return</span> <span>all</span><span>(</span><span>isinstance</span><span>(</span><span>x</span><span>,</span> <span>str</span><span>)</span> <span>for</span> <span>x</span> <span>in</span> <span>val</span><span>)</span>

<span>def</span> <span>func1</span><span>(</span><span>val</span><span>:</span> <span>list</span><span>[</span><span>object</span><span>]):</span>
    <span>if</span> <span>is_str_list</span><span>(</span><span>val</span><span>):</span>
        <span># Type of ``val`` is narrowed to ``list[str]``.</span>
        <span>print</span><span>(</span><span>" "</span><span>.</span><span>join</span><span>(</span><span>val</span><span>))</span>
    <span>else</span><span>:</span>
        <span># Type of ``val`` remains as ``list[object]``.</span>
        <span>print</span><span>(</span><span>"Not a list of strings!"</span><span>)</span>
</pre></div>
<p>If <code><span>is_str_list</span></code> is a class or instance method, then the type in
<code><span>TypeGuard</span></code> maps to the type of the second parameter (after <code><span>cls</span></code> or
<code><span>self</span></code>).</p>
<p>In short, the form <code><span>def</span> <span>foo(arg:</span> <span>TypeA)</span> <span>-&gt;</span> <span>TypeGuard[TypeB]:</span> <span>...</span></code>,
means that if <code><span>foo(arg)</span></code> returns <code><span>True</span></code>, then <code><span>arg</span></code> narrows from
<code><span>TypeA</span></code> to <code><span>TypeB</span></code>.</p>
<div>
<p>Note</p>
<p><code><span>TypeB</span></code> need not be a narrower form of <code><span>TypeA</span></code> – it can even be a
wider form. The main reason is to allow for things like
narrowing <code><span>list[object]</span></code> to <code><span>list[str]</span></code> even though the latter
is not a subtype of the former, since <code><span>list</span></code> is invariant.
The responsibility of writing type-safe type guards is left to the user.</p>
</div>
<p><code><span>TypeGuard</span></code> also works with type variables.  See <span></span><a href="https://peps.python.org/pep-0647/"><strong>PEP 647</strong></a> for more details.</p>
<p><span>Added in version 3.10.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Unpack</span></span><a href="#typing.Unpack">¶</a></dt>
<dd><p>Typing operator to conceptually mark an object as having been unpacked.</p>
<p>For example, using the unpack operator <code><span>*</span></code> on a
<a href="#typevartuple"><span>type variable tuple</span></a> is equivalent to using <code><span>Unpack</span></code>
to mark the type variable tuple as having been unpacked:</p>
<div><pre><span></span><span>Ts</span> <span>=</span> <span>TypeVarTuple</span><span>(</span><span>'Ts'</span><span>)</span>
<span>tup</span><span>:</span> <span>tuple</span><span>[</span><span>*</span><span>Ts</span><span>]</span>
<span># Effectively does:</span>
<span>tup</span><span>:</span> <span>tuple</span><span>[</span><span>Unpack</span><span>[</span><span>Ts</span><span>]]</span>
</pre></div>
<p>In fact, <code><span>Unpack</span></code> can be used interchangeably with <code><span>*</span></code> in the context
of <a href="#typing.TypeVarTuple"><code><span>typing.TypeVarTuple</span></code></a> and
<a href="https://docs.python.org/3/library/stdtypes.html#tuple"><code><span>builtins.tuple</span></code></a> types. You might see <code><span>Unpack</span></code> being used
explicitly in older versions of Python, where <code><span>*</span></code> couldn’t be used in
certain places:</p>
<div><pre><span></span><span># In older versions of Python, TypeVarTuple and Unpack</span>
<span># are located in the `typing_extensions` backports package.</span>
<span>from</span> <span>typing_extensions</span> <span>import</span> <span>TypeVarTuple</span><span>,</span> <span>Unpack</span>

<span>Ts</span> <span>=</span> <span>TypeVarTuple</span><span>(</span><span>'Ts'</span><span>)</span>
<span>tup</span><span>:</span> <span>tuple</span><span>[</span><span>*</span><span>Ts</span><span>]</span>         <span># Syntax error on Python &lt;= 3.10!</span>
<span>tup</span><span>:</span> <span>tuple</span><span>[</span><span>Unpack</span><span>[</span><span>Ts</span><span>]]</span>  <span># Semantically equivalent, and backwards-compatible</span>
</pre></div>
<p><code><span>Unpack</span></code> can also be used along with <a href="#typing.TypedDict"><code><span>typing.TypedDict</span></code></a> for typing
<code><span>**kwargs</span></code> in a function signature:</p>
<div><pre><span></span><span>from</span> <span>typing</span> <span>import</span> <span>TypedDict</span><span>,</span> <span>Unpack</span>

<span>class</span> <span>Movie</span><span>(</span><span>TypedDict</span><span>):</span>
    <span>name</span><span>:</span> <span>str</span>
    <span>year</span><span>:</span> <span>int</span>

<span># This function expects two keyword arguments - `name` of type `str`</span>
<span># and `year` of type `int`.</span>
<span>def</span> <span>foo</span><span>(</span><span>**</span><span>kwargs</span><span>:</span> <span>Unpack</span><span>[</span><span>Movie</span><span>]):</span> <span>...</span>
</pre></div>
<p>See <span></span><a href="https://peps.python.org/pep-0692/"><strong>PEP 692</strong></a> for more details on using <code><span>Unpack</span></code> for <code><span>**kwargs</span></code> typing.</p>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

</section>
<section>
<h4>Building generic types and type aliases<a href="#building-generic-types-and-type-aliases">¶</a></h4>
<p>The following classes should not be used directly as annotations.
Their intended purpose is to be building blocks
for creating generic types and type aliases.</p>
<p>These objects can be created through special syntax
(<a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter lists</span></a> and the <a href="https://docs.python.org/3/reference/simple_stmts.html#type"><code><span>type</span></code></a> statement).
For compatibility with Python 3.11 and earlier, they can also be created
without the dedicated syntax, as documented below.</p>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Generic</span></span><a href="#typing.Generic">¶</a></dt>
<dd><p>Abstract base class for generic types.</p>
<p>A generic type is typically declared by adding a list of type parameters
after the class name:</p>
<div><pre><span></span><span>class</span> <span>Mapping</span><span>[</span><span>KT</span><span>,</span> <span>VT</span><span>]:</span>
    <span>def</span> <span>__getitem__</span><span>(</span><span>self</span><span>,</span> <span>key</span><span>:</span> <span>KT</span><span>)</span> <span>-&gt;</span> <span>VT</span><span>:</span>
        <span>...</span>
        <span># Etc.</span>
</pre></div>
<p>Such a class implicitly inherits from <code><span>Generic</span></code>.
The runtime semantics of this syntax are discussed in the
<a href="https://docs.python.org/3/reference/compound_stmts.html#generic-classes"><span>Language Reference</span></a>.</p>
<p>This class can then be used as follows:</p>
<div><pre><span></span><span>def</span> <span>lookup_name</span><span>[</span><span>X</span><span>,</span> <span>Y</span><span>](</span><span>mapping</span><span>:</span> <span>Mapping</span><span>[</span><span>X</span><span>,</span> <span>Y</span><span>],</span> <span>key</span><span>:</span> <span>X</span><span>,</span> <span>default</span><span>:</span> <span>Y</span><span>)</span> <span>-&gt;</span> <span>Y</span><span>:</span>
    <span>try</span><span>:</span>
        <span>return</span> <span>mapping</span><span>[</span><span>key</span><span>]</span>
    <span>except</span> <span>KeyError</span><span>:</span>
        <span>return</span> <span>default</span>
</pre></div>
<p>Here the brackets after the function name indicate a
<a href="https://docs.python.org/3/reference/compound_stmts.html#generic-functions"><span>generic function</span></a>.</p>
<p>For backwards compatibility, generic classes can also be
declared by explicitly inheriting from
<code><span>Generic</span></code>. In this case, the type parameters must be declared
separately:</p>
<div><pre><span></span><span>KT</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'KT'</span><span>)</span>
<span>VT</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'VT'</span><span>)</span>

<span>class</span> <span>Mapping</span><span>(</span><span>Generic</span><span>[</span><span>KT</span><span>,</span> <span>VT</span><span>]):</span>
    <span>def</span> <span>__getitem__</span><span>(</span><span>self</span><span>,</span> <span>key</span><span>:</span> <span>KT</span><span>)</span> <span>-&gt;</span> <span>VT</span><span>:</span>
        <span>...</span>
        <span># Etc.</span>
</pre></div>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>TypeVar</span></span><span>(</span><em><span><span>name</span></span></em>, <em><span><span>*</span></span><span><span>constraints</span></span></em>, <em><span><span>bound</span></span><span><span>=</span></span><span><span>None</span></span></em>, <em><span><span>covariant</span></span><span><span>=</span></span><span><span>False</span></span></em>, <em><span><span>contravariant</span></span><span><span>=</span></span><span><span>False</span></span></em>, <em><span><span>infer_variance</span></span><span><span>=</span></span><span><span>False</span></span></em><span>)</span><a href="#typing.TypeVar">¶</a></dt>
<dd><p>Type variable.</p>
<p>The preferred way to construct a type variable is via the dedicated syntax
for <a href="https://docs.python.org/3/reference/compound_stmts.html#generic-functions"><span>generic functions</span></a>,
<a href="https://docs.python.org/3/reference/compound_stmts.html#generic-classes"><span>generic classes</span></a>, and
<a href="https://docs.python.org/3/reference/compound_stmts.html#generic-type-aliases"><span>generic type aliases</span></a>:</p>
<div><pre><span></span><span>class</span> <span>Sequence</span><span>[</span><span>T</span><span>]:</span>  <span># T is a TypeVar</span>
    <span>...</span>
</pre></div>
<p>This syntax can also be used to create bound and constrained type
variables:</p>
<div><pre><span></span><span>class</span> <span>StrSequence</span><span>[</span><span>S</span><span>:</span> <span>str</span><span>]:</span>  <span># S is a TypeVar bound to str</span>
    <span>...</span>


<span>class</span> <span>StrOrBytesSequence</span><span>[</span><span>A</span><span>:</span> <span>(</span><span>str</span><span>,</span> <span>bytes</span><span>)]:</span>  <span># A is a TypeVar constrained to str or bytes</span>
    <span>...</span>
</pre></div>
<p>However, if desired, reusable type variables can also be constructed manually, like so:</p>
<div><pre><span></span><span>T</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'T'</span><span>)</span>  <span># Can be anything</span>
<span>S</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'S'</span><span>,</span> <span>bound</span><span>=</span><span>str</span><span>)</span>  <span># Can be any subtype of str</span>
<span>A</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'A'</span><span>,</span> <span>str</span><span>,</span> <span>bytes</span><span>)</span>  <span># Must be exactly str or bytes</span>
</pre></div>
<p>Type variables exist primarily for the benefit of static type
checkers.  They serve as the parameters for generic types as well
as for generic function and type alias definitions.
See <a href="#typing.Generic"><code><span>Generic</span></code></a> for more
information on generic types.  Generic functions work as follows:</p>
<div><pre><span></span><span>def</span> <span>repeat</span><span>[</span><span>T</span><span>](</span><span>x</span><span>:</span> <span>T</span><span>,</span> <span>n</span><span>:</span> <span>int</span><span>)</span> <span>-&gt;</span> <span>Sequence</span><span>[</span><span>T</span><span>]:</span>
<span>    </span><span>"""Return a list containing n references to x."""</span>
    <span>return</span> <span>[</span><span>x</span><span>]</span><span>*</span><span>n</span>


<span>def</span> <span>print_capitalized</span><span>[</span><span>S</span><span>:</span> <span>str</span><span>](</span><span>x</span><span>:</span> <span>S</span><span>)</span> <span>-&gt;</span> <span>S</span><span>:</span>
<span>    </span><span>"""Print x capitalized, and return x."""</span>
    <span>print</span><span>(</span><span>x</span><span>.</span><span>capitalize</span><span>())</span>
    <span>return</span> <span>x</span>


<span>def</span> <span>concatenate</span><span>[</span><span>A</span><span>:</span> <span>(</span><span>str</span><span>,</span> <span>bytes</span><span>)](</span><span>x</span><span>:</span> <span>A</span><span>,</span> <span>y</span><span>:</span> <span>A</span><span>)</span> <span>-&gt;</span> <span>A</span><span>:</span>
<span>    </span><span>"""Add two strings or bytes objects together."""</span>
    <span>return</span> <span>x</span> <span>+</span> <span>y</span>
</pre></div>
<p>Note that type variables can be <em>bound</em>, <em>constrained</em>, or neither, but
cannot be both bound <em>and</em> constrained.</p>
<p>The variance of type variables is inferred by type checkers when they are created
through the <a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter syntax</span></a> or when
<code><span>infer_variance=True</span></code> is passed.
Manually created type variables may be explicitly marked covariant or contravariant by passing
<code><span>covariant=True</span></code> or <code><span>contravariant=True</span></code>.
By default, manually created type variables are invariant.
See <span></span><a href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> and <span></span><a href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a> for more details.</p>
<p>Bound type variables and constrained type variables have different
semantics in several important ways. Using a <em>bound</em> type variable means
that the <code><span>TypeVar</span></code> will be solved using the most specific type possible:</p>
<div><pre><span></span><span>x</span> <span>=</span> <span>print_capitalized</span><span>(</span><span>'a string'</span><span>)</span>
<span>reveal_type</span><span>(</span><span>x</span><span>)</span>  <span># revealed type is str</span>

<span>class</span> <span>StringSubclass</span><span>(</span><span>str</span><span>):</span>
    <span>pass</span>

<span>y</span> <span>=</span> <span>print_capitalized</span><span>(</span><span>StringSubclass</span><span>(</span><span>'another string'</span><span>))</span>
<span>reveal_type</span><span>(</span><span>y</span><span>)</span>  <span># revealed type is StringSubclass</span>

<span>z</span> <span>=</span> <span>print_capitalized</span><span>(</span><span>45</span><span>)</span>  <span># error: int is not a subtype of str</span>
</pre></div>
<p>Type variables can be bound to concrete types, abstract types (ABCs or
protocols), and even unions of types:</p>
<div><pre><span></span><span># Can be anything with an __abs__ method</span>
<span>def</span> <span>print_abs</span><span>[</span><span>T</span><span>:</span> <span>SupportsAbs</span><span>](</span><span>arg</span><span>:</span> <span>T</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>print</span><span>(</span><span>"Absolute value:"</span><span>,</span> <span>abs</span><span>(</span><span>arg</span><span>))</span>

<span>U</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'U'</span><span>,</span> <span>bound</span><span>=</span><span>str</span><span>|</span><span>bytes</span><span>)</span>  <span># Can be any subtype of the union str|bytes</span>
<span>V</span> <span>=</span> <span>TypeVar</span><span>(</span><span>'V'</span><span>,</span> <span>bound</span><span>=</span><span>SupportsAbs</span><span>)</span>  <span># Can be anything with an __abs__ method</span>
</pre></div>
<p>Using a <em>constrained</em> type variable, however, means that the <code><span>TypeVar</span></code>
can only ever be solved as being exactly one of the constraints given:</p>
<div><pre><span></span><span>a</span> <span>=</span> <span>concatenate</span><span>(</span><span>'one'</span><span>,</span> <span>'two'</span><span>)</span>
<span>reveal_type</span><span>(</span><span>a</span><span>)</span>  <span># revealed type is str</span>

<span>b</span> <span>=</span> <span>concatenate</span><span>(</span><span>StringSubclass</span><span>(</span><span>'one'</span><span>),</span> <span>StringSubclass</span><span>(</span><span>'two'</span><span>))</span>
<span>reveal_type</span><span>(</span><span>b</span><span>)</span>  <span># revealed type is str, despite StringSubclass being passed in</span>

<span>c</span> <span>=</span> <span>concatenate</span><span>(</span><span>'one'</span><span>,</span> <span>b</span><span>'two'</span><span>)</span>  <span># error: type variable 'A' can be either str or bytes in a function call, but not both</span>
</pre></div>
<p>At runtime, <code><span>isinstance(x,</span> <span>T)</span></code> will raise <a href="https://docs.python.org/3/library/exceptions.html#TypeError"><code><span>TypeError</span></code></a>.</p>
<dl>
<dt>
<span><span>__name__</span></span><a href="#typing.TypeVar.__name__">¶</a></dt>
<dd><p>The name of the type variable.</p>
</dd></dl>

<dl>
<dt>
<span><span>__covariant__</span></span><a href="#typing.TypeVar.__covariant__">¶</a></dt>
<dd><p>Whether the type var has been explicitly marked as covariant.</p>
</dd></dl>

<dl>
<dt>
<span><span>__contravariant__</span></span><a href="#typing.TypeVar.__contravariant__">¶</a></dt>
<dd><p>Whether the type var has been explicitly marked as contravariant.</p>
</dd></dl>

<dl>
<dt>
<span><span>__infer_variance__</span></span><a href="#typing.TypeVar.__infer_variance__">¶</a></dt>
<dd><p>Whether the type variable’s variance should be inferred by type checkers.</p>
<p><span>Added in version 3.12.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>__bound__</span></span><a href="#typing.TypeVar.__bound__">¶</a></dt>
<dd><p>The bound of the type variable, if any.</p>
<p><span>Changed in version 3.12: </span>For type variables created through <a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter syntax</span></a>,
the bound is evaluated only when the attribute is accessed, not when
the type variable is created (see <a href="https://docs.python.org/3/reference/executionmodel.html#lazy-evaluation"><span>Lazy evaluation</span></a>).</p>
</dd></dl>

<dl>
<dt>
<span><span>__constraints__</span></span><a href="#typing.TypeVar.__constraints__">¶</a></dt>
<dd><p>A tuple containing the constraints of the type variable, if any.</p>
<p><span>Changed in version 3.12: </span>For type variables created through <a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter syntax</span></a>,
the constraints are evaluated only when the attribute is accessed, not when
the type variable is created (see <a href="https://docs.python.org/3/reference/executionmodel.html#lazy-evaluation"><span>Lazy evaluation</span></a>).</p>
</dd></dl>

<p><span>Changed in version 3.12: </span>Type variables can now be declared using the
<a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter</span></a> syntax introduced by <span></span><a href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a>.
The <code><span>infer_variance</span></code> parameter was added.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>TypeVarTuple</span></span><span>(</span><em><span><span>name</span></span></em><span>)</span><a href="#typing.TypeVarTuple">¶</a></dt>
<dd><p>Type variable tuple. A specialized form of <a href="#typevar"><span>type variable</span></a>
that enables <em>variadic</em> generics.</p>
<p>Type variable tuples can be declared in <a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter lists</span></a>
using a single asterisk (<code><span>*</span></code>) before the name:</p>
<div><pre><span></span><span>def</span> <span>move_first_element_to_last</span><span>[</span><span>T</span><span>,</span> <span>*</span><span>Ts</span><span>](</span><span>tup</span><span>:</span> <span>tuple</span><span>[</span><span>T</span><span>,</span> <span>*</span><span>Ts</span><span>])</span> <span>-&gt;</span> <span>tuple</span><span>[</span><span>*</span><span>Ts</span><span>,</span> <span>T</span><span>]:</span>
    <span>return</span> <span>(</span><span>*</span><span>tup</span><span>[</span><span>1</span><span>:],</span> <span>tup</span><span>[</span><span>0</span><span>])</span>
</pre></div>
<p>Or by explicitly invoking the <code><span>TypeVarTuple</span></code> constructor:</p>
<div><pre><span></span><span>T</span> <span>=</span> <span>TypeVar</span><span>(</span><span>"T"</span><span>)</span>
<span>Ts</span> <span>=</span> <span>TypeVarTuple</span><span>(</span><span>"Ts"</span><span>)</span>

<span>def</span> <span>move_first_element_to_last</span><span>(</span><span>tup</span><span>:</span> <span>tuple</span><span>[</span><span>T</span><span>,</span> <span>*</span><span>Ts</span><span>])</span> <span>-&gt;</span> <span>tuple</span><span>[</span><span>*</span><span>Ts</span><span>,</span> <span>T</span><span>]:</span>
    <span>return</span> <span>(</span><span>*</span><span>tup</span><span>[</span><span>1</span><span>:],</span> <span>tup</span><span>[</span><span>0</span><span>])</span>
</pre></div>
<p>A normal type variable enables parameterization with a single type. A type
variable tuple, in contrast, allows parameterization with an
<em>arbitrary</em> number of types by acting like an <em>arbitrary</em> number of type
variables wrapped in a tuple. For example:</p>
<div><pre><span></span><span># T is bound to int, Ts is bound to ()</span>
<span># Return value is (1,), which has type tuple[int]</span>
<span>move_first_element_to_last</span><span>(</span><span>tup</span><span>=</span><span>(</span><span>1</span><span>,))</span>

<span># T is bound to int, Ts is bound to (str,)</span>
<span># Return value is ('spam', 1), which has type tuple[str, int]</span>
<span>move_first_element_to_last</span><span>(</span><span>tup</span><span>=</span><span>(</span><span>1</span><span>,</span> <span>'spam'</span><span>))</span>

<span># T is bound to int, Ts is bound to (str, float)</span>
<span># Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]</span>
<span>move_first_element_to_last</span><span>(</span><span>tup</span><span>=</span><span>(</span><span>1</span><span>,</span> <span>'spam'</span><span>,</span> <span>3.0</span><span>))</span>

<span># This fails to type check (and fails at runtime)</span>
<span># because tuple[()] is not compatible with tuple[T, *Ts]</span>
<span># (at least one element is required)</span>
<span>move_first_element_to_last</span><span>(</span><span>tup</span><span>=</span><span>())</span>
</pre></div>
<p>Note the use of the unpacking operator <code><span>*</span></code> in <code><span>tuple[T,</span> <span>*Ts]</span></code>.
Conceptually, you can think of <code><span>Ts</span></code> as a tuple of type variables
<code><span>(T1,</span> <span>T2,</span> <span>...)</span></code>. <code><span>tuple[T,</span> <span>*Ts]</span></code> would then become
<code><span>tuple[T,</span> <span>*(T1,</span> <span>T2,</span> <span>...)]</span></code>, which is equivalent to
<code><span>tuple[T,</span> <span>T1,</span> <span>T2,</span> <span>...]</span></code>. (Note that in older versions of Python, you might
see this written using <a href="#typing.Unpack"><code><span>Unpack</span></code></a> instead, as
<code><span>Unpack[Ts]</span></code>.)</p>
<p>Type variable tuples must <em>always</em> be unpacked. This helps distinguish type
variable tuples from normal type variables:</p>
<div><pre><span></span><span>x</span><span>:</span> <span>Ts</span>          <span># Not valid</span>
<span>x</span><span>:</span> <span>tuple</span><span>[</span><span>Ts</span><span>]</span>   <span># Not valid</span>
<span>x</span><span>:</span> <span>tuple</span><span>[</span><span>*</span><span>Ts</span><span>]</span>  <span># The correct way to do it</span>
</pre></div>
<p>Type variable tuples can be used in the same contexts as normal type
variables. For example, in class definitions, arguments, and return types:</p>
<div><pre><span></span><span>class</span> <span>Array</span><span>[</span><span>*</span><span>Shape</span><span>]:</span>
    <span>def</span> <span>__getitem__</span><span>(</span><span>self</span><span>,</span> <span>key</span><span>:</span> <span>tuple</span><span>[</span><span>*</span><span>Shape</span><span>])</span> <span>-&gt;</span> <span>float</span><span>:</span> <span>...</span>
    <span>def</span> <span>__abs__</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>"Array[*Shape]"</span><span>:</span> <span>...</span>
    <span>def</span> <span>get_shape</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>tuple</span><span>[</span><span>*</span><span>Shape</span><span>]:</span> <span>...</span>
</pre></div>
<p>Type variable tuples can be happily combined with normal type variables:</p>
<div><pre><span></span><span>class</span> <span>Array</span><span>[</span><span>DType</span><span>,</span> <span>*</span><span>Shape</span><span>]:</span>  <span># This is fine</span>
    <span>pass</span>

<span>class</span> <span>Array2</span><span>[</span><span>*</span><span>Shape</span><span>,</span> <span>DType</span><span>]:</span>  <span># This would also be fine</span>
    <span>pass</span>

<span>class</span> <span>Height</span><span>:</span> <span>...</span>
<span>class</span> <span>Width</span><span>:</span> <span>...</span>

<span>float_array_1d</span><span>:</span> <span>Array</span><span>[</span><span>float</span><span>,</span> <span>Height</span><span>]</span> <span>=</span> <span>Array</span><span>()</span>     <span># Totally fine</span>
<span>int_array_2d</span><span>:</span> <span>Array</span><span>[</span><span>int</span><span>,</span> <span>Height</span><span>,</span> <span>Width</span><span>]</span> <span>=</span> <span>Array</span><span>()</span>  <span># Yup, fine too</span>
</pre></div>
<p>However, note that at most one type variable tuple may appear in a single
list of type arguments or type parameters:</p>
<div><pre><span></span><span>x</span><span>:</span> <span>tuple</span><span>[</span><span>*</span><span>Ts</span><span>,</span> <span>*</span><span>Ts</span><span>]</span>            <span># Not valid</span>
<span>class</span> <span>Array</span><span>[</span><span>*</span><span>Shape</span><span>,</span> <span>*</span><span>Shape</span><span>]:</span>  <span># Not valid</span>
    <span>pass</span>
</pre></div>
<p>Finally, an unpacked type variable tuple can be used as the type annotation
of <code><span>*args</span></code>:</p>
<div><pre><span></span><span>def</span> <span>call_soon</span><span>[</span><span>*</span><span>Ts</span><span>](</span>
    <span>callback</span><span>:</span> <span>Callable</span><span>[[</span><span>*</span><span>Ts</span><span>],</span> <span>None</span><span>],</span>
    <span>*</span><span>args</span><span>:</span> <span>*</span><span>Ts</span>
<span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>
    <span>callback</span><span>(</span><span>*</span><span>args</span><span>)</span>
</pre></div>
<p>In contrast to non-unpacked annotations of <code><span>*args</span></code> - e.g. <code><span>*args:</span> <span>int</span></code>,
which would specify that <em>all</em> arguments are <code><span>int</span></code> - <code><span>*args:</span> <span>*Ts</span></code>
enables reference to the types of the <em>individual</em> arguments in <code><span>*args</span></code>.
Here, this allows us to ensure the types of the <code><span>*args</span></code> passed
to <code><span>call_soon</span></code> match the types of the (positional) arguments of
<code><span>callback</span></code>.</p>
<p>See <span></span><a href="https://peps.python.org/pep-0646/"><strong>PEP 646</strong></a> for more details on type variable tuples.</p>
<dl>
<dt>
<span><span>__name__</span></span><a href="#typing.TypeVarTuple.__name__">¶</a></dt>
<dd><p>The name of the type variable tuple.</p>
</dd></dl>

<p><span>Added in version 3.11.</span></p>
<p><span>Changed in version 3.12: </span>Type variable tuples can now be declared using the
<a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter</span></a> syntax introduced by <span></span><a href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a>.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>ParamSpec</span></span><span>(</span><em><span><span>name</span></span></em>, <em><span><span>*</span></span></em>, <em><span><span>bound</span></span><span><span>=</span></span><span><span>None</span></span></em>, <em><span><span>covariant</span></span><span><span>=</span></span><span><span>False</span></span></em>, <em><span><span>contravariant</span></span><span><span>=</span></span><span><span>False</span></span></em><span>)</span><a href="#typing.ParamSpec">¶</a></dt>
<dd><p>Parameter specification variable.  A specialized version of
<a href="#typevar"><span>type variables</span></a>.</p>
<p>In <a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter lists</span></a>, parameter specifications
can be declared with two asterisks (<code><span>**</span></code>):</p>
<div><pre><span></span><span>type</span> <span>IntFunc</span><span>[</span><span>**</span><span>P</span><span>]</span> <span>=</span> <span>Callable</span><span>[</span><span>P</span><span>,</span> <span>int</span><span>]</span>
</pre></div>
<p>For compatibility with Python 3.11 and earlier, <code><span>ParamSpec</span></code> objects
can also be created as follows:</p>

<p>Parameter specification variables exist primarily for the benefit of static
type checkers.  They are used to forward the parameter types of one
callable to another callable – a pattern commonly found in higher order
functions and decorators.  They are only valid when used in <code><span>Concatenate</span></code>,
or as the first argument to <code><span>Callable</span></code>, or as parameters for user-defined
Generics.  See <a href="#typing.Generic"><code><span>Generic</span></code></a> for more information on generic types.</p>
<p>For example, to add basic logging to a function, one can create a decorator
<code><span>add_logging</span></code> to log function calls.  The parameter specification variable
tells the type checker that the callable passed into the decorator and the
new callable returned by it have inter-dependent type parameters:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Callable</span>
<span>import</span> <span>logging</span>

<span>def</span> <span>add_logging</span><span>[</span><span>T</span><span>,</span> <span>**</span><span>P</span><span>](</span><span>f</span><span>:</span> <span>Callable</span><span>[</span><span>P</span><span>,</span> <span>T</span><span>])</span> <span>-&gt;</span> <span>Callable</span><span>[</span><span>P</span><span>,</span> <span>T</span><span>]:</span>
<span>    </span><span>'''A type-safe decorator to add logging to a function.'''</span>
    <span>def</span> <span>inner</span><span>(</span><span>*</span><span>args</span><span>:</span> <span>P</span><span>.</span><span>args</span><span>,</span> <span>**</span><span>kwargs</span><span>:</span> <span>P</span><span>.</span><span>kwargs</span><span>)</span> <span>-&gt;</span> <span>T</span><span>:</span>
        <span>logging</span><span>.</span><span>info</span><span>(</span><span>f</span><span>'</span><span>{</span><span>f</span><span>.</span><span>__name__</span><span>}</span><span> was called'</span><span>)</span>
        <span>return</span> <span>f</span><span>(</span><span>*</span><span>args</span><span>,</span> <span>**</span><span>kwargs</span><span>)</span>
    <span>return</span> <span>inner</span>

<span>@add_logging</span>
<span>def</span> <span>add_two</span><span>(</span><span>x</span><span>:</span> <span>float</span><span>,</span> <span>y</span><span>:</span> <span>float</span><span>)</span> <span>-&gt;</span> <span>float</span><span>:</span>
<span>    </span><span>'''Add two numbers together.'''</span>
    <span>return</span> <span>x</span> <span>+</span> <span>y</span>
</pre></div>
<p>Without <code><span>ParamSpec</span></code>, the simplest way to annotate this previously was to
use a <a href="#typing.TypeVar"><code><span>TypeVar</span></code></a> with bound <code><span>Callable[...,</span> <span>Any]</span></code>.  However this
causes two problems:</p>
<ol>
<li><p>The type checker can’t type check the <code><span>inner</span></code> function because
<code><span>*args</span></code> and <code><span>**kwargs</span></code> have to be typed <a href="#typing.Any"><code><span>Any</span></code></a>.</p></li>
<li><p><a href="#typing.cast"><code><span>cast()</span></code></a> may be required in the body of the <code><span>add_logging</span></code>
decorator when returning the <code><span>inner</span></code> function, or the static type
checker must be told to ignore the <code><span>return</span> <span>inner</span></code>.</p></li>
</ol>
<dl>
<dt>
<span><span>args</span></span><a href="#typing.ParamSpec.args">¶</a></dt>
<dd></dd></dl>

<dl>
<dt>
<span><span>kwargs</span></span><a href="#typing.ParamSpec.kwargs">¶</a></dt>
<dd><p>Since <code><span>ParamSpec</span></code> captures both positional and keyword parameters,
<code><span>P.args</span></code> and <code><span>P.kwargs</span></code> can be used to split a <code><span>ParamSpec</span></code> into its
components.  <code><span>P.args</span></code> represents the tuple of positional parameters in a
given call and should only be used to annotate <code><span>*args</span></code>.  <code><span>P.kwargs</span></code>
represents the mapping of keyword parameters to their values in a given call,
and should be only be used to annotate <code><span>**kwargs</span></code>.  Both
attributes require the annotated parameter to be in scope. At runtime,
<code><span>P.args</span></code> and <code><span>P.kwargs</span></code> are instances respectively of
<a href="#typing.ParamSpecArgs"><code><span>ParamSpecArgs</span></code></a> and <a href="#typing.ParamSpecKwargs"><code><span>ParamSpecKwargs</span></code></a>.</p>
</dd></dl>

<dl>
<dt>
<span><span>__name__</span></span><a href="#typing.ParamSpec.__name__">¶</a></dt>
<dd><p>The name of the parameter specification.</p>
</dd></dl>

<p>Parameter specification variables created with <code><span>covariant=True</span></code> or
<code><span>contravariant=True</span></code> can be used to declare covariant or contravariant
generic types.  The <code><span>bound</span></code> argument is also accepted, similar to
<a href="#typing.TypeVar"><code><span>TypeVar</span></code></a>.  However the actual semantics of these keywords are yet to
be decided.</p>
<p><span>Added in version 3.10.</span></p>
<p><span>Changed in version 3.12: </span>Parameter specifications can now be declared using the
<a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter</span></a> syntax introduced by <span></span><a href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a>.</p>
<div>
<p>Note</p>
<p>Only parameter specification variables defined in global scope can
be pickled.</p>
</div>
<div>
<p>See also</p>
<ul>
<li><p><span></span><a href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> – Parameter Specification Variables (the PEP which introduced
<code><span>ParamSpec</span></code> and <code><span>Concatenate</span></code>)</p></li>
<li><p><a href="#typing.Concatenate"><code><span>Concatenate</span></code></a></p></li>
<li><p><a href="#annotating-callables"><span>Annotating callable objects</span></a></p></li>
</ul>
</div>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>ParamSpecArgs</span></span><a href="#typing.ParamSpecArgs">¶</a></dt>
<dt>
<span><span>typing.</span></span><span><span>ParamSpecKwargs</span></span><a href="#typing.ParamSpecKwargs">¶</a></dt>
<dd><p>Arguments and keyword arguments attributes of a <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a>. The
<code><span>P.args</span></code> attribute of a <code><span>ParamSpec</span></code> is an instance of <code><span>ParamSpecArgs</span></code>,
and <code><span>P.kwargs</span></code> is an instance of <code><span>ParamSpecKwargs</span></code>. They are intended
for runtime introspection and have no special meaning to static type checkers.</p>
<p>Calling <a href="#typing.get_origin"><code><span>get_origin()</span></code></a> on either of these objects will return the
original <code><span>ParamSpec</span></code>:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>from</span> <span>typing</span> <span>import</span> <span>ParamSpec</span><span>,</span> <span>get_origin</span>
<span>&gt;&gt;&gt; </span><span>P</span> <span>=</span> <span>ParamSpec</span><span>(</span><span>"P"</span><span>)</span>
<span>&gt;&gt;&gt; </span><span>get_origin</span><span>(</span><span>P</span><span>.</span><span>args</span><span>)</span> <span>is</span> <span>P</span>
<span>True</span>
<span>&gt;&gt;&gt; </span><span>get_origin</span><span>(</span><span>P</span><span>.</span><span>kwargs</span><span>)</span> <span>is</span> <span>P</span>
<span>True</span>
</pre></div>
<p><span>Added in version 3.10.</span></p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>TypeAliasType</span></span><span>(</span><em><span><span>name</span></span></em>, <em><span><span>value</span></span></em>, <em><span><span>*</span></span></em>, <em><span><span>type_params</span></span><span><span>=</span></span><span><span>()</span></span></em><span>)</span><a href="#typing.TypeAliasType">¶</a></dt>
<dd><p>The type of type aliases created through the <a href="https://docs.python.org/3/reference/simple_stmts.html#type"><code><span>type</span></code></a> statement.</p>
<p>Example:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>type</span> <span>Alias</span> <span>=</span> <span>int</span>
<span>&gt;&gt;&gt; </span><span>type</span><span>(</span><span>Alias</span><span>)</span>
<span>&lt;class 'typing.TypeAliasType'&gt;</span>
</pre></div>
<p><span>Added in version 3.12.</span></p>
<dl>
<dt>
<span><span>__name__</span></span><a href="#typing.TypeAliasType.__name__">¶</a></dt>
<dd><p>The name of the type alias:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>type</span> <span>Alias</span> <span>=</span> <span>int</span>
<span>&gt;&gt;&gt; </span><span>Alias</span><span>.</span><span>__name__</span>
<span>'Alias'</span>
</pre></div>
</dd></dl>

<dl>
<dt>
<span><span>__module__</span></span><a href="#typing.TypeAliasType.__module__">¶</a></dt>
<dd><p>The module in which the type alias was defined:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>type</span> <span>Alias</span> <span>=</span> <span>int</span>
<span>&gt;&gt;&gt; </span><span>Alias</span><span>.</span><span>__module__</span>
<span>'__main__'</span>
</pre></div>
</dd></dl>

<dl>
<dt>
<span><span>__type_params__</span></span><a href="#typing.TypeAliasType.__type_params__">¶</a></dt>
<dd><p>The type parameters of the type alias, or an empty tuple if the alias is
not generic:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>type</span> <span>ListOrSet</span><span>[</span><span>T</span><span>]</span> <span>=</span> <span>list</span><span>[</span><span>T</span><span>]</span> <span>|</span> <span>set</span><span>[</span><span>T</span><span>]</span>
<span>&gt;&gt;&gt; </span><span>ListOrSet</span><span>.</span><span>__type_params__</span>
<span>(T,)</span>
<span>&gt;&gt;&gt; </span><span>type</span> <span>NotGeneric</span> <span>=</span> <span>int</span>
<span>&gt;&gt;&gt; </span><span>NotGeneric</span><span>.</span><span>__type_params__</span>
<span>()</span>
</pre></div>
</dd></dl>

<dl>
<dt>
<span><span>__value__</span></span><a href="#typing.TypeAliasType.__value__">¶</a></dt>
<dd><p>The type alias’s value. This is <a href="https://docs.python.org/3/reference/executionmodel.html#lazy-evaluation"><span>lazily evaluated</span></a>,
so names used in the definition of the alias are not resolved until the
<code><span>__value__</span></code> attribute is accessed:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>type</span> <span>Mutually</span> <span>=</span> <span>Recursive</span>
<span>&gt;&gt;&gt; </span><span>type</span> <span>Recursive</span> <span>=</span> <span>Mutually</span>
<span>&gt;&gt;&gt; </span><span>Mutually</span>
<span>Mutually</span>
<span>&gt;&gt;&gt; </span><span>Recursive</span>
<span>Recursive</span>
<span>&gt;&gt;&gt; </span><span>Mutually</span><span>.</span><span>__value__</span>
<span>Recursive</span>
<span>&gt;&gt;&gt; </span><span>Recursive</span><span>.</span><span>__value__</span>
<span>Mutually</span>
</pre></div>
</dd></dl>

</dd></dl>

</section>
<section>
<h4>Other special directives<a href="#other-special-directives">¶</a></h4>
<p>These functions and classes should not be used directly as annotations.
Their intended purpose is to be building blocks for creating and declaring
types.</p>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>NamedTuple</span></span><a href="#typing.NamedTuple">¶</a></dt>
<dd><p>Typed version of <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple"><code><span>collections.namedtuple()</span></code></a>.</p>
<p>Usage:</p>
<div><pre><span></span><span>class</span> <span>Employee</span><span>(</span><span>NamedTuple</span><span>):</span>
    <span>name</span><span>:</span> <span>str</span>
    <span>id</span><span>:</span> <span>int</span>
</pre></div>
<p>This is equivalent to:</p>
<div><pre><span></span><span>Employee</span> <span>=</span> <span>collections</span><span>.</span><span>namedtuple</span><span>(</span><span>'Employee'</span><span>,</span> <span>[</span><span>'name'</span><span>,</span> <span>'id'</span><span>])</span>
</pre></div>
<p>To give a field a default value, you can assign to it in the class body:</p>
<div><pre><span></span><span>class</span> <span>Employee</span><span>(</span><span>NamedTuple</span><span>):</span>
    <span>name</span><span>:</span> <span>str</span>
    <span>id</span><span>:</span> <span>int</span> <span>=</span> <span>3</span>

<span>employee</span> <span>=</span> <span>Employee</span><span>(</span><span>'Guido'</span><span>)</span>
<span>assert</span> <span>employee</span><span>.</span><span>id</span> <span>==</span> <span>3</span>
</pre></div>
<p>Fields with a default value must come after any fields without a default.</p>
<p>The resulting class has an extra attribute <code><span>__annotations__</span></code> giving a
dict that maps the field names to the field types.  (The field names are in
the <code><span>_fields</span></code> attribute and the default values are in the
<code><span>_field_defaults</span></code> attribute, both of which are part of the <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple"><code><span>namedtuple()</span></code></a>
API.)</p>
<p><code><span>NamedTuple</span></code> subclasses can also have docstrings and methods:</p>
<div><pre><span></span><span>class</span> <span>Employee</span><span>(</span><span>NamedTuple</span><span>):</span>
<span>    </span><span>"""Represents an employee."""</span>
    <span>name</span><span>:</span> <span>str</span>
    <span>id</span><span>:</span> <span>int</span> <span>=</span> <span>3</span>

    <span>def</span> <span>__repr__</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>str</span><span>:</span>
        <span>return</span> <span>f</span><span>'&lt;Employee </span><span>{</span><span>self</span><span>.</span><span>name</span><span>}</span><span>, id=</span><span>{</span><span>self</span><span>.</span><span>id</span><span>}</span><span>&gt;'</span>
</pre></div>
<p><code><span>NamedTuple</span></code> subclasses can be generic:</p>
<div><pre><span></span><span>class</span> <span>Group</span><span>[</span><span>T</span><span>](</span><span>NamedTuple</span><span>):</span>
    <span>key</span><span>:</span> <span>T</span>
    <span>group</span><span>:</span> <span>list</span><span>[</span><span>T</span><span>]</span>
</pre></div>
<p>Backward-compatible usage:</p>
<div><pre><span></span><span># For creating a generic NamedTuple on Python 3.11 or lower</span>
<span>class</span> <span>Group</span><span>(</span><span>NamedTuple</span><span>,</span> <span>Generic</span><span>[</span><span>T</span><span>]):</span>
    <span>key</span><span>:</span> <span>T</span>
    <span>group</span><span>:</span> <span>list</span><span>[</span><span>T</span><span>]</span>

<span># A functional syntax is also supported</span>
<span>Employee</span> <span>=</span> <span>NamedTuple</span><span>(</span><span>'Employee'</span><span>,</span> <span>[(</span><span>'name'</span><span>,</span> <span>str</span><span>),</span> <span>(</span><span>'id'</span><span>,</span> <span>int</span><span>)])</span>
</pre></div>
<p><span>Changed in version 3.6: </span>Added support for <span></span><a href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a> variable annotation syntax.</p>
<p><span>Changed in version 3.6.1: </span>Added support for default values, methods, and docstrings.</p>
<p><span>Changed in version 3.8: </span>The <code><span>_field_types</span></code> and <code><span>__annotations__</span></code> attributes are
now regular dictionaries instead of instances of <code><span>OrderedDict</span></code>.</p>
<p><span>Changed in version 3.9: </span>Removed the <code><span>_field_types</span></code> attribute in favor of the more
standard <code><span>__annotations__</span></code> attribute which has the same information.</p>
<p><span>Changed in version 3.11: </span>Added support for generic namedtuples.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>NewType</span></span><span>(</span><em><span><span>name</span></span></em>, <em><span><span>tp</span></span></em><span>)</span><a href="#typing.NewType">¶</a></dt>
<dd><p>Helper class to create low-overhead <a href="#distinct"><span>distinct types</span></a>.</p>
<p>A <code><span>NewType</span></code> is considered a distinct type by a typechecker. At runtime,
however, calling a <code><span>NewType</span></code> returns its argument unchanged.</p>
<p>Usage:</p>
<div><pre><span></span><span>UserId</span> <span>=</span> <span>NewType</span><span>(</span><span>'UserId'</span><span>,</span> <span>int</span><span>)</span>  <span># Declare the NewType "UserId"</span>
<span>first_user</span> <span>=</span> <span>UserId</span><span>(</span><span>1</span><span>)</span>  <span># "UserId" returns the argument unchanged at runtime</span>
</pre></div>
<dl>
<dt>
<span><span>__module__</span></span><a href="#typing.NewType.__module__">¶</a></dt>
<dd><p>The module in which the new type is defined.</p>
</dd></dl>

<dl>
<dt>
<span><span>__name__</span></span><a href="#typing.NewType.__name__">¶</a></dt>
<dd><p>The name of the new type.</p>
</dd></dl>

<dl>
<dt>
<span><span>__supertype__</span></span><a href="#typing.NewType.__supertype__">¶</a></dt>
<dd><p>The type that the new type is based on.</p>
</dd></dl>

<p><span>Added in version 3.5.2.</span></p>
<p><span>Changed in version 3.10: </span><code><span>NewType</span></code> is now a class rather than a function.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Protocol</span></span><span>(</span><em><span><span>Generic</span></span></em><span>)</span><a href="#typing.Protocol">¶</a></dt>
<dd><p>Base class for protocol classes.</p>
<p>Protocol classes are defined like this:</p>
<div><pre><span></span><span>class</span> <span>Proto</span><span>(</span><span>Protocol</span><span>):</span>
    <span>def</span> <span>meth</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>int</span><span>:</span>
        <span>...</span>
</pre></div>
<p>Such classes are primarily used with static type checkers that recognize
structural subtyping (static duck-typing), for example:</p>
<div><pre><span></span><span>class</span> <span>C</span><span>:</span>
    <span>def</span> <span>meth</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>int</span><span>:</span>
        <span>return</span> <span>0</span>

<span>def</span> <span>func</span><span>(</span><span>x</span><span>:</span> <span>Proto</span><span>)</span> <span>-&gt;</span> <span>int</span><span>:</span>
    <span>return</span> <span>x</span><span>.</span><span>meth</span><span>()</span>

<span>func</span><span>(</span><span>C</span><span>())</span>  <span># Passes static type check</span>
</pre></div>
<p>See <span></span><a href="https://peps.python.org/pep-0544/"><strong>PEP 544</strong></a> for more details. Protocol classes decorated with
<a href="#typing.runtime_checkable"><code><span>runtime_checkable()</span></code></a> (described later) act as simple-minded runtime
protocols that check only the presence of given attributes, ignoring their
type signatures.</p>
<p>Protocol classes can be generic, for example:</p>
<div><pre><span></span><span>class</span> <span>GenProto</span><span>[</span><span>T</span><span>](</span><span>Protocol</span><span>):</span>
    <span>def</span> <span>meth</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>T</span><span>:</span>
        <span>...</span>
</pre></div>
<p>In code that needs to be compatible with Python 3.11 or older, generic
Protocols can be written as follows:</p>
<div><pre><span></span><span>T</span> <span>=</span> <span>TypeVar</span><span>(</span><span>"T"</span><span>)</span>

<span>class</span> <span>GenProto</span><span>(</span><span>Protocol</span><span>[</span><span>T</span><span>]):</span>
    <span>def</span> <span>meth</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>T</span><span>:</span>
        <span>...</span>
</pre></div>
<p><span>Added in version 3.8.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>@</span></span><span><span>typing.</span></span><span><span>runtime_checkable</span></span><a href="#typing.runtime_checkable">¶</a></dt>
<dd><p>Mark a protocol class as a runtime protocol.</p>
<p>Such a protocol can be used with <a href="https://docs.python.org/3/library/functions.html#isinstance"><code><span>isinstance()</span></code></a> and <a href="https://docs.python.org/3/library/functions.html#issubclass"><code><span>issubclass()</span></code></a>.
This raises <a href="https://docs.python.org/3/library/exceptions.html#TypeError"><code><span>TypeError</span></code></a> when applied to a non-protocol class.  This
allows a simple-minded structural check, very similar to “one trick ponies”
in <a href="https://docs.python.org/3/library/collections.abc.html#module-collections.abc"><code><span>collections.abc</span></code></a> such as <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable"><code><span>Iterable</span></code></a>.  For example:</p>
<div><pre><span></span><span>@runtime_checkable</span>
<span>class</span> <span>Closable</span><span>(</span><span>Protocol</span><span>):</span>
    <span>def</span> <span>close</span><span>(</span><span>self</span><span>):</span> <span>...</span>

<span>assert</span> <span>isinstance</span><span>(</span><span>open</span><span>(</span><span>'/some/file'</span><span>),</span> <span>Closable</span><span>)</span>

<span>@runtime_checkable</span>
<span>class</span> <span>Named</span><span>(</span><span>Protocol</span><span>):</span>
    <span>name</span><span>:</span> <span>str</span>

<span>import</span> <span>threading</span>
<span>assert</span> <span>isinstance</span><span>(</span><span>threading</span><span>.</span><span>Thread</span><span>(</span><span>name</span><span>=</span><span>'Bob'</span><span>),</span> <span>Named</span><span>)</span>
</pre></div>
<div>
<p>Note</p>
<p><code><span>runtime_checkable()</span></code> will check only the presence of the required
methods or attributes, not their type signatures or types.
For example, <a href="https://docs.python.org/3/library/ssl.html#ssl.SSLObject"><code><span>ssl.SSLObject</span></code></a>
is a class, therefore it passes an <a href="https://docs.python.org/3/library/functions.html#issubclass"><code><span>issubclass()</span></code></a>
check against <a href="#annotating-callables"><span>Callable</span></a>. However, the
<code><span>ssl.SSLObject.__init__</span></code> method exists only to raise a
<a href="https://docs.python.org/3/library/exceptions.html#TypeError"><code><span>TypeError</span></code></a> with a more informative message, therefore making
it impossible to call (instantiate) <a href="https://docs.python.org/3/library/ssl.html#ssl.SSLObject"><code><span>ssl.SSLObject</span></code></a>.</p>
</div>
<div>
<p>Note</p>
<p>An <a href="https://docs.python.org/3/library/functions.html#isinstance"><code><span>isinstance()</span></code></a> check against a runtime-checkable protocol can be
surprisingly slow compared to an <code><span>isinstance()</span></code> check against
a non-protocol class. Consider using alternative idioms such as
<a href="https://docs.python.org/3/library/functions.html#hasattr"><code><span>hasattr()</span></code></a> calls for structural checks in performance-sensitive
code.</p>
</div>
<p><span>Added in version 3.8.</span></p>
<p><span>Changed in version 3.12: </span>The internal implementation of <a href="https://docs.python.org/3/library/functions.html#isinstance"><code><span>isinstance()</span></code></a> checks against
runtime-checkable protocols now uses <a href="https://docs.python.org/3/library/inspect.html#inspect.getattr_static"><code><span>inspect.getattr_static()</span></code></a>
to look up attributes (previously, <a href="https://docs.python.org/3/library/functions.html#hasattr"><code><span>hasattr()</span></code></a> was used).
As a result, some objects which used to be considered instances
of a runtime-checkable protocol may no longer be considered instances
of that protocol on Python 3.12+, and vice versa.
Most users are unlikely to be affected by this change.</p>
<p><span>Changed in version 3.12: </span>The members of a runtime-checkable protocol are now considered “frozen”
at runtime as soon as the class has been created. Monkey-patching
attributes onto a runtime-checkable protocol will still work, but will
have no impact on <a href="https://docs.python.org/3/library/functions.html#isinstance"><code><span>isinstance()</span></code></a> checks comparing objects to the
protocol. See <a href="https://docs.python.org/3/whatsnew/3.12.html#whatsnew-typing-py312"><span>“What’s new in Python 3.12”</span></a>
for more details.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>TypedDict</span></span><span>(</span><em><span><span>dict</span></span></em><span>)</span><a href="#typing.TypedDict">¶</a></dt>
<dd><p>Special construct to add type hints to a dictionary.
At runtime it is a plain <a href="https://docs.python.org/3/library/stdtypes.html#dict"><code><span>dict</span></code></a>.</p>
<p><code><span>TypedDict</span></code> declares a dictionary type that expects all of its
instances to have a certain set of keys, where each key is
associated with a value of a consistent type. This expectation
is not checked at runtime but is only enforced by type checkers.
Usage:</p>
<div><pre><span></span><span>class</span> <span>Point2D</span><span>(</span><span>TypedDict</span><span>):</span>
    <span>x</span><span>:</span> <span>int</span>
    <span>y</span><span>:</span> <span>int</span>
    <span>label</span><span>:</span> <span>str</span>

<span>a</span><span>:</span> <span>Point2D</span> <span>=</span> <span>{</span><span>'x'</span><span>:</span> <span>1</span><span>,</span> <span>'y'</span><span>:</span> <span>2</span><span>,</span> <span>'label'</span><span>:</span> <span>'good'</span><span>}</span>  <span># OK</span>
<span>b</span><span>:</span> <span>Point2D</span> <span>=</span> <span>{</span><span>'z'</span><span>:</span> <span>3</span><span>,</span> <span>'label'</span><span>:</span> <span>'bad'</span><span>}</span>           <span># Fails type check</span>

<span>assert</span> <span>Point2D</span><span>(</span><span>x</span><span>=</span><span>1</span><span>,</span> <span>y</span><span>=</span><span>2</span><span>,</span> <span>label</span><span>=</span><span>'first'</span><span>)</span> <span>==</span> <span>dict</span><span>(</span><span>x</span><span>=</span><span>1</span><span>,</span> <span>y</span><span>=</span><span>2</span><span>,</span> <span>label</span><span>=</span><span>'first'</span><span>)</span>
</pre></div>
<p>To allow using this feature with older versions of Python that do not
support <span></span><a href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a>, <code><span>TypedDict</span></code> supports two additional equivalent
syntactic forms:</p>
<ul>
<li><p>Using a literal <a href="https://docs.python.org/3/library/stdtypes.html#dict"><code><span>dict</span></code></a> as the second argument:</p>
<div><pre><span></span><span>Point2D</span> <span>=</span> <span>TypedDict</span><span>(</span><span>'Point2D'</span><span>,</span> <span>{</span><span>'x'</span><span>:</span> <span>int</span><span>,</span> <span>'y'</span><span>:</span> <span>int</span><span>,</span> <span>'label'</span><span>:</span> <span>str</span><span>})</span>
</pre></div>
</li>
<li><p>Using keyword arguments:</p>
<div><pre><span></span><span>Point2D</span> <span>=</span> <span>TypedDict</span><span>(</span><span>'Point2D'</span><span>,</span> <span>x</span><span>=</span><span>int</span><span>,</span> <span>y</span><span>=</span><span>int</span><span>,</span> <span>label</span><span>=</span><span>str</span><span>)</span>
</pre></div>
<p><span>Deprecated since version 3.11, will be removed in version 3.13: </span>The keyword-argument syntax is deprecated in 3.11 and will be removed
in 3.13. It may also be unsupported by static type checkers.</p>
</li>
</ul>
<p>The functional syntax should also be used when any of the keys are not valid
<a href="https://docs.python.org/3/reference/lexical_analysis.html#identifiers"><span>identifiers</span></a>, for example because they are keywords or contain hyphens.
Example:</p>
<div><pre><span></span><span># raises SyntaxError</span>
<span>class</span> <span>Point2D</span><span>(</span><span>TypedDict</span><span>):</span>
    <span>in</span><span>:</span> <span>int</span>  <span># 'in' is a keyword</span>
    <span>x</span><span>-</span><span>y</span><span>:</span> <span>int</span>  <span># name with hyphens</span>

<span># OK, functional syntax</span>
<span>Point2D</span> <span>=</span> <span>TypedDict</span><span>(</span><span>'Point2D'</span><span>,</span> <span>{</span><span>'in'</span><span>:</span> <span>int</span><span>,</span> <span>'x-y'</span><span>:</span> <span>int</span><span>})</span>
</pre></div>
<p>By default, all keys must be present in a <code><span>TypedDict</span></code>. It is possible to
mark individual keys as non-required using <a href="#typing.NotRequired"><code><span>NotRequired</span></code></a>:</p>
<div><pre><span></span><span>class</span> <span>Point2D</span><span>(</span><span>TypedDict</span><span>):</span>
    <span>x</span><span>:</span> <span>int</span>
    <span>y</span><span>:</span> <span>int</span>
    <span>label</span><span>:</span> <span>NotRequired</span><span>[</span><span>str</span><span>]</span>

<span># Alternative syntax</span>
<span>Point2D</span> <span>=</span> <span>TypedDict</span><span>(</span><span>'Point2D'</span><span>,</span> <span>{</span><span>'x'</span><span>:</span> <span>int</span><span>,</span> <span>'y'</span><span>:</span> <span>int</span><span>,</span> <span>'label'</span><span>:</span> <span>NotRequired</span><span>[</span><span>str</span><span>]})</span>
</pre></div>
<p>This means that a <code><span>Point2D</span></code> <code><span>TypedDict</span></code> can have the <code><span>label</span></code>
key omitted.</p>
<p>It is also possible to mark all keys as non-required by default
by specifying a totality of <code><span>False</span></code>:</p>
<div><pre><span></span><span>class</span> <span>Point2D</span><span>(</span><span>TypedDict</span><span>,</span> <span>total</span><span>=</span><span>False</span><span>):</span>
    <span>x</span><span>:</span> <span>int</span>
    <span>y</span><span>:</span> <span>int</span>

<span># Alternative syntax</span>
<span>Point2D</span> <span>=</span> <span>TypedDict</span><span>(</span><span>'Point2D'</span><span>,</span> <span>{</span><span>'x'</span><span>:</span> <span>int</span><span>,</span> <span>'y'</span><span>:</span> <span>int</span><span>},</span> <span>total</span><span>=</span><span>False</span><span>)</span>
</pre></div>
<p>This means that a <code><span>Point2D</span></code> <code><span>TypedDict</span></code> can have any of the keys
omitted. A type checker is only expected to support a literal <code><span>False</span></code> or
<code><span>True</span></code> as the value of the <code><span>total</span></code> argument. <code><span>True</span></code> is the default,
and makes all items defined in the class body required.</p>
<p>Individual keys of a <code><span>total=False</span></code> <code><span>TypedDict</span></code> can be marked as
required using <a href="#typing.Required"><code><span>Required</span></code></a>:</p>
<div><pre><span></span><span>class</span> <span>Point2D</span><span>(</span><span>TypedDict</span><span>,</span> <span>total</span><span>=</span><span>False</span><span>):</span>
    <span>x</span><span>:</span> <span>Required</span><span>[</span><span>int</span><span>]</span>
    <span>y</span><span>:</span> <span>Required</span><span>[</span><span>int</span><span>]</span>
    <span>label</span><span>:</span> <span>str</span>

<span># Alternative syntax</span>
<span>Point2D</span> <span>=</span> <span>TypedDict</span><span>(</span><span>'Point2D'</span><span>,</span> <span>{</span>
    <span>'x'</span><span>:</span> <span>Required</span><span>[</span><span>int</span><span>],</span>
    <span>'y'</span><span>:</span> <span>Required</span><span>[</span><span>int</span><span>],</span>
    <span>'label'</span><span>:</span> <span>str</span>
<span>},</span> <span>total</span><span>=</span><span>False</span><span>)</span>
</pre></div>
<p>It is possible for a <code><span>TypedDict</span></code> type to inherit from one or more other <code><span>TypedDict</span></code> types
using the class-based syntax.
Usage:</p>
<div><pre><span></span><span>class</span> <span>Point3D</span><span>(</span><span>Point2D</span><span>):</span>
    <span>z</span><span>:</span> <span>int</span>
</pre></div>
<p><code><span>Point3D</span></code> has three items: <code><span>x</span></code>, <code><span>y</span></code> and <code><span>z</span></code>. It is equivalent to this
definition:</p>
<div><pre><span></span><span>class</span> <span>Point3D</span><span>(</span><span>TypedDict</span><span>):</span>
    <span>x</span><span>:</span> <span>int</span>
    <span>y</span><span>:</span> <span>int</span>
    <span>z</span><span>:</span> <span>int</span>
</pre></div>
<p>A <code><span>TypedDict</span></code> cannot inherit from a non-<code><span>TypedDict</span></code> class,
except for <a href="#typing.Generic"><code><span>Generic</span></code></a>. For example:</p>
<div><pre><span></span><span>class</span> <span>X</span><span>(</span><span>TypedDict</span><span>):</span>
    <span>x</span><span>:</span> <span>int</span>

<span>class</span> <span>Y</span><span>(</span><span>TypedDict</span><span>):</span>
    <span>y</span><span>:</span> <span>int</span>

<span>class</span> <span>Z</span><span>(</span><span>object</span><span>):</span> <span>pass</span>  <span># A non-TypedDict class</span>

<span>class</span> <span>XY</span><span>(</span><span>X</span><span>,</span> <span>Y</span><span>):</span> <span>pass</span>  <span># OK</span>

<span>class</span> <span>XZ</span><span>(</span><span>X</span><span>,</span> <span>Z</span><span>):</span> <span>pass</span>  <span># raises TypeError</span>
</pre></div>
<p>A <code><span>TypedDict</span></code> can be generic:</p>
<div><pre><span></span><span>class</span> <span>Group</span><span>[</span><span>T</span><span>](</span><span>TypedDict</span><span>):</span>
    <span>key</span><span>:</span> <span>T</span>
    <span>group</span><span>:</span> <span>list</span><span>[</span><span>T</span><span>]</span>
</pre></div>
<p>To create a generic <code><span>TypedDict</span></code> that is compatible with Python 3.11
or lower, inherit from <a href="#typing.Generic"><code><span>Generic</span></code></a> explicitly:</p>
<div><pre><span></span><span>T</span> <span>=</span> <span>TypeVar</span><span>(</span><span>"T"</span><span>)</span>

<span>class</span> <span>Group</span><span>(</span><span>TypedDict</span><span>,</span> <span>Generic</span><span>[</span><span>T</span><span>]):</span>
    <span>key</span><span>:</span> <span>T</span>
    <span>group</span><span>:</span> <span>list</span><span>[</span><span>T</span><span>]</span>
</pre></div>
<p>A <code><span>TypedDict</span></code> can be introspected via annotations dicts
(see <a href="https://docs.python.org/3/howto/annotations.html#annotations-howto"><span>Annotations Best Practices</span></a> for more information on annotations best practices),
<a href="#typing.TypedDict.__total__"><code><span>__total__</span></code></a>, <a href="#typing.TypedDict.__required_keys__"><code><span>__required_keys__</span></code></a>, and <a href="#typing.TypedDict.__optional_keys__"><code><span>__optional_keys__</span></code></a>.</p>
<dl>
<dt>
<span><span>__total__</span></span><a href="#typing.TypedDict.__total__">¶</a></dt>
<dd><p><code><span>Point2D.__total__</span></code> gives the value of the <code><span>total</span></code> argument.
Example:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>from</span> <span>typing</span> <span>import</span> <span>TypedDict</span>
<span>&gt;&gt;&gt; </span><span>class</span> <span>Point2D</span><span>(</span><span>TypedDict</span><span>):</span> <span>pass</span>
<span>&gt;&gt;&gt; </span><span>Point2D</span><span>.</span><span>__total__</span>
<span>True</span>
<span>&gt;&gt;&gt; </span><span>class</span> <span>Point2D</span><span>(</span><span>TypedDict</span><span>,</span> <span>total</span><span>=</span><span>False</span><span>):</span> <span>pass</span>
<span>&gt;&gt;&gt; </span><span>Point2D</span><span>.</span><span>__total__</span>
<span>False</span>
<span>&gt;&gt;&gt; </span><span>class</span> <span>Point3D</span><span>(</span><span>Point2D</span><span>):</span> <span>pass</span>
<span>&gt;&gt;&gt; </span><span>Point3D</span><span>.</span><span>__total__</span>
<span>True</span>
</pre></div>
<p>This attribute reflects <em>only</em> the value of the <code><span>total</span></code> argument
to the current <code><span>TypedDict</span></code> class, not whether the class is semantically
total. For example, a <code><span>TypedDict</span></code> with <code><span>__total__</span></code> set to <code><span>True</span></code> may
have keys marked with <a href="#typing.NotRequired"><code><span>NotRequired</span></code></a>, or it may inherit from another
<code><span>TypedDict</span></code> with <code><span>total=False</span></code>. Therefore, it is generally better to use
<a href="#typing.TypedDict.__required_keys__"><code><span>__required_keys__</span></code></a> and <a href="#typing.TypedDict.__optional_keys__"><code><span>__optional_keys__</span></code></a> for introspection.</p>
</dd></dl>

<dl>
<dt>
<span><span>__required_keys__</span></span><a href="#typing.TypedDict.__required_keys__">¶</a></dt>
<dd><p><span>Added in version 3.9.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>__optional_keys__</span></span><a href="#typing.TypedDict.__optional_keys__">¶</a></dt>
<dd><p><code><span>Point2D.__required_keys__</span></code> and <code><span>Point2D.__optional_keys__</span></code> return
<a href="https://docs.python.org/3/library/stdtypes.html#frozenset"><code><span>frozenset</span></code></a> objects containing required and non-required keys, respectively.</p>
<p>Keys marked with <a href="#typing.Required"><code><span>Required</span></code></a> will always appear in <code><span>__required_keys__</span></code>
and keys marked with <a href="#typing.NotRequired"><code><span>NotRequired</span></code></a> will always appear in <code><span>__optional_keys__</span></code>.</p>
<p>For backwards compatibility with Python 3.10 and below,
it is also possible to use inheritance to declare both required and
non-required keys in the same <code><span>TypedDict</span></code> . This is done by declaring a
<code><span>TypedDict</span></code> with one value for the <code><span>total</span></code> argument and then
inheriting from it in another <code><span>TypedDict</span></code> with a different value for
<code><span>total</span></code>:</p>
<div><pre><span></span><span>&gt;&gt;&gt; </span><span>class</span> <span>Point2D</span><span>(</span><span>TypedDict</span><span>,</span> <span>total</span><span>=</span><span>False</span><span>):</span>
<span>... </span>    <span>x</span><span>:</span> <span>int</span>
<span>... </span>    <span>y</span><span>:</span> <span>int</span>
<span>...</span>
<span>&gt;&gt;&gt; </span><span>class</span> <span>Point3D</span><span>(</span><span>Point2D</span><span>):</span>
<span>... </span>    <span>z</span><span>:</span> <span>int</span>
<span>...</span>
<span>&gt;&gt;&gt; </span><span>Point3D</span><span>.</span><span>__required_keys__</span> <span>==</span> <span>frozenset</span><span>({</span><span>'z'</span><span>})</span>
<span>True</span>
<span>&gt;&gt;&gt; </span><span>Point3D</span><span>.</span><span>__optional_keys__</span> <span>==</span> <span>frozenset</span><span>({</span><span>'x'</span><span>,</span> <span>'y'</span><span>})</span>
<span>True</span>
</pre></div>
<p><span>Added in version 3.9.</span></p>
<div>
<p>Note</p>
<p>If <code><span>from</span> <span>__future__</span> <span>import</span> <span>annotations</span></code> is used or if annotations
are given as strings, annotations are not evaluated when the
<code><span>TypedDict</span></code> is defined. Therefore, the runtime introspection that
<code><span>__required_keys__</span></code> and <code><span>__optional_keys__</span></code> rely on may not work
properly, and the values of the attributes may be incorrect.</p>
</div>
</dd></dl>

<p>See <span></span><a href="https://peps.python.org/pep-0589/"><strong>PEP 589</strong></a> for more examples and detailed rules of using <code><span>TypedDict</span></code>.</p>
<p><span>Added in version 3.8.</span></p>
<p><span>Changed in version 3.11: </span>Added support for marking individual keys as <a href="#typing.Required"><code><span>Required</span></code></a> or <a href="#typing.NotRequired"><code><span>NotRequired</span></code></a>.
See <span></span><a href="https://peps.python.org/pep-0655/"><strong>PEP 655</strong></a>.</p>
<p><span>Changed in version 3.11: </span>Added support for generic <code><span>TypedDict</span></code>s.</p>
</dd></dl>

</section>
</section>
<section>
<h3>Protocols<a href="#protocols">¶</a></h3>
<p>The following protocols are provided by the typing module. All are decorated
with <a href="#typing.runtime_checkable"><code><span>@runtime_checkable</span></code></a>.</p>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>SupportsAbs</span></span><a href="#typing.SupportsAbs">¶</a></dt>
<dd><p>An ABC with one abstract method <code><span>__abs__</span></code> that is covariant
in its return type.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>SupportsBytes</span></span><a href="#typing.SupportsBytes">¶</a></dt>
<dd><p>An ABC with one abstract method <code><span>__bytes__</span></code>.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>SupportsComplex</span></span><a href="#typing.SupportsComplex">¶</a></dt>
<dd><p>An ABC with one abstract method <code><span>__complex__</span></code>.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>SupportsFloat</span></span><a href="#typing.SupportsFloat">¶</a></dt>
<dd><p>An ABC with one abstract method <code><span>__float__</span></code>.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>SupportsIndex</span></span><a href="#typing.SupportsIndex">¶</a></dt>
<dd><p>An ABC with one abstract method <code><span>__index__</span></code>.</p>
<p><span>Added in version 3.8.</span></p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>SupportsInt</span></span><a href="#typing.SupportsInt">¶</a></dt>
<dd><p>An ABC with one abstract method <code><span>__int__</span></code>.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>SupportsRound</span></span><a href="#typing.SupportsRound">¶</a></dt>
<dd><p>An ABC with one abstract method <code><span>__round__</span></code>
that is covariant in its return type.</p>
</dd></dl>

</section>
<section>
<h3>ABCs for working with IO<a href="#abcs-for-working-with-io">¶</a></h3>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>IO</span></span><a href="#typing.IO">¶</a></dt>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>TextIO</span></span><a href="#typing.TextIO">¶</a></dt>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>BinaryIO</span></span><a href="#typing.BinaryIO">¶</a></dt>
<dd><p>Generic type <code><span>IO[AnyStr]</span></code> and its subclasses <code><span>TextIO(IO[str])</span></code>
and <code><span>BinaryIO(IO[bytes])</span></code>
represent the types of I/O streams such as returned by
<a href="https://docs.python.org/3/library/functions.html#open"><code><span>open()</span></code></a>.</p>
</dd></dl>

</section>
<section>
<h3>Functions and decorators<a href="#functions-and-decorators">¶</a></h3>
<dl>
<dt>
<span><span>typing.</span></span><span><span>cast</span></span><span>(</span><em><span><span>typ</span></span></em>, <em><span><span>val</span></span></em><span>)</span><a href="#typing.cast">¶</a></dt>
<dd><p>Cast a value to a type.</p>
<p>This returns the value unchanged.  To the type checker this
signals that the return value has the designated type, but at
runtime we intentionally don’t check anything (we want this
to be as fast as possible).</p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>assert_type</span></span><span>(</span><em><span><span>val</span></span></em>, <em><span><span>typ</span></span></em>, <em><span><span>/</span></span></em><span>)</span><a href="#typing.assert_type">¶</a></dt>
<dd><p>Ask a static type checker to confirm that <em>val</em> has an inferred type of <em>typ</em>.</p>
<p>At runtime this does nothing: it returns the first argument unchanged with no
checks or side effects, no matter the actual type of the argument.</p>
<p>When a static type checker encounters a call to <code><span>assert_type()</span></code>, it
emits an error if the value is not of the specified type:</p>
<div><pre><span></span><span>def</span> <span>greet</span><span>(</span><span>name</span><span>:</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>assert_type</span><span>(</span><span>name</span><span>,</span> <span>str</span><span>)</span>  <span># OK, inferred type of `name` is `str`</span>
    <span>assert_type</span><span>(</span><span>name</span><span>,</span> <span>int</span><span>)</span>  <span># type checker error</span>
</pre></div>
<p>This function is useful for ensuring the type checker’s understanding of a
script is in line with the developer’s intentions:</p>
<div><pre><span></span><span>def</span> <span>complex_function</span><span>(</span><span>arg</span><span>:</span> <span>object</span><span>):</span>
    <span># Do some complex type-narrowing logic,</span>
    <span># after which we hope the inferred type will be `int`</span>
    <span>...</span>
    <span># Test whether the type checker correctly understands our function</span>
    <span>assert_type</span><span>(</span><span>arg</span><span>,</span> <span>int</span><span>)</span>
</pre></div>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>assert_never</span></span><span>(</span><em><span><span>arg</span></span></em>, <em><span><span>/</span></span></em><span>)</span><a href="#typing.assert_never">¶</a></dt>
<dd><p>Ask a static type checker to confirm that a line of code is unreachable.</p>
<p>Example:</p>
<div><pre><span></span><span>def</span> <span>int_or_str</span><span>(</span><span>arg</span><span>:</span> <span>int</span> <span>|</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>match</span> <span>arg</span><span>:</span>
        <span>case</span> <span>int</span><span>():</span>
            <span>print</span><span>(</span><span>"It's an int"</span><span>)</span>
        <span>case</span> <span>str</span><span>():</span>
            <span>print</span><span>(</span><span>"It's a str"</span><span>)</span>
        <span>case</span><span> </span><span>_</span> <span>as</span> <span>unreachable</span><span>:</span>
            <span>assert_never</span><span>(</span><span>unreachable</span><span>)</span>
</pre></div>
<p>Here, the annotations allow the type checker to infer that the
last case can never execute, because <code><span>arg</span></code> is either
an <a href="https://docs.python.org/3/library/functions.html#int"><code><span>int</span></code></a> or a <a href="https://docs.python.org/3/library/stdtypes.html#str"><code><span>str</span></code></a>, and both options are covered by
earlier cases.</p>
<p>If a type checker finds that a call to <code><span>assert_never()</span></code> is
reachable, it will emit an error. For example, if the type annotation
for <code><span>arg</span></code> was instead <code><span>int</span> <span>|</span> <span>str</span> <span>|</span> <span>float</span></code>, the type checker would
emit an error pointing out that <code><span>unreachable</span></code> is of type <a href="https://docs.python.org/3/library/functions.html#float"><code><span>float</span></code></a>.
For a call to <code><span>assert_never</span></code> to pass type checking, the inferred type of
the argument passed in must be the bottom type, <a href="#typing.Never"><code><span>Never</span></code></a>, and nothing
else.</p>
<p>At runtime, this throws an exception when called.</p>

<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>reveal_type</span></span><span>(</span><em><span><span>obj</span></span></em>, <em><span><span>/</span></span></em><span>)</span><a href="#typing.reveal_type">¶</a></dt>
<dd><p>Ask a static type checker to reveal the inferred type of an expression.</p>
<p>When a static type checker encounters a call to this function,
it emits a diagnostic with the inferred type of the argument. For example:</p>
<div><pre><span></span><span>x</span><span>:</span> <span>int</span> <span>=</span> <span>1</span>
<span>reveal_type</span><span>(</span><span>x</span><span>)</span>  <span># Revealed type is "builtins.int"</span>
</pre></div>
<p>This can be useful when you want to debug how your type checker
handles a particular piece of code.</p>
<p>At runtime, this function prints the runtime type of its argument to
<a href="https://docs.python.org/3/library/sys.html#sys.stderr"><code><span>sys.stderr</span></code></a> and returns the argument unchanged (allowing the call to
be used within an expression):</p>
<div><pre><span></span><span>x</span> <span>=</span> <span>reveal_type</span><span>(</span><span>1</span><span>)</span>  <span># prints "Runtime type is int"</span>
<span>print</span><span>(</span><span>x</span><span>)</span>  <span># prints "1"</span>
</pre></div>
<p>Note that the runtime type may be different from (more or less specific
than) the type statically inferred by a type checker.</p>
<p>Most type checkers support <code><span>reveal_type()</span></code> anywhere, even if the
name is not imported from <code><span>typing</span></code>. Importing the name from
<code><span>typing</span></code>, however, allows your code to run without runtime errors and
communicates intent more clearly.</p>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>@</span></span><span><span>typing.</span></span><span><span>dataclass_transform</span></span><span>(</span><em><span><span>*</span></span></em>, <em><span><span>eq_default</span></span><span><span>=</span></span><span><span>True</span></span></em>, <em><span><span>order_default</span></span><span><span>=</span></span><span><span>False</span></span></em>, <em><span><span>kw_only_default</span></span><span><span>=</span></span><span><span>False</span></span></em>, <em><span><span>frozen_default</span></span><span><span>=</span></span><span><span>False</span></span></em>, <em><span><span>field_specifiers</span></span><span><span>=</span></span><span><span>()</span></span></em>, <em><span><span>**</span></span><span><span>kwargs</span></span></em><span>)</span><a href="#typing.dataclass_transform">¶</a></dt>
<dd><p>Decorator to mark an object as providing
<a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass"><code><span>dataclass</span></code></a>-like behavior.</p>
<p><code><span>dataclass_transform</span></code> may be used to
decorate a class, metaclass, or a function that is itself a decorator.
The presence of <code><span>@dataclass_transform()</span></code> tells a static type checker that the
decorated object performs runtime “magic” that
transforms a class in a similar way to
<a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass"><code><span>@dataclasses.dataclass</span></code></a>.</p>
<p>Example usage with a decorator function:</p>
<div><pre><span></span><span>@dataclass_transform</span><span>()</span>
<span>def</span> <span>create_model</span><span>[</span><span>T</span><span>](</span><span>cls</span><span>:</span> <span>type</span><span>[</span><span>T</span><span>])</span> <span>-&gt;</span> <span>type</span><span>[</span><span>T</span><span>]:</span>
    <span>...</span>
    <span>return</span> <span>cls</span>

<span>@create_model</span>
<span>class</span> <span>CustomerModel</span><span>:</span>
    <span>id</span><span>:</span> <span>int</span>
    <span>name</span><span>:</span> <span>str</span>
</pre></div>
<p>On a base class:</p>
<div><pre><span></span><span>@dataclass_transform</span><span>()</span>
<span>class</span> <span>ModelBase</span><span>:</span> <span>...</span>

<span>class</span> <span>CustomerModel</span><span>(</span><span>ModelBase</span><span>):</span>
    <span>id</span><span>:</span> <span>int</span>
    <span>name</span><span>:</span> <span>str</span>
</pre></div>
<p>On a metaclass:</p>
<div><pre><span></span><span>@dataclass_transform</span><span>()</span>
<span>class</span> <span>ModelMeta</span><span>(</span><span>type</span><span>):</span> <span>...</span>

<span>class</span> <span>ModelBase</span><span>(</span><span>metaclass</span><span>=</span><span>ModelMeta</span><span>):</span> <span>...</span>

<span>class</span> <span>CustomerModel</span><span>(</span><span>ModelBase</span><span>):</span>
    <span>id</span><span>:</span> <span>int</span>
    <span>name</span><span>:</span> <span>str</span>
</pre></div>
<p>The <code><span>CustomerModel</span></code> classes defined above will
be treated by type checkers similarly to classes created with
<a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass"><code><span>@dataclasses.dataclass</span></code></a>.
For example, type checkers will assume these classes have
<code><span>__init__</span></code> methods that accept <code><span>id</span></code> and <code><span>name</span></code>.</p>
<p>The decorated class, metaclass, or function may accept the following bool
arguments which type checkers will assume have the same effect as they
would have on the
<a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass"><code><span>@dataclasses.dataclass</span></code></a> decorator: <code><span>init</span></code>,
<code><span>eq</span></code>, <code><span>order</span></code>, <code><span>unsafe_hash</span></code>, <code><span>frozen</span></code>, <code><span>match_args</span></code>,
<code><span>kw_only</span></code>, and <code><span>slots</span></code>. It must be possible for the value of these
arguments (<code><span>True</span></code> or <code><span>False</span></code>) to be statically evaluated.</p>
<p>The arguments to the <code><span>dataclass_transform</span></code> decorator can be used to
customize the default behaviors of the decorated class, metaclass, or
function:</p>
<dl>
<dt>Parameters<span>:</span></dt>
<dd><ul>
<li><p><strong>eq_default</strong> (<a href="https://docs.python.org/3/library/functions.html#bool"><em>bool</em></a>) – Indicates whether the <code><span>eq</span></code> parameter is assumed to be
<code><span>True</span></code> or <code><span>False</span></code> if it is omitted by the caller.
Defaults to <code><span>True</span></code>.</p></li>
<li><p><strong>order_default</strong> (<a href="https://docs.python.org/3/library/functions.html#bool"><em>bool</em></a>) – Indicates whether the <code><span>order</span></code> parameter is
assumed to be <code><span>True</span></code> or <code><span>False</span></code> if it is omitted by the caller.
Defaults to <code><span>False</span></code>.</p></li>
<li><p><strong>kw_only_default</strong> (<a href="https://docs.python.org/3/library/functions.html#bool"><em>bool</em></a>) – Indicates whether the <code><span>kw_only</span></code> parameter is
assumed to be <code><span>True</span></code> or <code><span>False</span></code> if it is omitted by the caller.
Defaults to <code><span>False</span></code>.</p></li>
<li><p><strong>frozen_default</strong> (<a href="https://docs.python.org/3/library/functions.html#bool"><em>bool</em></a>) – </p><p>Indicates whether the <code><span>frozen</span></code> parameter is
assumed to be <code><span>True</span></code> or <code><span>False</span></code> if it is omitted by the caller.
Defaults to <code><span>False</span></code>.</p>
<p><span>Added in version 3.12.</span></p>
</li>
<li><p><strong>field_specifiers</strong> (<a href="https://docs.python.org/3/library/stdtypes.html#tuple"><em>tuple</em></a><em>[</em><a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable"><em>Callable</em></a><em>[</em><em>...</em><em>, </em><em>Any</em><em>]</em><em>, </em><em>...</em><em>]</em>) – Specifies a static list of supported classes
or functions that describe fields, similar to <a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.field"><code><span>dataclasses.field()</span></code></a>.
Defaults to <code><span>()</span></code>.</p></li>
<li><p><strong>**kwargs</strong> (<em>Any</em>) – Arbitrary other keyword arguments are accepted in order to allow for
possible future extensions.</p></li>
</ul>
</dd>
</dl>
<p>Type checkers recognize the following optional parameters on field
specifiers:</p>
<table>
<caption><span><strong>Recognised parameters for field specifiers</strong></span><a href="#id6">¶</a></caption>
<colgroup>
<col/>
<col/>
</colgroup>
<thead>
<tr><th><p>Parameter name</p></th>
<th><p>Description</p></th>
</tr>
</thead>
<tbody>
<tr><td><p><code><span>init</span></code></p></td>
<td><p>Indicates whether the field should be included in the
synthesized <code><span>__init__</span></code> method. If unspecified, <code><span>init</span></code> defaults to
<code><span>True</span></code>.</p></td>
</tr>
<tr><td><p><code><span>default</span></code></p></td>
<td><p>Provides the default value for the field.</p></td>
</tr>
<tr><td><p><code><span>default_factory</span></code></p></td>
<td><p>Provides a runtime callback that returns the
default value for the field. If neither <code><span>default</span></code> nor
<code><span>default_factory</span></code> are specified, the field is assumed to have no
default value and must be provided a value when the class is
instantiated.</p></td>
</tr>
<tr><td><p><code><span>factory</span></code></p></td>
<td><p>An alias for the <code><span>default_factory</span></code> parameter on field specifiers.</p></td>
</tr>
<tr><td><p><code><span>kw_only</span></code></p></td>
<td><p>Indicates whether the field should be marked as
keyword-only. If <code><span>True</span></code>, the field will be keyword-only. If
<code><span>False</span></code>, it will not be keyword-only. If unspecified, the value of
the <code><span>kw_only</span></code> parameter on the object decorated with
<code><span>dataclass_transform</span></code> will be used, or if that is unspecified, the
value of <code><span>kw_only_default</span></code> on <code><span>dataclass_transform</span></code> will be used.</p></td>
</tr>
<tr><td><p><code><span>alias</span></code></p></td>
<td><p>Provides an alternative name for the field. This alternative
name is used in the synthesized <code><span>__init__</span></code> method.</p></td>
</tr>
</tbody>
</table>
<p>At runtime, this decorator records its arguments in the
<code><span>__dataclass_transform__</span></code> attribute on the decorated object.
It has no other runtime effect.</p>
<p>See <span></span><a href="https://peps.python.org/pep-0681/"><strong>PEP 681</strong></a> for more details.</p>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>@</span></span><span><span>typing.</span></span><span><span>overload</span></span><a href="#typing.overload">¶</a></dt>
<dd><p>Decorator for creating overloaded functions and methods.</p>
<p>The <code><span>@overload</span></code> decorator allows describing functions and methods
that support multiple different combinations of argument types. A series
of <code><span>@overload</span></code>-decorated definitions must be followed by exactly one
non-<code><span>@overload</span></code>-decorated definition (for the same function/method).</p>
<p><code><span>@overload</span></code>-decorated definitions are for the benefit of the
type checker only, since they will be overwritten by the
non-<code><span>@overload</span></code>-decorated definition. The non-<code><span>@overload</span></code>-decorated
definition, meanwhile, will be used at
runtime but should be ignored by a type checker.  At runtime, calling
an <code><span>@overload</span></code>-decorated function directly will raise
<a href="https://docs.python.org/3/library/exceptions.html#NotImplementedError"><code><span>NotImplementedError</span></code></a>.</p>
<p>An example of overload that gives a more
precise type than can be expressed using a union or a type variable:</p>
<div><pre><span></span><span>@overload</span>
<span>def</span> <span>process</span><span>(</span><span>response</span><span>:</span> <span>None</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>...</span>
<span>@overload</span>
<span>def</span> <span>process</span><span>(</span><span>response</span><span>:</span> <span>int</span><span>)</span> <span>-&gt;</span> <span>tuple</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>]:</span>
    <span>...</span>
<span>@overload</span>
<span>def</span> <span>process</span><span>(</span><span>response</span><span>:</span> <span>bytes</span><span>)</span> <span>-&gt;</span> <span>str</span><span>:</span>
    <span>...</span>
<span>def</span> <span>process</span><span>(</span><span>response</span><span>):</span>
    <span>...</span>  <span># actual implementation goes here</span>
</pre></div>
<p>See <span></span><a href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> for more details and comparison with other typing semantics.</p>
<p><span>Changed in version 3.11: </span>Overloaded functions can now be introspected at runtime using
<a href="#typing.get_overloads"><code><span>get_overloads()</span></code></a>.</p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>get_overloads</span></span><span>(</span><em><span><span>func</span></span></em><span>)</span><a href="#typing.get_overloads">¶</a></dt>
<dd><p>Return a sequence of <a href="#typing.overload"><code><span>@overload</span></code></a>-decorated definitions for
<em>func</em>.</p>
<p><em>func</em> is the function object for the implementation of the
overloaded function. For example, given the definition of <code><span>process</span></code> in
the documentation for <a href="#typing.overload"><code><span>@overload</span></code></a>,
<code><span>get_overloads(process)</span></code> will return a sequence of three function objects
for the three defined overloads. If called on a function with no overloads,
<code><span>get_overloads()</span></code> returns an empty sequence.</p>
<p><code><span>get_overloads()</span></code> can be used for introspecting an overloaded function at
runtime.</p>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>clear_overloads</span></span><span>(</span><span>)</span><a href="#typing.clear_overloads">¶</a></dt>
<dd><p>Clear all registered overloads in the internal registry.</p>
<p>This can be used to reclaim the memory used by the registry.</p>
<p><span>Added in version 3.11.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>@</span></span><span><span>typing.</span></span><span><span>final</span></span><a href="#typing.final">¶</a></dt>
<dd><p>Decorator to indicate final methods and final classes.</p>
<p>Decorating a method with <code><span>@final</span></code> indicates to a type checker that the
method cannot be overridden in a subclass. Decorating a class with <code><span>@final</span></code>
indicates that it cannot be subclassed.</p>
<p>For example:</p>
<div><pre><span></span><span>class</span> <span>Base</span><span>:</span>
    <span>@final</span>
    <span>def</span> <span>done</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
        <span>...</span>
<span>class</span> <span>Sub</span><span>(</span><span>Base</span><span>):</span>
    <span>def</span> <span>done</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>  <span># Error reported by type checker</span>
        <span>...</span>

<span>@final</span>
<span>class</span> <span>Leaf</span><span>:</span>
    <span>...</span>
<span>class</span> <span>Other</span><span>(</span><span>Leaf</span><span>):</span>  <span># Error reported by type checker</span>
    <span>...</span>
</pre></div>
<p>There is no runtime checking of these properties. See <span></span><a href="https://peps.python.org/pep-0591/"><strong>PEP 591</strong></a> for
more details.</p>
<p><span>Added in version 3.8.</span></p>
<p><span>Changed in version 3.11: </span>The decorator will now attempt to set a <code><span>__final__</span></code> attribute to <code><span>True</span></code>
on the decorated object. Thus, a check like
<code><span>if</span> <span>getattr(obj,</span> <span>"__final__",</span> <span>False)</span></code> can be used at runtime
to determine whether an object <code><span>obj</span></code> has been marked as final.
If the decorated object does not support setting attributes,
the decorator returns the object unchanged without raising an exception.</p>
</dd></dl>

<dl>
<dt>
<span><span>@</span></span><span><span>typing.</span></span><span><span>no_type_check</span></span><a href="#typing.no_type_check">¶</a></dt>
<dd><p>Decorator to indicate that annotations are not type hints.</p>
<p>This works as a class or function <a href="https://docs.python.org/3/glossary.html#term-decorator"><span>decorator</span></a>.  With a class, it
applies recursively to all methods and classes defined in that class
(but not to methods defined in its superclasses or subclasses). Type
checkers will ignore all annotations in a function or class with this
decorator.</p>
<p><code><span>@no_type_check</span></code> mutates the decorated object in place.</p>
</dd></dl>

<dl>
<dt>
<span><span>@</span></span><span><span>typing.</span></span><span><span>no_type_check_decorator</span></span><a href="#typing.no_type_check_decorator">¶</a></dt>
<dd><p>Decorator to give another decorator the <a href="#typing.no_type_check"><code><span>no_type_check()</span></code></a> effect.</p>
<p>This wraps the decorator with something that wraps the decorated
function in <a href="#typing.no_type_check"><code><span>no_type_check()</span></code></a>.</p>
</dd></dl>

<dl>
<dt>
<span><span>@</span></span><span><span>typing.</span></span><span><span>override</span></span><a href="#typing.override">¶</a></dt>
<dd><p>Decorator to indicate that a method in a subclass is intended to override a
method or attribute in a superclass.</p>
<p>Type checkers should emit an error if a method decorated with <code><span>@override</span></code>
does not, in fact, override anything.
This helps prevent bugs that may occur when a base class is changed without
an equivalent change to a child class.</p>
<p>For example:</p>
<div><pre><span></span><span>class</span> <span>Base</span><span>:</span>
    <span>def</span> <span>log_status</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
        <span>...</span>

<span>class</span> <span>Sub</span><span>(</span><span>Base</span><span>):</span>
    <span>@override</span>
    <span>def</span> <span>log_status</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>  <span># Okay: overrides Base.log_status</span>
        <span>...</span>

    <span>@override</span>
    <span>def</span> <span>done</span><span>(</span><span>self</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>  <span># Error reported by type checker</span>
        <span>...</span>
</pre></div>
<p>There is no runtime checking of this property.</p>
<p>The decorator will attempt to set an <code><span>__override__</span></code> attribute to <code><span>True</span></code> on
the decorated object. Thus, a check like
<code><span>if</span> <span>getattr(obj,</span> <span>"__override__",</span> <span>False)</span></code> can be used at runtime to determine
whether an object <code><span>obj</span></code> has been marked as an override.  If the decorated object
does not support setting attributes, the decorator returns the object unchanged
without raising an exception.</p>
<p>See <span></span><a href="https://peps.python.org/pep-0698/"><strong>PEP 698</strong></a> for more details.</p>
<p><span>Added in version 3.12.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>@</span></span><span><span>typing.</span></span><span><span>type_check_only</span></span><a href="#typing.type_check_only">¶</a></dt>
<dd><p>Decorator to mark a class or function as unavailable at runtime.</p>
<p>This decorator is itself not available at runtime. It is mainly
intended to mark classes that are defined in type stub files if
an implementation returns an instance of a private class:</p>
<div><pre><span></span><span>@type_check_only</span>
<span>class</span> <span>Response</span><span>:</span>  <span># private or not available at runtime</span>
    <span>code</span><span>:</span> <span>int</span>
    <span>def</span> <span>get_header</span><span>(</span><span>self</span><span>,</span> <span>name</span><span>:</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>str</span><span>:</span> <span>...</span>

<span>def</span> <span>fetch_response</span><span>()</span> <span>-&gt;</span> <span>Response</span><span>:</span> <span>...</span>
</pre></div>
<p>Note that returning instances of private classes is not recommended.
It is usually preferable to make such classes public.</p>
</dd></dl>

</section>
<section>
<h3>Introspection helpers<a href="#introspection-helpers">¶</a></h3>
<dl>
<dt>
<span><span>typing.</span></span><span><span>get_type_hints</span></span><span>(</span><em><span><span>obj</span></span></em>, <em><span><span>globalns</span></span><span><span>=</span></span><span><span>None</span></span></em>, <em><span><span>localns</span></span><span><span>=</span></span><span><span>None</span></span></em>, <em><span><span>include_extras</span></span><span><span>=</span></span><span><span>False</span></span></em><span>)</span><a href="#typing.get_type_hints">¶</a></dt>
<dd><p>Return a dictionary containing type hints for a function, method, module
or class object.</p>
<p>This is often the same as <code><span>obj.__annotations__</span></code>, but this function makes
the following changes to the annotations dictionary:</p>
<ul>
<li><p>Forward references encoded as string literals or <a href="#typing.ForwardRef"><code><span>ForwardRef</span></code></a>
objects are handled by evaluating them in <em>globalns</em>, <em>localns</em>, and
(where applicable) <em>obj</em>’s <a href="https://docs.python.org/3/reference/compound_stmts.html#type-params"><span>type parameter</span></a> namespace.
If <em>globalns</em> or <em>localns</em> is not given, appropriate namespace
dictionaries are inferred from <em>obj</em>.</p></li>
<li><p><code><span>None</span></code> is replaced with <a href="https://docs.python.org/3/library/types.html#types.NoneType"><code><span>types.NoneType</span></code></a>.</p></li>
<li><p>If <a href="#typing.no_type_check"><code><span>@no_type_check</span></code></a> has been applied to <em>obj</em>, an
empty dictionary is returned.</p></li>
<li><p>If <em>obj</em> is a class <code><span>C</span></code>, the function returns a dictionary that merges
annotations from <code><span>C</span></code>’s base classes with those on <code><span>C</span></code> directly. This
is done by traversing <code><span>C.__mro__</span></code> and iteratively combining
<code><span>__annotations__</span></code> dictionaries. Annotations on classes appearing
earlier in the <a href="https://docs.python.org/3/glossary.html#term-method-resolution-order"><span>method resolution order</span></a> always take precedence over
annotations on classes appearing later in the method resolution order.</p></li>
<li><p>The function recursively replaces all occurrences of <code><span>Annotated[T,</span> <span>...]</span></code>
with <code><span>T</span></code>, unless <em>include_extras</em> is set to <code><span>True</span></code> (see
<a href="#typing.Annotated"><code><span>Annotated</span></code></a> for more information).</p></li>
</ul>
<p>See also <a href="https://docs.python.org/3/library/inspect.html#inspect.get_annotations"><code><span>inspect.get_annotations()</span></code></a>, a lower-level function that
returns annotations more directly.</p>
<div>
<p>Note</p>
<p>If any forward references in the annotations of <em>obj</em> are not resolvable
or are not valid Python code, this function will raise an exception
such as <a href="https://docs.python.org/3/library/exceptions.html#NameError"><code><span>NameError</span></code></a>. For example, this can happen with imported
<a href="#type-aliases"><span>type aliases</span></a> that include forward references,
or with names imported under <a href="#typing.TYPE_CHECKING"><code><span>if</span> <span>TYPE_CHECKING</span></code></a>.</p>
</div>
<p><span>Changed in version 3.9: </span>Added <code><span>include_extras</span></code> parameter as part of <span></span><a href="https://peps.python.org/pep-0593/"><strong>PEP 593</strong></a>.
See the documentation on <a href="#typing.Annotated"><code><span>Annotated</span></code></a> for more information.</p>
<p><span>Changed in version 3.11: </span>Previously, <code><span>Optional[t]</span></code> was added for function and method annotations
if a default value equal to <code><span>None</span></code> was set.
Now the annotation is returned unchanged.</p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>get_origin</span></span><span>(</span><em><span><span>tp</span></span></em><span>)</span><a href="#typing.get_origin">¶</a></dt>
<dd><p>Get the unsubscripted version of a type: for a typing object of the form
<code><span>X[Y,</span> <span>Z,</span> <span>...]</span></code> return <code><span>X</span></code>.</p>
<p>If <code><span>X</span></code> is a typing-module alias for a builtin or
<a href="https://docs.python.org/3/library/collections.html#module-collections"><code><span>collections</span></code></a> class, it will be normalized to the original class.
If <code><span>X</span></code> is an instance of <a href="#typing.ParamSpecArgs"><code><span>ParamSpecArgs</span></code></a> or <a href="#typing.ParamSpecKwargs"><code><span>ParamSpecKwargs</span></code></a>,
return the underlying <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a>.
Return <code><span>None</span></code> for unsupported objects.</p>
<p>Examples:</p>
<div><pre><span></span><span>assert</span> <span>get_origin</span><span>(</span><span>str</span><span>)</span> <span>is</span> <span>None</span>
<span>assert</span> <span>get_origin</span><span>(</span><span>Dict</span><span>[</span><span>str</span><span>,</span> <span>int</span><span>])</span> <span>is</span> <span>dict</span>
<span>assert</span> <span>get_origin</span><span>(</span><span>Union</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>])</span> <span>is</span> <span>Union</span>
<span>P</span> <span>=</span> <span>ParamSpec</span><span>(</span><span>'P'</span><span>)</span>
<span>assert</span> <span>get_origin</span><span>(</span><span>P</span><span>.</span><span>args</span><span>)</span> <span>is</span> <span>P</span>
<span>assert</span> <span>get_origin</span><span>(</span><span>P</span><span>.</span><span>kwargs</span><span>)</span> <span>is</span> <span>P</span>
</pre></div>
<p><span>Added in version 3.8.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>get_args</span></span><span>(</span><em><span><span>tp</span></span></em><span>)</span><a href="#typing.get_args">¶</a></dt>
<dd><p>Get type arguments with all substitutions performed: for a typing object
of the form <code><span>X[Y,</span> <span>Z,</span> <span>...]</span></code> return <code><span>(Y,</span> <span>Z,</span> <span>...)</span></code>.</p>
<p>If <code><span>X</span></code> is a union or <a href="#typing.Literal"><code><span>Literal</span></code></a> contained in another
generic type, the order of <code><span>(Y,</span> <span>Z,</span> <span>...)</span></code> may be different from the order
of the original arguments <code><span>[Y,</span> <span>Z,</span> <span>...]</span></code> due to type caching.
Return <code><span>()</span></code> for unsupported objects.</p>
<p>Examples:</p>
<div><pre><span></span><span>assert</span> <span>get_args</span><span>(</span><span>int</span><span>)</span> <span>==</span> <span>()</span>
<span>assert</span> <span>get_args</span><span>(</span><span>Dict</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>])</span> <span>==</span> <span>(</span><span>int</span><span>,</span> <span>str</span><span>)</span>
<span>assert</span> <span>get_args</span><span>(</span><span>Union</span><span>[</span><span>int</span><span>,</span> <span>str</span><span>])</span> <span>==</span> <span>(</span><span>int</span><span>,</span> <span>str</span><span>)</span>
</pre></div>
<p><span>Added in version 3.8.</span></p>
</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>is_typeddict</span></span><span>(</span><em><span><span>tp</span></span></em><span>)</span><a href="#typing.is_typeddict">¶</a></dt>
<dd><p>Check if a type is a <a href="#typing.TypedDict"><code><span>TypedDict</span></code></a>.</p>
<p>For example:</p>
<div><pre><span></span><span>class</span> <span>Film</span><span>(</span><span>TypedDict</span><span>):</span>
    <span>title</span><span>:</span> <span>str</span>
    <span>year</span><span>:</span> <span>int</span>

<span>assert</span> <span>is_typeddict</span><span>(</span><span>Film</span><span>)</span>
<span>assert</span> <span>not</span> <span>is_typeddict</span><span>(</span><span>list</span> <span>|</span> <span>str</span><span>)</span>

<span># TypedDict is a factory for creating typed dicts,</span>
<span># not a typed dict itself</span>
<span>assert</span> <span>not</span> <span>is_typeddict</span><span>(</span><span>TypedDict</span><span>)</span>
</pre></div>
<p><span>Added in version 3.10.</span></p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>ForwardRef</span></span><a href="#typing.ForwardRef">¶</a></dt>
<dd><p>Class used for internal typing representation of string forward references.</p>
<p>For example, <code><span>List["SomeClass"]</span></code> is implicitly transformed into
<code><span>List[ForwardRef("SomeClass")]</span></code>.  <code><span>ForwardRef</span></code> should not be instantiated by
a user, but may be used by introspection tools.</p>
<div>
<p>Note</p>
<p><span></span><a href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> generic types such as <code><span>list["SomeClass"]</span></code> will not be
implicitly transformed into <code><span>list[ForwardRef("SomeClass")]</span></code> and thus
will not automatically resolve to <code><span>list[SomeClass]</span></code>.</p>
</div>
<p><span>Added in version 3.7.4.</span></p>
</dd></dl>

</section>
<section>
<h3>Constant<a href="#constant">¶</a></h3>
<dl>
<dt>
<span><span>typing.</span></span><span><span>TYPE_CHECKING</span></span><a href="#typing.TYPE_CHECKING">¶</a></dt>
<dd><p>A special constant that is assumed to be <code><span>True</span></code> by 3rd party static
type checkers. It is <code><span>False</span></code> at runtime.</p>
<p>Usage:</p>
<div><pre><span></span><span>if</span> <span>TYPE_CHECKING</span><span>:</span>
    <span>import</span> <span>expensive_mod</span>

<span>def</span> <span>fun</span><span>(</span><span>arg</span><span>:</span> <span>'expensive_mod.SomeType'</span><span>)</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>local_var</span><span>:</span> <span>expensive_mod</span><span>.</span><span>AnotherType</span> <span>=</span> <span>other_fun</span><span>()</span>
</pre></div>
<p>The first type annotation must be enclosed in quotes, making it a
“forward reference”, to hide the <code><span>expensive_mod</span></code> reference from the
interpreter runtime.  Type annotations for local variables are not
evaluated, so the second annotation does not need to be enclosed in quotes.</p>
<div>
<p>Note</p>
<p>If <code><span>from</span> <span>__future__</span> <span>import</span> <span>annotations</span></code> is used,
annotations are not evaluated at function definition time.
Instead, they are stored as strings in <code><span>__annotations__</span></code>.
This makes it unnecessary to use quotes around the annotation
(see <span></span><a href="https://peps.python.org/pep-0563/"><strong>PEP 563</strong></a>).</p>
</div>
<p><span>Added in version 3.5.2.</span></p>
</dd></dl>

</section>
<section>
<span></span><span></span><h3>Deprecated aliases<a href="#deprecated-aliases">¶</a></h3>
<p>This module defines several deprecated aliases to pre-existing
standard library classes. These were originally included in the typing
module in order to support parameterizing these generic classes using <code><span>[]</span></code>.
However, the aliases became redundant in Python 3.9 when the
corresponding pre-existing classes were enhanced to support <code><span>[]</span></code> (see
<span></span><a href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a>).</p>
<p>The redundant types are deprecated as of Python 3.9. However, while the aliases
may be removed at some point, removal of these aliases is not currently
planned. As such, no deprecation warnings are currently issued by the
interpreter for these aliases.</p>
<p>If at some point it is decided to remove these deprecated aliases, a
deprecation warning will be issued by the interpreter for at least two releases
prior to removal. The aliases are guaranteed to remain in the typing module
without deprecation warnings until at least Python 3.14.</p>
<p>Type checkers are encouraged to flag uses of the deprecated types if the
program they are checking targets a minimum Python version of 3.9 or newer.</p>
<section>
<span></span><h4>Aliases to built-in types<a href="#aliases-to-built-in-types">¶</a></h4>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Dict</span></span><span>(</span><em><span>dict,</span> <span>MutableMapping[KT,</span> <span>VT]</span></em><span>)</span><a href="#typing.Dict">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/stdtypes.html#dict"><code><span>dict</span></code></a>.</p>
<p>Note that to annotate arguments, it is preferred
to use an abstract collection type such as <a href="#typing.Mapping"><code><span>Mapping</span></code></a>
rather than to use <a href="https://docs.python.org/3/library/stdtypes.html#dict"><code><span>dict</span></code></a> or <code><span>typing.Dict</span></code>.</p>
<p>This type can be used as follows:</p>
<div><pre><span></span><span>def</span> <span>count_words</span><span>(</span><span>text</span><span>:</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>Dict</span><span>[</span><span>str</span><span>,</span> <span>int</span><span>]:</span>
    <span>...</span>
</pre></div>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>List</span></span><span>(</span><em><span>list,</span> <span>MutableSequence[T]</span></em><span>)</span><a href="#typing.List">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/stdtypes.html#list"><code><span>list</span></code></a>.</p>
<p>Note that to annotate arguments, it is preferred
to use an abstract collection type such as <a href="#typing.Sequence"><code><span>Sequence</span></code></a> or
<a href="#typing.Iterable"><code><span>Iterable</span></code></a> rather than to use <a href="https://docs.python.org/3/library/stdtypes.html#list"><code><span>list</span></code></a> or <code><span>typing.List</span></code>.</p>
<p>This type may be used as follows:</p>
<div><pre><span></span><span>def</span> <span>vec2</span><span>[</span><span>T</span><span>:</span> <span>(</span><span>int</span><span>,</span> <span>float</span><span>)](</span><span>x</span><span>:</span> <span>T</span><span>,</span> <span>y</span><span>:</span> <span>T</span><span>)</span> <span>-&gt;</span> <span>List</span><span>[</span><span>T</span><span>]:</span>
    <span>return</span> <span>[</span><span>x</span><span>,</span> <span>y</span><span>]</span>

<span>def</span> <span>keep_positives</span><span>[</span><span>T</span><span>:</span> <span>(</span><span>int</span><span>,</span> <span>float</span><span>)](</span><span>vector</span><span>:</span> <span>Sequence</span><span>[</span><span>T</span><span>])</span> <span>-&gt;</span> <span>List</span><span>[</span><span>T</span><span>]:</span>
    <span>return</span> <span>[</span><span>item</span> <span>for</span> <span>item</span> <span>in</span> <span>vector</span> <span>if</span> <span>item</span> <span>&gt;</span> <span>0</span><span>]</span>
</pre></div>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Set</span></span><span>(</span><em><span>set,</span> <span>MutableSet[T]</span></em><span>)</span><a href="#typing.Set">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/stdtypes.html#set"><code><span>builtins.set</span></code></a>.</p>
<p>Note that to annotate arguments, it is preferred
to use an abstract collection type such as <a href="#typing.AbstractSet"><code><span>AbstractSet</span></code></a>
rather than to use <a href="https://docs.python.org/3/library/stdtypes.html#set"><code><span>set</span></code></a> or <code><span>typing.Set</span></code>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>FrozenSet</span></span><span>(</span><em><span>frozenset,</span> <span>AbstractSet[T_co]</span></em><span>)</span><a href="#typing.FrozenSet">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/stdtypes.html#frozenset"><code><span>builtins.frozenset</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Tuple</span></span><a href="#typing.Tuple">¶</a></dt>
<dd><p>Deprecated alias for <a href="https://docs.python.org/3/library/stdtypes.html#tuple"><code><span>tuple</span></code></a>.</p>
<p><a href="https://docs.python.org/3/library/stdtypes.html#tuple"><code><span>tuple</span></code></a> and <code><span>Tuple</span></code> are special-cased in the type system; see
<a href="#annotating-tuples"><span>Annotating tuples</span></a> for more details.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Type</span></span><span>(</span><em><span>Generic[CT_co]</span></em><span>)</span><a href="#typing.Type">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/functions.html#type"><code><span>type</span></code></a>.</p>
<p>See <a href="#type-of-class-objects"><span>The type of class objects</span></a> for details on using <a href="https://docs.python.org/3/library/functions.html#type"><code><span>type</span></code></a> or
<code><span>typing.Type</span></code> in type annotations.</p>
<p><span>Added in version 3.5.2.</span></p>

</dd></dl>

</section>
<section>
<span></span><h4>Aliases to types in <a href="https://docs.python.org/3/library/collections.html#module-collections"><code><span>collections</span></code></a><a href="#aliases-to-types-in-collections">¶</a></h4>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>DefaultDict</span></span><span>(</span><em><span>collections.defaultdict,</span> <span>MutableMapping[KT,</span> <span>VT]</span></em><span>)</span><a href="#typing.DefaultDict">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict"><code><span>collections.defaultdict</span></code></a>.</p>
<p><span>Added in version 3.5.2.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>OrderedDict</span></span><span>(</span><em><span>collections.OrderedDict,</span> <span>MutableMapping[KT,</span> <span>VT]</span></em><span>)</span><a href="#typing.OrderedDict">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict"><code><span>collections.OrderedDict</span></code></a>.</p>
<p><span>Added in version 3.7.2.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>ChainMap</span></span><span>(</span><em><span>collections.ChainMap,</span> <span>MutableMapping[KT,</span> <span>VT]</span></em><span>)</span><a href="#typing.ChainMap">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.html#collections.ChainMap"><code><span>collections.ChainMap</span></code></a>.</p>
<p><span>Added in version 3.6.1.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Counter</span></span><span>(</span><em><span>collections.Counter,</span> <span>Dict[T,</span> <span>int]</span></em><span>)</span><a href="#typing.Counter">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.html#collections.Counter"><code><span>collections.Counter</span></code></a>.</p>
<p><span>Added in version 3.6.1.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Deque</span></span><span>(</span><em><span>deque,</span> <span>MutableSequence[T]</span></em><span>)</span><a href="#typing.Deque">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.html#collections.deque"><code><span>collections.deque</span></code></a>.</p>
<p><span>Added in version 3.6.1.</span></p>

</dd></dl>

</section>
<section>
<span></span><h4>Aliases to other concrete types<a href="#aliases-to-other-concrete-types">¶</a></h4>
<blockquote>
<div><p><span>Deprecated since version 3.8, will be removed in version 3.13: </span>The <code><span>typing.io</span></code> namespace is deprecated and will be removed.
These types should be directly imported from <code><span>typing</span></code> instead.</p>
</div></blockquote>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Pattern</span></span><a href="#typing.Pattern">¶</a></dt>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Match</span></span><a href="#typing.Match">¶</a></dt>
<dd><p>Deprecated aliases corresponding to the return types from
<a href="https://docs.python.org/3/library/re.html#re.compile"><code><span>re.compile()</span></code></a> and <a href="https://docs.python.org/3/library/re.html#re.match"><code><span>re.match()</span></code></a>.</p>
<p>These types (and the corresponding functions) are generic over
<a href="#typing.AnyStr"><code><span>AnyStr</span></code></a>. <code><span>Pattern</span></code> can be specialised as <code><span>Pattern[str]</span></code> or
<code><span>Pattern[bytes]</span></code>; <code><span>Match</span></code> can be specialised as <code><span>Match[str]</span></code> or
<code><span>Match[bytes]</span></code>.</p>
<p><span>Deprecated since version 3.8, will be removed in version 3.13: </span>The <code><span>typing.re</span></code> namespace is deprecated and will be removed.
These types should be directly imported from <code><span>typing</span></code> instead.</p>
<p><span>Deprecated since version 3.9: </span>Classes <code><span>Pattern</span></code> and <code><span>Match</span></code> from <a href="https://docs.python.org/3/library/re.html#module-re"><code><span>re</span></code></a> now support <code><span>[]</span></code>.
See <span></span><a href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a> and <a href="https://docs.python.org/3/library/stdtypes.html#types-genericalias"><span>Generic Alias Type</span></a>.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Text</span></span><a href="#typing.Text">¶</a></dt>
<dd><p>Deprecated alias for <a href="https://docs.python.org/3/library/stdtypes.html#str"><code><span>str</span></code></a>.</p>
<p><code><span>Text</span></code> is provided to supply a forward
compatible path for Python 2 code: in Python 2, <code><span>Text</span></code> is an alias for
<code><span>unicode</span></code>.</p>
<p>Use <code><span>Text</span></code> to indicate that a value must contain a unicode string in
a manner that is compatible with both Python 2 and Python 3:</p>
<div><pre><span></span><span>def</span> <span>add_unicode_checkmark</span><span>(</span><span>text</span><span>:</span> <span>Text</span><span>)</span> <span>-&gt;</span> <span>Text</span><span>:</span>
    <span>return</span> <span>text</span> <span>+</span> <span>u</span><span>' </span><span>\u2713</span><span>'</span>
</pre></div>
<p><span>Added in version 3.5.2.</span></p>
<p><span>Deprecated since version 3.11: </span>Python 2 is no longer supported, and most type checkers also no longer
support type checking Python 2 code. Removal of the alias is not
currently planned, but users are encouraged to use
<a href="https://docs.python.org/3/library/stdtypes.html#str"><code><span>str</span></code></a> instead of <code><span>Text</span></code>.</p>
</dd></dl>

</section>
<section>
<span></span><span></span><h4>Aliases to container ABCs in <a href="https://docs.python.org/3/library/collections.abc.html#module-collections.abc"><code><span>collections.abc</span></code></a><a href="#aliases-to-container-abcs-in-collections-abc">¶</a></h4>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>AbstractSet</span></span><span>(</span><em><span>Collection[T_co]</span></em><span>)</span><a href="#typing.AbstractSet">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Set"><code><span>collections.abc.Set</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>ByteString</span></span><span>(</span><em><span>Sequence[int]</span></em><span>)</span><a href="#typing.ByteString">¶</a></dt>
<dd><p>This type represents the types <a href="https://docs.python.org/3/library/stdtypes.html#bytes"><code><span>bytes</span></code></a>, <a href="https://docs.python.org/3/library/stdtypes.html#bytearray"><code><span>bytearray</span></code></a>,
and <a href="https://docs.python.org/3/library/stdtypes.html#memoryview"><code><span>memoryview</span></code></a> of byte sequences.</p>
<p><span>Deprecated since version 3.9, will be removed in version 3.14: </span>Prefer <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Buffer"><code><span>collections.abc.Buffer</span></code></a>, or a union like <code><span>bytes</span> <span>|</span> <span>bytearray</span> <span>|</span> <span>memoryview</span></code>.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Collection</span></span><span>(</span><em><span>Sized,</span> <span>Iterable[T_co],</span> <span>Container[T_co]</span></em><span>)</span><a href="#typing.Collection">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Collection"><code><span>collections.abc.Collection</span></code></a>.</p>
<p><span>Added in version 3.6.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Container</span></span><span>(</span><em><span>Generic[T_co]</span></em><span>)</span><a href="#typing.Container">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Container"><code><span>collections.abc.Container</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>ItemsView</span></span><span>(</span><em><span>MappingView,</span> <span>AbstractSet[tuple[KT_co,</span> <span>VT_co]]</span></em><span>)</span><a href="#typing.ItemsView">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.ItemsView"><code><span>collections.abc.ItemsView</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>KeysView</span></span><span>(</span><em><span>MappingView,</span> <span>AbstractSet[KT_co]</span></em><span>)</span><a href="#typing.KeysView">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.KeysView"><code><span>collections.abc.KeysView</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Mapping</span></span><span>(</span><em><span>Collection[KT],</span> <span>Generic[KT,</span> <span>VT_co]</span></em><span>)</span><a href="#typing.Mapping">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping"><code><span>collections.abc.Mapping</span></code></a>.</p>
<p>This type can be used as follows:</p>
<div><pre><span></span><span>def</span> <span>get_position_in_index</span><span>(</span><span>word_list</span><span>:</span> <span>Mapping</span><span>[</span><span>str</span><span>,</span> <span>int</span><span>],</span> <span>word</span><span>:</span> <span>str</span><span>)</span> <span>-&gt;</span> <span>int</span><span>:</span>
    <span>return</span> <span>word_list</span><span>[</span><span>word</span><span>]</span>
</pre></div>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>MappingView</span></span><span>(</span><em><span><span>Sized</span></span></em><span>)</span><a href="#typing.MappingView">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.MappingView"><code><span>collections.abc.MappingView</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>MutableMapping</span></span><span>(</span><em><span>Mapping[KT,</span> <span>VT]</span></em><span>)</span><a href="#typing.MutableMapping">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping"><code><span>collections.abc.MutableMapping</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>MutableSequence</span></span><span>(</span><em><span>Sequence[T]</span></em><span>)</span><a href="#typing.MutableSequence">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableSequence"><code><span>collections.abc.MutableSequence</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>MutableSet</span></span><span>(</span><em><span>AbstractSet[T]</span></em><span>)</span><a href="#typing.MutableSet">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableSet"><code><span>collections.abc.MutableSet</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Sequence</span></span><span>(</span><em><span>Reversible[T_co],</span> <span>Collection[T_co]</span></em><span>)</span><a href="#typing.Sequence">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence"><code><span>collections.abc.Sequence</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>ValuesView</span></span><span>(</span><em><span>MappingView,</span> <span>Collection[_VT_co]</span></em><span>)</span><a href="#typing.ValuesView">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.ValuesView"><code><span>collections.abc.ValuesView</span></code></a>.</p>

</dd></dl>

</section>
<section>
<span></span><h4>Aliases to asynchronous ABCs in <a href="https://docs.python.org/3/library/collections.abc.html#module-collections.abc"><code><span>collections.abc</span></code></a><a href="#aliases-to-asynchronous-abcs-in-collections-abc">¶</a></h4>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Coroutine</span></span><span>(</span><em><span>Awaitable[ReturnType],</span> <span>Generic[YieldType,</span> <span>SendType,</span> <span>ReturnType]</span></em><span>)</span><a href="#typing.Coroutine">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Coroutine"><code><span>collections.abc.Coroutine</span></code></a>.</p>
<p>The variance and order of type variables
correspond to those of <a href="#typing.Generator"><code><span>Generator</span></code></a>, for example:</p>
<div><pre><span></span><span>from</span> <span>collections.abc</span> <span>import</span> <span>Coroutine</span>
<span>c</span><span>:</span> <span>Coroutine</span><span>[</span><span>list</span><span>[</span><span>str</span><span>],</span> <span>str</span><span>,</span> <span>int</span><span>]</span>  <span># Some coroutine defined elsewhere</span>
<span>x</span> <span>=</span> <span>c</span><span>.</span><span>send</span><span>(</span><span>'hi'</span><span>)</span>                   <span># Inferred type of 'x' is list[str]</span>
<span>async</span> <span>def</span> <span>bar</span><span>()</span> <span>-&gt;</span> <span>None</span><span>:</span>
    <span>y</span> <span>=</span> <span>await</span> <span>c</span>                    <span># Inferred type of 'y' is int</span>
</pre></div>
<p><span>Added in version 3.5.3.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>AsyncGenerator</span></span><span>(</span><em><span>AsyncIterator[YieldType],</span> <span>Generic[YieldType,</span> <span>SendType]</span></em><span>)</span><a href="#typing.AsyncGenerator">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.AsyncGenerator"><code><span>collections.abc.AsyncGenerator</span></code></a>.</p>
<p>An async generator can be annotated by the generic type
<code><span>AsyncGenerator[YieldType,</span> <span>SendType]</span></code>. For example:</p>
<div><pre><span></span><span>async</span> <span>def</span> <span>echo_round</span><span>()</span> <span>-&gt;</span> <span>AsyncGenerator</span><span>[</span><span>int</span><span>,</span> <span>float</span><span>]:</span>
    <span>sent</span> <span>=</span> <span>yield</span> <span>0</span>
    <span>while</span> <span>sent</span> <span>&gt;=</span> <span>0.0</span><span>:</span>
        <span>rounded</span> <span>=</span> <span>await</span> <span>round</span><span>(</span><span>sent</span><span>)</span>
        <span>sent</span> <span>=</span> <span>yield</span> <span>rounded</span>
</pre></div>
<p>Unlike normal generators, async generators cannot return a value, so there
is no <code><span>ReturnType</span></code> type parameter. As with <a href="#typing.Generator"><code><span>Generator</span></code></a>, the
<code><span>SendType</span></code> behaves contravariantly.</p>
<p>If your generator will only yield values, set the <code><span>SendType</span></code> to
<code><span>None</span></code>:</p>
<div><pre><span></span><span>async</span> <span>def</span> <span>infinite_stream</span><span>(</span><span>start</span><span>:</span> <span>int</span><span>)</span> <span>-&gt;</span> <span>AsyncGenerator</span><span>[</span><span>int</span><span>,</span> <span>None</span><span>]:</span>
    <span>while</span> <span>True</span><span>:</span>
        <span>yield</span> <span>start</span>
        <span>start</span> <span>=</span> <span>await</span> <span>increment</span><span>(</span><span>start</span><span>)</span>
</pre></div>
<p>Alternatively, annotate your generator as having a return type of
either <code><span>AsyncIterable[YieldType]</span></code> or <code><span>AsyncIterator[YieldType]</span></code>:</p>
<div><pre><span></span><span>async</span> <span>def</span> <span>infinite_stream</span><span>(</span><span>start</span><span>:</span> <span>int</span><span>)</span> <span>-&gt;</span> <span>AsyncIterator</span><span>[</span><span>int</span><span>]:</span>
    <span>while</span> <span>True</span><span>:</span>
        <span>yield</span> <span>start</span>
        <span>start</span> <span>=</span> <span>await</span> <span>increment</span><span>(</span><span>start</span><span>)</span>
</pre></div>
<p><span>Added in version 3.6.1.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>AsyncIterable</span></span><span>(</span><em><span>Generic[T_co]</span></em><span>)</span><a href="#typing.AsyncIterable">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.AsyncIterable"><code><span>collections.abc.AsyncIterable</span></code></a>.</p>
<p><span>Added in version 3.5.2.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>AsyncIterator</span></span><span>(</span><em><span>AsyncIterable[T_co]</span></em><span>)</span><a href="#typing.AsyncIterator">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.AsyncIterator"><code><span>collections.abc.AsyncIterator</span></code></a>.</p>
<p><span>Added in version 3.5.2.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Awaitable</span></span><span>(</span><em><span>Generic[T_co]</span></em><span>)</span><a href="#typing.Awaitable">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Awaitable"><code><span>collections.abc.Awaitable</span></code></a>.</p>
<p><span>Added in version 3.5.2.</span></p>

</dd></dl>

</section>
<section>
<span></span><h4>Aliases to other ABCs in <a href="https://docs.python.org/3/library/collections.abc.html#module-collections.abc"><code><span>collections.abc</span></code></a><a href="#aliases-to-other-abcs-in-collections-abc">¶</a></h4>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Iterable</span></span><span>(</span><em><span>Generic[T_co]</span></em><span>)</span><a href="#typing.Iterable">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable"><code><span>collections.abc.Iterable</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Iterator</span></span><span>(</span><em><span>Iterable[T_co]</span></em><span>)</span><a href="#typing.Iterator">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator"><code><span>collections.abc.Iterator</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<span><span>typing.</span></span><span><span>Callable</span></span><a href="#typing.Callable">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable"><code><span>collections.abc.Callable</span></code></a>.</p>
<p>See <a href="#annotating-callables"><span>Annotating callable objects</span></a> for details on how to use
<a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable"><code><span>collections.abc.Callable</span></code></a> and <code><span>typing.Callable</span></code> in type annotations.</p>

<p><span>Changed in version 3.10: </span><code><span>Callable</span></code> now supports <a href="#typing.ParamSpec"><code><span>ParamSpec</span></code></a> and <a href="#typing.Concatenate"><code><span>Concatenate</span></code></a>.
See <span></span><a href="https://peps.python.org/pep-0612/"><strong>PEP 612</strong></a> for more details.</p>
</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Generator</span></span><span>(</span><em><span>Iterator[YieldType],</span> <span>Generic[YieldType,</span> <span>SendType,</span> <span>ReturnType]</span></em><span>)</span><a href="#typing.Generator">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator"><code><span>collections.abc.Generator</span></code></a>.</p>
<p>A generator can be annotated by the generic type
<code><span>Generator[YieldType,</span> <span>SendType,</span> <span>ReturnType]</span></code>. For example:</p>
<div><pre><span></span><span>def</span> <span>echo_round</span><span>()</span> <span>-&gt;</span> <span>Generator</span><span>[</span><span>int</span><span>,</span> <span>float</span><span>,</span> <span>str</span><span>]:</span>
    <span>sent</span> <span>=</span> <span>yield</span> <span>0</span>
    <span>while</span> <span>sent</span> <span>&gt;=</span> <span>0</span><span>:</span>
        <span>sent</span> <span>=</span> <span>yield</span> <span>round</span><span>(</span><span>sent</span><span>)</span>
    <span>return</span> <span>'Done'</span>
</pre></div>
<p>Note that unlike many other generics in the typing module, the <code><span>SendType</span></code>
of <a href="#typing.Generator"><code><span>Generator</span></code></a> behaves contravariantly, not covariantly or
invariantly.</p>
<p>If your generator will only yield values, set the <code><span>SendType</span></code> and
<code><span>ReturnType</span></code> to <code><span>None</span></code>:</p>
<div><pre><span></span><span>def</span> <span>infinite_stream</span><span>(</span><span>start</span><span>:</span> <span>int</span><span>)</span> <span>-&gt;</span> <span>Generator</span><span>[</span><span>int</span><span>,</span> <span>None</span><span>,</span> <span>None</span><span>]:</span>
    <span>while</span> <span>True</span><span>:</span>
        <span>yield</span> <span>start</span>
        <span>start</span> <span>+=</span> <span>1</span>
</pre></div>
<p>Alternatively, annotate your generator as having a return type of
either <code><span>Iterable[YieldType]</span></code> or <code><span>Iterator[YieldType]</span></code>:</p>
<div><pre><span></span><span>def</span> <span>infinite_stream</span><span>(</span><span>start</span><span>:</span> <span>int</span><span>)</span> <span>-&gt;</span> <span>Iterator</span><span>[</span><span>int</span><span>]:</span>
    <span>while</span> <span>True</span><span>:</span>
        <span>yield</span> <span>start</span>
        <span>start</span> <span>+=</span> <span>1</span>
</pre></div>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Hashable</span></span><a href="#typing.Hashable">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Hashable"><code><span>collections.abc.Hashable</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Reversible</span></span><span>(</span><em><span>Iterable[T_co]</span></em><span>)</span><a href="#typing.Reversible">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Reversible"><code><span>collections.abc.Reversible</span></code></a>.</p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>Sized</span></span><a href="#typing.Sized">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Sized"><code><span>collections.abc.Sized</span></code></a>.</p>

</dd></dl>

</section>
<section>
<span></span><h4>Aliases to <a href="https://docs.python.org/3/library/contextlib.html#module-contextlib"><code><span>contextlib</span></code></a> ABCs<a href="#aliases-to-contextlib-abcs">¶</a></h4>
<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>ContextManager</span></span><span>(</span><em><span>Generic[T_co]</span></em><span>)</span><a href="#typing.ContextManager">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/contextlib.html#contextlib.AbstractContextManager"><code><span>contextlib.AbstractContextManager</span></code></a>.</p>
<p><span>Added in version 3.5.4.</span></p>

</dd></dl>

<dl>
<dt>
<em><span>class</span><span> </span></em><span><span>typing.</span></span><span><span>AsyncContextManager</span></span><span>(</span><em><span>Generic[T_co]</span></em><span>)</span><a href="#typing.AsyncContextManager">¶</a></dt>
<dd><p>Deprecated alias to <a href="https://docs.python.org/3/library/contextlib.html#contextlib.AbstractAsyncContextManager"><code><span>contextlib.AbstractAsyncContextManager</span></code></a>.</p>
<p><span>Added in version 3.6.2.</span></p>

</dd></dl>

</section>
</section>
</section>
<section>
<h2>Deprecation Timeline of Major Features<a href="#deprecation-timeline-of-major-features">¶</a></h2>
<p>Certain features in <code><span>typing</span></code> are deprecated and may be removed in a future
version of Python. The following table summarizes major deprecations for your
convenience. This is subject to change, and not all deprecations are listed.</p>
<table>
<thead>
<tr><th><p>Feature</p></th>
<th><p>Deprecated in</p></th>
<th><p>Projected removal</p></th>
<th><p>PEP/issue</p></th>
</tr>
</thead>
<tbody>
<tr><td><p><code><span>typing.io</span></code> and <code><span>typing.re</span></code> submodules</p></td>
<td><p>3.8</p></td>
<td><p>3.13</p></td>
<td><p><a href="https://bugs.python.org/issue?@action=redirect&amp;bpo=38291">bpo-38291</a></p></td>
</tr>
<tr><td><p><code><span>typing</span></code> versions of standard collections</p></td>
<td><p>3.9</p></td>
<td><p>Undecided (see <a href="#deprecated-aliases"><span>Deprecated aliases</span></a> for more information)</p></td>
<td><p><span></span><a href="https://peps.python.org/pep-0585/"><strong>PEP 585</strong></a></p></td>
</tr>
<tr><td><p><a href="#typing.ByteString"><code><span>typing.ByteString</span></code></a></p></td>
<td><p>3.9</p></td>
<td><p>3.14</p></td>
<td><p><a href="https://github.com/python/cpython/issues/91896">gh-91896</a></p></td>
</tr>
<tr><td><p><a href="#typing.Text"><code><span>typing.Text</span></code></a></p></td>
<td><p>3.11</p></td>
<td><p>Undecided</p></td>
<td><p><a href="https://github.com/python/cpython/issues/92332">gh-92332</a></p></td>
</tr>
<tr><td><p><a href="#typing.Hashable"><code><span>typing.Hashable</span></code></a> and <a href="#typing.Sized"><code><span>typing.Sized</span></code></a></p></td>
<td><p>3.12</p></td>
<td><p>Undecided</p></td>
<td><p><a href="https://github.com/python/cpython/issues/94309">gh-94309</a></p></td>
</tr>
<tr><td><p><a href="#typing.TypeAlias"><code><span>typing.TypeAlias</span></code></a></p></td>
<td><p>3.12</p></td>
<td><p>Undecided</p></td>
<td><p><span></span><a href="https://peps.python.org/pep-0695/"><strong>PEP 695</strong></a></p></td>
</tr>
</tbody>
</table>
</section>
</section></div>||||I||||    Theme Auto Light Dark

      Table of Contents

        * typing — Support for type hints
            + Specification for the Python Type System
            + Type aliases
            + NewType
            + Annotating callable objects
            + Generics
            + Annotating tuples
            + The type of class objects
            + User-defined generic types
            + The Any type
            + Nominal vs structural subtyping
            + Module contents
                o Special typing primitives
                    - Special types
                    - Special forms
                    - Building generic types and type aliases
                    - Other special directives
                o Protocols
                o ABCs for working with IO
                o Functions and decorators
                o Introspection helpers
                o Constant
                o Deprecated aliases
                    - Aliases to built-in types
                    - Aliases to types in collections
                    - Aliases to other concrete types
                    - Aliases to container ABCs in collections.abc
                    - Aliases to asynchronous ABCs in collections.abc
                    - Aliases to other ABCs in collections.abc
                    - Aliases to contextlib ABCs
            + Deprecation Timeline of Major Features

      Previous topic

      Development Tools

      Next topic

      pydoc — Documentation generator and online help system

      This Page

        * Report a Bug
        * Show Source

  Navigation

    * index
    * modules |
    * next |
    * previous |
    * 
    * Python »
    * 
    * 
    * 3.12.5 Documentation »
    * The Python Standard Library »
    * Development Tools »
    * typing — Support for type hints
    * |
    * Theme Auto Light Dark |

        typing — Support for type hints¶

          Added in version 3.5.

        Source code: Lib/typing.py

          Note

          The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers , IDEs, linters, etc.

        This module provides runtime support for type hints.

        Consider the function below:

            def surface_area_of_cube(edge_length: float) -> str:
                return f"The surface area of the cube is {6 * edge_length ** 2}."
            

        The function surface_area_of_cube takes an argument expected to be an instance of float , as indicated by the type hint edge_length: float . The function is expected to return an instance of str , as indicated by the -> str hint.

        While type hints can be simple classes like float or str , they can also be more complex. The typing module provides a vocabulary of more advanced type hints.

        New features are frequently added to the typing module. The typing_extensions package provides backports of these new features to older versions of Python.

          See also

          “Typing cheat sheet”

          A quick overview of type hints (hosted at the mypy docs)

          “Type System Reference” section of the mypy docs

          The Python typing system is standardised via PEPs, so this reference should broadly apply to most Python type checkers. (Some parts may still be specific to mypy.)

          “Static Typing with Python”

          Type-checker-agnostic documentation written by the community detailing type system features, useful typing related tools and typing best practices.

        Specification for the Python Type System¶

        The canonical, up-to-date specification of the Python type system can be found at “Specification for the Python type system”.

        Type aliases¶

        A type alias is defined using the type statement, which creates an instance of TypeAliasType . In this example, Vector and list[float] will be treated equivalently by static type checkers:

            type Vector = list[float]
            
            def scale(scalar: float, vector: Vector) -> Vector:
                return [scalar * num for num in vector]
            
            # passes type checking; a list of floats qualifies as a Vector.
            new_vector = scale(2.0, [1.0, -4.2, 5.4])
            

        Type aliases are useful for simplifying complex type signatures. For example:

            from collections.abc import Sequence
            
            type ConnectionOptions = dict[str, str]
            type Address = tuple[str, int]
            type Server = tuple[Address, ConnectionOptions]
            
            def broadcast_message(message: str, servers: Sequence[Server]) -> None:
                ...
            
            # The static type checker will treat the previous type signature as
            # being exactly equivalent to this one.
            def broadcast_message(
                message: str,
                servers: Sequence[tuple[tuple[str, int], dict[str, str]]]
            ) -> None:
                ...
            

        The type statement is new in Python 3.12. For backwards compatibility, type aliases can also be created through simple assignment:

            Vector = list[float]
            

        Or marked with TypeAlias to make it explicit that this is a type alias, not a normal variable assignment:

            from typing import TypeAlias
            
            Vector: TypeAlias = list[float]
            

        NewType¶

        Use the NewType helper to create distinct types:

            from typing import NewType
            
            UserId = NewType('UserId', int)
            some_id = UserId(524313)
            

        The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors:

            def get_user_name(user_id: UserId) -> str:
                ...
            
            # passes type checking
            user_a = get_user_name(UserId(42351))
            
            # fails type checking; an int is not a UserId
            user_b = get_user_name(-1)
            

        You may still perform all int operations on a variable of type UserId , but the result will always be of type int . This lets you pass in a UserId wherever an int might be expected, but will prevent you from accidentally creating a UserId in an invalid way:

            # 'output' is of type 'int', not 'UserId'
            output = UserId(23413) + UserId(54341)
            

        Note that these checks are enforced only by the static type checker. At runtime, the statement Derived = NewType('Derived', Base) will make Derived a callable that immediately returns whatever parameter you pass it. That means the expression Derived(some_value) does not create a new class or introduce much overhead beyond that of a regular function call.

        More precisely, the expression some_value is Derived(some_value) is always true at runtime.

        It is invalid to create a subtype of Derived :

            from typing import NewType
            
            UserId = NewType('UserId', int)
            
            # Fails at runtime and does not pass type checking
            class AdminUserId(UserId): pass
            

        However, it is possible to create a NewType based on a ‘derived’ NewType :

            from typing import NewType
            
            UserId = NewType('UserId', int)
            
            ProUserId = NewType('ProUserId', UserId)
            

        and typechecking for ProUserId will work as expected.

        See PEP 484 for more details.

          Note

          Recall that the use of a type alias declares two types to be equivalent to one another. Doing type Alias = Original will make the static type checker treat Alias as being exactly equivalent to Original in all cases. This is useful when you want to simplify complex type signatures.

          In contrast, NewType declares one type to be a subtype of another. Doing Derived = NewType('Derived', Original) will make the static type checker treat Derived as a subclass of Original , which means a value of type Original cannot be used in places where a value of type Derived is expected. This is useful when you want to prevent logic errors with minimal runtime cost.

          Added in version 3.5.2.

          Changed in version 3.10: NewType is now a class rather than a function. As a result, there is some additional runtime cost when calling NewType over a regular function.

          Changed in version 3.11: The performance of calling NewType has been restored to its level in Python 3.9.

        Annotating callable objects¶

        Functions – or other callable objects – can be annotated using collections.abc.Callable or typing.Callable . Callable[[int], str] signifies a function that takes a single parameter of type int and returns a str .

        For example:

            from collections.abc import Callable, Awaitable
            
            def feeder(get_next_item: Callable[[], str]) -> None:
                ...  # Body
            
            def async_query(on_success: Callable[[int], None],
                            on_error: Callable[[int, Exception], None]) -> None:
                ...  # Body
            
            async def on_update(value: str) -> None:
                ...  # Body
            
            callback: Callable[[str], Awaitable[None]] = on_update
            

        The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types, a ParamSpec , Concatenate , or an ellipsis. The return type must be a single type.

        If a literal ellipsis ... is given as the argument list, it indicates that a callable with any arbitrary parameter list would be acceptable:

            def concat(x: str, y: str) -> str:
                return x + y
            
            x: Callable[..., str]
            x = str     # OK
            x = concat  # Also OK
            

        Callable cannot express complex signatures such as functions that take a variadic number of arguments, overloaded functions , or functions that have keyword-only parameters. However, these signatures can be expressed by defining a Protocol class with a __call__() method:

            from collections.abc import Iterable
            from typing import Protocol
            
            class Combiner(Protocol):
                def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...
            
            def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
                for item in data:
                    ...
            
            def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
                ...
            def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:
                ...
            
            batch_proc([], good_cb)  # OK
            batch_proc([], bad_cb)   # Error! Argument 2 has incompatible type because of
                                     # different name and kind in the callback
            

        Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec . Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType] respectively.

          Changed in version 3.10: Callable now supports ParamSpec and Concatenate . See PEP 612 for more details.

          See also

          The documentation for ParamSpec and Concatenate provides examples of usage in Callable .

        Generics¶

        Since type information about objects kept in containers cannot be statically inferred in a generic way, many container classes in the standard library support subscription to denote the expected types of container elements.

            from collections.abc import Mapping, Sequence
            
            class Employee: ...
            
            # Sequence[Employee] indicates that all elements in the sequence
            # must be instances of "Employee".
            # Mapping[str, str] indicates that all keys and all values in the mapping
            # must be strings.
            def notify_by_email(employees: Sequence[Employee],
                                overrides: Mapping[str, str]) -> None: ...
            

        Generic functions and classes can be parameterized by using type parameter syntax :

            from collections.abc import Sequence
            
            def first[T](l: Sequence[T]) -> T:  # Function is generic over the TypeVar "T"
                return l[0]
            

        Or by using the TypeVar factory directly:

            from collections.abc import Sequence
            from typing import TypeVar
            
            U = TypeVar('U')                  # Declare type variable "U"
            
            def second(l: Sequence[U]) -> U:  # Function is generic over the TypeVar "U"
                return l[1]
            

          Changed in version 3.12: Syntactic support for generics is new in Python 3.12.

        Annotating tuples¶

        For most containers in Python, the typing system assumes that all elements in the container will be of the same type. For example:

            from collections.abc import Mapping
            
            # Type checker will infer that all elements in ``x`` are meant to be ints
            x: list[int] = []
            
            # Type checker error: ``list`` only accepts a single type argument:
            y: list[int, str] = [1, 'foo']
            
            # Type checker will infer that all keys in ``z`` are meant to be strings,
            # and that all values in ``z`` are meant to be either strings or ints
            z: Mapping[str, str | int] = {}
            

        list only accepts one type argument, so a type checker would emit an error on the y assignment above. Similarly, Mapping only accepts two type arguments: the first indicates the type of the keys, and the second indicates the type of the values.

        Unlike most other Python containers, however, it is common in idiomatic Python code for tuples to have elements which are not all of the same type. For this reason, tuples are special-cased in Python’s typing system. tuple accepts any number of type arguments:

            # OK: ``x`` is assigned to a tuple of length 1 where the sole element is an int
            x: tuple[int] = (5,)
            
            # OK: ``y`` is assigned to a tuple of length 2;
            # element 1 is an int, element 2 is a str
            y: tuple[int, str] = (5, "foo")
            
            # Error: the type annotation indicates a tuple of length 1,
            # but ``z`` has been assigned to a tuple of length 3
            z: tuple[int] = (1, 2, 3)
            

        To denote a tuple which could be of any length, and in which all elements are of the same type T , use tuple[T, ...] . To denote an empty tuple, use tuple[()] . Using plain tuple as an annotation is equivalent to using tuple[Any, ...] :

            x: tuple[int, ...] = (1, 2)
            # These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any length
            x = (1, 2, 3)
            x = ()
            # This reassignment is an error: all elements in ``x`` must be ints
            x = ("foo", "bar")
            
            # ``y`` can only ever be assigned to an empty tuple
            y: tuple[()] = ()
            
            z: tuple = ("foo", "bar")
            # These reassignments are OK: plain ``tuple`` is equivalent to ``tuple[Any, ...]``
            z = (1, 2, 3)
            z = ()
            

        The type of class objects¶

        A variable annotated with C may accept a value of type C . In contrast, a variable annotated with type[C] (or typing.Type[C] ) may accept values that are classes themselves – specifically, it will accept the class object of C . For example:

            a = 3         # Has type ``int``
            b = int       # Has type ``type[int]``
            c = type(a)   # Also has type ``type[int]``
            

        Note that type[C] is covariant:

            class User: ...
            class ProUser(User): ...
            class TeamUser(User): ...
            
            def make_new_user(user_class: type[User]) -> User:
                # ...
                return user_class()
            
            make_new_user(User)      # OK
            make_new_user(ProUser)   # Also OK: ``type[ProUser]`` is a subtype of ``type[User]``
            make_new_user(TeamUser)  # Still fine
            make_new_user(User())    # Error: expected ``type[User]`` but got ``User``
            make_new_user(int)       # Error: ``type[int]`` is not a subtype of ``type[User]``
            

        The only legal parameters for type are classes, Any , type variables , and unions of any of these types. For example:

            def new_non_team_user(user_class: type[BasicUser | ProUser]): ...
            
            new_non_team_user(BasicUser)  # OK
            new_non_team_user(ProUser)    # OK
            new_non_team_user(TeamUser)   # Error: ``type[TeamUser]`` is not a subtype
                                          # of ``type[BasicUser | ProUser]``
            new_non_team_user(User)       # Also an error
            

        type[Any] is equivalent to type , which is the root of Python’s metaclass hierarchy .

        User-defined generic types¶

        A user-defined class can be defined as a generic class.

            from logging import Logger
            
            class LoggedVar[T]:
                def __init__(self, value: T, name: str, logger: Logger) -> None:
                    self.name = name
                    self.logger = logger
                    self.value = value
            
                def set(self, new: T) -> None:
                    self.log('Set ' + repr(self.value))
                    self.value = new
            
                def get(self) -> T:
                    self.log('Get ' + repr(self.value))
                    return self.value
            
                def log(self, message: str) -> None:
                    self.logger.info('%s: %s', self.name, message)
            

        This syntax indicates that the class LoggedVar is parameterised around a single type variable T . This also makes T valid as a type within the class body.

        Generic classes implicitly inherit from Generic . For compatibility with Python 3.11 and lower, it is also possible to inherit explicitly from Generic to indicate a generic class:

            from typing import TypeVar, Generic
            
            T = TypeVar('T')
            
            class LoggedVar(Generic[T]):
                ...
            

        Generic classes have __class_getitem__() methods, meaning they can be parameterised at runtime (e.g. LoggedVar[int] below):

            from collections.abc import Iterable
            
            def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
                for var in vars:
                    var.set(0)
            

        A generic type can have any number of type variables. All varieties of TypeVar are permissible as parameters for a generic type:

            from typing import TypeVar, Generic, Sequence
            
            class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:
                ...
            
            OldT = TypeVar('OldT', contravariant=True)
            OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True)
            OldS = TypeVar('OldS', int, str)
            
            class OldWeirdTrio(Generic[OldT, OldB, OldS]):
                ...
            

        Each type variable argument to Generic must be distinct. This is thus invalid:

            from typing import TypeVar, Generic
            ...
            
            class Pair[M, M]:  # SyntaxError
                ...
            
            T = TypeVar('T')
            
            class Pair(Generic[T, T]):   # INVALID
                ...
            

        Generic classes can also inherit from other classes:

            from collections.abc import Sized
            
            class LinkedList[T](Sized):
                ...
            

        When inheriting from generic classes, some type parameters could be fixed:

            from collections.abc import Mapping
            
            class MyDict[T](Mapping[str, T]):
                ...
            

        In this case MyDict has a single parameter, T .

        Using a generic class without specifying type parameters assumes Any for each position. In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any] :

            from collections.abc import Iterable
            
            class MyIterable(Iterable): # Same as Iterable[Any]
                ...
            

        User-defined generic type aliases are also supported. Examples:

            from collections.abc import Iterable
            
            type Response[S] = Iterable[S] | int
            
            # Return type here is same as Iterable[str] | int
            def response(query: str) -> Response[str]:
                ...
            
            type Vec[T] = Iterable[tuple[T, T]]
            
            def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
                return sum(x*y for x, y in v)
            

        For backward compatibility, generic type aliases can also be created through a simple assignment:

            from collections.abc import Iterable
            from typing import TypeVar
            
            S = TypeVar("S")
            Response = Iterable[S] | int
            

          Changed in version 3.7: Generic no longer has a custom metaclass.

          Changed in version 3.12: Syntactic support for generics and type aliases is new in version 3.12. Previously, generic classes had to explicitly inherit from Generic or contain a type variable in one of their bases.

        User-defined generics for parameter expressions are also supported via parameter specification variables in the form [**P] . The behavior is consistent with type variables’ described above as parameter specification variables are treated by the typing module as a specialized type variable. The one exception to this is that a list of types can be used to substitute a ParamSpec :

            >>> class Z[T, **P]: ...  # T is a TypeVar; P is a ParamSpec
            ...
            >>> Z[int, [dict, float]]
            __main__.Z[int, [dict, float]]
            

        Classes generic over a ParamSpec can also be created using explicit inheritance from Generic . In this case, ** is not used:

            from typing import ParamSpec, Generic
            
            P = ParamSpec('P')
            
            class Z(Generic[P]):
                ...
            

        Another difference between TypeVar and ParamSpec is that a generic with only one parameter specification variable will accept parameter lists in the forms X[[Type1, Type2, ...]] and also X[Type1, Type2, ...] for aesthetic reasons. Internally, the latter is converted to the former, so the following are equivalent:

            >>> class X[**P]: ...
            ...
            >>> X[int, str]
            __main__.X[[int, str]]
            >>> X[[int, str]]
            __main__.X[[int, str]]
            

        Note that generics with ParamSpec may not have correct __parameters__ after substitution in some cases because they are intended primarily for static type checking.

          Changed in version 3.10: Generic can now be parameterized over parameter expressions. See ParamSpec and PEP 612 for more details.

        A user-defined generic class can have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the typing module are hashable and comparable for equality.

        The Any type¶

        A special kind of type is Any . A static type checker will treat every type as being compatible with Any and Any as being compatible with every type.

        This means that it is possible to perform any operation or method call on a value of type Any and assign it to any variable:

            from typing import Any
            
            a: Any = None
            a = []          # OK
            a = 2           # OK
            
            s: str = ''
            s = a           # OK
            
            def foo(item: Any) -> int:
                # Passes type checking; 'item' could be any type,
                # and that type might have a 'bar' method
                item.bar()
                ...
            

        Notice that no type checking is performed when assigning a value of type Any to a more precise type. For example, the static type checker did not report an error when assigning a to s even though s was declared to be of type str and receives an int value at runtime!

        Furthermore, all functions without a return type or parameter types will implicitly default to using Any :

            def legacy_parser(text):
                ...
                return data
            
            # A static type checker will treat the above
            # as having the same signature as:
            def legacy_parser(text: Any) -> Any:
                ...
                return data
            

        This behavior allows Any to be used as an escape hatch when you need to mix dynamically and statically typed code.

        Contrast the behavior of Any with the behavior of object . Similar to Any , every type is a subtype of object . However, unlike Any , the reverse is not true: object is not a subtype of every other type.

        That means when the type of a value is object , a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example:

            def hash_a(item: object) -> int:
                # Fails type checking; an object does not have a 'magic' method.
                item.magic()
                ...
            
            def hash_b(item: Any) -> int:
                # Passes type checking
                item.magic()
                ...
            
            # Passes type checking, since ints and strs are subclasses of object
            hash_a(42)
            hash_a("foo")
            
            # Passes type checking, since Any is compatible with all types
            hash_b(42)
            hash_b("foo")
            

        Use object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed.

        Nominal vs structural subtyping¶

        Initially PEP 484 defined the Python static type system as using nominal subtyping. This means that a class A is allowed where a class B is expected if and only if A is a subclass of B .

        This requirement previously also applied to abstract base classes, such as Iterable . The problem with this approach is that a class had to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. For example, this conforms to PEP 484:

            from collections.abc import Sized, Iterable, Iterator
            
            class Bucket(Sized, Iterable[int]):
                ...
                def __len__(self) -> int: ...
                def __iter__(self) -> Iterator[int]: ...
            

        PEP 544 allows to solve this problem by allowing users to write the above code without explicit base classes in the class definition, allowing Bucket to be implicitly considered a subtype of both Sized and Iterable[int] by static type checkers. This is known as structural subtyping (or static duck-typing):

            from collections.abc import Iterator, Iterable
            
            class Bucket:  # Note: no base classes
                ...
                def __len__(self) -> int: ...
                def __iter__(self) -> Iterator[int]: ...
            
            def collect(items: Iterable[int]) -> int: ...
            result = collect(Bucket())  # Passes type check
            

        Moreover, by subclassing a special class Protocol , a user can define new custom protocols to fully enjoy structural subtyping (see examples below).

        Module contents¶

        The typing module defines the following classes, functions and decorators.

        Special typing primitives¶

        Special types¶

        These can be used as types in annotations. They do not support subscription using [] .

        typing. Any ¶

        Special type indicating an unconstrained type.

          * Every type is compatible with Any .

          * Any is compatible with every type.

          Changed in version 3.11: Any can now be used as a base class. This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.

        typing. AnyStr ¶

        A constrained type variable .

        Definition:

            AnyStr = TypeVar('AnyStr', str, bytes)
            

        AnyStr is meant to be used for functions that may accept str or bytes arguments but cannot allow the two to mix.

        For example:

            def concat(a: AnyStr, b: AnyStr) -> AnyStr:
                return a + b
            
            concat("foo", "bar")    # OK, output has type 'str'
            concat(b"foo", b"bar")  # OK, output has type 'bytes'
            concat("foo", b"bar")   # Error, cannot mix str and bytes
            

        Note that, despite its name, AnyStr has nothing to do with the Any type, nor does it mean “any string”. In particular, AnyStr and str | bytes are different from each other and have different use cases:

            # Invalid use of AnyStr:
            # The type variable is used only once in the function signature,
            # so cannot be "solved" by the type checker
            def greet_bad(cond: bool) -> AnyStr:
                return "hi there!" if cond else b"greetings!"
            
            # The better way of annotating this function:
            def greet_proper(cond: bool) -> str | bytes:
                return "hi there!" if cond else b"greetings!"
            
        typing. LiteralString ¶

        Special type that includes only literal strings.

        Any string literal is compatible with LiteralString , as is another LiteralString . However, an object typed as just str is not. A string created by composing LiteralString -typed objects is also acceptable as a LiteralString .

        Example:

            def run_query(sql: LiteralString) -> None:
                ...
            
            def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
                run_query("SELECT * FROM students")  # OK
                run_query(literal_string)  # OK
                run_query("SELECT * FROM " + literal_string)  # OK
                run_query(arbitrary_string)  # type checker error
                run_query(  # type checker error
                    f"SELECT * FROM students WHERE name = {arbitrary_string}"
                )
            

        LiteralString is useful for sensitive APIs where arbitrary user-generated strings could generate problems. For example, the two cases above that generate type checker errors could be vulnerable to an SQL injection attack.

        See PEP 675 for more details.

          Added in version 3.11.

        typing. Never ¶ typing. NoReturn ¶

        Never and NoReturn represent the bottom type, a type that has no members.

        They can be used to indicate that a function never returns, such as sys.exit() :

            from typing import Never  # or NoReturn
            
            def stop() -> Never:
                raise RuntimeError('no way')
            

        Or to define a function that should never be called, as there are no valid arguments, such as assert_never() :

            from typing import Never  # or NoReturn
            
            def never_call_me(arg: Never) -> None:
                pass
            
            def int_or_str(arg: int | str) -> None:
                never_call_me(arg)  # type checker error
                match arg:
                    case int():
                        print("It's an int")
                    case str():
                        print("It's a str")
                    case _:
                        never_call_me(arg)  # OK, arg is of type Never (or NoReturn)
            

        Never and NoReturn have the same meaning in the type system and static type checkers treat both equivalently.

          Added in version 3.6.2: Added NoReturn .

          Added in version 3.11: Added Never .

        typing. Self ¶

        Special type to represent the current enclosed class.

        For example:

            from typing import Self, reveal_type
            
            class Foo:
                def return_self(self) -> Self:
                    ...
                    return self
            
            class SubclassOfFoo(Foo): pass
            
            reveal_type(Foo().return_self())  # Revealed type is "Foo"
            reveal_type(SubclassOfFoo().return_self())  # Revealed type is "SubclassOfFoo"
            

        This annotation is semantically equivalent to the following, albeit in a more succinct fashion:

            from typing import TypeVar
            
            Self = TypeVar("Self", bound="Foo")
            
            class Foo:
                def return_self(self: Self) -> Self:
                    ...
                    return self
            

        In general, if something returns self , as in the above examples, you should use Self as the return annotation. If Foo.return_self was annotated as returning "Foo" , then the type checker would infer the object returned from SubclassOfFoo.return_self as being of type Foo rather than SubclassOfFoo .

        Other common use cases include:

          * classmethod s that are used as alternative constructors and return instances of the cls parameter.

          * Annotating an __enter__() method which returns self.

        You should not use Self as the return annotation if the method is not guaranteed to return an instance of a subclass when the class is subclassed:

            class Eggs:
                # Self would be an incorrect return annotation here,
                # as the object returned is always an instance of Eggs,
                # even in subclasses
                def returns_eggs(self) -> "Eggs":
                    return Eggs()
            

        See PEP 673 for more details.

          Added in version 3.11.

        typing. TypeAlias ¶

        Special annotation for explicitly declaring a type alias .

        For example:

            from typing import TypeAlias
            
            Factors: TypeAlias = list[int]
            

        TypeAlias is particularly useful on older Python versions for annotating aliases that make use of forward references, as it can be hard for type checkers to distinguish these from normal variable assignments:

            from typing import Generic, TypeAlias, TypeVar
            
            T = TypeVar("T")
            
            # "Box" does not exist yet,
            # so we have to use quotes for the forward reference on Python <3.12.
            # Using ``TypeAlias`` tells the type checker that this is a type alias declaration,
            # not a variable assignment to a string.
            BoxOfStrings: TypeAlias = "Box[str]"
            
            class Box(Generic[T]):
                @classmethod
                def make_box_of_strings(cls) -> BoxOfStrings: ...
            

        See PEP 613 for more details.

          Added in version 3.10.

          Deprecated since version 3.12: TypeAlias is deprecated in favor of the type statement, which creates instances of TypeAliasType and which natively supports forward references. Note that while TypeAlias and TypeAliasType serve similar purposes and have similar names, they are distinct and the latter is not the type of the former. Removal of TypeAlias is not currently planned, but users are encouraged to migrate to type statements.

        Special forms¶

        These can be used as types in annotations. They all support subscription using [] , but each has a unique syntax.

        typing. Union ¶

        Union type; Union[X, Y] is equivalent to X | Y and means either X or Y.

        To define a union, use e.g. Union[int, str] or the shorthand int | str . Using that shorthand is recommended. Details:

          * The arguments must be types and there must be at least one.

          * Unions of unions are flattened, e.g.:

                Union[Union[int, str], float] == Union[int, str, float]
                

          * Unions of a single argument vanish, e.g.:

                Union[int] == int  # The constructor actually returns int
                

          * Redundant arguments are skipped, e.g.:

                Union[int, str, int] == Union[int, str] == int | str
                

          * When comparing unions, the argument order is ignored, e.g.:

                Union[int, str] == Union[str, int]
                

          * You cannot subclass or instantiate a Union .

          * You cannot write Union[X][Y] .

          Changed in version 3.7: Don’t remove explicit subclasses from unions at runtime.

          Changed in version 3.10: Unions can now be written as X | Y . See union type expressions .

        typing. Optional ¶

        Optional[X] is equivalent to X | None (or Union[X, None] ).

        Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the Optional qualifier on its type annotation just because it is optional. For example:

            def foo(arg: int = 0) -> None:
                ...
            

        On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:

            def foo(arg: Optional[int] = None) -> None:
                ...
            

          Changed in version 3.10: Optional can now be written as X | None . See union type expressions .

        typing. Concatenate ¶

        Special form for annotating higher-order functions.

        Concatenate can be used in conjunction with Callable and ParamSpec to annotate a higher-order callable which adds, removes, or transforms parameters of another callable. Usage is in the form Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable] . Concatenate is currently only valid when used as the first argument to a Callable . The last parameter to Concatenate must be a ParamSpec or ellipsis ( ... ).

        For example, to annotate a decorator with_lock which provides a threading.Lock to the decorated function, Concatenate can be used to indicate that with_lock expects a callable which takes in a Lock as the first argument, and returns a callable with a different type signature. In this case, the ParamSpec indicates that the returned callable’s parameter types are dependent on the parameter types of the callable being passed in:

            from collections.abc import Callable
            from threading import Lock
            from typing import Concatenate
            
            # Use this lock to ensure that only one thread is executing a function
            # at any time.
            my_lock = Lock()
            
            def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
                '''A type-safe decorator which provides a lock.'''
                def inner(*args: P.args, **kwargs: P.kwargs) -> R:
                    # Provide the lock as the first argument.
                    return f(my_lock, *args, **kwargs)
                return inner
            
            @with_lock
            def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
                '''Add a list of numbers together in a thread-safe manner.'''
                with lock:
                    return sum(numbers)
            
            # We don't need to pass in the lock ourselves thanks to the decorator.
            sum_threadsafe([1.1, 2.2, 3.3])
            

          Added in version 3.10.

          See also

            * PEP 612 – Parameter Specification Variables (the PEP which introduced ParamSpec and Concatenate )

            * ParamSpec

            * Annotating callable objects

        typing. Literal ¶

        Special typing form to define “literal types”.

        Literal can be used to indicate to type checkers that the annotated object has a value equivalent to one of the provided literals.

        For example:

            def validate_simple(data: Any) -> Literal[True]:  # always returns True
                ...
            
            type Mode = Literal['r', 'rb', 'w', 'wb']
            def open_helper(file: str, mode: Mode) -> str:
                ...
            
            open_helper('/some/path', 'r')      # Passes type check
            open_helper('/other/path', 'typo')  # Error in type checker
            

        Literal[...] cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to Literal[...] , but type checkers may impose restrictions. See PEP 586 for more details about literal types.

          Added in version 3.8.

          Changed in version 3.9.1: Literal now de-duplicates parameters. Equality comparisons of Literal objects are no longer order dependent. Literal objects will now raise a TypeError exception during equality comparisons if one of their parameters are not hashable .

        typing. ClassVar ¶

        Special type construct to mark class variables.

        As introduced in PEP 526, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:

            class Starship:
                stats: ClassVar[dict[str, int]] = {} # class variable
                damage: int = 10                     # instance variable
            

        ClassVar accepts only types and cannot be further subscribed.

        ClassVar is not a class itself, and should not be used with isinstance() or issubclass() . ClassVar does not change Python runtime behavior, but it can be used by third-party type checkers. For example, a type checker might flag the following code as an error:

            enterprise_d = Starship(3000)
            enterprise_d.stats = {} # Error, setting class variable on instance
            Starship.stats = {}     # This is OK
            

          Added in version 3.5.3.

        typing. Final ¶

        Special typing construct to indicate final names to type checkers.

        Final names cannot be reassigned in any scope. Final names declared in class scopes cannot be overridden in subclasses.

        For example:

            MAX_SIZE: Final = 9000
            MAX_SIZE += 1  # Error reported by type checker
            
            class Connection:
                TIMEOUT: Final[int] = 10
            
            class FastConnector(Connection):
                TIMEOUT = 1  # Error reported by type checker
            

        There is no runtime checking of these properties. See PEP 591 for more details.

          Added in version 3.8.

        typing. Required ¶

        Special typing construct to mark a TypedDict key as required.

        This is mainly useful for total=False TypedDicts. See TypedDict and PEP 655 for more details.

          Added in version 3.11.

        typing. NotRequired ¶

        Special typing construct to mark a TypedDict key as potentially missing.

        See TypedDict and PEP 655 for more details.

          Added in version 3.11.

        typing. Annotated ¶

        Special typing form to add context-specific metadata to an annotation.

        Add metadata x to a given type T by using the annotation Annotated[T, x] . Metadata added using Annotated can be used by static analysis tools or at runtime. At runtime, the metadata is stored in a __metadata__ attribute.

        If a library or tool encounters an annotation Annotated[T, x] and has no special logic for the metadata, it should ignore the metadata and simply treat the annotation as T . As such, Annotated can be useful for code that wants to use annotations for purposes outside Python’s static typing system.

        Using Annotated[T, x] as an annotation still allows for static typechecking of T , as type checkers will simply ignore the metadata x . In this way, Annotated differs from the @no_type_check decorator, which can also be used for adding annotations outside the scope of the typing system, but completely disables typechecking for a function or class.

        The responsibility of how to interpret the metadata lies with the tool or library encountering an Annotated annotation. A tool or library encountering an Annotated type can scan through the metadata elements to determine if they are of interest (e.g., using isinstance() ).

        Annotated[<type>, <metadata>]

        Here is an example of how you might use Annotated to add metadata to type annotations if you were doing range analysis:

            @dataclass
            class ValueRange:
                lo: int
                hi: int
            
            T1 = Annotated[int, ValueRange(-10, 5)]
            T2 = Annotated[T1, ValueRange(-20, 3)]
            

        Details of the syntax:

          * The first argument to Annotated must be a valid type

          * Multiple metadata elements can be supplied ( Annotated supports variadic arguments):

                @dataclass
                class ctype:
                    kind: str
                
                Annotated[int, ValueRange(3, 10), ctype("char")]
                

            It is up to the tool consuming the annotations to decide whether the client is allowed to add multiple metadata elements to one annotation and how to merge those annotations.

          * Annotated must be subscripted with at least two arguments ( Annotated[int] is not valid)

          * The order of the metadata elements is preserved and matters for equality checks:

                assert Annotated[int, ValueRange(3, 10), ctype("char")] != Annotated[
                    int, ctype("char"), ValueRange(3, 10)
                ]
                

          * Nested Annotated types are flattened. The order of the metadata elements starts with the innermost annotation:

                assert Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
                    int, ValueRange(3, 10), ctype("char")
                ]
                

          * Duplicated metadata elements are not removed:

                assert Annotated[int, ValueRange(3, 10)] != Annotated[
                    int, ValueRange(3, 10), ValueRange(3, 10)
                ]
                

          * Annotated can be used with nested and generic aliases:

                @dataclass
                class MaxLen:
                    value: int
                
                type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)]
                
                # When used in a type annotation, a type checker will treat "V" the same as
                # ``Annotated[list[tuple[int, int]], MaxLen(10)]``:
                type V = Vec[int]
                

          * Annotated cannot be used with an unpacked TypeVarTuple :

                type Variadic[*Ts] = Annotated[*Ts, Ann1]  # NOT valid
                

            This would be equivalent to:

                Annotated[T1, T2, T3, ..., Ann1]
                

            where T1 , T2 , etc. are TypeVars . This would be invalid: only one type should be passed to Annotated.

          * By default, get_type_hints() strips the metadata from annotations. Pass include_extras=True to have the metadata preserved:

                >>> from typing import Annotated, get_type_hints
                >>> def func(x: Annotated[int, "metadata"]) -> None: pass
                ...
                >>> get_type_hints(func)
                {'x': <class 'int'>, 'return': <class 'NoneType'>}
                >>> get_type_hints(func, include_extras=True)
                {'x': typing.Annotated[int, 'metadata'], 'return': <class 'NoneType'>}
                

          * At runtime, the metadata associated with an Annotated type can be retrieved via the __metadata__ attribute:

                >>> from typing import Annotated
                >>> X = Annotated[int, "very", "important", "metadata"]
                >>> X
                typing.Annotated[int, 'very', 'important', 'metadata']
                >>> X.__metadata__
                ('very', 'important', 'metadata')
                

          See also

          PEP 593 - Flexible function and variable annotations

          The PEP introducing Annotated to the standard library.

          Added in version 3.9.

        typing. TypeGuard ¶

        Special typing construct for marking user-defined type guard functions.

        TypeGuard can be used to annotate the return type of a user-defined type guard function. TypeGuard only accepts a single type argument. At runtime, functions marked this way should return a boolean.

        TypeGuard aims to benefit type narrowing – a technique used by static type checkers to determine a more precise type of an expression within a program’s code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a “type guard”:

            def is_str(val: str | float):
                # "isinstance" type guard
                if isinstance(val, str):
                    # Type of ``val`` is narrowed to ``str``
                    ...
                else:
                    # Else, type of ``val`` is narrowed to ``float``.
                    ...
            

        Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use TypeGuard[...] as its return type to alert static type checkers to this intention.

        Using -> TypeGuard tells the static type checker that for a given function:

         1. The return value is a boolean.

         2. If the return value is True , the type of its argument is the type inside TypeGuard .

        For example:

            def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
                '''Determines whether all objects in the list are strings'''
                return all(isinstance(x, str) for x in val)
            
            def func1(val: list[object]):
                if is_str_list(val):
                    # Type of ``val`` is narrowed to ``list[str]``.
                    print(" ".join(val))
                else:
                    # Type of ``val`` remains as ``list[object]``.
                    print("Not a list of strings!")
            

        If is_str_list is a class or instance method, then the type in TypeGuard maps to the type of the second parameter (after cls or self ).

        In short, the form def foo(arg: TypeA) -> TypeGuard[TypeB]: ... , means that if foo(arg) returns True , then arg narrows from TypeA to TypeB .

          Note

          TypeB need not be a narrower form of TypeA – it can even be a wider form. The main reason is to allow for things like narrowing list[object] to list[str] even though the latter is not a subtype of the former, since list is invariant. The responsibility of writing type-safe type guards is left to the user.

        TypeGuard also works with type variables. See PEP 647 for more details.

          Added in version 3.10.

        typing. Unpack ¶

        Typing operator to conceptually mark an object as having been unpacked.

        For example, using the unpack operator * on a type variable tuple is equivalent to using Unpack to mark the type variable tuple as having been unpacked:

            Ts = TypeVarTuple('Ts')
            tup: tuple[*Ts]
            # Effectively does:
            tup: tuple[Unpack[Ts]]
            

        In fact, Unpack can be used interchangeably with * in the context of typing.TypeVarTuple and builtins.tuple types. You might see Unpack being used explicitly in older versions of Python, where * couldn’t be used in certain places:

            # In older versions of Python, TypeVarTuple and Unpack
            # are located in the `typing_extensions` backports package.
            from typing_extensions import TypeVarTuple, Unpack
            
            Ts = TypeVarTuple('Ts')
            tup: tuple[*Ts]         # Syntax error on Python <= 3.10!
            tup: tuple[Unpack[Ts]]  # Semantically equivalent, and backwards-compatible
            

        Unpack can also be used along with typing.TypedDict for typing **kwargs in a function signature:

            from typing import TypedDict, Unpack
            
            class Movie(TypedDict):
                name: str
                year: int
            
            # This function expects two keyword arguments - `name` of type `str`
            # and `year` of type `int`.
            def foo(**kwargs: Unpack[Movie]): ...
            

        See PEP 692 for more details on using Unpack for **kwargs typing.

          Added in version 3.11.

        Building generic types and type aliases¶

        The following classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating generic types and type aliases.

        These objects can be created through special syntax ( type parameter lists and the type statement). For compatibility with Python 3.11 and earlier, they can also be created without the dedicated syntax, as documented below.

        class typing. Generic ¶

        Abstract base class for generic types.

        A generic type is typically declared by adding a list of type parameters after the class name:

            class Mapping[KT, VT]:
                def __getitem__(self, key: KT) -> VT:
                    ...
                    # Etc.
            

        Such a class implicitly inherits from Generic . The runtime semantics of this syntax are discussed in the Language Reference .

        This class can then be used as follows:

            def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:
                try:
                    return mapping[key]
                except KeyError:
                    return default
            

        Here the brackets after the function name indicate a generic function .

        For backwards compatibility, generic classes can also be declared by explicitly inheriting from Generic . In this case, the type parameters must be declared separately:

            KT = TypeVar('KT')
            VT = TypeVar('VT')
            
            class Mapping(Generic[KT, VT]):
                def __getitem__(self, key: KT) -> VT:
                    ...
                    # Etc.
            
        class typing. TypeVar ( name , * constraints , bound = None , covariant = False , contravariant = False , infer_variance = False ) ¶

        Type variable.

        The preferred way to construct a type variable is via the dedicated syntax for generic functions , generic classes , and generic type aliases :

            class Sequence[T]:  # T is a TypeVar
                ...
            

        This syntax can also be used to create bound and constrained type variables:

            class StrSequence[S: str]:  # S is a TypeVar bound to str
                ...
            
            
            class StrOrBytesSequence[A: (str, bytes)]:  # A is a TypeVar constrained to str or bytes
                ...
            

        However, if desired, reusable type variables can also be constructed manually, like so:

            T = TypeVar('T')  # Can be anything
            S = TypeVar('S', bound=str)  # Can be any subtype of str
            A = TypeVar('A', str, bytes)  # Must be exactly str or bytes
            

        Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions. See Generic for more information on generic types. Generic functions work as follows:

            def repeat[T](x: T, n: int) -> Sequence[T]:
                """Return a list containing n references to x."""
                return [x]*n
            
            
            def print_capitalized[S: str](x: S) -> S:
                """Print x capitalized, and return x."""
                print(x.capitalize())
                return x
            
            
            def concatenate[A: (str, bytes)](x: A, y: A) -> A:
                """Add two strings or bytes objects together."""
                return x + y
            

        Note that type variables can be bound, constrained, or neither, but cannot be both bound and constrained.

        The variance of type variables is inferred by type checkers when they are created through the type parameter syntax or when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True . By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

        Bound type variables and constrained type variables have different semantics in several important ways. Using a bound type variable means that the TypeVar will be solved using the most specific type possible:

            x = print_capitalized('a string')
            reveal_type(x)  # revealed type is str
            
            class StringSubclass(str):
                pass
            
            y = print_capitalized(StringSubclass('another string'))
            reveal_type(y)  # revealed type is StringSubclass
            
            z = print_capitalized(45)  # error: int is not a subtype of str
            

        Type variables can be bound to concrete types, abstract types (ABCs or protocols), and even unions of types:

            # Can be anything with an __abs__ method
            def print_abs[T: SupportsAbs](arg: T) -> None:
                print("Absolute value:", abs(arg))
            
            U = TypeVar('U', bound=str|bytes)  # Can be any subtype of the union str|bytes
            V = TypeVar('V', bound=SupportsAbs)  # Can be anything with an __abs__ method
            

        Using a constrained type variable, however, means that the TypeVar can only ever be solved as being exactly one of the constraints given:

            a = concatenate('one', 'two')
            reveal_type(a)  # revealed type is str
            
            b = concatenate(StringSubclass('one'), StringSubclass('two'))
            reveal_type(b)  # revealed type is str, despite StringSubclass being passed in
            
            c = concatenate('one', b'two')  # error: type variable 'A' can be either str or bytes in a function call, but not both
            

        At runtime, isinstance(x, T) will raise TypeError .

        __name__ ¶

        The name of the type variable.

        __covariant__ ¶

        Whether the type var has been explicitly marked as covariant.

        __contravariant__ ¶

        Whether the type var has been explicitly marked as contravariant.

        __infer_variance__ ¶

        Whether the type variable’s variance should be inferred by type checkers.

          Added in version 3.12.

        __bound__ ¶

        The bound of the type variable, if any.

          Changed in version 3.12: For type variables created through type parameter syntax , the bound is evaluated only when the attribute is accessed, not when the type variable is created (see Lazy evaluation ).

        __constraints__ ¶

        A tuple containing the constraints of the type variable, if any.

          Changed in version 3.12: For type variables created through type parameter syntax , the constraints are evaluated only when the attribute is accessed, not when the type variable is created (see Lazy evaluation ).

          Changed in version 3.12: Type variables can now be declared using the type parameter syntax introduced by PEP 695. The infer_variance parameter was added.

        class typing. TypeVarTuple ( name ) ¶

        Type variable tuple. A specialized form of type variable that enables variadic generics.

        Type variable tuples can be declared in type parameter lists using a single asterisk ( * ) before the name:

            def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
                return (*tup[1:], tup[0])
            

        Or by explicitly invoking the TypeVarTuple constructor:

            T = TypeVar("T")
            Ts = TypeVarTuple("Ts")
            
            def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
                return (*tup[1:], tup[0])
            

        A normal type variable enables parameterization with a single type. A type variable tuple, in contrast, allows parameterization with an arbitrary number of types by acting like an arbitrary number of type variables wrapped in a tuple. For example:

            # T is bound to int, Ts is bound to ()
            # Return value is (1,), which has type tuple[int]
            move_first_element_to_last(tup=(1,))
            
            # T is bound to int, Ts is bound to (str,)
            # Return value is ('spam', 1), which has type tuple[str, int]
            move_first_element_to_last(tup=(1, 'spam'))
            
            # T is bound to int, Ts is bound to (str, float)
            # Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
            move_first_element_to_last(tup=(1, 'spam', 3.0))
            
            # This fails to type check (and fails at runtime)
            # because tuple[()] is not compatible with tuple[T, *Ts]
            # (at least one element is required)
            move_first_element_to_last(tup=())
            

        Note the use of the unpacking operator * in tuple[T, *Ts] . Conceptually, you can think of Ts as a tuple of type variables (T1, T2, ...) . tuple[T, *Ts] would then become tuple[T, *(T1, T2, ...)] , which is equivalent to tuple[T, T1, T2, ...] . (Note that in older versions of Python, you might see this written using Unpack instead, as Unpack[Ts] .)

        Type variable tuples must always be unpacked. This helps distinguish type variable tuples from normal type variables:

            x: Ts          # Not valid
            x: tuple[Ts]   # Not valid
            x: tuple[*Ts]  # The correct way to do it
            

        Type variable tuples can be used in the same contexts as normal type variables. For example, in class definitions, arguments, and return types:

            class Array[*Shape]:
                def __getitem__(self, key: tuple[*Shape]) -> float: ...
                def __abs__(self) -> "Array[*Shape]": ...
                def get_shape(self) -> tuple[*Shape]: ...
            

        Type variable tuples can be happily combined with normal type variables:

            class Array[DType, *Shape]:  # This is fine
                pass
            
            class Array2[*Shape, DType]:  # This would also be fine
                pass
            
            class Height: ...
            class Width: ...
            
            float_array_1d: Array[float, Height] = Array()     # Totally fine
            int_array_2d: Array[int, Height, Width] = Array()  # Yup, fine too
            

        However, note that at most one type variable tuple may appear in a single list of type arguments or type parameters:

            x: tuple[*Ts, *Ts]            # Not valid
            class Array[*Shape, *Shape]:  # Not valid
                pass
            

        Finally, an unpacked type variable tuple can be used as the type annotation of *args :

            def call_soon[*Ts](
                callback: Callable[[*Ts], None],
                *args: *Ts
            ) -> None:
                ...
                callback(*args)
            

        In contrast to non-unpacked annotations of *args - e.g. *args: int , which would specify that all arguments are int - *args: *Ts enables reference to the types of the individual arguments in *args . Here, this allows us to ensure the types of the *args passed to call_soon match the types of the (positional) arguments of callback .

        See PEP 646 for more details on type variable tuples.

        __name__ ¶

        The name of the type variable tuple.

          Added in version 3.11.

          Changed in version 3.12: Type variable tuples can now be declared using the type parameter syntax introduced by PEP 695.

        class typing. ParamSpec ( name , * , bound = None , covariant = False , contravariant = False ) ¶

        Parameter specification variable. A specialized version of type variables .

        In type parameter lists , parameter specifications can be declared with two asterisks ( ** ):

            type IntFunc[**P] = Callable[P, int]
            

        For compatibility with Python 3.11 and earlier, ParamSpec objects can also be created as follows:

            P = ParamSpec('P')
            

        Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable – a pattern commonly found in higher order functions and decorators. They are only valid when used in Concatenate , or as the first argument to Callable , or as parameters for user-defined Generics. See Generic for more information on generic types.

        For example, to add basic logging to a function, one can create a decorator add_logging to log function calls. The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters:

            from collections.abc import Callable
            import logging
            
            def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:
                '''A type-safe decorator to add logging to a function.'''
                def inner(*args: P.args, **kwargs: P.kwargs) -> T:
                    logging.info(f'{f.__name__} was called')
                    return f(*args, **kwargs)
                return inner
            
            @add_logging
            def add_two(x: float, y: float) -> float:
                '''Add two numbers together.'''
                return x + y
            

        Without ParamSpec , the simplest way to annotate this previously was to use a TypeVar with bound Callable[..., Any] . However this causes two problems:

         1. The type checker can’t type check the inner function because *args and **kwargs have to be typed Any .

         2. cast() may be required in the body of the add_logging decorator when returning the inner function, or the static type checker must be told to ignore the return inner .

        args ¶ kwargs ¶

        Since ParamSpec captures both positional and keyword parameters, P.args and P.kwargs can be used to split a ParamSpec into its components. P.args represents the tuple of positional parameters in a given call and should only be used to annotate *args . P.kwargs represents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate **kwargs . Both attributes require the annotated parameter to be in scope. At runtime, P.args and P.kwargs are instances respectively of ParamSpecArgs and ParamSpecKwargs .

        __name__ ¶

        The name of the parameter specification.

        Parameter specification variables created with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. The bound argument is also accepted, similar to TypeVar . However the actual semantics of these keywords are yet to be decided.

          Added in version 3.10.

          Changed in version 3.12: Parameter specifications can now be declared using the type parameter syntax introduced by PEP 695.

          Note

          Only parameter specification variables defined in global scope can be pickled.

          See also

            * PEP 612 – Parameter Specification Variables (the PEP which introduced ParamSpec and Concatenate )

            * Concatenate

            * Annotating callable objects

        typing. ParamSpecArgs ¶ typing. ParamSpecKwargs ¶

        Arguments and keyword arguments attributes of a ParamSpec . The P.args attribute of a ParamSpec is an instance of ParamSpecArgs , and P.kwargs is an instance of ParamSpecKwargs . They are intended for runtime introspection and have no special meaning to static type checkers.

        Calling get_origin() on either of these objects will return the original ParamSpec :

            >>> from typing import ParamSpec, get_origin
            >>> P = ParamSpec("P")
            >>> get_origin(P.args) is P
            True
            >>> get_origin(P.kwargs) is P
            True
            

          Added in version 3.10.

        class typing. TypeAliasType ( name , value , * , type_params = () ) ¶

        The type of type aliases created through the type statement.

        Example:

            >>> type Alias = int
            >>> type(Alias)
            <class 'typing.TypeAliasType'>
            

          Added in version 3.12.

        __name__ ¶

        The name of the type alias:

            >>> type Alias = int
            >>> Alias.__name__
            'Alias'
            
        __module__ ¶

        The module in which the type alias was defined:

            >>> type Alias = int
            >>> Alias.__module__
            '__main__'
            
        __type_params__ ¶

        The type parameters of the type alias, or an empty tuple if the alias is not generic:

            >>> type ListOrSet[T] = list[T] | set[T]
            >>> ListOrSet.__type_params__
            (T,)
            >>> type NotGeneric = int
            >>> NotGeneric.__type_params__
            ()
            
        __value__ ¶

        The type alias’s value. This is lazily evaluated , so names used in the definition of the alias are not resolved until the __value__ attribute is accessed:

            >>> type Mutually = Recursive
            >>> type Recursive = Mutually
            >>> Mutually
            Mutually
            >>> Recursive
            Recursive
            >>> Mutually.__value__
            Recursive
            >>> Recursive.__value__
            Mutually
            

        Other special directives¶

        These functions and classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating and declaring types.

        class typing. NamedTuple ¶

        Typed version of collections.namedtuple() .

        Usage:

            class Employee(NamedTuple):
                name: str
                id: int
            

        This is equivalent to:

            Employee = collections.namedtuple('Employee', ['name', 'id'])
            

        To give a field a default value, you can assign to it in the class body:

            class Employee(NamedTuple):
                name: str
                id: int = 3
            
            employee = Employee('Guido')
            assert employee.id == 3
            

        Fields with a default value must come after any fields without a default.

        The resulting class has an extra attribute __annotations__ giving a dict that maps the field names to the field types. (The field names are in the _fields attribute and the default values are in the _field_defaults attribute, both of which are part of the namedtuple() API.)

        NamedTuple subclasses can also have docstrings and methods:

            class Employee(NamedTuple):
                """Represents an employee."""
                name: str
                id: int = 3
            
                def __repr__(self) -> str:
                    return f'<Employee {self.name}, id={self.id}>'
            

        NamedTuple subclasses can be generic:

            class Group[T](NamedTuple):
                key: T
                group: list[T]
            

        Backward-compatible usage:

            # For creating a generic NamedTuple on Python 3.11 or lower
            class Group(NamedTuple, Generic[T]):
                key: T
                group: list[T]
            
            # A functional syntax is also supported
            Employee = NamedTuple('Employee', [('name', str), ('id', int)])
            

          Changed in version 3.6: Added support for PEP 526 variable annotation syntax.

          Changed in version 3.6.1: Added support for default values, methods, and docstrings.

          Changed in version 3.8: The _field_types and __annotations__ attributes are now regular dictionaries instead of instances of OrderedDict .

          Changed in version 3.9: Removed the _field_types attribute in favor of the more standard __annotations__ attribute which has the same information.

          Changed in version 3.11: Added support for generic namedtuples.

        class typing. NewType ( name , tp ) ¶

        Helper class to create low-overhead distinct types .

        A NewType is considered a distinct type by a typechecker. At runtime, however, calling a NewType returns its argument unchanged.

        Usage:

            UserId = NewType('UserId', int)  # Declare the NewType "UserId"
            first_user = UserId(1)  # "UserId" returns the argument unchanged at runtime
            
        __module__ ¶

        The module in which the new type is defined.

        __name__ ¶

        The name of the new type.

        __supertype__ ¶

        The type that the new type is based on.

          Added in version 3.5.2.

          Changed in version 3.10: NewType is now a class rather than a function.

        class typing. Protocol ( Generic ) ¶

        Base class for protocol classes.

        Protocol classes are defined like this:

            class Proto(Protocol):
                def meth(self) -> int:
                    ...
            

        Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:

            class C:
                def meth(self) -> int:
                    return 0
            
            def func(x: Proto) -> int:
                return x.meth()
            
            func(C())  # Passes static type check
            

        See PEP 544 for more details. Protocol classes decorated with runtime_checkable() (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures.

        Protocol classes can be generic, for example:

            class GenProto[T](Protocol):
                def meth(self) -> T:
                    ...
            

        In code that needs to be compatible with Python 3.11 or older, generic Protocols can be written as follows:

            T = TypeVar("T")
            
            class GenProto(Protocol[T]):
                def meth(self) -> T:
                    ...
            

          Added in version 3.8.

        @ typing. runtime_checkable ¶

        Mark a protocol class as a runtime protocol.

        Such a protocol can be used with isinstance() and issubclass() . This raises TypeError when applied to a non-protocol class. This allows a simple-minded structural check, very similar to “one trick ponies” in collections.abc such as Iterable . For example:

            @runtime_checkable
            class Closable(Protocol):
                def close(self): ...
            
            assert isinstance(open('/some/file'), Closable)
            
            @runtime_checkable
            class Named(Protocol):
                name: str
            
            import threading
            assert isinstance(threading.Thread(name='Bob'), Named)
            

          Note

          runtime_checkable() will check only the presence of the required methods or attributes, not their type signatures or types. For example, ssl.SSLObject is a class, therefore it passes an issubclass() check against Callable . However, the ssl.SSLObject.__init__ method exists only to raise a TypeError with a more informative message, therefore making it impossible to call (instantiate) ssl.SSLObject .

          Note

          An isinstance() check against a runtime-checkable protocol can be surprisingly slow compared to an isinstance() check against a non-protocol class. Consider using alternative idioms such as hasattr() calls for structural checks in performance-sensitive code.

          Added in version 3.8.

          Changed in version 3.12: The internal implementation of isinstance() checks against runtime-checkable protocols now uses inspect.getattr_static() to look up attributes (previously, hasattr() was used). As a result, some objects which used to be considered instances of a runtime-checkable protocol may no longer be considered instances of that protocol on Python 3.12+, and vice versa. Most users are unlikely to be affected by this change.

          Changed in version 3.12: The members of a runtime-checkable protocol are now considered “frozen” at runtime as soon as the class has been created. Monkey-patching attributes onto a runtime-checkable protocol will still work, but will have no impact on isinstance() checks comparing objects to the protocol. See “What’s new in Python 3.12” for more details.

        class typing. TypedDict ( dict ) ¶

        Special construct to add type hints to a dictionary. At runtime it is a plain dict .

        TypedDict declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:

            class Point2D(TypedDict):
                x: int
                y: int
                label: str
            
            a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
            b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
            
            assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
            

        To allow using this feature with older versions of Python that do not support PEP 526, TypedDict supports two additional equivalent syntactic forms:

          * Using a literal dict as the second argument:

                Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
                

          * Using keyword arguments:

                Point2D = TypedDict('Point2D', x=int, y=int, label=str)
                

              Deprecated since version 3.11, will be removed in version 3.13: The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13. It may also be unsupported by static type checkers.

        The functional syntax should also be used when any of the keys are not valid identifiers , for example because they are keywords or contain hyphens. Example:

            # raises SyntaxError
            class Point2D(TypedDict):
                in: int  # 'in' is a keyword
                x-y: int  # name with hyphens
            
            # OK, functional syntax
            Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})
            

        By default, all keys must be present in a TypedDict . It is possible to mark individual keys as non-required using NotRequired :

            class Point2D(TypedDict):
                x: int
                y: int
                label: NotRequired[str]
            
            # Alternative syntax
            Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]})
            

        This means that a Point2D TypedDict can have the label key omitted.

        It is also possible to mark all keys as non-required by default by specifying a totality of False :

            class Point2D(TypedDict, total=False):
                x: int
                y: int
            
            # Alternative syntax
            Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)
            

        This means that a Point2D TypedDict can have any of the keys omitted. A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body required.

        Individual keys of a total=False TypedDict can be marked as required using Required :

            class Point2D(TypedDict, total=False):
                x: Required[int]
                y: Required[int]
                label: str
            
            # Alternative syntax
            Point2D = TypedDict('Point2D', {
                'x': Required[int],
                'y': Required[int],
                'label': str
            }, total=False)
            

        It is possible for a TypedDict type to inherit from one or more other TypedDict types using the class-based syntax. Usage:

            class Point3D(Point2D):
                z: int
            

        Point3D has three items: x , y and z . It is equivalent to this definition:

            class Point3D(TypedDict):
                x: int
                y: int
                z: int
            

        A TypedDict cannot inherit from a non- TypedDict class, except for Generic . For example:

            class X(TypedDict):
                x: int
            
            class Y(TypedDict):
                y: int
            
            class Z(object): pass  # A non-TypedDict class
            
            class XY(X, Y): pass  # OK
            
            class XZ(X, Z): pass  # raises TypeError
            

        A TypedDict can be generic:

            class Group[T](TypedDict):
                key: T
                group: list[T]
            

        To create a generic TypedDict that is compatible with Python 3.11 or lower, inherit from Generic explicitly:

            T = TypeVar("T")
            
            class Group(TypedDict, Generic[T]):
                key: T
                group: list[T]
            

        A TypedDict can be introspected via annotations dicts (see Annotations Best Practices for more information on annotations best practices), __total__ , __required_keys__ , and __optional_keys__ .

        __total__ ¶

        Point2D.__total__ gives the value of the total argument. Example:

            >>> from typing import TypedDict
            >>> class Point2D(TypedDict): pass
            >>> Point2D.__total__
            True
            >>> class Point2D(TypedDict, total=False): pass
            >>> Point2D.__total__
            False
            >>> class Point3D(Point2D): pass
            >>> Point3D.__total__
            True
            

        This attribute reflects only the value of the total argument to the current TypedDict class, not whether the class is semantically total. For example, a TypedDict with __total__ set to True may have keys marked with NotRequired , or it may inherit from another TypedDict with total=False . Therefore, it is generally better to use __required_keys__ and __optional_keys__ for introspection.

        __required_keys__ ¶

          Added in version 3.9.

        __optional_keys__ ¶

        Point2D.__required_keys__ and Point2D.__optional_keys__ return frozenset objects containing required and non-required keys, respectively.

        Keys marked with Required will always appear in __required_keys__ and keys marked with NotRequired will always appear in __optional_keys__ .

        For backwards compatibility with Python 3.10 and below, it is also possible to use inheritance to declare both required and non-required keys in the same TypedDict . This is done by declaring a TypedDict with one value for the total argument and then inheriting from it in another TypedDict with a different value for total :

            >>> class Point2D(TypedDict, total=False):
            ...     x: int
            ...     y: int
            ...
            >>> class Point3D(Point2D):
            ...     z: int
            ...
            >>> Point3D.__required_keys__ == frozenset({'z'})
            True
            >>> Point3D.__optional_keys__ == frozenset({'x', 'y'})
            True
            

          Added in version 3.9.

          Note

          If from __future__ import annotations is used or if annotations are given as strings, annotations are not evaluated when the TypedDict is defined. Therefore, the runtime introspection that __required_keys__ and __optional_keys__ rely on may not work properly, and the values of the attributes may be incorrect.

        See PEP 589 for more examples and detailed rules of using TypedDict .

          Added in version 3.8.

          Changed in version 3.11: Added support for marking individual keys as Required or NotRequired . See PEP 655.

          Changed in version 3.11: Added support for generic TypedDict s.

        Protocols¶

        The following protocols are provided by the typing module. All are decorated with @runtime_checkable .

        class typing. SupportsAbs ¶

        An ABC with one abstract method __abs__ that is covariant in its return type.

        class typing. SupportsBytes ¶

        An ABC with one abstract method __bytes__ .

        class typing. SupportsComplex ¶

        An ABC with one abstract method __complex__ .

        class typing. SupportsFloat ¶

        An ABC with one abstract method __float__ .

        class typing. SupportsIndex ¶

        An ABC with one abstract method __index__ .

          Added in version 3.8.

        class typing. SupportsInt ¶

        An ABC with one abstract method __int__ .

        class typing. SupportsRound ¶

        An ABC with one abstract method __round__ that is covariant in its return type.

        ABCs for working with IO¶

        class typing. IO ¶ class typing. TextIO ¶ class typing. BinaryIO ¶

        Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open() .

        Functions and decorators¶

        typing. cast ( typ , val ) ¶

        Cast a value to a type.

        This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).

        typing. assert_type ( val , typ , / ) ¶

        Ask a static type checker to confirm that val has an inferred type of typ.

        At runtime this does nothing: it returns the first argument unchanged with no checks or side effects, no matter the actual type of the argument.

        When a static type checker encounters a call to assert_type() , it emits an error if the value is not of the specified type:

            def greet(name: str) -> None:
                assert_type(name, str)  # OK, inferred type of `name` is `str`
                assert_type(name, int)  # type checker error
            

        This function is useful for ensuring the type checker’s understanding of a script is in line with the developer’s intentions:

            def complex_function(arg: object):
                # Do some complex type-narrowing logic,
                # after which we hope the inferred type will be `int`
                ...
                # Test whether the type checker correctly understands our function
                assert_type(arg, int)
            

          Added in version 3.11.

        typing. assert_never ( arg , / ) ¶

        Ask a static type checker to confirm that a line of code is unreachable.

        Example:

            def int_or_str(arg: int | str) -> None:
                match arg:
                    case int():
                        print("It's an int")
                    case str():
                        print("It's a str")
                    case _ as unreachable:
                        assert_never(unreachable)
            

        Here, the annotations allow the type checker to infer that the last case can never execute, because arg is either an int or a str , and both options are covered by earlier cases.

        If a type checker finds that a call to assert_never() is reachable, it will emit an error. For example, if the type annotation for arg was instead int | str | float , the type checker would emit an error pointing out that unreachable is of type float . For a call to assert_never to pass type checking, the inferred type of the argument passed in must be the bottom type, Never , and nothing else.

        At runtime, this throws an exception when called.

          See also

          Unreachable Code and Exhaustiveness Checking has more information about exhaustiveness checking with static typing.

          Added in version 3.11.

        typing. reveal_type ( obj , / ) ¶

        Ask a static type checker to reveal the inferred type of an expression.

        When a static type checker encounters a call to this function, it emits a diagnostic with the inferred type of the argument. For example:

            x: int = 1
            reveal_type(x)  # Revealed type is "builtins.int"
            

        This can be useful when you want to debug how your type checker handles a particular piece of code.

        At runtime, this function prints the runtime type of its argument to sys.stderr and returns the argument unchanged (allowing the call to be used within an expression):

            x = reveal_type(1)  # prints "Runtime type is int"
            print(x)  # prints "1"
            

        Note that the runtime type may be different from (more or less specific than) the type statically inferred by a type checker.

        Most type checkers support reveal_type() anywhere, even if the name is not imported from typing . Importing the name from typing , however, allows your code to run without runtime errors and communicates intent more clearly.

          Added in version 3.11.

        @ typing. dataclass_transform ( * , eq_default = True , order_default = False , kw_only_default = False , frozen_default = False , field_specifiers = () , ** kwargs ) ¶

        Decorator to mark an object as providing dataclass -like behavior.

        dataclass_transform may be used to decorate a class, metaclass, or a function that is itself a decorator. The presence of @dataclass_transform() tells a static type checker that the decorated object performs runtime “magic” that transforms a class in a similar way to @dataclasses.dataclass .

        Example usage with a decorator function:

            @dataclass_transform()
            def create_model[T](cls: type[T]) -> type[T]:
                ...
                return cls
            
            @create_model
            class CustomerModel:
                id: int
                name: str
            

        On a base class:

            @dataclass_transform()
            class ModelBase: ...
            
            class CustomerModel(ModelBase):
                id: int
                name: str
            

        On a metaclass:

            @dataclass_transform()
            class ModelMeta(type): ...
            
            class ModelBase(metaclass=ModelMeta): ...
            
            class CustomerModel(ModelBase):
                id: int
                name: str
            

        The CustomerModel classes defined above will be treated by type checkers similarly to classes created with @dataclasses.dataclass . For example, type checkers will assume these classes have __init__ methods that accept id and name .

        The decorated class, metaclass, or function may accept the following bool arguments which type checkers will assume have the same effect as they would have on the @dataclasses.dataclass decorator: init , eq , order , unsafe_hash , frozen , match_args , kw_only , and slots . It must be possible for the value of these arguments ( True or False ) to be statically evaluated.

        The arguments to the dataclass_transform decorator can be used to customize the default behaviors of the decorated class, metaclass, or function:

        Parameters :

          * eq_default (bool) – Indicates whether the eq parameter is assumed to be True or False if it is omitted by the caller. Defaults to True .

          * order_default (bool) – Indicates whether the order parameter is assumed to be True or False if it is omitted by the caller. Defaults to False .

          * kw_only_default (bool) – Indicates whether the kw_only parameter is assumed to be True or False if it is omitted by the caller. Defaults to False .

          * frozen_default (bool) –

            Indicates whether the frozen parameter is assumed to be True or False if it is omitted by the caller. Defaults to False .

              Added in version 3.12.

          * field_specifiers (tuple[Callable[..., Any], ...]) – Specifies a static list of supported classes or functions that describe fields, similar to dataclasses.field() . Defaults to () .

          * **kwargs (Any) – Arbitrary other keyword arguments are accepted in order to allow for possible future extensions.

        Type checkers recognize the following optional parameters on field specifiers:

        Recognised parameters for field specifiers¶
        Parameter name   Description                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                                                       
        init             Indicates whether the field should be included in the synthesized __init__ method. If unspecified, init defaults to True .                                                                                                                                                                                                                                    
                                                                                                                                                                                                                                                                                                                                                                                       
        default          Provides the default value for the field.                                                                                                                                                                                                                                                                                                                     
                                                                                                                                                                                                                                                                                                                                                                                       
        default_factory  Provides a runtime callback that returns the default value for the field. If neither default nor default_factory are specified, the field is assumed to have no default value and must be provided a value when the class is instantiated.                                                                                                                    
                                                                                                                                                                                                                                                                                                                                                                                       
        factory          An alias for the default_factory parameter on field specifiers.                                                                                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                                                                                                                                                       
        kw_only          Indicates whether the field should be marked as keyword-only. If True , the field will be keyword-only. If False , it will not be keyword-only. If unspecified, the value of the kw_only parameter on the object decorated with dataclass_transform will be used, or if that is unspecified, the value of kw_only_default on dataclass_transform will be used.
                                                                                                                                                                                                                                                                                                                                                                                       
        alias            Provides an alternative name for the field. This alternative name is used in the synthesized __init__ method.                                                                                                                                                                                                                                                 
                                                                                                                                                                                                                                                                                                                                                                                       
        

        At runtime, this decorator records its arguments in the __dataclass_transform__ attribute on the decorated object. It has no other runtime effect.

        See PEP 681 for more details.

          Added in version 3.11.

        @ typing. overload ¶

        Decorator for creating overloaded functions and methods.

        The @overload decorator allows describing functions and methods that support multiple different combinations of argument types. A series of @overload -decorated definitions must be followed by exactly one non- @overload -decorated definition (for the same function/method).

        @overload -decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non- @overload -decorated definition. The non- @overload -decorated definition, meanwhile, will be used at runtime but should be ignored by a type checker. At runtime, calling an @overload -decorated function directly will raise NotImplementedError .

        An example of overload that gives a more precise type than can be expressed using a union or a type variable:

            @overload
            def process(response: None) -> None:
                ...
            @overload
            def process(response: int) -> tuple[int, str]:
                ...
            @overload
            def process(response: bytes) -> str:
                ...
            def process(response):
                ...  # actual implementation goes here
            

        See PEP 484 for more details and comparison with other typing semantics.

          Changed in version 3.11: Overloaded functions can now be introspected at runtime using get_overloads() .

        typing. get_overloads ( func ) ¶

        Return a sequence of @overload -decorated definitions for func.

        func is the function object for the implementation of the overloaded function. For example, given the definition of process in the documentation for @overload , get_overloads(process) will return a sequence of three function objects for the three defined overloads. If called on a function with no overloads, get_overloads() returns an empty sequence.

        get_overloads() can be used for introspecting an overloaded function at runtime.

          Added in version 3.11.

        typing. clear_overloads ( ) ¶

        Clear all registered overloads in the internal registry.

        This can be used to reclaim the memory used by the registry.

          Added in version 3.11.

        @ typing. final ¶

        Decorator to indicate final methods and final classes.

        Decorating a method with @final indicates to a type checker that the method cannot be overridden in a subclass. Decorating a class with @final indicates that it cannot be subclassed.

        For example:

            class Base:
                @final
                def done(self) -> None:
                    ...
            class Sub(Base):
                def done(self) -> None:  # Error reported by type checker
                    ...
            
            @final
            class Leaf:
                ...
            class Other(Leaf):  # Error reported by type checker
                ...
            

        There is no runtime checking of these properties. See PEP 591 for more details.

          Added in version 3.8.

          Changed in version 3.11: The decorator will now attempt to set a __final__ attribute to True on the decorated object. Thus, a check like if getattr(obj, "__final__", False) can be used at runtime to determine whether an object obj has been marked as final. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

        @ typing. no_type_check ¶

        Decorator to indicate that annotations are not type hints.

        This works as a class or function decorator . With a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). Type checkers will ignore all annotations in a function or class with this decorator.

        @no_type_check mutates the decorated object in place.

        @ typing. no_type_check_decorator ¶

        Decorator to give another decorator the no_type_check() effect.

        This wraps the decorator with something that wraps the decorated function in no_type_check() .

        @ typing. override ¶

        Decorator to indicate that a method in a subclass is intended to override a method or attribute in a superclass.

        Type checkers should emit an error if a method decorated with @override does not, in fact, override anything. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class.

        For example:

            class Base:
                def log_status(self) -> None:
                    ...
            
            class Sub(Base):
                @override
                def log_status(self) -> None:  # Okay: overrides Base.log_status
                    ...
            
                @override
                def done(self) -> None:  # Error reported by type checker
                    ...
            

        There is no runtime checking of this property.

        The decorator will attempt to set an __override__ attribute to True on the decorated object. Thus, a check like if getattr(obj, "__override__", False) can be used at runtime to determine whether an object obj has been marked as an override. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

        See PEP 698 for more details.

          Added in version 3.12.

        @ typing. type_check_only ¶

        Decorator to mark a class or function as unavailable at runtime.

        This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class:

            @type_check_only
            class Response:  # private or not available at runtime
                code: int
                def get_header(self, name: str) -> str: ...
            
            def fetch_response() -> Response: ...
            

        Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.

        Introspection helpers¶

        typing. get_type_hints ( obj , globalns = None , localns = None , include_extras = False ) ¶

        Return a dictionary containing type hints for a function, method, module or class object.

        This is often the same as obj.__annotations__ , but this function makes the following changes to the annotations dictionary:

          * Forward references encoded as string literals or ForwardRef objects are handled by evaluating them in globalns, localns, and (where applicable) obj’s type parameter namespace. If globalns or localns is not given, appropriate namespace dictionaries are inferred from obj.

          * None is replaced with types.NoneType .

          * If @no_type_check has been applied to obj, an empty dictionary is returned.

          * If obj is a class C , the function returns a dictionary that merges annotations from C ’s base classes with those on C directly. This is done by traversing C.__mro__ and iteratively combining __annotations__ dictionaries. Annotations on classes appearing earlier in the method resolution order always take precedence over annotations on classes appearing later in the method resolution order.

          * The function recursively replaces all occurrences of Annotated[T, ...] with T , unless include_extras is set to True (see Annotated for more information).

        See also inspect.get_annotations() , a lower-level function that returns annotations more directly.

          Note

          If any forward references in the annotations of obj are not resolvable or are not valid Python code, this function will raise an exception such as NameError . For example, this can happen with imported type aliases that include forward references, or with names imported under if TYPE_CHECKING .

          Changed in version 3.9: Added include_extras parameter as part of PEP 593. See the documentation on Annotated for more information.

          Changed in version 3.11: Previously, Optional[t] was added for function and method annotations if a default value equal to None was set. Now the annotation is returned unchanged.

        typing. get_origin ( tp ) ¶

        Get the unsubscripted version of a type: for a typing object of the form X[Y, Z, ...] return X .

        If X is a typing-module alias for a builtin or collections class, it will be normalized to the original class. If X is an instance of ParamSpecArgs or ParamSpecKwargs , return the underlying ParamSpec . Return None for unsupported objects.

        Examples:

            assert get_origin(str) is None
            assert get_origin(Dict[str, int]) is dict
            assert get_origin(Union[int, str]) is Union
            P = ParamSpec('P')
            assert get_origin(P.args) is P
            assert get_origin(P.kwargs) is P
            

          Added in version 3.8.

        typing. get_args ( tp ) ¶

        Get type arguments with all substitutions performed: for a typing object of the form X[Y, Z, ...] return (Y, Z, ...) .

        If X is a union or Literal contained in another generic type, the order of (Y, Z, ...) may be different from the order of the original arguments [Y, Z, ...] due to type caching. Return () for unsupported objects.

        Examples:

            assert get_args(int) == ()
            assert get_args(Dict[int, str]) == (int, str)
            assert get_args(Union[int, str]) == (int, str)
            

          Added in version 3.8.

        typing. is_typeddict ( tp ) ¶

        Check if a type is a TypedDict .

        For example:

            class Film(TypedDict):
                title: str
                year: int
            
            assert is_typeddict(Film)
            assert not is_typeddict(list | str)
            
            # TypedDict is a factory for creating typed dicts,
            # not a typed dict itself
            assert not is_typeddict(TypedDict)
            

          Added in version 3.10.

        class typing. ForwardRef ¶

        Class used for internal typing representation of string forward references.

        For example, List["SomeClass"] is implicitly transformed into List[ForwardRef("SomeClass")] . ForwardRef should not be instantiated by a user, but may be used by introspection tools.

          Note

          PEP 585 generic types such as list["SomeClass"] will not be implicitly transformed into list[ForwardRef("SomeClass")] and thus will not automatically resolve to list[SomeClass] .

          Added in version 3.7.4.

        Constant¶

        typing. TYPE_CHECKING ¶

        A special constant that is assumed to be True by 3rd party static type checkers. It is False at runtime.

        Usage:

            if TYPE_CHECKING:
                import expensive_mod
            
            def fun(arg: 'expensive_mod.SomeType') -> None:
                local_var: expensive_mod.AnotherType = other_fun()
            

        The first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the expensive_mod reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.

          Note

          If from __future__ import annotations is used, annotations are not evaluated at function definition time. Instead, they are stored as strings in __annotations__ . This makes it unnecessary to use quotes around the annotation (see PEP 563).

          Added in version 3.5.2.

        Deprecated aliases¶

        This module defines several deprecated aliases to pre-existing standard library classes. These were originally included in the typing module in order to support parameterizing these generic classes using [] . However, the aliases became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support [] (see PEP 585).

        The redundant types are deprecated as of Python 3.9. However, while the aliases may be removed at some point, removal of these aliases is not currently planned. As such, no deprecation warnings are currently issued by the interpreter for these aliases.

        If at some point it is decided to remove these deprecated aliases, a deprecation warning will be issued by the interpreter for at least two releases prior to removal. The aliases are guaranteed to remain in the typing module without deprecation warnings until at least Python 3.14.

        Type checkers are encouraged to flag uses of the deprecated types if the program they are checking targets a minimum Python version of 3.9 or newer.

        Aliases to built-in types¶

        class typing. Dict ( dict, MutableMapping[KT, VT] ) ¶

        Deprecated alias to dict .

        Note that to annotate arguments, it is preferred to use an abstract collection type such as Mapping rather than to use dict or typing.Dict .

        This type can be used as follows:

            def count_words(text: str) -> Dict[str, int]:
                ...
            

          Deprecated since version 3.9: builtins.dict now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. List ( list, MutableSequence[T] ) ¶

        Deprecated alias to list .

        Note that to annotate arguments, it is preferred to use an abstract collection type such as Sequence or Iterable rather than to use list or typing.List .

        This type may be used as follows:

            def vec2[T: (int, float)](x: T, y: T) -> List[T]:
                return [x, y]
            
            def keep_positives[T: (int, float)](vector: Sequence[T]) -> List[T]:
                return [item for item in vector if item > 0]
            

          Deprecated since version 3.9: builtins.list now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Set ( set, MutableSet[T] ) ¶

        Deprecated alias to builtins.set .

        Note that to annotate arguments, it is preferred to use an abstract collection type such as AbstractSet rather than to use set or typing.Set .

          Deprecated since version 3.9: builtins.set now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. FrozenSet ( frozenset, AbstractSet[T_co] ) ¶

        Deprecated alias to builtins.frozenset .

          Deprecated since version 3.9: builtins.frozenset now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        typing. Tuple ¶

        Deprecated alias for tuple .

        tuple and Tuple are special-cased in the type system; see Annotating tuples for more details.

          Deprecated since version 3.9: builtins.tuple now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Type ( Generic[CT_co] ) ¶

        Deprecated alias to type .

        See The type of class objects for details on using type or typing.Type in type annotations.

          Added in version 3.5.2.

          Deprecated since version 3.9: builtins.type now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        Aliases to types in collections ¶

        class typing. DefaultDict ( collections.defaultdict, MutableMapping[KT, VT] ) ¶

        Deprecated alias to collections.defaultdict .

          Added in version 3.5.2.

          Deprecated since version 3.9: collections.defaultdict now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. OrderedDict ( collections.OrderedDict, MutableMapping[KT, VT] ) ¶

        Deprecated alias to collections.OrderedDict .

          Added in version 3.7.2.

          Deprecated since version 3.9: collections.OrderedDict now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. ChainMap ( collections.ChainMap, MutableMapping[KT, VT] ) ¶

        Deprecated alias to collections.ChainMap .

          Added in version 3.6.1.

          Deprecated since version 3.9: collections.ChainMap now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Counter ( collections.Counter, Dict[T, int] ) ¶

        Deprecated alias to collections.Counter .

          Added in version 3.6.1.

          Deprecated since version 3.9: collections.Counter now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Deque ( deque, MutableSequence[T] ) ¶

        Deprecated alias to collections.deque .

          Added in version 3.6.1.

          Deprecated since version 3.9: collections.deque now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        Aliases to other concrete types¶

            Deprecated since version 3.8, will be removed in version 3.13: The typing.io namespace is deprecated and will be removed. These types should be directly imported from typing instead.

        class typing. Pattern ¶ class typing. Match ¶

        Deprecated aliases corresponding to the return types from re.compile() and re.match() .

        These types (and the corresponding functions) are generic over AnyStr . Pattern can be specialised as Pattern[str] or Pattern[bytes] ; Match can be specialised as Match[str] or Match[bytes] .

          Deprecated since version 3.8, will be removed in version 3.13: The typing.re namespace is deprecated and will be removed. These types should be directly imported from typing instead.

          Deprecated since version 3.9: Classes Pattern and Match from re now support [] . See PEP 585 and Generic Alias Type .

        class typing. Text ¶

        Deprecated alias for str .

        Text is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for unicode .

        Use Text to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:

            def add_unicode_checkmark(text: Text) -> Text:
                return text + u' \u2713'
            

          Added in version 3.5.2.

          Deprecated since version 3.11: Python 2 is no longer supported, and most type checkers also no longer support type checking Python 2 code. Removal of the alias is not currently planned, but users are encouraged to use str instead of Text .

        Aliases to container ABCs in collections.abc ¶

        class typing. AbstractSet ( Collection[T_co] ) ¶

        Deprecated alias to collections.abc.Set .

          Deprecated since version 3.9: collections.abc.Set now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. ByteString ( Sequence[int] ) ¶

        This type represents the types bytes , bytearray , and memoryview of byte sequences.

          Deprecated since version 3.9, will be removed in version 3.14: Prefer collections.abc.Buffer , or a union like bytes | bytearray | memoryview .

        class typing. Collection ( Sized, Iterable[T_co], Container[T_co] ) ¶

        Deprecated alias to collections.abc.Collection .

          Added in version 3.6.

          Deprecated since version 3.9: collections.abc.Collection now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Container ( Generic[T_co] ) ¶

        Deprecated alias to collections.abc.Container .

          Deprecated since version 3.9: collections.abc.Container now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. ItemsView ( MappingView, AbstractSet[tuple[KT_co, VT_co]] ) ¶

        Deprecated alias to collections.abc.ItemsView .

          Deprecated since version 3.9: collections.abc.ItemsView now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. KeysView ( MappingView, AbstractSet[KT_co] ) ¶

        Deprecated alias to collections.abc.KeysView .

          Deprecated since version 3.9: collections.abc.KeysView now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Mapping ( Collection[KT], Generic[KT, VT_co] ) ¶

        Deprecated alias to collections.abc.Mapping .

        This type can be used as follows:

            def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
                return word_list[word]
            

          Deprecated since version 3.9: collections.abc.Mapping now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. MappingView ( Sized ) ¶

        Deprecated alias to collections.abc.MappingView .

          Deprecated since version 3.9: collections.abc.MappingView now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. MutableMapping ( Mapping[KT, VT] ) ¶

        Deprecated alias to collections.abc.MutableMapping .

          Deprecated since version 3.9: collections.abc.MutableMapping now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. MutableSequence ( Sequence[T] ) ¶

        Deprecated alias to collections.abc.MutableSequence .

          Deprecated since version 3.9: collections.abc.MutableSequence now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. MutableSet ( AbstractSet[T] ) ¶

        Deprecated alias to collections.abc.MutableSet .

          Deprecated since version 3.9: collections.abc.MutableSet now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Sequence ( Reversible[T_co], Collection[T_co] ) ¶

        Deprecated alias to collections.abc.Sequence .

          Deprecated since version 3.9: collections.abc.Sequence now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. ValuesView ( MappingView, Collection[_VT_co] ) ¶

        Deprecated alias to collections.abc.ValuesView .

          Deprecated since version 3.9: collections.abc.ValuesView now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        Aliases to asynchronous ABCs in collections.abc ¶

        class typing. Coroutine ( Awaitable[ReturnType], Generic[YieldType, SendType, ReturnType] ) ¶

        Deprecated alias to collections.abc.Coroutine .

        The variance and order of type variables correspond to those of Generator , for example:

            from collections.abc import Coroutine
            c: Coroutine[list[str], str, int]  # Some coroutine defined elsewhere
            x = c.send('hi')                   # Inferred type of 'x' is list[str]
            async def bar() -> None:
                y = await c                    # Inferred type of 'y' is int
            

          Added in version 3.5.3.

          Deprecated since version 3.9: collections.abc.Coroutine now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. AsyncGenerator ( AsyncIterator[YieldType], Generic[YieldType, SendType] ) ¶

        Deprecated alias to collections.abc.AsyncGenerator .

        An async generator can be annotated by the generic type AsyncGenerator[YieldType, SendType] . For example:

            async def echo_round() -> AsyncGenerator[int, float]:
                sent = yield 0
                while sent >= 0.0:
                    rounded = await round(sent)
                    sent = yield rounded
            

        Unlike normal generators, async generators cannot return a value, so there is no ReturnType type parameter. As with Generator , the SendType behaves contravariantly.

        If your generator will only yield values, set the SendType to None :

            async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
                while True:
                    yield start
                    start = await increment(start)
            

        Alternatively, annotate your generator as having a return type of either AsyncIterable[YieldType] or AsyncIterator[YieldType] :

            async def infinite_stream(start: int) -> AsyncIterator[int]:
                while True:
                    yield start
                    start = await increment(start)
            

          Added in version 3.6.1.

          Deprecated since version 3.9: collections.abc.AsyncGenerator now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. AsyncIterable ( Generic[T_co] ) ¶

        Deprecated alias to collections.abc.AsyncIterable .

          Added in version 3.5.2.

          Deprecated since version 3.9: collections.abc.AsyncIterable now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. AsyncIterator ( AsyncIterable[T_co] ) ¶

        Deprecated alias to collections.abc.AsyncIterator .

          Added in version 3.5.2.

          Deprecated since version 3.9: collections.abc.AsyncIterator now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Awaitable ( Generic[T_co] ) ¶

        Deprecated alias to collections.abc.Awaitable .

          Added in version 3.5.2.

          Deprecated since version 3.9: collections.abc.Awaitable now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        Aliases to other ABCs in collections.abc ¶

        class typing. Iterable ( Generic[T_co] ) ¶

        Deprecated alias to collections.abc.Iterable .

          Deprecated since version 3.9: collections.abc.Iterable now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Iterator ( Iterable[T_co] ) ¶

        Deprecated alias to collections.abc.Iterator .

          Deprecated since version 3.9: collections.abc.Iterator now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        typing. Callable ¶

        Deprecated alias to collections.abc.Callable .

        See Annotating callable objects for details on how to use collections.abc.Callable and typing.Callable in type annotations.

          Deprecated since version 3.9: collections.abc.Callable now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

          Changed in version 3.10: Callable now supports ParamSpec and Concatenate . See PEP 612 for more details.

        class typing. Generator ( Iterator[YieldType], Generic[YieldType, SendType, ReturnType] ) ¶

        Deprecated alias to collections.abc.Generator .

        A generator can be annotated by the generic type Generator[YieldType, SendType, ReturnType] . For example:

            def echo_round() -> Generator[int, float, str]:
                sent = yield 0
                while sent >= 0:
                    sent = yield round(sent)
                return 'Done'
            

        Note that unlike many other generics in the typing module, the SendType of Generator behaves contravariantly, not covariantly or invariantly.

        If your generator will only yield values, set the SendType and ReturnType to None :

            def infinite_stream(start: int) -> Generator[int, None, None]:
                while True:
                    yield start
                    start += 1
            

        Alternatively, annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType] :

            def infinite_stream(start: int) -> Iterator[int]:
                while True:
                    yield start
                    start += 1
            

          Deprecated since version 3.9: collections.abc.Generator now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Hashable ¶

        Deprecated alias to collections.abc.Hashable .

          Deprecated since version 3.12: Use collections.abc.Hashable directly instead.

        class typing. Reversible ( Iterable[T_co] ) ¶

        Deprecated alias to collections.abc.Reversible .

          Deprecated since version 3.9: collections.abc.Reversible now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. Sized ¶

        Deprecated alias to collections.abc.Sized .

          Deprecated since version 3.12: Use collections.abc.Sized directly instead.

        Aliases to contextlib ABCs¶

        class typing. ContextManager ( Generic[T_co] ) ¶

        Deprecated alias to contextlib.AbstractContextManager .

          Added in version 3.5.4.

          Deprecated since version 3.9: contextlib.AbstractContextManager now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        class typing. AsyncContextManager ( Generic[T_co] ) ¶

        Deprecated alias to contextlib.AbstractAsyncContextManager .

          Added in version 3.6.2.

          Deprecated since version 3.9: contextlib.AbstractAsyncContextManager now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

        Deprecation Timeline of Major Features¶

        Certain features in typing are deprecated and may be removed in a future version of Python. The following table summarizes major deprecations for your convenience. This is subject to change, and not all deprecations are listed.

        Feature                                  Deprecated in  Projected removal                                        PEP/issue
                                                                                                                                  
        typing.io and typing.re submodules       3.8            3.13                                                     bpo-38291
                                                                                                                                  
        typing versions of standard collections  3.9            Undecided (see Deprecated aliases for more information)  PEP 585  
                                                                                                                                  
        typing.ByteString                        3.9            3.14                                                     gh-91896 
                                                                                                                                  
        typing.Text                              3.11           Undecided                                                gh-92332 
                                                                                                                                  
        typing.Hashable and typing.Sized         3.12           Undecided                                                gh-94309 
                                                                                                                                  
        typing.TypeAlias                         3.12           Undecided                                                PEP 695  
                                                                                                                                  
        

        Table of Contents

          * typing — Support for type hints
              + Specification for the Python Type System
              + Type aliases
              + NewType
              + Annotating callable objects
              + Generics
              + Annotating tuples
              + The type of class objects
              + User-defined generic types
              + The Any type
              + Nominal vs structural subtyping
              + Module contents
                  o Special typing primitives
                      - Special types
                      - Special forms
                      - Building generic types and type aliases
                      - Other special directives
                  o Protocols
                  o ABCs for working with IO
                  o Functions and decorators
                  o Introspection helpers
                  o Constant
                  o Deprecated aliases
                      - Aliases to built-in types
                      - Aliases to types in collections
                      - Aliases to other concrete types
                      - Aliases to container ABCs in collections.abc
                      - Aliases to asynchronous ABCs in collections.abc
                      - Aliases to other ABCs in collections.abc
                      - Aliases to contextlib ABCs
              + Deprecation Timeline of Major Features

        Previous topic

        Development Tools

        Next topic

        pydoc — Documentation generator and online help system

        This Page

          * Report a Bug
          * Show Source
      «

  Navigation

    * index
    * modules |
    * next |
    * previous |
    * 
    * Python »
    * 
    * 
    * 3.12.5 Documentation »
    * The Python Standard Library »
    * Development Tools »
    * typing — Support for type hints
    * |
    * Theme Auto Light Dark |
  © Copyright 2001-2024, Python Software Foundation.
  This page is licensed under the Python Software Foundation License Version 2.
  Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  See History and License for more information.

  The Python Software Foundation is a non-profit corporation. Please donate.

  Last updated on Aug 16, 2024 (06:09 UTC). Found a bug?
  Created using Sphinx 8.0.2.
typing — Support for type hints
https://docs.python.org/3/library/typing.html
Contributors to Wikimedia projects
2024-06-20T23:46:36Z
<div><div>
							

						<p>From Wikipedia, the free encyclopedia</p>
					</div><div>
<p>This article is about entering text. For classification of data into types in programming, see <a href="https://en.wikipedia.org/wiki/Type_system">Type system</a>. For China-related meanings, see <a href="https://en.wikipedia.org/wiki/Taiping_(disambiguation)">Taiping</a>.</p>

<figure><a href="https://en.wikipedia.org/wiki/File:Computer_keyboard.png"></a><figcaption>Person typing on a <a href="https://en.wikipedia.org/wiki/Laptop">laptop</a> keyboard</figcaption></figure>
<figure><span></span><figcaption>Video of typing on a notebook computer keyboard</figcaption></figure>
<p><b>Typing</b> is the process of writing or inputting text by pressing keys on a <a href="https://en.wikipedia.org/wiki/Typewriter">typewriter</a>, <a href="https://en.wikipedia.org/wiki/Computer_keyboard">computer keyboard</a>, <a href="https://en.wikipedia.org/wiki/Mobile_phone">mobile phone</a>, or <a href="https://en.wikipedia.org/wiki/Calculator">calculator</a>. It can be distinguished from other means of text input, such as <a href="https://en.wikipedia.org/wiki/Handwriting_recognition">handwriting</a> and <a href="https://en.wikipedia.org/wiki/Speech_recognition">speech recognition</a>. Text can be in the form of letters, numbers and other symbols. The world's first typist was Lillian Sholes from <a href="https://en.wikipedia.org/wiki/Wisconsin">Wisconsin</a> in the <a href="https://en.wikipedia.org/wiki/United_States">United States</a>,<sup><a href="#cite_note-wisconsinhistory.org-1"><span>[</span>1<span>]</span></a></sup><sup><a href="#cite_note-e-referencedesk.com-2"><span>[</span>2<span>]</span></a></sup> the daughter of <a href="https://en.wikipedia.org/wiki/Christopher_Sholes">Christopher Sholes</a>, who invented the first practical typewriter.<sup><a href="#cite_note-wisconsinhistory.org-1"><span>[</span>1<span>]</span></a></sup>
</p><p><a href="https://en.wikipedia.org/wiki/User_interface">User interface</a> features such as <a href="https://en.wikipedia.org/wiki/Spell_checker">spell checker</a> and <a href="https://en.wikipedia.org/wiki/Autocomplete">autocomplete</a> serve to facilitate and speed up typing and to prevent or correct errors the typist may make.
</p>



<p><b>Hunt and peck</b> (<i>two-fingered typing</i>) is a common form of typing in which the typist presses each key individually. Instead of relying on the memorized position of keys, the typist must find each key by sight. Although good accuracy may be achieved, the use of this method may also prevent the typist from being able to see what has been typed without glancing away from the keys, and any <a href="https://en.wikipedia.org/wiki/Typographical_error">typing errors</a> that are made may not be noticed immediately.  Due to the fact that only a few fingers are used in this technique, this also means that the fingers are forced to move a much greater distance.
</p>
<figure><a href="https://en.wikipedia.org/wiki/File:Civilian_Conservation_Corps,_Third_Corps_Area,_typing_class_with_W.P.A._instructor_-_NARA_-_197144.jpg"></a><figcaption>Civilian Conservation Corps typing class, 1933</figcaption></figure>

<figure><a href="https://en.wikipedia.org/wiki/File:Touch_typing.svg"></a><figcaption>Typing zones on a <a href="https://en.wikipedia.org/wiki/QWERTY">QWERTY</a> keyboard for each finger taken from <a href="https://en.wikipedia.org/wiki/KTouch">KTouch</a> (home row keys are circled)</figcaption></figure>

<p>In this technique, the typist keeps their eyes on the source copy at all times. Touch typing also involves the use of the <a href="https://en.wikipedia.org/wiki/Home_row">home row</a> method, where typists rest their wrist down, rather than lifting up and typing (which can cause <a href="https://en.wikipedia.org/wiki/Carpal_tunnel_syndrome">carpal tunnel syndrome</a> <sup>[<i><a href="https://en.wikipedia.org/wiki/Wikipedia:Citation_needed"><span>citation needed</span></a></i>]</sup>). To avoid this, typists should sit up tall, leaning slightly forward from the waist, place their feet flat on the floor in front of them with one foot slightly in front of the other, and keep their elbows close to their sides with forearms slanted slightly upward to the keyboard; fingers should be curved slightly and rest on the home row.
</p><p>Many touch typists also use <a href="https://en.wikipedia.org/wiki/Keyboard_shortcut">keyboard shortcuts</a> when typing on a computer. This allows them to edit their document without having to take their hands off the keyboard to use a mouse. An example of a keyboard shortcut is pressing the <kbd>Ctrl</kbd> key plus the <kbd>S</kbd> key to save a document as they type, or the <kbd>Ctrl</kbd> key plus the <kbd>Z</kbd> key to undo a mistake. Other shortcuts are the <kbd>Ctrl</kbd> key plus the <kbd>C</kbd> to copy and the <kbd>Ctrl</kbd> key and the <kbd>V</kbd> key to paste, and the <kbd>Ctrl</kbd> key and the <kbd>X</kbd> key to cut. Many experienced typists can feel or sense when they have made an error and can hit the <kbd>← Backspace</kbd> key and make the correction with no increase in time between keystrokes.
</p>

<p>There are many idiosyncratic typing styles in between novice-style "hunt and peck" and touch typing. For example, many "hunt and peck" typists have the <a href="https://en.wikipedia.org/wiki/Keyboard_layout">keyboard layout</a> memorized and are able to type while focusing their gaze on the screen. Some use just two fingers, while others use 3–6 fingers. Some use their fingers very consistently, with the same finger being used to type the same character every time, while others vary the way they use their fingers.
</p><p>One study examining 30 subjects, of varying different styles and expertise, has found minimal difference in typing speed between touch typists and self-taught hybrid typists.<sup><a href="#cite_note-3"><span>[</span>3<span>]</span></a></sup> According to the study, "The number of fingers does not determine typing speed... People using self-taught typing strategies were found to be as fast as trained typists... instead of the number of fingers, there are other factors that predict typing speed... fast typists... keep their hands fixed on one position, instead of moving them over the keyboard, and more consistently use the same finger to type a certain letter." To quote Prof. Dr. Anna Feit: "We were surprised to observe that people who took a typing course, performed at similar average speed and accuracy, as those that taught typing to themselves and only used 6 fingers on average."<sup><a href="#cite_note-4"><span>[</span>4<span>]</span></a></sup>
</p>

<p>A late 20th century trend in typing, primarily used with devices with small keyboards (such as PDAs and Smartphones), is <i>thumbing</i> or thumb typing.  This can be accomplished using either only one thumb or both the thumbs, with more proficient typists reaching speeds of 100 words per minute.<sup><a href="#cite_note-5"><span>[</span>5<span>]</span></a></sup> Similar to desktop keyboards and input devices, if a user overuses keys which need hard presses and/or have small and unergonomic layouts, it could cause thumb tendonitis or other <a href="https://en.wikipedia.org/wiki/Repetitive_strain_injury">repetitive strain injury</a>.<sup><a href="#cite_note-6"><span>[</span>6<span>]</span></a></sup>
</p>


<p><a href="https://en.wikipedia.org/wiki/Words_per_minute">Words per minute</a> (WPM) is a measure of typing speed, commonly used in <a href="https://en.wikipedia.org/wiki/Recruitment">recruitment</a>. For the purposes of WPM measurement a word is standardized to five characters or keystrokes. Therefore, "brown" counts as one word, but "mozzarella" counts as two.
</p><p>The benefits of a standardized measurement of input speed are that it enables comparison across language and hardware boundaries. The speed of an <a href="https://en.wikipedia.org/wiki/Afrikaans">Afrikaans</a>-speaking operator in <a href="https://en.wikipedia.org/wiki/Cape_Town">Cape Town</a> can be compared with a <a href="https://en.wikipedia.org/wiki/French_language">French</a>-speaking operator in <a href="https://en.wikipedia.org/wiki/Paris">Paris</a>.
</p><p>Today, even <a href="https://en.wikipedia.org/wiki/Written_Chinese">Written Chinese</a> can be typed very quickly using the combination of a software prediction system and by typing their sounds in <a href="https://en.wikipedia.org/wiki/Pinyin">Pinyin</a>.<sup><a href="#cite_note-7"><span>[</span>7<span>]</span></a></sup> Such prediction software even allows typing short-hand forms while producing complete characters. For example, the phrase "nǐ chī le ma" (你吃了吗) meaning "Have you eaten yet?" can be typed with just 4 strokes: "nclm".
</p>

<p>In one study of average computer users, the average rate for transcription was 33 words per minute, and 19 words per minute for composition.<sup><a href="#cite_note-8"><span>[</span>8<span>]</span></a></sup> In the same study, when the group was divided into "fast", "moderate" and "slow" groups, the average speeds were 40 wpm, 35 wpm, and 23 wpm respectively. An average professional <a href="https://en.wikipedia.org/wiki/Copy_typist">typist</a> reaches 50 to 80 wpm, while some positions can require 80 to 95 wpm (usually the minimum required for dispatch positions and other typing jobs), and some advanced typists work at speeds above 120 wpm.<sup><a href="#cite_note-Ayres&amp;Martinás2005-9"><span>[</span>9<span>]</span></a></sup><sup><a href="#cite_note-10"><span>[</span>10<span>]</span></a></sup> Two-finger typists, sometimes also referred to as "hunt and peck" typists, commonly reach sustained speeds of about 37 wpm for memorized text and 27 wpm when copying text, but in bursts may be able to reach speeds of 60 to 70 wpm.<sup><a href="#cite_note-multiple-11"><span>[</span>11<span>]</span></a></sup>  From the 1920s through the 1970s, typing speed (along with shorthand speed) was an important secretarial qualification and typing contests were popular and often publicized by typewriter companies as promotional tools.
</p><p>A less common measure of the speed of a typist, CPM is used to identify the number of characters typed per minute. This is a common measurement for typing programs, or typing tutors, as it can give a more accurate measure of a person's typing speed without having to type for a prolonged period of time. The common conversion factor between WPM and CPM is 5. It is also used occasionally for associating the speed of a reader with the amount they have read. CPM has also been applied to 20th century printers, but modern faster printers more commonly use PPM (pages per minute).
</p><p>The fastest typing speed ever, 216 words per minute, was achieved by Stella Pajunas-Garnand from Chicago in 1946 in one minute on an <a href="https://en.wikipedia.org/wiki/IBM_Electric_typewriter">IBM electric</a><sup><a href="#cite_note-12"><span>[</span>12<span>]</span></a></sup><sup><a href="#cite_note-13"><span>[</span>13<span>]</span></a></sup><sup><a href="#cite_note-14"><span>[</span>14<span>]</span></a></sup><sup><a href="#cite_note-15"><span>[</span>15<span>]</span></a></sup> using the <a href="https://en.wikipedia.org/wiki/QWERTY">QWERTY</a> keyboard layout.<sup><a href="#cite_note-16"><span>[</span>16<span>]</span></a></sup><sup><a href="#cite_note-17"><span>[</span>17<span>]</span></a></sup> As of 2005, writer <a href="https://en.wikipedia.org/wiki/Barbara_Blackburn_(typist)">Barbara Blackburn</a> was the fastest <a href="https://en.wikipedia.org/wiki/English_language">English language</a> typist in the world, according to <i><a href="https://en.wikipedia.org/wiki/The_Guinness_Book_of_World_Records">The Guinness Book of World Records</a></i>. Using the <a href="https://en.wikipedia.org/wiki/Dvorak_keyboard_layout">Dvorak keyboard layout</a>, she had maintained 150 wpm for 50 minutes, and 170 wpm for shorter periods, with a peak speed of 212 wpm. Barbara Blackburn, who failed her <a href="https://en.wikipedia.org/wiki/QWERTY">QWERTY</a> typing class in high school, first encountered the Dvorak layout in 1938 and then she quickly learned to achieve very high speeds of typing, also she occasionally toured giving speed-typing demonstrations during her secretarial career. She appeared on <i><a href="https://en.wikipedia.org/wiki/Late_Night_with_David_Letterman">Late Night with David Letterman</a></i> on January 24, 1985, but felt that Letterman made a spectacle of her.<sup><a href="#cite_note-Letterman-18"><span>[</span>18<span>]</span></a></sup>
</p><p>The recent emergence of several competitive typing websites has allowed fast typists on computer keyboards to emerge along with new records, though many of these are unverifiable. Some notable, verified records include 255 wpm on a one-minute, random-word test by a user under the username slekap and occasionally bailey,<sup><a href="#cite_note-19"><span>[</span>19<span>]</span></a></sup> 213 wpm on a 1-hour, random-word test by Joshua Hu,<sup><a href="#cite_note-20"><span>[</span>20<span>]</span></a></sup> 221 wpm average on 10 random quotes by Joshua Hu,<sup><a href="#cite_note-21"><span>[</span>21<span>]</span></a></sup> and first place in the 2020 <a href="https://en.wikipedia.org/wiki/Ultimate_Typing_Championship">Ultimate Typing Championship</a> by Anthony Ermollin based on an average of 180.88 wpm on texts of various lengths.<sup><a href="#cite_note-22"><span>[</span>22<span>]</span></a></sup><sup><a href="#cite_note-23"><span>[</span>23<span>]</span></a></sup> These three people are the most commonly cited fastest typists in online typing communities.<sup>[<i><a href="https://en.wikipedia.org/wiki/Wikipedia:Citation_needed"><span>citation needed</span></a></i>]</sup> All of their records were set on the <a href="https://en.wikipedia.org/wiki/QWERTY">QWERTY</a> keyboard layout.
</p><p>Using a personalized <a href="https://en.wikipedia.org/wiki/User_interface">interface</a>, <a href="https://en.wikipedia.org/wiki/Physicist">physicist</a> <a href="https://en.wikipedia.org/wiki/Stephen_Hawking">Stephen Hawking</a>, who suffered from <a href="https://en.wikipedia.org/wiki/Amyotrophic_lateral_sclerosis">amyotrophic lateral sclerosis</a>, managed to type 15 wpm with a switch and adapted software created by Walt Woltosz. Due to a slowdown of his motor skills, his interface was upgraded with an <a href="https://en.wikipedia.org/wiki/Thermographic_camera">infrared camera</a> that detected "twitches in the cheek muscle under the eye."<sup><a href="#cite_note-hawkingcamera-24"><span>[</span>24<span>]</span></a></sup> His typing speed decreased to approximately one word per minute in the later part of his life.<sup><a href="#cite_note-25"><span>[</span>25<span>]</span></a></sup>
</p>

<p>The numeric entry, or 10-key, speed is a measure of one's ability to manipulate a numeric keypad. Generally, it is measured in keystrokes per hour (KPH).
</p>
<div><h2>Text-entry research</h2><p><span><span>[</span><a href="https://en.wikipedia.org/w/index.php?title=Typing&amp;action=edit&amp;section=9"><span>edit</span></a><span>]</span></span></p></div>


<p>With the introduction of computers and word-processors, there has been a change in how text-entry is performed. In the past, using a typewriter, speed was measured with a stopwatch and errors were tallied by hand. With the current technology, document preparation is more about using word-processors as a composition aid, changing the meaning of error rate and how it is measured. Research performed by R. William Soukoreff and I. Scott MacKenzie, has led to a discovery of the application of a well-known algorithm. Through the use of this algorithm and accompanying analysis technique, two statistics were used, <i>minimum string distance error rate</i> (MSD error rate) and <i>keystrokes per character</i> (KSPC). The two advantages of this technique include:
</p>
<ul><li>Participants are allowed to enter text naturally, since they may commit errors and correct them.</li>
<li>The identification of errors and generation of error rate statistics is easy to automate.</li></ul>
<div><h4>Deconstructing the text input process</h4><p><span><span>[</span><a href="https://en.wikipedia.org/w/index.php?title=Typing&amp;action=edit&amp;section=11"><span>edit</span></a><span>]</span></span></p></div>
<p>Through analysis of keystrokes, the keystrokes of the input stream were divided into four classes: Correct (C), Incorrect Fixed (IF), Fixes (F), and Incorrect Not Fixed (INF). These key stroke classification are broken down into the following
</p>
<ul><li>The two classes Correct and Incorrect Not Fixed comprise all of the characters in transcribed text.</li>
<li>Fixes (F) keystrokes are easy to identify, and include keystrokes such as backspace, delete, cursor movements, and modifier keys.</li>
<li>Incorrect Fixed (IF) keystrokes are found in the input stream, but not the transcribed text, and are not editing keys.</li></ul>
<p>Using these classes, the Minimum String Distance Error Rate and the Key Strokes per Character statistics can both be calculated.
</p>
<div><h4>Minimum string distance error rate</h4><p><span><span>[</span><a href="https://en.wikipedia.org/w/index.php?title=Typing&amp;action=edit&amp;section=12"><span>edit</span></a><span>]</span></span></p></div>
<p>The minimum string distance (MSD) is the number of "primitives" which is the number of insertions, deletions, or substitutions to transform one string into another. The following equation was found for the MSD Error Rate.
</p><p><i>MSD Error Rate</i> = <span></span>
</p>
<div><h4><span></span>Key strokes per character (KSPC)</h4><p><span><span>[</span><a href="https://en.wikipedia.org/w/index.php?title=Typing&amp;action=edit&amp;section=13"><span>edit</span></a><span>]</span></span></p></div>
<p>With the minimum string distance error, errors that are corrected do not appear in the transcribed text. The following example shows why this can be an important class of errors to consider:
</p><p><i>Presented Text</i>:       the quick brown<br/>
<i>Input Stream</i>:         the quix&lt;-ck brown<br/>
<i>Transcribed Text</i>:     the quick brown
</p><p>In the above example, the incorrect character ('x') was deleted with a backspace ('&lt;-'). Since these errors do not appear in the transcribed text, the MSD error rate is 0%. That is the purpose of the key strokes per character (KSPC) statistic.
</p><p><i>KSPC</i> = <span></span>
</p><p>There are some shortcomings of the KSPC statistic, such as:
</p>
<ul><li>High KSPC values can be related to either many errors which were corrected, or few errors which were not corrected; however, there is no way to distinguish the two.</li>
<li>KSPC depends on the text input method, and cannot be used to meaningfully compare two different input methods, such as a <a href="https://en.wikipedia.org/wiki/QWERTY">QWERTY</a> keyboard and a multi-tap device.</li>
<li>There is no obvious way to combine KSPC and MSD into an overall error rate, even though they have an inverse relationship.</li></ul>

<p>Using the <a href="https://en.wikipedia.org/wiki/Classes_of_computers">classes</a> described above, further metrics were defined by R. William Soukoreff and I.Scott MacKenzie:
</p><p><i>Error correction efficiency</i> refers to the ease with which the participant performed error correction.
</p>
<ul><li><i>Correction Efficiency</i> = IF/F</li></ul>
<p><i>Participant conscientiousness</i> is the ratio of corrected errors to the total number of error, which helps distinguish <a href="https://en.wikipedia.org/wiki/Perfectionism_(psychology)">perfectionists</a> from apathetic participants.
</p>
<ul><li><i>Participant Conscientiousness</i> = IF / (IF + INF)</li></ul>
<p>If C represents the amount of useful information transferred, INF, IF, and F represent the proportion of bandwidth wasted.
</p>
<ul><li><i>Utilized Bandwidth</i> = C / (C + INF + IF + F)</li>
<li><i>Wasted Bandwidth</i> = (INF + IF + F)/ (C + INF + IF + F)</li></ul>

<p>The classes described also provide an intuitive definition of total <a href="https://en.wikipedia.org/wiki/Error">error</a> rate:
</p>
<ul><li><i>Total Error Rate</i> = ((INF + IF)/ (C + INF + IF)) * 100%</li>
<li><i>Not Corrected Error Rate</i> = (INF/ (C + INF + IF)) * 100%</li>
<li><i>Corrected Error Rate</i> = (IF/ (C + INF + IF)) * 100%</li></ul>
<p>Since these three error rates are ratios, they are comparable between different devices, something that cannot be done with the KSPC statistic, which is device dependent.<sup><a href="#cite_note-26"><span>[</span>26<span>]</span></a></sup>
</p>
<div><h3>Tools for text entry research</h3><p><span><span>[</span><a href="https://en.wikipedia.org/w/index.php?title=Typing&amp;action=edit&amp;section=16"><span>edit</span></a><span>]</span></span></p></div>
<p>Currently, two tools are publicly available for text entry researchers to record text entry performance metrics. The first is TEMA<sup><a href="#cite_note-27"><span>[</span>27<span>]</span></a></sup> that runs only on the <a href="https://en.wikipedia.org/wiki/Android_(operating_system)">Android (operating system)</a>. The second is <a href="http://www.asarif.com/resources/WebTEM/">WebTEM</a> that runs on any device with a modern Web browser, and works with almost all text entry technique.<sup><a href="#cite_note-28"><span>[</span>28<span>]</span></a></sup>
</p>

<p><a href="https://en.wikipedia.org/wiki/Keystroke_dynamics">Keystroke dynamics</a>, or <i>typing dynamics</i>, is the obtaining of detailed timing information that describes exactly when each key was pressed and when it was released as a person is typing at a <a href="https://en.wikipedia.org/wiki/Computer_keyboard">computer keyboard</a> for <a href="https://en.wikipedia.org/wiki/Biometric">biometric</a> identification,<sup><a href="#cite_note-29"><span>[</span>29<span>]</span></a></sup> similar to <a href="https://en.wikipedia.org/wiki/Speaker_recognition">speaker recognition</a>.<sup><a href="#cite_note-30"><span>[</span>30<span>]</span></a></sup> Data needed to analyze keystroke dynamics is obtained by <a href="https://en.wikipedia.org/wiki/Keystroke_logging">keystroke logging</a>.
</p><p>The <a href="https://en.wikipedia.org/wiki/Biometric">behavioral biometric</a> of Keystroke Dynamics uses the manner and rhythm in which an individual types characters on a keyboard or keypad.<sup><a href="#cite_note-31"><span>[</span>31<span>]</span></a></sup>
</p>

<figure><a href="https://en.wikipedia.org/wiki/File:War_correspondent_typing_his_despatch.jpg"></a><figcaption>War correspondent typing his dispatch in a wood outside Arnhem, 1944</figcaption></figure>
<ul><li><a href="https://en.wikipedia.org/wiki/Muscle_memory">Muscle memory</a></li>
<li><a href="https://en.wikipedia.org/wiki/Stenotype">Stenotype</a></li>
<li><a href="https://en.wikipedia.org/wiki/Copy_typist">Copy typist</a></li>
<li><a href="https://en.wikipedia.org/wiki/Audio_typist">Audio typist</a></li>
<li><a href="https://en.wikipedia.org/wiki/Data_entry_clerk">Data entry clerk</a></li>
<li><a href="https://en.wikipedia.org/wiki/Speed_typing_contest">Speed typing contest</a></li>
<li><a href="https://en.wikipedia.org/wiki/Typesetting">Typesetting</a></li>
<li><a href="https://en.wikipedia.org/wiki/Typing_Day">Typing Day</a></li></ul>

<div>
<ol>
<li><span>^ <a href="#cite_ref-wisconsinhistory.org_1-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-wisconsinhistory.org_1-1"><sup><i><b>b</b></i></sup></a></span> <span><cite><a href="http://www.wisconsinhistory.org/whi/fullRecord.asp?id=3196&amp;qstring=http%3A%2F%2Fwww.wisconsinhistory.org%2Fwhi%2Fresults.asp%3Fsubject_narrow%3DInventors">"World's First Typist"</a>. <i>Wisconsin Historical Society</i>. December 2003. <a href="https://web.archive.org/web/20121107022719/http://www.wisconsinhistory.org/whi/fullRecord.asp?id=3196&amp;qstring=http:%2F%2Fwww.wisconsinhistory.org%2Fwhi%2Fresults.asp%3Fsubject_narrow=Inventors">Archived</a> from the original on 2012-11-07<span>. Retrieved <span>2010-09-11</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-e-referencedesk.com_2-0">^</a></b></span> <span><cite><a href="http://www.e-referencedesk.com/resources/state-facts/wisconsin.html">"Wisconsin History Facts"</a>. <i>e-ReferenceDesk</i>. <a href="https://web.archive.org/web/20101119044802/http://www.e-referencedesk.com/resources/state-facts/wisconsin.html">Archived</a> from the original on 2010-11-19<span>. Retrieved <span>2010-09-11</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-3">^</a></b></span> <span><cite><a href="http://phys.org/news/2016-02-ten-fingers-fast.html">"Ten fingers not needed for fast typing, study shows"</a>. <i>phys.org</i>. <a href="https://web.archive.org/web/20160213144457/http://phys.org/news/2016-02-ten-fingers-fast.html">Archived</a> from the original on 2016-02-13<span>. Retrieved <span>2016-02-13</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-4">^</a></b></span> <span><cite>Feit, Anna Maria; Weir, Daryl; Oulasvirta, Antti (2016-05-07). <a href="https://dl.acm.org/doi/10.1145/2858036.2858233">"How We Type: Movement Strategies and Performance in Everyday Typing"</a>. <i>Proceedings of the 2016 CHI Conference on Human Factors in Computing Systems</i>. CHI '16. New York, NY, USA: Association for Computing Machinery. pp. 4262–4273. <a href="https://en.wikipedia.org/wiki/Doi_(identifier)">doi</a>:<a href="https://doi.org/10.1145%2F2858036.2858233">10.1145/2858036.2858233</a>. <a href="https://en.wikipedia.org/wiki/ISBN_(identifier)">ISBN</a> <a href="https://en.wikipedia.org/wiki/Special:BookSources/978-1-4503-3362-7"><bdi>978-1-4503-3362-7</bdi></a>. <a href="https://web.archive.org/web/20231213175117/https://dl.acm.org/doi/10.1145/2858036.2858233">Archived</a> from the original on 2023-12-13<span>. Retrieved <span>2023-12-13</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-5">^</a></b></span> <span><cite>Blakely, Rhys (2 October 2019). <a href="https://www.thetimes.co.uk/article/thumbs-up-for-speedy-smartphone-typists-j78n3jq53">"Thumbs up for speedy smartphone typists"</a>. <i>The Times</i>. <a href="https://web.archive.org/web/20220207131552/https://www.thetimes.co.uk/article/thumbs-up-for-speedy-smartphone-typists-j78n3jq53">Archived</a> from the original on 7 February 2022<span>. Retrieved <span>7 February</span> 2022</span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-6">^</a></b></span> <span><cite><a href="https://www.cbsnews.com/news/smartphone-thumb-texting-tendinitis-plaguing-more-people/">"<span></span>"Smartphone thumb" is plaguing more people, doctors say"</a>. <i>CBS News</i>. 29 March 2017. <a href="https://web.archive.org/web/20220207131543/https://www.cbsnews.com/news/smartphone-thumb-texting-tendinitis-plaguing-more-people/">Archived</a> from the original on 7 February 2022<span>. Retrieved <span>7 February</span> 2022</span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-7">^</a></b></span> <span><cite>Eli MacKinnon (2016-08-01). <a href="https://www.livescience.com/55607-whats-the-fastest-language-for-texting.html">"What's the Fastest Language to Type In?"</a>. <i>livescience.com</i>. <a href="https://web.archive.org/web/20220125222144/https://www.livescience.com/55607-whats-the-fastest-language-for-texting.html">Archived</a> from the original on 2022-01-25<span>. Retrieved <span>2022-01-25</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-8">^</a></b></span> <span><cite>Karat, C.M.; Halverson, C.; Horn, D.; Karat, J. (1999), "Patterns of entry and correction in large vocabulary continuous speech recognition systems", <i>CHI 99 Conference Proceedings</i>, pp. 568–575</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-Ayres&amp;Martinás2005_9-0">^</a></b></span> <span><cite><a href="https://en.wikipedia.org/wiki/Robert_Ayres_(scientist)">Ayres, Robert U</a>; Martinás, Katalin (2005), <a href="https://books.google.com/books?id=ksxK7J95IF8C&amp;q=typists+%22120+words+per+minute%22&amp;pg=PA41">"120 wpm for very skilled typist"</a>, <a href="https://books.google.com/books?id=ksxK7J95IF8C&amp;q=reappraisal+microeconomics"><i>On the Reappraisal of Microeconomics: Economic Growth and Change in a Material World</i></a>, Cheltenham, UK &amp; Northampton, Massachusetts: Edward Elgar Publishing, p. 41, <a href="https://en.wikipedia.org/wiki/ISBN_(identifier)">ISBN</a> <a href="https://en.wikipedia.org/wiki/Special:BookSources/1-84542-272-4"><bdi>1-84542-272-4</bdi></a><span>, retrieved <span>22 November</span> 2010</span></cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-10">^</a></b></span> <span><cite>Ostrach, Teresia R. (1997), <a href="https://web.archive.org/web/20120502164156/http://onlinestudentreadiness.org/documents/TypingSpeed.pdf"><i>Typing Speed: How Fast is Average</i></a> <span>(PDF)</span>, archived from <a href="http://onlinestudentreadiness.org/documents/TypingSpeed.pdf">the original</a> <span>(PDF)</span> on 2012-05-02</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-multiple_11-0">^</a></b></span> <span>Brown, C. M. (1988). Human-computer interface design guidelines. Norwood, NJ: <a href="https://en.wikipedia.org/wiki/Ablex_Publishing">Ablex Publishing</a>.</span>
</li>
<li><span><b><a href="#cite_ref-12">^</a></b></span> <span><cite><a href="http://www.bigsiteofamazingfacts.com/history-of-typewriters">"History of Typewriters | Big Site of Amazing Facts ®"</a>. Bigsiteofamazingfacts.com. 12 September 2007. <a href="https://web.archive.org/web/20130515165828/http://www.bigsiteofamazingfacts.com/history-of-typewriters">Archived</a> from the original on 2013-05-15<span>. Retrieved <span>2012-06-13</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-13">^</a></b></span> <span><cite><a href="http://www.owled.com/typing.html">"World Records in Typing"</a>. Owled.com. 2006-09-02. <a href="https://web.archive.org/web/20180826043812/http://www.owled.com/typing.html">Archived</a> from the original on 2018-08-26<span>. Retrieved <span>2012-06-13</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-14">^</a></b></span> <span><cite><a href="http://www-03.ibm.com/ibm/history/exhibits/modelb/modelb_4509PH04.html">"IBM Archives: Typing posture"</a>. 03.ibm.com. 23 January 2003. <a href="https://web.archive.org/web/20160720232526/http://www-03.ibm.com/ibm/history/exhibits/modelb/modelb_4509PH04.html">Archived</a> from the original on 2016-07-20<span>. Retrieved <span>2012-06-13</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-15">^</a></b></span> <span><cite><a href="http://www.deskstore.com/INFORMATION-1/en/Plan-Your-Office/Believe-it-or-not">"Believe it or not ..."</a> Deskstore.com. <a href="https://web.archive.org/web/20200807234602/https://www.deskstore.com/INFORMATION-1/en/Plan-Your-Office/Believe-it-or-not/">Archived</a> from the original on 2020-08-07<span>. Retrieved <span>2012-06-13</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-16">^</a></b></span> <span><cite>Lowell (2017-03-15). <a href="http://thekindle3books.com/qwerty-vs-dvorak-the-two-great-keyboards-the-time-were-born/">"QWERTY vs Dvorak: The two great keyboards the time were born"</a>. <a href="https://web.archive.org/web/20190119230910/http://thekindle3books.com/qwerty-vs-dvorak-the-two-great-keyboards-the-time-were-born/">Archived</a> from the original on 2019-01-19<span>. Retrieved <span>2019-01-19</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-17">^</a></b></span> <span><cite>RetroFootage. <a href="https://www.pond5.com/stock-footage/75268195/miss-stella-pajunas-worlds-fast-typist-types-ibm-electric-ty.html">"Miss Stella Pajunas, World's Fast Typist, Types On An Ibm Electric Typewriterƒ"</a>. Pond5.com. <a href="https://web.archive.org/web/20190119230948/https://www.pond5.com/stock-footage/75268195/miss-stella-pajunas-worlds-fast-typist-types-ibm-electric-ty.html">Archived</a> from the original on 2019-01-19<span>. Retrieved <span>2019-01-19</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-Letterman_18-0">^</a></b></span> <span><cite>Ranger, Robert. <a href="https://web.archive.org/web/20201108004025/http://rcranger.mysite.syr.edu/dvorak/">"Barbara Blackburn, the World's Fastest Typist"</a>. Archived from <a href="http://rcranger.mysite.syr.edu/dvorak/">the original</a> on 2020-11-08<span>. Retrieved <span>2008-05-08</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-19">^</a></b></span> <span><cite><a href="https://www.youtube.com/watch?v=poGFlGf-jO0"><i>255 WPM Monkey Type 60s (World Record)</i></a>, <a href="https://web.archive.org/web/20220505030022/https://www.youtube.com/watch?v=poGFlGf-jO0&amp;gl=US&amp;hl=en">archived</a> from the original on 2022-05-05<span>, retrieved <span>2022-05-05</span></span></cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-20">^</a></b></span> <span><cite><a href="https://www.youtube.com/watch?v=mBuDtqdx57g"><i>Typing 213 wpm for an hour straight</i></a>, <a href="https://web.archive.org/web/20220505030022/https://www.youtube.com/watch?v=mBuDtqdx57g&amp;gl=US&amp;hl=en">archived</a> from the original on 2022-05-05<span>, retrieved <span>2022-05-05</span></span></cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-21">^</a></b></span> <span><cite><a href="https://data.typeracer.com/pit/race_history?user=joshua728">"TypeRacer Race History"</a>. <i>data.typeracer.com</i>. <a href="https://web.archive.org/web/20201031111847/https://data.typeracer.com/pit/race_history?user=joshua728">Archived</a> from the original on 2020-10-31<span>. Retrieved <span>2022-05-05</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-22">^</a></b></span> <span><cite><a href="https://ultimatetypingchampionship.com/leaderboard#:~:text=Anthony%20%22chack%22%20Ermollin%20has%20been,Typing%20Champion%20and%20win%20$5,000.">"Ultimate Typing Championship"</a>. <i>ultimatetypingchampionship.com</i>. <a href="https://web.archive.org/web/20220415132750/https://ultimatetypingchampionship.com/leaderboard#:~:text=Anthony%20%22chack%22%20Ermollin%20has%20been,Typing%20Champion%20and%20win%20$5,000.">Archived</a> from the original on 2022-04-15<span>. Retrieved <span>2022-05-05</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-23">^</a></b></span> <span><cite><a href="https://www.businesswire.com/news/home/20200825005348/en/Das-Keyboard-Announces-Winners-of-the-Ultimate-Typing-Championship-2020-and-Crowns-Best-Typist-on-the-Planet">"Das Keyboard Announces Winners of the Ultimate Typing Championship 2020 and Crowns Best Typist on the Planet"</a>. <i>www.businesswire.com</i>. 2020-08-25. <a href="https://web.archive.org/web/20220505030033/https://www.businesswire.com/news/home/20200825005348/en/Das-Keyboard-Announces-Winners-of-the-Ultimate-Typing-Championship-2020-and-Crowns-Best-Typist-on-the-Planet">Archived</a> from the original on 2022-05-05<span>. Retrieved <span>2022-05-05</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-hawkingcamera_24-0">^</a></b></span> <span><cite><a href="http://singularityhub.com/2010/05/03/how-does-stephen-hawking-talk-video/">"How Does Stephen Hawking Talk? (video)"</a>. Singularity Hub. 2010-05-03. <a href="https://web.archive.org/web/20120624175500/http://singularityhub.com/2010/05/03/how-does-stephen-hawking-talk-video/">Archived</a> from the original on 2012-06-24<span>. Retrieved <span>2012-06-13</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-25">^</a></b></span> <span><cite><a href="https://www.newscientist.com/article/dn21323-the-man-who-saves-stephen-hawkings-voice.html">"The man who saves Stephen Hawking's voice"</a>. <i>newscientist.com</i>. <a href="https://web.archive.org/web/20120825092537/http://www.newscientist.com/article/dn21323-the-man-who-saves-stephen-hawkings-voice.html">Archived</a> from the original on 2012-08-25<span>. Retrieved <span>2017-09-17</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-26">^</a></b></span> <span><cite><a href="http://www.soukoreff.com/academic/chi03">"Soukoreff, R. W., &amp; MacKenzie, I. S. (2003). Metrics for text entry research: An evaluation of MSD and KSPC, and a new unified error metric. Proceedings of the ACM Conference on Human Factors in Computing Systems - CHI 2003, pp. 113-120. New York: ACM"</a>. <a href="https://web.archive.org/web/20110824164440/http://soukoreff.com/academic/chi03/">Archived</a> from the original on 2011-08-24<span>. Retrieved <span>2013-05-16</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-27">^</a></b></span> <span><cite>Castellucci, Steven J.; MacKenzie, I. Scott (2011-01-01). "Gathering text entry metrics on android devices". <i>CHI '11 Extended Abstracts on Human Factors in Computing Systems</i>. CHI EA '11. New York, NY, USA: ACM. pp. 1507–1512. <a href="https://en.wikipedia.org/wiki/Doi_(identifier)">doi</a>:<a href="https://doi.org/10.1145%2F1979742.1979799">10.1145/1979742.1979799</a>. <a href="https://en.wikipedia.org/wiki/ISBN_(identifier)">ISBN</a> <a href="https://en.wikipedia.org/wiki/Special:BookSources/9781450302685"><bdi>9781450302685</bdi></a>. <a href="https://en.wikipedia.org/wiki/S2CID_(identifier)">S2CID</a> <a href="https://api.semanticscholar.org/CorpusID:2107842">2107842</a>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-28">^</a></b></span> <span><cite>Arif, Ahmed Sabbir; Mazalek, Ali (2016-01-01). "WebTEM". <i>Proceedings of the 2016 ACM International Conference on Interactive Surfaces and Spaces</i>. ISS '16. New York, NY, USA: ACM. pp. 415–420. <a href="https://en.wikipedia.org/wiki/Doi_(identifier)">doi</a>:<a href="https://doi.org/10.1145%2F2992154.2996791">10.1145/2992154.2996791</a>. <a href="https://en.wikipedia.org/wiki/ISBN_(identifier)">ISBN</a> <a href="https://en.wikipedia.org/wiki/Special:BookSources/9781450342483"><bdi>9781450342483</bdi></a>. <a href="https://en.wikipedia.org/wiki/S2CID_(identifier)">S2CID</a> <a href="https://api.semanticscholar.org/CorpusID:16022337">16022337</a>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-29">^</a></b></span> <span><cite><a href="https://web.archive.org/web/20140304233632/http://ai.pku.edu.cn/aiwebsite/research.files/collected%20papers%20-%20others/User%20authentication%20through%20typing%20biometrics%20features.pdf">"User authentication through typing biometrics features"</a> <span>(PDF)</span>. <i>pku.edu.cn</i>. Archived from <a href="http://ai.pku.edu.cn/aiwebsite/research.files/collected%20papers%20-%20others/User%20authentication%20through%20typing%20biometrics%20features.pdf">the original</a> <span>(PDF)</span> on 2014-03-04<span>. Retrieved <span>2013-11-14</span></span>.</cite><span></span></span>
</li>
<li><span><b><a href="#cite_ref-30">^</a></b></span> <span><cite>Robert Moskovitch, Clint Feher, Arik Messerman, Niklas Kirschnick, Tarik Mustafic, Ahmet Camtepe, Bernhard Löhlein, Ulrich Heister, <a href="https://en.wikipedia.org/wiki/Sebastian_M%C3%B6ller">Sebastian Möller</a>, Lior Rokach, Yuval Elovici (2009). <a href="http://www.ise.bgu.ac.il/faculty/liorr/idth.pdf"><i>Identity theft, computers and behavioral biometrics</i></a> <span>(PDF)</span>. Proceedings of the IEEE International Conference on Intelligence and Security Informatics. pp. 155–160. <a href="https://web.archive.org/web/20130927073140/http://www.ise.bgu.ac.il/faculty/liorr/idth.pdf">Archived</a> <span>(PDF)</span> from the original on 2013-09-27<span>. Retrieved <span>2013-11-14</span></span>.</cite><span></span><span><code>{{<a href="https://en.wikipedia.org/wiki/Template:Cite_conference">cite conference</a>}}</code>:  CS1 maint: multiple names: authors list (<a href="https://en.wikipedia.org/wiki/Category:CS1_maint:_multiple_names:_authors_list">link</a>)</span></span>
</li>
<li><span><b><a href="#cite_ref-31">^</a></b></span> <span><cite><a href="https://ieeexplore.ieee.org/document/491588">"Continuous authentication by analysis of keyboard typing characteristics - IET Conference Publication"</a>. May 1995: 111–114. <a href="https://en.wikipedia.org/wiki/Doi_(identifier)">doi</a>:<a href="https://doi.org/10.1049%2Fcp%3A19950480">10.1049/cp:19950480</a>. <a href="https://web.archive.org/web/20201001045003/https://ieeexplore.ieee.org/document/491588">Archived</a> from the original on 2020-10-01<span>. Retrieved <span>2019-12-07</span></span>.</cite><span></span> </span>
</li>
</ol></div>

<div>
<p><span><span></span></span></p>
<p>Wikiversity has learning resources about <i><b><a href="https://en.wikiversity.org/wiki/Typing"> Typing</a></b></i></p></div>
<ul><li><span><a href="https://en.wikipedia.org/wiki/File:Commons-logo.svg"></a></span> Media related to <a href="https://commons.wikimedia.org/wiki/Category:Typing">Typing</a> at Wikimedia Commons</li></ul>





</div></div>||||I||||Jump to content
      Main menu
                Main menu
              move to sidebar hide
                Navigation
                  * Main page
                  * Contents
                  * Current events
                  * Random article
                  * About Wikipedia
                  * Contact us
                  * Donate
                Contribute
                  * Help
                  * Learn to edit
                  * Community portal
                  * Recent changes
                  * Upload file
      Search
          Search
        Appearance
            * Create account
            * Log in
      Personal tools
              * Create account
              * Log in
            Pages for logged out editors learn more
              * Contributions
              * Talk

              Contents

              move to sidebar hide
                * (Top)
                * 1 Techniques
                Toggle Techniques subsection
                    + 1.1 Hunt and peck
                    + 1.2 Touch typing
                    + 1.3 Hybrid
                    + 1.4 Thumbing
                * 2 Words per minute
                Toggle Words per minute subsection
                    + 2.1 Alphanumeric entry
                    + 2.2 Numeric entry
                * 3 Text-entry research
                Toggle Text-entry research subsection
                    + 3.1 Error analysis
                        o 3.1.1 Deconstructing the text input process
                        o 3.1.2 Minimum string distance error rate
                        o 3.1.3 Key strokes per character (KSPC)
                        o 3.1.4 Further metrics
                        o 3.1.5 Total error rate
                    + 3.2 Tools for text entry research
                * 4 Keystroke dynamics
                * 5 See also
                * 6 References
                * 7 External links
        Toggle the table of contents

      Typing

        30 languages
              * Afrikaans
              * العربية
              * भोजपुरी
              * Български
              * Català
              * Čeština
              * Español
              * Esperanto
              * Euskara
              * فارسی
              * Français
              * Galego
              * 한국어
              * हिन्दी
              * Bahasa Indonesia
              * Italiano
              * Magyar
              * Nederlands
              * 日本語
              * Português
              * Русский
              * Slovenčina
              * کوردی
              * Српски / srpski
              * Suomi
              * తెలుగు
              * Tiếng Việt
              * ייִדיש
              * 粵語
              * 中文
              Edit links
                  * Article
                  * Talk
              English
                  * Read
                  * Edit
                  * View history
              Tools
                        Tools
                      move to sidebar hide
                        Actions
                          * Read
                          * Edit
                          * View history
                        General
                          * What links here
                          * Related changes
                          * Upload file
                          * Special pages
                          * Permanent link
                          * Page information
                          * Cite this page
                          * Get shortened URL
                          * Download QR code
                          * Wikidata item
                        Print/export
                          * Download as PDF
                          * Printable version
                        In other projects
                          * Wikimedia Commons
                          * Wikiversity
                  Appearance
                move to sidebar hide
            From Wikipedia, the free encyclopedia
              This article is about entering text. For classification of data into types in programming, see Type system. For China-related meanings, see Taiping.
                  This article possibly contains original research. Please improve it by verifying the claims made and adding inline citations . Statements consisting only of original research should be removed. ( March 2017 ) (Learn how and when to remove this message)
              

              Person typing on a laptop keyboard

              Video of typing on a notebook computer keyboard

              Typing is the process of writing or inputting text by pressing keys on a typewriter, computer keyboard, mobile phone, or calculator. It can be distinguished from other means of text input, such as handwriting and speech recognition. Text can be in the form of letters, numbers and other symbols. The world's first typist was Lillian Sholes from Wisconsin in the United States, [ 1 ] [ 2 ] the daughter of Christopher Sholes, who invented the first practical typewriter. [ 1 ]

              User interface features such as spell checker and autocomplete serve to facilitate and speed up typing and to prevent or correct errors the typist may make.

                Techniques

                [ edit ]

                Hunt and peck

                [ edit ]

              Hunt and peck (two-fingered typing) is a common form of typing in which the typist presses each key individually. Instead of relying on the memorized position of keys, the typist must find each key by sight. Although good accuracy may be achieved, the use of this method may also prevent the typist from being able to see what has been typed without glancing away from the keys, and any typing errors that are made may not be noticed immediately. Due to the fact that only a few fingers are used in this technique, this also means that the fingers are forced to move a much greater distance.

              Civilian Conservation Corps typing class, 1933

                Touch typing

                [ edit ]

              Typing zones on a QWERTY keyboard for each finger taken from KTouch (home row keys are circled)

                Main article: Touch typing

              In this technique, the typist keeps their eyes on the source copy at all times. Touch typing also involves the use of the home row method, where typists rest their wrist down, rather than lifting up and typing (which can cause carpal tunnel syndrome [ citation needed ]). To avoid this, typists should sit up tall, leaning slightly forward from the waist, place their feet flat on the floor in front of them with one foot slightly in front of the other, and keep their elbows close to their sides with forearms slanted slightly upward to the keyboard; fingers should be curved slightly and rest on the home row.

              Many touch typists also use keyboard shortcuts when typing on a computer. This allows them to edit their document without having to take their hands off the keyboard to use a mouse. An example of a keyboard shortcut is pressing the Ctrl key plus the S key to save a document as they type, or the Ctrl key plus the Z key to undo a mistake. Other shortcuts are the Ctrl key plus the C to copy and the Ctrl key and the V key to paste, and the Ctrl key and the X key to cut. Many experienced typists can feel or sense when they have made an error and can hit the ← Backspace key and make the correction with no increase in time between keystrokes.

                Hybrid

                [ edit ]

              There are many idiosyncratic typing styles in between novice-style "hunt and peck" and touch typing. For example, many "hunt and peck" typists have the keyboard layout memorized and are able to type while focusing their gaze on the screen. Some use just two fingers, while others use 3–6 fingers. Some use their fingers very consistently, with the same finger being used to type the same character every time, while others vary the way they use their fingers.

              One study examining 30 subjects, of varying different styles and expertise, has found minimal difference in typing speed between touch typists and self-taught hybrid typists. [ 3 ] According to the study, "The number of fingers does not determine typing speed... People using self-taught typing strategies were found to be as fast as trained typists... instead of the number of fingers, there are other factors that predict typing speed... fast typists... keep their hands fixed on one position, instead of moving them over the keyboard, and more consistently use the same finger to type a certain letter." To quote Prof. Dr. Anna Feit: "We were surprised to observe that people who took a typing course, performed at similar average speed and accuracy, as those that taught typing to themselves and only used 6 fingers on average." [ 4 ]

                Thumbing

                [ edit ]

              A late 20th century trend in typing, primarily used with devices with small keyboards (such as PDAs and Smartphones), is thumbing or thumb typing. This can be accomplished using either only one thumb or both the thumbs, with more proficient typists reaching speeds of 100 words per minute. [ 5 ] Similar to desktop keyboards and input devices, if a user overuses keys which need hard presses and/or have small and unergonomic layouts, it could cause thumb tendonitis or other repetitive strain injury. [ 6 ]

                Words per minute

                [ edit ]
                Further information: Words per minute

              Words per minute (WPM) is a measure of typing speed, commonly used in recruitment. For the purposes of WPM measurement a word is standardized to five characters or keystrokes. Therefore, "brown" counts as one word, but "mozzarella" counts as two.

              The benefits of a standardized measurement of input speed are that it enables comparison across language and hardware boundaries. The speed of an Afrikaans-speaking operator in Cape Town can be compared with a French-speaking operator in Paris.

              Today, even Written Chinese can be typed very quickly using the combination of a software prediction system and by typing their sounds in Pinyin. [ 7 ] Such prediction software even allows typing short-hand forms while producing complete characters. For example, the phrase "nǐ chī le ma" (你吃了吗) meaning "Have you eaten yet?" can be typed with just 4 strokes: "nclm".

                Alphanumeric entry

                [ edit ]

              In one study of average computer users, the average rate for transcription was 33 words per minute, and 19 words per minute for composition. [ 8 ] In the same study, when the group was divided into "fast", "moderate" and "slow" groups, the average speeds were 40 wpm, 35 wpm, and 23 wpm respectively. An average professional typist reaches 50 to 80 wpm, while some positions can require 80 to 95 wpm (usually the minimum required for dispatch positions and other typing jobs), and some advanced typists work at speeds above 120 wpm. [ 9 ] [ 10 ] Two-finger typists, sometimes also referred to as "hunt and peck" typists, commonly reach sustained speeds of about 37 wpm for memorized text and 27 wpm when copying text, but in bursts may be able to reach speeds of 60 to 70 wpm. [ 11 ] From the 1920s through the 1970s, typing speed (along with shorthand speed) was an important secretarial qualification and typing contests were popular and often publicized by typewriter companies as promotional tools.

              A less common measure of the speed of a typist, CPM is used to identify the number of characters typed per minute. This is a common measurement for typing programs, or typing tutors, as it can give a more accurate measure of a person's typing speed without having to type for a prolonged period of time. The common conversion factor between WPM and CPM is 5. It is also used occasionally for associating the speed of a reader with the amount they have read. CPM has also been applied to 20th century printers, but modern faster printers more commonly use PPM (pages per minute).

              The fastest typing speed ever, 216 words per minute, was achieved by Stella Pajunas-Garnand from Chicago in 1946 in one minute on an IBM electric [ 12 ] [ 13 ] [ 14 ] [ 15 ] using the QWERTY keyboard layout. [ 16 ] [ 17 ] As of 2005, writer Barbara Blackburn was the fastest English language typist in the world, according to The Guinness Book of World Records. Using the Dvorak keyboard layout, she had maintained 150 wpm for 50 minutes, and 170 wpm for shorter periods, with a peak speed of 212 wpm. Barbara Blackburn, who failed her QWERTY typing class in high school, first encountered the Dvorak layout in 1938 and then she quickly learned to achieve very high speeds of typing, also she occasionally toured giving speed-typing demonstrations during her secretarial career. She appeared on Late Night with David Letterman on January 24, 1985, but felt that Letterman made a spectacle of her. [ 18 ]

              The recent emergence of several competitive typing websites has allowed fast typists on computer keyboards to emerge along with new records, though many of these are unverifiable. Some notable, verified records include 255 wpm on a one-minute, random-word test by a user under the username slekap and occasionally bailey, [ 19 ] 213 wpm on a 1-hour, random-word test by Joshua Hu, [ 20 ] 221 wpm average on 10 random quotes by Joshua Hu, [ 21 ] and first place in the 2020 Ultimate Typing Championship by Anthony Ermollin based on an average of 180.88 wpm on texts of various lengths. [ 22 ] [ 23 ] These three people are the most commonly cited fastest typists in online typing communities.[ citation needed ] All of their records were set on the QWERTY keyboard layout.

              Using a personalized interface, physicist Stephen Hawking, who suffered from amyotrophic lateral sclerosis, managed to type 15 wpm with a switch and adapted software created by Walt Woltosz. Due to a slowdown of his motor skills, his interface was upgraded with an infrared camera that detected "twitches in the cheek muscle under the eye." [ 24 ] His typing speed decreased to approximately one word per minute in the later part of his life. [ 25 ]

                Numeric entry

                [ edit ]

              The numeric entry, or 10-key, speed is a measure of one's ability to manipulate a numeric keypad. Generally, it is measured in keystrokes per hour (KPH).

                Text-entry research

                [ edit ]
                    This section needs additional citations for verification. Please help improve this article by adding citations to reliable sources in this section. Unsourced material may be challenged and removed.
                    Find sources: "Typing" – news · newspapers · books · scholar · JSTOR ( June 2024 ) (Learn how and when to remove this message)                                                                       
                

                  Error analysis

                  [ edit ]

                With the introduction of computers and word-processors, there has been a change in how text-entry is performed. In the past, using a typewriter, speed was measured with a stopwatch and errors were tallied by hand. With the current technology, document preparation is more about using word-processors as a composition aid, changing the meaning of error rate and how it is measured. Research performed by R. William Soukoreff and I. Scott MacKenzie, has led to a discovery of the application of a well-known algorithm. Through the use of this algorithm and accompanying analysis technique, two statistics were used, minimum string distance error rate (MSD error rate) and keystrokes per character (KSPC). The two advantages of this technique include:

                  * Participants are allowed to enter text naturally, since they may commit errors and correct them.
                  * The identification of errors and generation of error rate statistics is easy to automate.

                  Deconstructing the text input process

                  [ edit ]

                Through analysis of keystrokes, the keystrokes of the input stream were divided into four classes: Correct (C), Incorrect Fixed (IF), Fixes (F), and Incorrect Not Fixed (INF). These key stroke classification are broken down into the following

                  * The two classes Correct and Incorrect Not Fixed comprise all of the characters in transcribed text.
                  * Fixes (F) keystrokes are easy to identify, and include keystrokes such as backspace, delete, cursor movements, and modifier keys.
                  * Incorrect Fixed (IF) keystrokes are found in the input stream, but not the transcribed text, and are not editing keys.

                Using these classes, the Minimum String Distance Error Rate and the Key Strokes per Character statistics can both be calculated.

                  Minimum string distance error rate

                  [ edit ]

                The minimum string distance (MSD) is the number of "primitives" which is the number of insertions, deletions, or substitutions to transform one string into another. The following equation was found for the MSD Error Rate.

                MSD Error Rate =

                  Key strokes per character (KSPC)

                  [ edit ]

                With the minimum string distance error, errors that are corrected do not appear in the transcribed text. The following example shows why this can be an important class of errors to consider:

                Presented Text: the quick brown
                Input Stream: the quix<-ck brown
                Transcribed Text: the quick brown

                In the above example, the incorrect character ('x') was deleted with a backspace ('<-'). Since these errors do not appear in the transcribed text, the MSD error rate is 0%. That is the purpose of the key strokes per character (KSPC) statistic.

                KSPC =

                There are some shortcomings of the KSPC statistic, such as:

                  * High KSPC values can be related to either many errors which were corrected, or few errors which were not corrected; however, there is no way to distinguish the two.
                  * KSPC depends on the text input method, and cannot be used to meaningfully compare two different input methods, such as a QWERTY keyboard and a multi-tap device.
                  * There is no obvious way to combine KSPC and MSD into an overall error rate, even though they have an inverse relationship.

                  Further metrics

                  [ edit ]

                Using the classes described above, further metrics were defined by R. William Soukoreff and I.Scott MacKenzie:

                Error correction efficiency refers to the ease with which the participant performed error correction.

                  * Correction Efficiency = IF/F

                Participant conscientiousness is the ratio of corrected errors to the total number of error, which helps distinguish perfectionists from apathetic participants.

                  * Participant Conscientiousness = IF / (IF + INF)

                If C represents the amount of useful information transferred, INF, IF, and F represent the proportion of bandwidth wasted.

                  * Utilized Bandwidth = C / (C + INF + IF + F)
                  * Wasted Bandwidth = (INF + IF + F)/ (C + INF + IF + F)

                  Total error rate

                  [ edit ]

                The classes described also provide an intuitive definition of total error rate:

                  * Total Error Rate = ((INF + IF)/ (C + INF + IF)) * 100%
                  * Not Corrected Error Rate = (INF/ (C + INF + IF)) * 100%
                  * Corrected Error Rate = (IF/ (C + INF + IF)) * 100%

                Since these three error rates are ratios, they are comparable between different devices, something that cannot be done with the KSPC statistic, which is device dependent. [ 26 ]

                  Tools for text entry research

                  [ edit ]

                Currently, two tools are publicly available for text entry researchers to record text entry performance metrics. The first is TEMA [ 27 ] that runs only on the Android (operating system). The second is WebTEM that runs on any device with a modern Web browser, and works with almost all text entry technique. [ 28 ]

                  Keystroke dynamics

                  [ edit ]

                Keystroke dynamics, or typing dynamics, is the obtaining of detailed timing information that describes exactly when each key was pressed and when it was released as a person is typing at a computer keyboard for biometric identification, [ 29 ] similar to speaker recognition. [ 30 ] Data needed to analyze keystroke dynamics is obtained by keystroke logging.

                The behavioral biometric of Keystroke Dynamics uses the manner and rhythm in which an individual types characters on a keyboard or keypad. [ 31 ]

                  See also

                  [ edit ]

                War correspondent typing his dispatch in a wood outside Arnhem, 1944

                  * Muscle memory
                  * Stenotype
                  * Copy typist
                  * Audio typist
                  * Data entry clerk
                  * Speed typing contest
                  * Typesetting
                  * Typing Day

                  References

                  [ edit ]
                   1. ^ a b "World's First Typist". Wisconsin Historical Society. December 2003. Archived from the original on 2012-11-07 . Retrieved 2010-09-11 .
                   2. ^ "Wisconsin History Facts". e-ReferenceDesk. Archived from the original on 2010-11-19 . Retrieved 2010-09-11 .
                   3. ^ "Ten fingers not needed for fast typing, study shows". phys.org. Archived from the original on 2016-02-13 . Retrieved 2016-02-13 .
                   4. ^ Feit, Anna Maria; Weir, Daryl; Oulasvirta, Antti (2016-05-07). "How We Type: Movement Strategies and Performance in Everyday Typing". Proceedings of the 2016 CHI Conference on Human Factors in Computing Systems. CHI '16. New York, NY, USA: Association for Computing Machinery. pp. 4262–4273. doi:10.1145/2858036.2858233. ISBN 978-1-4503-3362-7. Archived from the original on 2023-12-13 . Retrieved 2023-12-13 .
                   5. ^ Blakely, Rhys (2 October 2019). "Thumbs up for speedy smartphone typists". The Times. Archived from the original on 7 February 2022 . Retrieved 7 February 2022 .
                   6. ^ ""Smartphone thumb" is plaguing more people, doctors say". CBS News. 29 March 2017. Archived from the original on 7 February 2022 . Retrieved 7 February 2022 .
                   7. ^ Eli MacKinnon (2016-08-01). "What's the Fastest Language to Type In?". livescience.com. Archived from the original on 2022-01-25 . Retrieved 2022-01-25 .
                   8. ^ Karat, C.M.; Halverson, C.; Horn, D.; Karat, J. (1999), "Patterns of entry and correction in large vocabulary continuous speech recognition systems", CHI 99 Conference Proceedings, pp. 568–575
                   9. ^ Ayres, Robert U; Martinás, Katalin (2005), "120 wpm for very skilled typist", On the Reappraisal of Microeconomics: Economic Growth and Change in a Material World, Cheltenham, UK & Northampton, Massachusetts: Edward Elgar Publishing, p. 41, ISBN 1-84542-272-4 , retrieved 22 November 2010
                  10. ^ Ostrach, Teresia R. (1997), Typing Speed: How Fast is Average (PDF) , archived from the original (PDF) on 2012-05-02
                  11. ^ Brown, C. M. (1988). Human-computer interface design guidelines. Norwood, NJ: Ablex Publishing .
                  12. ^ "History of Typewriters | Big Site of Amazing Facts ®". Bigsiteofamazingfacts.com. 12 September 2007. Archived from the original on 2013-05-15 . Retrieved 2012-06-13 .
                  13. ^ "World Records in Typing". Owled.com. 2006-09-02. Archived from the original on 2018-08-26 . Retrieved 2012-06-13 .
                  14. ^ "IBM Archives: Typing posture". 03.ibm.com. 23 January 2003. Archived from the original on 2016-07-20 . Retrieved 2012-06-13 .
                  15. ^ "Believe it or not ..." Deskstore.com. Archived from the original on 2020-08-07 . Retrieved 2012-06-13 .
                  16. ^ Lowell (2017-03-15). "QWERTY vs Dvorak: The two great keyboards the time were born". Archived from the original on 2019-01-19 . Retrieved 2019-01-19 .
                  17. ^ RetroFootage. "Miss Stella Pajunas, World's Fast Typist, Types On An Ibm Electric Typewriterƒ". Pond5.com. Archived from the original on 2019-01-19 . Retrieved 2019-01-19 .
                  18. ^ Ranger, Robert. "Barbara Blackburn, the World's Fastest Typist". Archived from the original on 2020-11-08 . Retrieved 2008-05-08 .
                  19. ^ 255 WPM Monkey Type 60s (World Record), archived from the original on 2022-05-05 , retrieved 2022-05-05
                  20. ^ Typing 213 wpm for an hour straight, archived from the original on 2022-05-05 , retrieved 2022-05-05
                  21. ^ "TypeRacer Race History". data.typeracer.com. Archived from the original on 2020-10-31 . Retrieved 2022-05-05 .
                  22. ^ "Ultimate Typing Championship". ultimatetypingchampionship.com. Archived from the original on 2022-04-15 . Retrieved 2022-05-05 .
                  23. ^ "Das Keyboard Announces Winners of the Ultimate Typing Championship 2020 and Crowns Best Typist on the Planet". www.businesswire.com. 2020-08-25. Archived from the original on 2022-05-05 . Retrieved 2022-05-05 .
                  24. ^ "How Does Stephen Hawking Talk? (video)". Singularity Hub. 2010-05-03. Archived from the original on 2012-06-24 . Retrieved 2012-06-13 .
                  25. ^ "The man who saves Stephen Hawking's voice". newscientist.com. Archived from the original on 2012-08-25 . Retrieved 2017-09-17 .
                  26. ^ "Soukoreff, R. W., & MacKenzie, I. S. (2003). Metrics for text entry research: An evaluation of MSD and KSPC, and a new unified error metric. Proceedings of the ACM Conference on Human Factors in Computing Systems - CHI 2003, pp. 113-120. New York: ACM". Archived from the original on 2011-08-24 . Retrieved 2013-05-16 .
                  27. ^ Castellucci, Steven J.; MacKenzie, I. Scott (2011-01-01). "Gathering text entry metrics on android devices". CHI '11 Extended Abstracts on Human Factors in Computing Systems. CHI EA '11. New York, NY, USA: ACM. pp. 1507–1512. doi:10.1145/1979742.1979799. ISBN 9781450302685. S2CID 2107842.
                  28. ^ Arif, Ahmed Sabbir; Mazalek, Ali (2016-01-01). "WebTEM". Proceedings of the 2016 ACM International Conference on Interactive Surfaces and Spaces. ISS '16. New York, NY, USA: ACM. pp. 415–420. doi:10.1145/2992154.2996791. ISBN 9781450342483. S2CID 16022337.
                  29. ^ "User authentication through typing biometrics features" (PDF) . pku.edu.cn. Archived from the original (PDF) on 2014-03-04 . Retrieved 2013-11-14 .
                  30. ^ Robert Moskovitch, Clint Feher, Arik Messerman, Niklas Kirschnick, Tarik Mustafic, Ahmet Camtepe, Bernhard Löhlein, Ulrich Heister, Sebastian Möller, Lior Rokach, Yuval Elovici (2009). Identity theft, computers and behavioral biometrics (PDF) . Proceedings of the IEEE International Conference on Intelligence and Security Informatics. pp. 155–160. Archived (PDF) from the original on 2013-09-27 . Retrieved 2013-11-14 .{{cite conference}} : CS1 maint: multiple names: authors list ( link )
                  31. ^ "Continuous authentication by analysis of keyboard typing characteristics - IET Conference Publication". May 1995: 111–114. doi:10.1049/cp:19950480. Archived from the original on 2020-10-01 . Retrieved 2019-12-07 . {{cite journal}} : Cite journal requires |journal= ( help )

                  External links

                  [ edit ]
                      Wikiversity has learning resources about Typing
                  * Media related to Typing at Wikimedia Commons
                                                               * France        
                                                               * BnF data      
                    Authority control databases: National      * Israel        
                                                               * United States 
                                                               * Czech Republic
                    
                  Retrieved from "https://en.wikipedia.org/w/index.php?title=Typing&oldid=1230149320"
                  Categories:
                    * Typing
                    * Text
                    * Input/output
                  Hidden categories:
                    * CS1 maint: multiple names: authors list
                    * CS1 errors: missing periodical
                    * Articles with short description
                    * Short description is different from Wikidata
                    * Articles that may contain original research from March 2017
                    * All articles that may contain original research
                    * All articles with unsourced statements
                    * Articles with unsourced statements from December 2022
                    * Articles containing potentially dated statements from 2005
                    * All articles containing potentially dated statements
                    * Articles with unsourced statements from May 2022
                    * Articles needing additional references from June 2024
                    * All articles needing additional references
                    * Commons category link from Wikidata
                    * Articles with BNF identifiers
                    * Articles with BNFdata identifiers
                    * Articles with J9U identifiers
                    * Articles with LCCN identifiers
                    * Articles with NKC identifiers
                    * Articles containing video clips
            * This page was last edited on 20 June 2024, at 23:46 (UTC) .
            * Text is available under the Creative Commons Attribution-ShareAlike License 4.0; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.
            * Privacy policy
            * About Wikipedia
            * Disclaimers
            * Contact Wikipedia
            * Code of Conduct
            * Developers
            * Statistics
            * Cookie statement
            * Mobile view
            * 
            * 
          * 
Typing
https://en.wikipedia.org/wiki/Typing