Background: #fff
Foreground: #000
PrimaryPale: #8cf
PrimaryLight: #18f
PrimaryMid: #04b
PrimaryDark: #014
SecondaryPale: #ffc
SecondaryLight: #fe8
SecondaryMid: #db4
SecondaryDark: #841
TertiaryPale: #eee
TertiaryLight: #ccc
TertiaryMid: #999
TertiaryDark: #666
Error: #f88
<!--{{{-->
<div class='toolbar' macro='toolbar [[ToolbarCommands::EditToolbar]]'></div>
<div class='title' macro='view title'></div>
<div class='editor' macro='edit title'></div>
<div macro='annotations'></div>
<div class='editor' macro='edit text'></div>
<div class='editor' macro='edit tags'></div><div class='editorFooter'><span macro='message views.editor.tagPrompt'></span><span macro='tagChooser excludeLists'></span></div>
<!--}}}-->
<<importTiddlers>>
<!--{{{-->
<link rel='alternate' type='application/rss+xml' title='RSS' href='index.xml' />
<!--}}}-->
These [[InterfaceOptions]] for customising [[TiddlyWiki]] are saved in your browser

Your username for signing your edits. Write it as a [[WikiWord]] (eg [[JoeBloggs]])

<<option txtUserName>>
<<option chkSaveBackups>> [[SaveBackups]]
<<option chkAutoSave>> [[AutoSave]]
<<option chkRegExpSearch>> [[RegExpSearch]]
<<option chkCaseSensitiveSearch>> [[CaseSensitiveSearch]]
<<option chkAnimate>> [[EnableAnimations]]

----
Also see [[AdvancedOptions]]
<!--{{{-->
<div class='header' role='banner'>
  <div class='headerShadow'>
    <span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
    <span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
  </div>
  <div class='headerForeground'>
    <span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>&nbsp;
    <span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
  </div>
</div>
<div id='mainMenu' role='navigation' refresh='content' tiddler='MainMenu'></div>
<div id='sidebar'>
  <div id='sidebarOptions' role='navigation' refresh='content' tiddler='SideBarOptions'></div>
  <div id='sidebarTabs' role='complementary' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea' role='main'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
/*{{{*/
body {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}

a {color:[[ColorPalette::PrimaryMid]];}
a:hover {background-color:[[ColorPalette::PrimaryMid]]; color:[[ColorPalette::Background]];}
a img {border:0;}

h1, h2, h3, h4, h5, h6 { color: [[ColorPalette::SecondaryDark]]; }
h1 {border-bottom:2px solid [[ColorPalette::TertiaryLight]];}
h2,h3 {border-bottom:1px solid [[ColorPalette::TertiaryLight]];}

.txtOptionInput {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}

.button {color:[[ColorPalette::PrimaryDark]]; border:1px solid [[ColorPalette::Background]];}
.button:hover {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::SecondaryLight]]; border-color:[[ColorPalette::SecondaryMid]];}
.button:active {color:[[ColorPalette::Background]]; background:[[ColorPalette::SecondaryMid]]; border:1px solid [[ColorPalette::SecondaryDark]];}

.header {
	background: -moz-linear-gradient(to bottom, [[ColorPalette::PrimaryLight]], [[ColorPalette::PrimaryMid]]);
	background: linear-gradient(to bottom, [[ColorPalette::PrimaryLight]], [[ColorPalette::PrimaryMid]]);
}
.header a:hover {background:transparent;}
.headerShadow {color:[[ColorPalette::Foreground]];}
.headerShadow a {font-weight:normal; color:[[ColorPalette::Foreground]];}
.headerForeground {color:[[ColorPalette::Background]];}
.headerForeground a {font-weight:normal; color:[[ColorPalette::PrimaryPale]];}

.tabSelected {
	color:[[ColorPalette::Foreground]];
	background:[[ColorPalette::Background]];
	border-left:1px solid [[ColorPalette::TertiaryLight]];
	border-top:1px solid [[ColorPalette::TertiaryLight]];
	border-right:1px solid [[ColorPalette::TertiaryLight]];
}
.tabUnselected {color:[[ColorPalette::Background]]; background:[[ColorPalette::TertiaryMid]];}
.tabContents {border:1px solid [[ColorPalette::TertiaryLight]];}
.tabContents .button {border:0;}

#sidebar {}
#sidebarOptions input {border:1px solid [[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel {background:[[ColorPalette::PrimaryPale]];}
#sidebarOptions .sliderPanel a {border:none;color:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:hover {color:[[ColorPalette::Background]]; background:[[ColorPalette::PrimaryMid]];}
#sidebarOptions .sliderPanel a:active {color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::Background]];}

.wizard { background:[[ColorPalette::PrimaryPale]]; }
.wizard__title    { color:[[ColorPalette::PrimaryDark]]; border:none; }
.wizard__subtitle { color:[[ColorPalette::Foreground]]; border:none; }
.wizardStep { background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]]; }
.wizardStep.wizardStepDone {background:[[ColorPalette::TertiaryLight]];}
.wizardFooter .status {background:[[ColorPalette::PrimaryDark]]; color:[[ColorPalette::Background]];}
.wizardFooter .status a { color: [[ColorPalette::PrimaryPale]]; }
.wizard .button {
	color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryLight]]; border: 1px solid;
	border-color:[[ColorPalette::SecondaryDark]];
}
.wizard .button:hover {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Background]];}
.wizard .button:active {
	color:[[ColorPalette::Background]]; background:[[ColorPalette::Foreground]]; border: 1px solid;
	border-color:[[ColorPalette::PrimaryDark]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryPale]] [[ColorPalette::PrimaryDark]];
}

.wizard .notChanged {background:transparent;}
.wizard .changedLocally {background:#80ff80;}
.wizard .changedServer {background:#8080ff;}
.wizard .changedBoth {background:#ff8080;}
.wizard .notFound {background:#ffff80;}
.wizard .putToServer {background:#ff80ff;}
.wizard .gotFromServer {background:#80ffff;}

#messageArea { background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; box-shadow: 1px 2px 5px [[ColorPalette::TertiaryMid]]; }
.messageToolbar__button { color:[[ColorPalette::PrimaryMid]]; background:[[ColorPalette::SecondaryPale]]; border:none; }
.messageToolbar__button_withIcon { background:inherit; }
.messageToolbar__button_withIcon:active { background:inherit; border:none; }
.tw-icon line { stroke: [[ColorPalette::TertiaryDark]]; }
.messageToolbar__button:hover .tw-icon line { stroke: [[ColorPalette::Foreground]]; }

.popup {
	background: [[ColorPalette::Background]];
	color: [[ColorPalette::TertiaryDark]];
	box-shadow: 1px 2px 5px [[ColorPalette::TertiaryMid]];
}
.popup li a, .popup li a:visited, .popup li a:hover, .popup li a:active {
	color:[[ColorPalette::Foreground]]; border: none;
}
.popup li a:hover { background:[[ColorPalette::SecondaryLight]]; }
.popup li a:active { background:[[ColorPalette::SecondaryPale]]; }
.popup li.disabled { color:[[ColorPalette::TertiaryMid]]; }
.popupHighlight {color:[[ColorPalette::Foreground]];}
.popup hr {color:[[ColorPalette::PrimaryDark]]; background:[[ColorPalette::PrimaryDark]]; border-bottom:1px;}
.listBreak div {border-bottom:1px solid [[ColorPalette::TertiaryDark]];}

.popupTiddler {background:[[ColorPalette::TertiaryPale]]; border:2px solid [[ColorPalette::TertiaryMid]];}

.tiddler .defaultCommand {font-weight:bold;}

.shadow .title {color:[[ColorPalette::TertiaryDark]];}

.title {color:[[ColorPalette::SecondaryDark]];}
.subtitle {color:[[ColorPalette::TertiaryDark]];}

.toolbar {color:[[ColorPalette::PrimaryMid]];}
.toolbar a {color:[[ColorPalette::TertiaryLight]];}
.selected .toolbar a {color:[[ColorPalette::TertiaryMid]];}
.selected .toolbar a:hover {color:[[ColorPalette::Foreground]];}

.tagging, .tagged { background: [[ColorPalette::Background]]; border: 2px solid [[ColorPalette::TertiaryPale]]; }
.selected .tagging, .selected .tagged { border: 2px solid [[ColorPalette::TertiaryLight]]; }
.tagging .listTitle, .tagged .listTitle {color:[[ColorPalette::PrimaryDark]];}
.tagging .button, .tagged .button { border:none; }

.footer {color:[[ColorPalette::TertiaryLight]];}
.selected .footer {color:[[ColorPalette::TertiaryMid]];}

.error, .errorButton {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::Error]];}
.warning {color:[[ColorPalette::Foreground]]; background:[[ColorPalette::SecondaryPale]];}
.lowlight {background:[[ColorPalette::TertiaryLight]];}

.zoomer {background:none; color:[[ColorPalette::TertiaryMid]]; border:3px solid [[ColorPalette::TertiaryMid]];}

.imageLink, #displayArea .imageLink {background:transparent;}

.annotation { background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; }

.viewer .listTitle {list-style-type:none; margin-left:-2em;}
.viewer .button {border:1px solid [[ColorPalette::SecondaryMid]];}
.viewer blockquote {border-left:3px solid [[ColorPalette::TertiaryDark]];}

.twtable { background: [[ColorPalette::Background]]; }
.viewer th, .viewer thead td, .twtable th, .twtable thead td { background: [[ColorPalette::SecondaryMid]]; color: [[ColorPalette::Background]]; }
.viewer td, .viewer tr, .twtable td, .twtable tr { border: 1px solid [[ColorPalette::TertiaryLight]]; }
.twtable caption { color: [[ColorPalette::TertiaryMid]]; }

.viewer pre {background:[[ColorPalette::SecondaryPale]];}
.viewer code {color:[[ColorPalette::SecondaryDark]];}
.viewer hr {border:0; border-top:dashed 1px [[ColorPalette::TertiaryDark]]; color:[[ColorPalette::TertiaryDark]];}

.highlight, .marked {background:[[ColorPalette::SecondaryLight]];}

.editor input {border:1px solid [[ColorPalette::PrimaryMid]]; background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
.editor textarea {border:1px solid [[ColorPalette::PrimaryMid]]; width:100%; background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
.editorFooter {color:[[ColorPalette::TertiaryMid]];}
.readOnly {background:[[ColorPalette::TertiaryPale]];}

#backstageArea {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::TertiaryMid]];}
#backstageArea a {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstageArea a:hover {background:[[ColorPalette::SecondaryLight]]; color:[[ColorPalette::Foreground]]; }
#backstageArea a.backstageSelTab {background:[[ColorPalette::Background]]; color:[[ColorPalette::Foreground]];}
#backstageButton a {background:none; color:[[ColorPalette::Background]]; border:none;}
#backstageButton a:hover {background:[[ColorPalette::Foreground]]; color:[[ColorPalette::Background]]; border:none;}
#backstagePanel {background:[[ColorPalette::Background]]; border-color: [[ColorPalette::Background]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]] [[ColorPalette::TertiaryDark]];}
.backstagePanelFooter .button {border:none; color:[[ColorPalette::Background]];}
.backstagePanelFooter .button:hover {color:[[ColorPalette::Foreground]];}
#backstageCloak {background:[[ColorPalette::Foreground]]; opacity:0.6; filter:alpha(opacity=60);}
/*}}}*/
/*{{{*/
body { font-size:.75em; font-family:arial,helvetica,sans-serif; margin:0; padding:0; }

* html .tiddler {height:1%;}

h1,h2,h3,h4,h5,h6 {font-weight:bold; text-decoration:none;}
h1,h2,h3 {padding-bottom:1px; margin-top:1.2em;margin-bottom:0.3em;}
h4,h5,h6 {margin-top:1em;}
h1 {font-size:1.35em;}
h2 {font-size:1.25em;}
h3 {font-size:1.1em;}
h4 {font-size:1em;}
h5 {font-size:.9em;}

hr {height:1px;}

dt {font-weight:bold;}

ol {list-style-type:decimal;}
ol ol {list-style-type:lower-alpha;}
ol ol ol {list-style-type:lower-roman;}
ol ol ol ol {list-style-type:decimal;}
ol ol ol ol ol {list-style-type:lower-alpha;}
ol ol ol ol ol ol {list-style-type:lower-roman;}
ol ol ol ol ol ol ol {list-style-type:decimal;}

.txtOptionInput {width:11em; border-width: 1px; }

#contentWrapper .chkOptionInput {border:0;}

.indent {margin-left:3em;}
.outdent {margin-left:3em; text-indent:-3em;}
code.escaped {white-space:nowrap;}


a {text-decoration:none;}

.externalLink {text-decoration:underline;}

.tiddlyLinkExisting {font-weight:bold;}
.tiddlyLinkNonExisting {font-style:italic;}

/* the 'a' is required for IE, otherwise it renders the whole tiddler in bold */
a.tiddlyLinkNonExisting.shadow {font-weight:bold;}

#mainMenu .tiddlyLinkExisting,
#mainMenu .tiddlyLinkNonExisting,
#sidebarTabs .tiddlyLinkNonExisting {font-weight:normal; font-style:normal;}
#sidebarTabs .tiddlyLinkExisting {font-weight:bold; font-style:normal;}


.header {position:relative;}
.headerShadow {position:relative; padding:3em 0 1em 1em; left:-1px; top:-1px;}
.headerForeground {position:absolute; padding:3em 0 1em 1em; left:0; top:0;}

.siteTitle {font-size:3em;}
.siteSubtitle {font-size:1.2em;}

#mainMenu {position:absolute; left:0; width:10em; text-align:right; line-height:1.6em; padding:1.5em 0.5em 0.5em 0.5em; font-size:1.1em;}

#sidebar {position:absolute; right:3px; width:16em; font-size:.9em;}
#sidebarOptions {padding-top:0.3em;}
#sidebarOptions a {margin:0 0.2em; padding:0.2em 0.3em; display:block;}
#sidebarOptions input {margin:0.4em 0.5em;}
#sidebarOptions .sliderPanel {margin-left:1em; padding:0.5em; font-size:.85em;}
#sidebarOptions .sliderPanel a {font-weight:bold; display:inline; padding:0;}
#sidebarOptions .sliderPanel input {margin:0 0 0.3em 0;}
#sidebarTabs .tabContents {width:15em; overflow:hidden;}
#sidebarTabs li:not(:last-child) { margin-bottom: 0.3em; }
#sidebarTabs ul:not(:last-child) { margin-bottom: 0.5em; }

.wizard { padding:0.1em 2em 0; }
.wizard__title    { font-size:2em; }
.wizard__subtitle { font-size:1.2em; }
.wizard__title, .wizard__subtitle { font-weight:bold; background:none; padding:0; margin:0.4em 0 0.2em; }
.wizardStep { padding:1em; }
.wizardFooter { padding: 0.8em 0; }
.wizardFooter .status { display: inline-block; line-height: 1.5; padding: 0.3em 1em; }
.wizardFooter .button { margin:0.5em 0 0; font-size:1.2em; padding:0.2em 0.5em; }

#messageArea { position:fixed; top:2em; right:0; margin:0.5em; padding:0.7em 1em; z-index:2000; }
.messageToolbar { text-align:right; padding:0.2em 0; }
.messageToolbar__button { text-decoration:underline; }
.messageToolbar__button_withIcon { display: inline-block; }
.tw-icon { height: 1em; width: 1em; } /* width for IE */
.tw-icon line { stroke-width: 1; stroke-linecap: round; }
.messageArea__text:not(:last-child) { margin-bottom: 0.3em; }
.messageArea__text a { text-decoration:underline; }

.popup {position:absolute; z-index:300; font-size:.9em; padding:0.3em 0; list-style:none; margin:0;}
.popup .popupMessage, .popup li.disabled, .popup li a { padding: 0.3em 0.7em; }
.popup li a {display:block; font-weight:normal; cursor:pointer;}
.popup hr {display:block; height:1px; width:auto; padding:0; margin:0.2em 0;}
.listBreak {font-size:1px; line-height:1px;}
.listBreak div {margin:2px 0;}

.tiddlerPopupButton {padding:0.2em;}
.popupTiddler {position: absolute; z-index:300; padding:1em; margin:0;}

.tabset {padding:1em 0 0 0.5em;}
.tab {display: inline-block; white-space: nowrap; position: relative; bottom: -0.7px; margin: 0 0.25em 0 0; padding:0.2em;}
.tabContents {padding:0.5em;}
.tabContents ul, .tabContents ol {margin:0; padding:0;}
.txtMainTab .tabContents li {list-style:none;}
.tabContents li.listLink { margin-left:.75em;}

#contentWrapper {display:block;}
#splashScreen {display:none;}

#displayArea {margin:1em 17em 0 14em;}

.toolbar {text-align:right; font-size:.9em;}

.tiddler { padding: 1em; }

.title { font-size: 1.6em; font-weight: bold; }
.subtitle { font-size: 1.1em; }

.missing .viewer, .missing .title { font-style: italic; }
.missing .subtitle { display: none; }

.tiddler .button {padding:0.2em 0.4em;}

.tagging {margin:0.5em 0.5em 0.5em 0; float:left; display:none;}
.isTag .tagging {display:block;}
.tagged {margin:0.5em; float:right;}
.tagging, .tagged {font-size:0.9em; padding:0.25em;}
.tagging ul, .tagged ul {list-style:none; margin:0.25em; padding:0;}
.tagged li, .tagging li { margin: 0.3em 0; }
.tagClear {clear:both;}

.footer {font-size:.9em;}
.footer li {display:inline;}

.annotation { padding: 0.5em 0.8em; margin: 0.5em 1px; }

.viewer {line-height:1.4em; padding-top:0.5em;}
.viewer .button {margin:0 0.25em; padding:0 0.25em;}
.viewer blockquote {line-height:1.5em; padding-left:0.8em;margin-left:2.5em;}
.viewer ul, .viewer ol {margin-left:0.5em; padding-left:1.5em;}

.viewer table, table.twtable { border-collapse: collapse; margin: 0.8em 0; }
.viewer th, .viewer td, .viewer tr, .viewer caption, .twtable th, .twtable td, .twtable tr, .twtable caption { padding: 0.2em 0.4em; }
.twtable caption { font-size: 0.9em; }
table.listView { margin: 0.8em 1.0em; }
table.listView th, table.listView td, table.listView tr { text-align: left; }
.listView > thead { position: sticky; top: 0; }

* html .viewer pre {width:99%; padding:0 0 1em 0;}
.viewer pre {padding:0.5em; overflow:auto;}
pre, code { font-family: monospace, monospace; font-size: 1em; }
.viewer pre, .viewer code { line-height: 1.4em; }

.editor {font-size:1.1em; line-height:1.4em;}
.editor input, .editor textarea { display: block; width: 100%; box-sizing: border-box; font: inherit; padding: 0.1em 0.4em; }
.editorFooter {padding:0.25em 0; font-size:.9em;}
.editorFooter .button {padding-top:0; padding-bottom:0;}

.fieldsetFix {border:0; padding:0; margin:1px 0;}

.zoomer {font-size:1.1em; position:absolute; overflow:hidden;}
.zoomer div {padding:1em;}

* html #backstage {width:99%;}
* html #backstageArea {width:99%;}
#backstageArea {display:none; position:relative; overflow: hidden; z-index:150; padding:0.3em 0.5em;}
#backstageToolbar {position:relative;}
#backstageArea a {font-weight:bold; margin-left:0.5em; padding:0.3em 0.5em;}
#backstageButton {display:none; position:absolute; z-index:175; top:0; right:0;}
#backstageButton a {padding: 0.3em 0.5em; display: inline-block;}
#backstage {position:relative; width:100%; z-index:50;}
#backstagePanel { display:none; z-index:100; position:absolute; width:90%; margin:0 5%; }
.backstagePanelFooter {padding-top:0.2em; float:right;}
.backstagePanelFooter a {padding:0.2em 0.4em;}
#backstageCloak {display:none; z-index:20; position:absolute; width:100%; height:100px;}

.whenBackstage {display:none;}
.backstageVisible .whenBackstage {display:block;}
/*}}}*/
/***
StyleSheet for use when a translation requires any css style changes.
This StyleSheet can be used directly by languages such as Chinese, Japanese and Korean which need larger font sizes.
***/
/*{{{*/
body {font-size:0.8em;}
#sidebarOptions {font-size:1.05em;}
#sidebarOptions a {font-style:normal;}
#sidebarOptions .sliderPanel {font-size:0.95em;}
.subtitle {font-size:0.8em;}
.viewer table.listView {font-size:0.95em;}
/*}}}*/
/*{{{*/
@media print {
  #mainMenu, #sidebar, #messageArea, .toolbar, #backstageButton, #backstageArea { display: none !important; }
  #displayArea { margin: 1em 1em 0em; }
}
/*}}}*/
<!--{{{-->
<div class='toolbar' role='navigation' macro='toolbar [[ToolbarCommands::ViewToolbar]]'></div>
<div class='title' macro='view title'></div>
<div class='subtitle'><span macro='view modifier link'></span>, <span macro='view modified date'></span> (<span macro='message views.wikified.createdPrompt'></span> <span macro='view created date'></span>)</div>
<div class='tagging' macro='tagging'></div>
<div class='tagged' macro='tags'></div>
<div class='viewer' macro='view text wikified'></div>
<div class='tagClear'></div>
<!--}}}-->
Ansible modules require Python on the target host, but fresh minimal OS installations often lack Python. Standard modules fail with "ansible requires a python interpreter on the target host". The solution is the <html><code>raw</code></html> module, which executes shell commands directly without Python, bypassing the interpreter requirement. Use raw to install Python before attempting standard modules. Set <html><code>gather_facts: false</code></html> initially (you can't gather facts without Python), then run the bootstrap, then execute <html><code>setup</code></html> to gather facts. This pattern is essential when deploying to immutable images, minimal container bases, or fresh server installations. After Python is installed, normal Ansible modules become available for the rest of the play.

----
''Sources''
* <html><code>training/library/topics/ansible-deep-dive/footguns.md</code></html>
Hardcoded AWS access keys in source code are a leading vector for account compromise. Automated bots scan GitHub and other platforms for exposed keys within seconds of a push. Keys committed to Git are in repository history permanently — recoverable via tools like <html><code>trufflehog</code></html> or <html><code>git log -S "AKIA"</code></html> even after deletion, and accessible from private repos through secondary surfaces: developer machines, CI systems, build logs, and error messages. An attacker with a harvested key can provision GPU instances for cryptocurrency mining or spin up expensive compute, leaving the account owner with a large bill.

Eliminate long-lived credentials from code entirely. AWS SDKs including boto3 automatically discover credentials from <html><code>~/.aws/credentials</code></html>, environment variables, and instance metadata without any code changes. Use IAM instance profiles for EC2, execution roles for Lambda, IRSA for EKS pods, and OIDC federation for CI/CD pipelines (GitHub Actions uses <html><code>AssumeRoleWithWebIdentity</code></html>). If long-lived keys are unavoidable, store them in environment variables or <html><code>~/.aws/credentials</code></html>, never in source files. Install <html><code>git-secrets</code></html> or <html><code>gitleaks</code></html> as pre-commit hooks to prevent credential commits. If a key is leaked, rotate it immediately with <html><code>aws iam delete-access-key</code></html> and audit history with <html><code>git log -S "AKIA"</code></html> to confirm scope.

----
''Sources''
* <html><code>training/library/topics/aws-iam/footguns.md</code></html>
* <html><code>training/library/topics/python-infra/footguns.md</code></html>

//Merged from 2 source atoms.//
Alpine Linux uses musl libc instead of glibc, which creates three classes of issues for containerized applications.

''DNS resolution:'' musl's resolver behaves differently from glibc's — it may require the <html><code>ndots:1</code></html> option and exhibits intermittent failures under rapid queries. This manifests as "Temporary failure in name resolution" appearing intermittently in production despite working in development.

''Python wheels:'' PyPI wheels are pre-compiled for glibc Linux x86_64. On Alpine, pip falls back to building from source, requiring <html><code>build-base</code></html>, <html><code>python3-dev</code></html>, <html><code>linux-headers</code></html>, and library headers (<html><code>libffi-dev</code></html>, <html><code>openssl-dev</code></html>). A 2-second wheel download becomes a 5-minute compilation. For packages with C extensions (numpy, psycopg2, cryptography, lxml), this bloats the layer by 100–500MB. Build dependencies remain in the layer unless explicitly cleaned up, inflating what was intended to be a lean image.

''C extension libraries:'' Libraries expecting glibc ABI compatibility require glibc shim packages; build toolchains expect glibc headers and fail without musl-specific packages like <html><code>musl-dev</code></html>.

For Python applications, use <html><code>python:3.12-slim</code></html> (Debian-based, ~180MB) rather than Alpine. Alpine is appropriate only for statically-compiled Go or Rust binaries where the full image can fit in ~50MB. For Python, Alpine trades a smaller base image for larger final layers and longer build times — the opposite of the intended goal.

----
''Sources''
* <html><code>training/library/topics/container-images/street_ops.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[Debugging segfaults in Python C extensions]]
* [[Quick fixes for common Python installation errors]]
Python's built-in http.server module can start a webserver in one command without installing anything. <html><code>python3 -m http.server 8080</code></html> serves the current working directory on localhost:8080; <html><code>python3 -m http.server 8080 --directory /var/log</code></html> serves a specific directory instead. Useful for ad-hoc file sharing across machines, quick log review (browse logs as HTML instead of cat), or serving static assets while debugging (test a CSS change before committing). The server handles directory listings and MIME types automatically. It's read-only by default — no PUT/DELETE endpoints. For production or persistence, use a real server (nginx, Flask, Node). For local development, this saves the friction of configuration.

----
''Sources''
* <html><code>training/library/topics/curl-and-wget/street_ops.md</code></html>

''Related atoms''
* [[What is the `http.server` module used for?]]
* [[What is the `requests` library?]]
* [[What is httpx?]]
Locust allows you to define user behavior as Python classes with setup, tasks, and wait times. Users can maintain state (login credentials, cart IDs, session tokens) across requests, modeling realistic workflows. The <html><code>on_start()</code></html> method runs once per user—useful for login flows. Tasks are weighted by frequency. Wait times between requests model think time.

Locust distributes load across multiple worker nodes, each running multiple users. This is essential for generating traffic from many source IPs, which is required if the system under test tracks per-IP rate limits or ban patterns. For Python teams, Locust's integration with the ecosystem (pytest, dataclasses, standard libraries) makes complex test flows natural. The tradeoff: Python is slower than Go (k6) or compiled languages. For high-throughput tests (>10k RPS), Locust's overhead matters. For API tests with complex user journeys, Locust is often the right choice.

----
''Sources''
* <html><code>training/library/topics/load-testing/primer.md</code></html>

''Related atoms''
* [[Code-first load testing is more accessible than UI-based tools]]
* [[concurrent.futures parallelizes I/O-bound infrastructure tasks]]
* [[What is pytest's key advantage over unittest?]]
Locust took the position that load test scenarios should be plain Python code, not XML configurations or GUI workflows. This was radical for the field—JMeter dominated at the time, with test flows defined by clicking buttons and exporting XML. Code-first testing meant engineers could use the same tools and practices they already knew. You define behavior as Python classes using if/else logic, loops, and libraries. Locust handles the distributed execution and metrics collection.

The name is apt: Locust references a swarm—many small agents creating massive aggregate load. The simplicity and approachability made it enormously popular in Python ecosystems where infrastructure-as-code was already the norm. You write test code the same way you write deployment and monitoring code. The barrier to entry dropped.

This principle—that testing infrastructure should use the same languages and tools as the systems being tested—is now table stakes. k6 uses JavaScript; Gatling uses Scala; Python-first teams use Locust. Tools that force domain-specific languages or UI workflows are increasingly seen as friction, not safety.

----
''Sources''
* <html><code>training/library/topics/load-testing/trivia.md</code></html>

''Related atoms''
* [[Locust enables stateful user workflows with distributed execution]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
* [[Python bridges ops scripting and software engineering]]
Unlike compiled languages, perf cannot directly resolve function names from JVM bytecode or Python interpreter code. The interpreter's internal functions appear in the profile, but application code remains as hex addresses unless the runtime writes a perf map file. JVM: enable with <html><code>java -XX:+PreserveFramePointers -XX:+DumpPerfMapAtExit -jar app.jar</code></html>, which writes <html><code>/tmp/perf-&lt;pid&gt;.map</code></html> at shutdown. For long-running services, use <html><code>-XX:+UnlockDiagnosticVMOptions -XX:+PreserveFramePointers</code></html> and periodically dump maps. Node.js: run with <html><code>--perf-basic-prof</code></html> to write <html><code>/tmp/perf-&lt;pid&gt;.map</code></html>. Python 3.12+: use <html><code>python -X perf</code></html>. Without these, the profile shows interpreter internals (GC, bytecode dispatch) but not application code. Enabling perf maps is a one-line flag change; without it, profiling these languages is nearly pointless.

----
''Sources''
* <html><code>training/library/topics/perf-profiling/primer.md</code></html>

''Related atoms''
* [[What is the `perf` profiler support added in Python 3.12?]]
Q: Find all pairs in an array that sum to k

A: Use a set to track complements in O(n) time.

def two_sum_pairs(arr, k):
    seen = set()
    pairs = []
    for x in arr:
        if k - x in seen:
            pairs.append((k - x, x))
        seen.add(x)
    return pairs

Alternative: sort + two-pointer approach runs O(n log n) but uses O(1) extra space. The hash-set approach is preferred for interviews unless space is constrained.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Two-pointer technique for sorted array problems]]
* [[Merge two sorted arrays]]
* [[Determine if a zero-sum subarray exists]]
Q: Find the first non-repeating character in a string

A: Use [[collections.Counter]] to count frequencies, then iterate to find the first with count 1.

from collections import Counter
def first_unique(s):
    counts = Counter(s)
    for ch in s:
        if counts[ch] == 1:
            return ch
    return None

Time: O(n), Space: O(k) where k is alphabet size. Two-pass approach — first pass counts, second finds.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Generate all permutations of a string]]
* [[Set comprehension]]
* [[enumerate()]]
Q: Product array — compute products of all elements except self

A: Build prefix and suffix product arrays, then multiply.

def product_except_self(nums):
    n = len(nums)
    result = [1] * n
    prefix = 1
    for i in range(n):
        result[i] = prefix
        prefix *= nums[i]
    suffix = 1
    for i in range(n - 1, -1, -1):
        result[i] *= suffix
        suffix *= nums[i]
    return result

O(n) time, O(1) extra space (output array not counted). No division needed — handles zeros correctly.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Determine if a zero-sum subarray exists]]
* [[What does `math.prod()` do, and when was it added?]]
* [[How do you use `itertools.product` to get the equivalent of a triple nested loop?]]
Q: Find the middle element of a linked list in one pass

A: Use slow/fast pointer technique (Floyd's tortoise and hare).

def find_middle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow

When fast reaches the end, slow is at the middle. O(n) time, O(1) space. For even-length lists, this returns the second middle node.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Detect a cycle in a linked list]]
* [[Implement a linked list with insert, find, delete]]
* [[Implement DFS and BFS for a graph]]
Q: Detect a cycle in a linked list

A: Floyd's cycle detection: use slow (1 step) and fast (2 step) pointers.

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

To find the cycle start: when slow == fast, reset one pointer to head and advance both by 1 — they meet at the cycle entry. O(n) time, O(1) space.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Find the middle element of a linked list in one pass]]
* [[Implement DFS and BFS for a graph]]
* [[Implement a linked list with insert, find, delete]]
Q: Implement DFS and BFS for a graph

A: DFS uses a stack (or recursion), BFS uses a queue.

from collections import deque

def bfs(graph, start):
    visited, queue = set(), deque([start])
    visited.add(start)
    while queue:
        node = queue.popleft()
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return visited

def dfs(graph, start, visited=None):
    if visited is None: visited = set()
    visited.add(start)
    for neighbor in graph[start]:
        if neighbor not in visited:
            dfs(graph, neighbor, visited)
    return visited

BFS finds shortest path in unweighted graphs. DFS is better for detecting cycles and topological sorting.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[What is the `graphlib` module?]]
* [[Detect a cycle in a linked list]]
* [[Implement a linked list with insert, find, delete]]
Q: Implement QuickSort

A: Divide-and-conquer: pick a pivot, partition, recurse.

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    mid = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + mid + quicksort(right)

Average O(n log n), worst O(n^2) with bad pivot choice. In-place variant uses Lomuto or Hoare partitioning. Python's built-in sorted() uses Timsort (O(n log n) guaranteed).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Implement binary search]]
* [[What is Timsort?]]
* [[Generate the largest number from a list of integers]]
Q: Implement a Trie (prefix tree)

A: A tree where each node represents a character prefix.

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
        node.is_end = True

    def search(self, word):
        node = self._find(word)
        return node is not None and node.is_end

    def starts_with(self, prefix):
        return self._find(prefix) is not None

Used for autocomplete, spell-check, IP routing. O(m) per operation where m is word length.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Implement a linked list with insert, find, delete]]
* [[Common string methods]]
* [[class]]
Q: Check anagram removal count for two strings

A: Count character frequencies and sum absolute differences.

from collections import Counter
def anagram_removals(s1, s2):
    c1, c2 = Counter(s1), Counter(s2)
    return sum((c1 - c2).values()) + sum((c2 - c1).values())

This gives the total characters to remove from both strings to make them anagrams. Counter subtraction only keeps positive counts, so we sum both directions. O(n + m) time.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Find the first non-repeating character in a string]]
* [[collections.Counter]]
* [[Find all pairs in an array that sum to k]]
Q: Determine if a zero-sum subarray exists

A: Track prefix sums — if a prefix sum repeats, a zero-sum subarray exists.

def has_zero_sum_subarray(arr):
    prefix_sums = set([0])
    running = 0
    for x in arr:
        running += x
        if running in prefix_sums:
            return True
        prefix_sums.add(running)
    return False

Key insight: if prefix_sum[j] == prefix_sum[i], then sum(arr[i+1:j+1]) == 0. Include 0 in initial set to catch subarrays starting at index 0. O(n) time and space.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Two-pointer technique for sorted array problems]]
* [[Product array — compute products of all elements except self]]
* [[What NumPy function creates an array of zeros?]]
Q: Generate the largest number from a list of integers

A: Custom sort: compare concatenated strings.

from functools import cmp_to_key
def largest_number(nums):
    strs = list(map(str, nums))
    strs.sort(key=cmp_to_key(lambda a, b: (1 if a+b < b+a else -1 if a+b > b+a else 0)))
    result = ''.join(strs)
    return '0' if result[0] == '0' else result

Compare '9'+'34' vs '34'+'9' -> '934' > '349' so 9 comes first. Edge case: all zeros -> return '0'. O(n log n) time.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Sliding window maximum]]
* [[What does `functools.cmp_to_key` do?]]
* [[sorted() and .sort()]]
Q: Calculate the stock span problem

A: Use a monotonic decreasing stack to find previous greater elements.

def stock_span(prices):
    spans = []
    stack = []  # (price, index)
    for i, price in enumerate(prices):
        while stack and stack[-1][0] <= price:
            stack.pop()
        span = i + 1 if not stack else i - stack[-1][1]
        spans.append(span)
        stack.append((price, i))
    return spans

The span for day i is the number of consecutive days before it (including itself) where price was <= price[i]. Classic monotonic stack pattern. O(n) amortized.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Sliding window maximum]]
* [[Walrus operator (:=)]]
* [[yield (generators)]]
Q: Implement a linked list with insert, find, delete

A: class Node:
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt

class LinkedList:
    def __init__(self):
        self.head = None

    def insert(self, val):
        self.head = Node(val, self.head)

    def find(self, val):
        curr = self.head
        while curr:
            if curr.val == val: return curr
            curr = curr.next
        return None

    def delete(self, val):
        if not self.head: return
        if self.head.val == val:
            self.head = self.head.next; return
        curr = self.head
        while curr.next:
            if curr.next.val == val:
                curr.next = curr.next.next; return
            curr = curr.next

Insert: O(1) at head. Find/Delete: O(n). Use a sentinel/dummy head node to simplify edge cases.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Find the middle element of a linked list in one pass]]
* [[Detect a cycle in a linked list]]
* [[Implement a Trie (prefix tree)]]
Q: Reverse words in a sentence

A: Split, reverse, rejoin.

def reverse_words(s):
    return ' '.join(s.split()[::-1])

split() without args handles multiple spaces. For in-place reversal (interview follow-up): reverse entire string, then reverse each word. Python strings are immutable, so true in-place requires a list of chars.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[String slicing]]
* [[Common string methods]]
* [[What does `reversed()` require?]]
Q: Generate all permutations of a string

A: Use backtracking or itertools.permutations.

def permutations(s):
    if len(s) <= 1:
        return [s]
    result = []
    for i, ch in enumerate(s):
        rest = s[:i] + s[i+1:]
        for perm in permutations(rest):
            result.append(ch + perm)
    return result

Or simply: from itertools import permutations as p; list(p('abc'))

Time: O(n! * n). For deduplication with repeated chars, use a set or sort + skip approach.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Find the first non-repeating character in a string]]
* [[What does `itertools.combinations('ABCD', 2)` return?]]
* [[How many items does `itertools.permutations('ABC', 2)` yield?]]
Q: Two-pointer technique for sorted array problems

A: Two pointers converging from both ends of a sorted array.

def two_sum_sorted(arr, target):
    left, right = 0, len(arr) - 1
    while left < right:
        s = arr[left] + arr[right]
        if s == target:
            return (left, right)
        elif s < target:
            left += 1
        else:
            right -= 1
    return None

O(n) time, O(1) space. Works because the array is sorted. Also used for: container with most water, remove duplicates, three-sum (fix one + two-pointer on rest).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Find all pairs in an array that sum to k]]
* [[Merge two sorted arrays]]
* [[Determine if a zero-sum subarray exists]]
Q: Implement binary search

A: Halve the search space each iteration.

def binary_search(arr, target):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

O(log n) time, O(1) space. Use bisect module in production: bisect.bisect_left(arr, target).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Implement QuickSort]]
* [[What module provides functions to maintain a list in sorted order without having to sor…]]
* [[Walrus operator (:=)]]
Q: Merge two sorted arrays

A: Two-pointer merge in O(n + m) time.

def merge_sorted(a, b):
    result = []
    i = j = 0
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            result.append(a[i]); i += 1
        else:
            result.append(b[j]); j += 1
    result.extend(a[i:])
    result.extend(b[j:])
    return result

This is the merge step of merge sort. O(n + m) time and space. In Python, heapq.merge(a, b) does this lazily.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[What function in `heapq` merges multiple sorted inputs into a single sorted output?]]
* [[Two-pointer technique for sorted array problems]]
* [[List operations]]
Q: Detect palindrome

A: Compare string to its reverse, or use two pointers.

def is_palindrome(s):
    return s == s[::-1]

! Two-pointer (better for follow-ups):
def is_palindrome_tp(s):
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1; right -= 1
    return True

For alphanumeric-only: filter with isalnum() and lower() first. Extends to 'valid palindrome II' (remove at most one char).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[Reverse words in a sentence]]
* [[String slicing]]
* [[What does `reversed()` require?]]
Q: Sliding window maximum

A: Use a monotonic deque to track max in O(n).

from collections import deque
def max_sliding_window(nums, k):
    dq = deque()  # indices of useful elements
    result = []
    for i, num in enumerate(nums):
        while dq and dq[0] < i - k + 1:
            dq.popleft()
        while dq and nums[dq[-1]] <= num:
            dq.pop()
        dq.append(i)
        if i >= k - 1:
            result.append(nums[dq[0]])
    return result

The deque stores indices in decreasing order of values. Front is always the max for the current window. O(n) total.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-algorithms.tsv</code></html>

''Related atoms''
* [[collections.deque]]
* [[Generate the largest number from a list of integers]]
* [[break]]
Python's Global Interpreter Lock (GIL) prevents multiple threads from executing Python bytecode simultaneously. Threads only parallelize I/O-bound work—operations where the GIL is released during syscalls (network, file, sleep). For CPU-bound work (data processing, parsing, math), <html><code>ProcessPoolExecutor</code></html> is required for actual parallelism. Using threads for CPU work adds context-switching overhead without speedup; the result is slower than single-threaded.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>

''Related atoms''
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
* [[Workload type determines the optimal concurrency model]]
* [[multiprocessing]]
CPython's Global Interpreter Lock is a mutex that permits only one thread to execute Python bytecode at a time, protecting the reference-counting garbage collector but eliminating true CPU parallelism. The GIL releases during I/O operations—network calls, file reads, blocking system calls—and when C extensions explicitly drop it (NumPy, hashlib). This means threading gains concurrency for I/O-bound workloads but gives zero speedup for CPU-bound tasks and may make them slower through contention and acquisition overhead. [[Multiprocessing|multiprocessing]] bypasses the GIL entirely by using separate OS processes with independent interpreters and locks. Non-CPython implementations (Jython, IronPython) lack the GIL. Critically, the GIL does not prevent data races on mutable Python objects; synchronization primitives remain necessary even for I/O-bound code. PEP 703 (accepted 2023) introduces a GIL-free CPython build expected in Python 3.15+.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>
* <html><code>training/library/topics/python-async-concurrency/primer.md</code></html>

//Merged from 3 source atoms.//

''Related atoms''
* [[Multiprocessing achieves true CPU parallelism with separate interpreters]]
* [[What is the per-interpreter GIL in Python 3.12?]]
* [[What is the difference between concurrency and parallelism in Python?]]
The Global Interpreter Lock prevents true parallel execution of Python bytecode. Many developers assume threads are broken and blame the GIL when profiling shows threads aren't running concurrently. This is correct for CPU-bound work: the GIL is a hard architectural constraint. However, the GIL releases during I/O operations—network requests, disk reads, file writes, time.sleep()—allowing concurrent execution. This distinction determines whether to use threading, [[multiprocessing]], or asyncio.

For CPU-bound parallelism, threading doesn't help; use multiprocessing or ProcessPoolExecutor to spawn separate Python processes with their own GILs. For I/O-bound concurrency, threads work fine because blocked I/O calls release the GIL, allowing other threads to run while you wait. The footgun is profiling a multi-threaded program, seeing sequential execution, and concluding threading is broken. You need to know whether your bottleneck is CPU or I/O; if you're wrong, you'll optimize the wrong tool and waste hours.

----
''Sources''
* <html><code>training/library/topics/python-debugging/footguns.md</code></html>

''Related atoms''
* [[Multiprocessing achieves true CPU parallelism with separate interpreters]]
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
* [[Workload type determines the optimal concurrency model]]
Calling <html><code>requests.get()</code></html> or <html><code>time.sleep()</code></html> inside <html><code>async def</code></html> pauses the entire event loop. All other coroutines block until the blocking call returns. In a FastAPI server serving 1000 concurrent users, a single blocking database query stops all request handling. Use async-aware libraries (<html><code>aiohttp</code></html>, <html><code>asyncpg</code></html>) for I/O. For unavoidable blocking calls, offload to a thread pool with <html><code>loop.run_in_executor(None, blocking_func)</code></html>. Enable <html><code>PYTHONASYNCIODEBUG=1</code></html> to detect blocking calls longer than 100ms.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>

''Related atoms''
* [[Debugging hung async code via debug mode and task inspection]]
* [[Event loops are thread-local; use run_coroutine_threadsafe to call async from threads]]
* [[subprocess.run blocks; use asyncio.create_subprocess_exec for concurrency]]
An async function is a coroutine that yields control back to the event loop during <html><code>await</code></html> calls. Any blocking operation (synchronous I/O, CPU work, <html><code>time.sleep()</code></html>) inside an async function stalls the event loop, preventing all other coroutines from running. FastAPI endpoints marked <html><code>async def</code></html> run in the same event loop (via Uvicorn/ASGI); a single blocking call blocks all concurrent requests. Inside an async endpoint, all I/O must use async libraries (<html><code>httpx.AsyncClient</code></html>, not <html><code>requests</code></html>). If an async library doesn't exist, either run the endpoint as plain <html><code>def</code></html> (FastAPI runs it in a thread pool, default 40 threads) or use <html><code>loop.run_in_executor()</code></html> to offload the blocking call. The gotcha: FastAPI's thread pool is finite; 50 concurrent requests to slow sync endpoints cause queueing and unpredictable latency spikes visible in access logs.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/street_ops.md</code></html>

''Related atoms''
* [[Event loop blocking in async Python services]]
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[Debugging hung async code via debug mode and task inspection]]
Each thread needs its own event loop. Calling <html><code>asyncio.run()</code></html> from a worker thread creates a new loop that conflicts with the main loop. To schedule a coroutine from a thread, use <html><code>asyncio.run_coroutine_threadsafe(coro, loop)</code></html>, which schedules the coroutine on the given loop and returns a <html><code>future</code></html>. Call <html><code>future.result(timeout=...)</code></html> to wait for completion without blocking the loop itself.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>

''Related atoms''
* [[Blocking I/O calls freeze the asyncio event loop and all other coroutines]]
* [[Debugging hung async code via debug mode and task inspection]]
* [[What is `asyncio.wait_for()` used for?]]
On Linux, <html><code>multiprocessing.Process</code></html> uses <html><code>fork()</code></html> by default. If threads exist before fork, the child process inherits all locks in their current state—including held locks that are now permanently locked with no way to release them. The child deadlocks on first use of the locked mutex. Call <html><code>multiprocessing.set_start_method('spawn')</code></html> at program start, before any threads are created, to avoid fork-based copying.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>
Docker containers run Python as PID 1 by default. The init process normally reaps zombie child processes; PID 1 doesn't, so workers created by <html><code>multiprocessing.Pool</code></html> or <html><code>ProcessPoolExecutor</code></html> become zombies when they exit, accumulating in <html><code>ps</code></html> output and consuming resources. Wrap your command with <html><code>tini</code></html> (or use <html><code>docker run --init</code></html>) to provide a proper init. Separately, the fork start method (default on Linux) copies the entire parent process including locked mutexes from threads. If you create any threads before forking (e.g., in thread pools, HTTP clients, or database connections), child processes inherit those locks and deadlock because no thread exists to unlock them. Use <html><code>multiprocessing.set_start_method("spawn")</code></html> or <html><code>"forkserver"</code></html> to start fresh Python processes instead of forking. Call this before creating any threads. In Docker, always prefer spawn or forkserver.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/street_ops.md</code></html>
Calling <html><code>Process.start()</code></html> without later calling <html><code>Process.join()</code></html> leaves zombie processes that remain in the OS process table. In long-running services, zombie processes accumulate until the OS PID limit is hit and new processes cannot be created. Always call <html><code>join(timeout=...)</code></html> to wait for completion, or better: use <html><code>ProcessPoolExecutor</code></html> or <html><code>multiprocessing.Pool</code></html> which manage process lifecycle automatically.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>
<html><code>counter += 1</code></html> is three bytecode instructions: load, add, store. A thread switch between load and store loses the update. Multiple threads incrementing a shared counter, appending to shared lists, or updating shared dictionaries will corrupt state without <html><code>threading.Lock</code></html>. Guard all read-modify-write operations on shared state with a lock, or redesign to avoid shared mutable state entirely by using message passing via queues.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>

''Related atoms''
* [[Why does the GIL exist?]]
* [[The Global Interpreter Lock constrains Python threading to I/O concurrency]]
* [[Shared mutable state in threads requires explicit synchronization]]
Creating <html><code>aiohttp.ClientSession()</code></html> without <html><code>async with</code></html> never closes the connection pool. Connections accumulate until <html><code>OSError: [Errno 24] Too many open files</code></html>. Always use <html><code>async with</code></html> for sessions, database connections, file handles, and any resource with <html><code>__aenter__</code></html>/<html><code>__aexit__</code></html> methods. Enable <html><code>PYTHONASYNCIODEBUG=1</code></html> or use Python warnings (<html><code>-W all</code></html>) to catch <html><code>ResourceWarning</code></html> for unclosed resources.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>

''Related atoms''
* [[Rate-limited async API client with retry and backoff handles bulk scanning safely]]
* [[Blocking I/O calls freeze the asyncio event loop and all other coroutines]]
Thread A acquires lock_x and waits for lock_y. Thread B acquires lock_y and waits for lock_x. Both threads block forever. Establish a global lock ordering (e.g., always acquire lock_x before lock_y) and use that order everywhere. Detect deadlocks with <html><code>lock.acquire(timeout=5)</code></html>—if the timeout fires, a deadlock is likely. Consider using coarser locks or lock-free designs (message passing) to eliminate deadlock risk.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>

''Related atoms''
* [[What is `threading.Lock` used for?]]
* [[Forking after threading creates deadlocked child processes with copied lock state]]
* [[Shared mutable state in threads requires explicit synchronization]]
Before Python 3.13, <html><code>ThreadPoolExecutor()</code></html> with no argument defaults to <html><code>min(32, os.cpu_count() + 4)</code></html> workers. On a 64-core machine that is 32 threads. If each thread opens a database connection, the executor consumes 32 connections immediately, exceeding typical database connection limits. Always set <html><code>max_workers</code></html> explicitly based on the bottleneck resource—database pool size, API rate limit, available file descriptors—not CPU count.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>

''Related atoms''
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
* [[ProcessPoolExecutor requires serializable functions and data; lambdas cannot be pickled]]
* [[Threads do not parallelize CPU-bound work; the GIL serializes operations]]
<html><code>ProcessPoolExecutor</code></html> serializes function arguments and return values between processes using <html><code>pickle</code></html>. Lambdas, nested functions, open file handles, and database connections cannot be pickled and raise <html><code>TypeError: can't pickle &lt;...&gt;</code></html>. Use module-level named functions and pass only serializable data (strings, numbers, dicts, lists). Create non-serializable resources (database connections, file handles) inside the worker process, not before passing to the executor.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/footguns.md</code></html>

''Related atoms''
* [[ThreadPoolExecutor defaults to too many workers for resource-limited services]]
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
* [[multiprocessing]]
Every DevOps system eventually hits a concurrency wall. A deployment script provisions 200 VMs one at a time instead of in parallel. A monitoring agent polls 500 endpoints sequentially, blocking on network I/O. A log shipper waits for each network call to complete before sending the next batch. Python provides three concurrency models—threading, [[multiprocessing]], asyncio—and picking the wrong one means your supposedly parallel code runs slower than serial, or crashes under load. The difference between a 3-minute deploy and a 45-minute one, between handling 100 concurrent requests and 10,000, hinges on understanding the GIL, the event loop, and process isolation. This knowledge is foundational: the choice compounds across every scale your system reaches. A poor choice made early becomes a system-wide drag that no amount of optimization fixes downstream.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/primer.md</code></html>

''Related atoms''
* [[Workload type determines the optimal concurrency model]]
* [[GIL prevents CPU parallelism but releases during I/O]]
* [[What is the difference between concurrency and parallelism in Python?]]
The threading module spawns OS-level threads that share process memory and state. Synchronization primitives coordinate access: Lock enforces mutual exclusion; RLock allows the same thread to reacquire; Semaphore bounds concurrent access; Event acts as a condition flag; Condition enables wait-notify patterns. Queue provides thread-safe producer-consumer workflows. ThreadPoolExecutor is the preferred interface: it manages a pool of reusable workers, abstracts job submission via <html><code>submit()</code></html> or <html><code>map()</code></html>, and provides <html><code>as_completed()</code></html> for incremental result collection. Thread pooling avoids the overhead of spawning a fresh OS thread for each task. For I/O-bound work with manageable concurrency (tens to hundreds of concurrent operations), ThreadPoolExecutor is simpler, faster, and less error-prone than asyncio. Data races require careful locking, but shared memory eliminates serialization overhead.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/primer.md</code></html>

''Related atoms''
* [[Workload type determines the optimal concurrency model]]
* [[GIL prevents CPU parallelism but releases during I/O]]
* [[ThreadPoolExecutor enables controlled parallel fleet operations]]
[[Multiprocessing|multiprocessing]] creates separate OS processes, each with its own Python interpreter, memory space, and GIL. Data must be serialized (pickled) to cross process boundaries, incurring overhead but enabling true CPU parallelism without GIL contention. Process creation is expensive; use Process for long-lived background work and Pool for distributing discrete tasks. Pool.map() and Pool.starmap() distribute work across workers and collect results. ProcessPoolExecutor provides the concurrent.futures interface, making it easy to swap threading for multiprocessing in existing code. For CPU-bound tasks—math, compression, data parsing, image processing—multiprocessing is the only path to scaling with multiple cores. The serialization cost is negligible compared to the speedup of true parallelism.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/primer.md</code></html>

''Related atoms''
* [[The Global Interpreter Lock constrains Python threading to I/O concurrency]]
* [[GIL prevents CPU parallelism but releases during I/O]]
* [[What is `multiprocessing.Pool` used for?]]
asyncio schedules coroutines (async def functions) on a single-threaded event loop. Coroutines voluntarily yield control at <html><code>await</code></html> points, allowing other coroutines to run without OS thread overhead or explicit synchronization. A Task wraps a coroutine and schedules it on the loop. <html><code>asyncio.gather()</code></html> runs multiple tasks concurrently and collects results in order; <html><code>asyncio.wait()</code></html> offers finer control (timeout, return_when=FIRST_COMPLETED). Semaphore rate-limits concurrent operations. The event loop executes one coroutine step at a time, so CPU-bound code blocks the entire loop—use only async-aware libraries (aiohttp instead of requests; asyncio.sleep instead of time.sleep). Thousands of concurrent connections become practical because there is no OS thread per connection. asyncio excels for high-concurrency I/O: bulk API calls, long-lived websockets, polling loops. The downside: code must be callback-free and async-native.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/primer.md</code></html>

''Related atoms''
* [[What is `asyncio.create_task()` vs `await`?]]
* [[What is `asyncio.wait_for()` used for?]]
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
<html><code>asyncio.Semaphore</code></html> enforces a cap on concurrent tasks. Create a semaphore with the desired limit, wrap each coroutine with <html><code>async with sem:</code></html>, and await normally. Tasks queue to acquire the semaphore; only N can proceed at once. Unlike <html><code>asyncio.gather()</code></html> with a fixed batch size, semaphores allow new coroutines to be submitted freely; they automatically wait their turn. Useful for rate-limiting API calls, database connections, or I/O operations without rewriting the submission logic. The pattern: create one semaphore, define a bounded async function that acquires the semaphore and runs the coroutine, then pass a list of bounded calls to <html><code>asyncio.gather()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/street_ops.md</code></html>

''Related atoms''
* [[What is `asyncio.Semaphore` used for?]]
* [[Blocking I/O calls freeze the asyncio event loop and all other coroutines]]
* [[Rate-limited async API client with retry and backoff handles bulk scanning safely]]
concurrent.futures provides ThreadPoolExecutor and ProcessPoolExecutor with identical interfaces: <html><code>submit(func, *args)</code></html> queues a task, <html><code>map(func, iterable)</code></html> distributes work and collects results in order, <html><code>as_completed(futures)</code></html> iterates results as they finish, <html><code>wait(futures, timeout=30)</code></html> blocks with timeout and return_when options (ALL_COMPLETED, FIRST_EXCEPTION, FIRST_COMPLETED). Future objects represent pending or completed results; <html><code>future.result(timeout)</code></html> blocks until ready and raises exceptions on failure. This abstraction lets you write one code path and swap backends: ThreadPoolExecutor for I/O-bound, ProcessPoolExecutor for CPU-bound, with no other changes. Easy experimentation with different concurrency strategies without restructuring the whole codebase.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/primer.md</code></html>

''Related atoms''
* [[What is the `concurrent.futures.as_completed()` function?]]
* [[threading]]
* [[concurrent.futures parallelizes I/O-bound infrastructure tasks]]
Q: What is <html><code>concurrent.futures</code></html> and when was it introduced?

A: Added in Python 3.2, it provides a high-level interface for asynchronous execution using <html><code>ThreadPoolExecutor</code></html> and <html><code>ProcessPoolExecutor</code></html>, both implementing a unified <html><code>Future</code></html> pattern.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `concurrent.futures.as_completed()` function?]]
* [[threading]]
* [[What is the difference between concurrency and parallelism in Python?]]
Bulk HTTP requests (hundreds to thousands) belong to asyncio: low memory per connection, thousands of sockets on a single thread. Parallel file I/O uses ThreadPoolExecutor: simple, GIL released during disk operations, minimal boilerplate. CPU-bound processing (parsing, math, compression, image work) demands ProcessPoolExecutor to bypass the GIL entirely. Real-time websockets and polling loops are asyncio. Subprocess management is asyncio.create_subprocess_exec() for non-blocking execution. Quick parallelism in scripts: ThreadPoolExecutor. Mixed I/O and CPU pipelines: spawn async I/O tasks, offload CPU work to a process pool via <html><code>loop.run_in_executor(pool, func)</code></html>. Decision heuristic: I/O waits? Threads. CPU burns? Processes. Thousands of sockets? Async.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/primer.md</code></html>

''Related atoms''
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[GIL prevents CPU parallelism but releases during I/O]]
* [[Threads do not parallelize CPU-bound work; the GIL serializes operations]]
<html><code>subprocess.run()</code></html> executes a command and blocks until completion, forcing sequential execution. Managing multiple subprocess calls (e.g., parallel kubectl, parallel git operations) becomes slow. <html><code>asyncio.create_subprocess_exec()</code></html> runs a command without blocking the event loop; you await the result. This makes subprocess calls composable with other async operations: spawn multiple subprocesses concurrently, poll their output, coordinate completion. Use the asyncio variant when managing many subprocess calls or when subprocess completion must not stall other async work.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/primer.md</code></html>

''Related atoms''
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[Blocking I/O calls freeze the asyncio event loop and all other coroutines]]
* [[Event loops are thread-local; use run_coroutine_threadsafe to call async from threads]]
asyncio signal handlers must be registered on the event loop via <html><code>loop.add_signal_handler()</code></html> and wrapped in an async shutdown callback that cancels pending tasks. Signal handlers in threading only work in the main thread; use <html><code>signal.signal()</code></html> to install them, then set a <html><code>threading.Event()</code></html> to coordinate graceful shutdown. Both require explicit cleanup to avoid zombie tasks or hung threads. Signal handling in concurrent code ensures that SIGTERM or SIGINT from the OS can trigger orderly shutdown instead of abrupt termination.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/primer.md</code></html>

''Related atoms''
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
* [[Event loops are thread-local; use run_coroutine_threadsafe to call async from threads]]
Bulk API calls (hundreds or thousands of endpoints) can overwhelm a service or trigger rate limiting. Use asyncio with a semaphore to bound concurrent requests, exponential backoff (2^attempt seconds) for transient failures, and respect for Retry-After headers. aiohttp.TCPConnector limits connections per host and globally. For 500+ concurrent requests, asyncio is the right tool; OS threading would exhaust file descriptor limits and context-switch overhead. The pattern: create a semaphore, wrap each fetch in <html><code>async with sem</code></html>, use exponential backoff on failure, parse Retry-After headers and sleep, return structured results (success or error dict). Compose many concurrent scans with <html><code>asyncio.gather()</code></html>. This approach scans thousands of endpoints without overwhelming the target or melting your own system.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/street_ops.md</code></html>

''Related atoms''
* [[Semaphore limits concurrent operations without blocking new submissions]]
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[Blocking I/O calls freeze the asyncio event loop and all other coroutines]]
ProcessPoolExecutor distributes CPU-bound work (log parsing, checksum computation, compression) across multiple processes, avoiding Python's GIL. Worker processes run independently; the main process submits tasks and collects results via futures. Use <html><code>as_completed()</code></html> to process results in order of completion rather than submission order, enabling progress feedback without waiting for slower tasks. Default worker count is <html><code>os.cpu_count()</code></html> (or <html><code>min(32, os.cpu_count() + 4)</code></html> in Python 3.13+). Each task runs in its own process, so exceptions are captured in <html><code>future.result()</code></html> rather than propagating immediately. For fine-grained progress reporting, track completion count and log at intervals. Timeouts on <html><code>future.result()</code></html> prevent hung tasks from blocking indefinitely.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/street_ops.md</code></html>

''Related atoms''
* [[GIL prevents CPU parallelism but releases during I/O]]
* [[ThreadPoolExecutor enables controlled parallel fleet operations]]
* [[Threads do not parallelize CPU-bound work; the GIL serializes operations]]
When async code hangs silently with no output or error, enable asyncio debug mode (<html><code>asyncio.run(main(), debug=True)</code></html> or <html><code>PYTHONASYNCIODEBUG=1</code></html>) to catch coroutines that were never awaited, callbacks blocking the loop, and unclosed resources. Dump all running tasks and their stack traces with <html><code>asyncio.all_tasks()</code></html> to see what's actually executing. Common causes of hangs: forgot <html><code>await</code></html> on a coroutine (returns an unawaited object, does nothing), deadlock on a queue or event that will never be signaled, blocking calls like <html><code>time.sleep()</code></html> in async code (use <html><code>await asyncio.sleep()</code></html> instead), or exception swallowing in <html><code>asyncio.gather()</code></html> (use <html><code>return_exceptions=True</code></html> to collect failures). The symptom — program appears to run but produces no output and never exits — maps to one of these patterns.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/street_ops.md</code></html>

''Related atoms''
* [[Blocking I/O calls freeze the asyncio event loop and all other coroutines]]
* [[Event loop blocking in async Python services]]
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
Multiple threads reading and modifying the same dict, list, or other mutable object create race conditions. Even a simple <html><code>count += 1</code></html> is unsafe: it reads the current value, increments it, and writes back, but another thread can interleave between read and write, causing lost updates. The fix is a lock: wrap all access to shared state in <html><code>with lock:</code></html> to ensure atomic read-modify-write. Better still, use thread-safe data structures like <html><code>queue.Queue</code></html>, which handle synchronization internally. Semaphores and condition variables are useful for coordinating thread activity (e.g., "wake up when 10 items arrive in the queue"), but for simple counters and collections, a lock or thread-safe queue is the straightforward choice.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/street_ops.md</code></html>

''Related atoms''
* [[The GIL does not make individual operations atomic; protect shared state with locks]]
* [[Threading pools coordinate I/O-bound work with shared memory and locks]]
* [[What is `threading.Lock` used for?]]
Async services must handle SIGINT and SIGTERM to shut down cleanly without losing work. Register signal handlers with <html><code>loop.add_signal_handler()</code></html> to trigger shutdown logic. Track all background tasks in a set, adding new tasks and discarding completed ones via callback. On shutdown, set a flag to stop workers from starting new work, cancel all tasks, and wait for them to finish with <html><code>asyncio.gather(*tasks, return_exceptions=True)</code></html>. Workers catch <html><code>asyncio.CancelledError</code></html> to perform cleanup (finish current item, flush buffers, close connections) before exiting. A common pattern: workers loop <html><code>while self.running</code></html>, catch <html><code>CancelledError</code></html> to log and break, and catch application exceptions to log and retry. This ensures clean exit without orphaned coroutines or half-processed items.

----
''Sources''
* <html><code>training/library/topics/python-async-concurrency/street_ops.md</code></html>

''Related atoms''
* [[Debugging hung async code via debug mode and task inspection]]
* [[Event loops are thread-local; use run_coroutine_threadsafe to call async from threads]]
Q: if / elif / else

A: x = 10
if x > 20:
    print("big")
elif x > 5:
    print("medium")  # ← this runs
else:
    print("small")

Conditions are evaluated top-to-bottom; first True branch wins. elif and else are optional.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[for/else and while/else]]
* [[Walrus operator (:=)]]
* [[while loop]]
Q: for loop

A: for name in ["alice", "bob", "carol"]:
    print(name.upper())

Iterates over any iterable: lists, strings, dicts, files, generators, range().

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[zip()]]
* [[collections.defaultdict]]
* [[Common string methods]]
Q: while loop

A: n = 5
while n > 0:
    print(n)
    n -= 1

Runs as long as the condition is True. Use break to exit early.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[for/else and while/else]]
* [[if / elif / else]]
* [[yield (generators)]]
Q: break

A: for n in range(100):
    if n > 4:
        break
    print(n)  # prints 0 1 2 3 4

Exits the innermost loop immediately.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[continue]]
* [[for/else and while/else]]
* [[any() and all()]]
Q: continue

A: for n in range(5):
    if n == 2:
        continue
    print(n)  # prints 0 1 3 4

Skips the rest of the current iteration, jumps to the next one.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[break]]
* [[for/else and while/else]]
* [[yield (generators)]]
Q: pass

A: class NotYet:
    pass  # placeholder — class body can't be empty

def todo():
    pass  # same for functions

Does nothing. Used as a syntactic placeholder.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What does `pass` do in Python?]]
* [[def (function definition)]]
* [[class]]
Q: def (function definition)

A: def greet(name):
    return f"hello, {name}"

print(greet("alice"))  # hello, alice

Functions are first-class objects — you can pass them, return them, store them.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What are first-class functions?]]
* [[class]]
* [[__init__ and __repr__]]
Q: lambda (anonymous function)

A: square = lambda x: x ** 2
print(square(5))  # 25

sorted(["bob", "alice"], key=lambda s: len(s))
! ['bob', 'alice']

Single-expression functions. No statements, no multi-line.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is a lambda function?]]
* [[What is the `operator` module?]]
* [[map() and filter()]]
Q: return

A: def add(a, b):
    return a + b

result = add(3, 4)  # 7

Sends a value back to the caller and exits the function. Without return, function returns None.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What value is returned if a function has no return statement?]]
* [[What is the difference between return and print?]]
* [[__add__, __eq__, __lt__ (operator overloading)]]
Q: yield (generators)

A: def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):
    print(x)  # 3 2 1

Pauses the function and produces a value. Resumes on next iteration. Memory-efficient for large sequences.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is a Python generator?]]
* [[What does the yield keyword do?]]
* [[continue]]
Q: class

A: class Dog:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return f"{self.name} says woof"

d = Dog("Rex")
print(d.speak())  # Rex says woof

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[def (function definition)]]
* [[__init__ and __repr__]]
* [[Class variable vs instance variable]]
Q: Inheritance

A: class Animal:
    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "woof"

class Cat(Animal):
    def speak(self):
        return "meow"

for a in [Dog(), Cat()]:
    print(a.speak())  # woof, meow

Subclasses override parent methods. Use super() to call the parent.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[super()]]
* [[How does super() work in Python 3?]]
* [[Explain Python's Method Resolution Order (MRO)]]
Q: self

A: class Counter:
    def __init__(self):
        self.count = 0
    def inc(self):
        self.count += 1

self is the instance — it's how methods access the object's data. Not a keyword, but always the first parameter.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[__init__ and __repr__]]
* [[Class variable vs instance variable]]
* [[class]]
Q: try / except

A: try:
    x = int("not a number")
except ValueError as e:
    print(f"bad input: {e}")

Catch specific exceptions. Avoid bare except: — always name the exception type.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is the `except*` syntax?]]
* [[try / except / else / finally]]
* [[What is a "Value Error"?]]
Q: [[try / except]] / else / finally

A: try:
    f = open("data.txt")
except FileNotFoundError:
    print("missing")
else:
    print(f.read())  # runs only if no exception
finally:
    print("always runs")  # cleanup goes here

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[with (context manager)]]
* [[try / except]]
* [[What is the `except*` syntax?]]
Q: raise

A: def divide(a, b):
    if b == 0:
        raise ValueError("cannot divide by zero")
    return a / b

Raise an exception explicitly. raise without args re-raises the current exception in an except block.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[try / except]]
* [[assert]]
* [[return]]
Q: assert

A: def avg(nums):
    assert len(nums) > 0, "empty list"
    return sum(nums) / len(nums)

Raises AssertionError if condition is False. Disabled with python -O. Use for sanity checks, not input validation.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Truthy and falsy values]]
* [[Assertions are development aids, removed in production with -O]]
* [[raise]]
Q: with (context manager)

A: with open("file.txt") as f:
    data = f.read()
! f is automatically closed here

Guarantees cleanup (close, unlock, etc.) even if an exception occurs. Calls [[__enter__ and __exit__]] under the hood.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[try / except / else / finally]]
* [[What is the difference between read() and readlines()?]]
* [[What does the open() mode 'a' do?]]
Q: as (aliasing)

A: import numpy as np          # module alias
with open("f") as fh:       # bind context manager result
except KeyError as e:        # bind exception to name

as binds a name in import, with, and except statements.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is the `with` statement's full syntax since Python 3.1?]]
* [[What does the `import` statement do in Python?]]
* [[What is the difference between `__import__()` and `importlib.import_module()`?]]
Q: in / not in (membership)

A: print(3 in [1, 2, 3])          # True
print("x" not in "hello")      # True
print("key" in {"key": 1})     # True (checks keys)

Works on lists, tuples, sets, dicts (keys), strings (substring).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[is / is not (identity)]]
* [[What is the result of `{} == set()`?]]
* [[What is the result of `bool([])`?]]
Q: is / is not (identity)

A: x = None
if x is None:
    print("nothing here")

a = [1, 2]
b = a
print(a is b)   # True (same object)
print(a is [1,2])  # False (different object, same value)

is checks identity (same object in memory). Use == for value equality.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[How do you check for `None` in Python?]]
* [[What is the difference between `is` and `==` in Python?]]
* [[What is the difference between == and is in Python?]]
Q: del (delete)

A: x = 42
del x         # unbinds the name

lst = [1, 2, 3]
del lst[1]    # [1, 3]

d = {"a": 1}
del d["a"]    # {}

Removes a name binding, list element, dict entry, or attribute.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is the `del` statement?]]
* [[Dict operations]]
* [[What is a "dictionary"?]]
Q: global / nonlocal

A: count = 0
def increment():
    global count
    count += 1

def outer():
    x = 10
    def inner():
        nonlocal x
        x += 1
    inner()
    print(x)  # 11

global refers to module scope; nonlocal refers to enclosing function scope.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Closure]]
* [[What is the `nonlocal` keyword used for?]]
* [[What is the `global` keyword used for?]]
Q: None

A: def find(lst, target):
    for item in lst:
        if item == target:
            return item
    return None  # explicit "not found"

result = find([1,2,3], 99)
if result is None:
    print("not found")

Python's null. There is exactly one None object. Always test with is None, not ==.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[How do you check for `None` in Python?]]
* [[is / is not (identity)]]
* [[What is the difference between `None` and `False`?]]
Q: f-string (formatted string literal)

A: name = "alice"
age = 30
print(f"{name} is {age} years old")

print(f"{age:>10}")     # right-align, width 10
print(f"{3.14159:.2f}") # 3.14
print(f"{1000:,}")      # 1,000

Expressions inside {} are evaluated at runtime. Python 3.6+.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[How do you format a number with thousands separators in an f-string?]]
* [[What are the three string formatting approaches in Python?]]
* [[What does `f'{value=}'` do, introduced in Python 3.8?]]
Q: Common string methods

A: s = "  Hello, World  "
s.strip()          # "Hello, World"
s.lower()          # "  hello, world  "
s.split(", ")      # ['  Hello', 'World  ']
"_".join(["a","b"]) # "a_b"
s.replace("World", "Python")
s.startswith("  He")  # True
s.find("World")       # 9 (-1 if not found)
"42".isdigit()         # True

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[re (regular expressions)]]
* [[String slicing]]
* [[Reverse words in a sentence]]
Q: String slicing

A: s = "python"
s[0]      # 'p'
s[-1]     # 'n'
s[2:4]    # 'th'
s[:3]     # 'pyt'
s[3:]     # 'hon'
s[::-1]   # 'nohtyp' (reverse)
s[::2]    # 'pto' (every other)

Same [start:stop:step] syntax works on lists and tuples.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Reverse words in a sentence]]
* [[What is "slicing" in Python?]]
* [[What does `[1, 2, 3][::-1]` return?]]
Q: List operations

A: a = [3, 1, 2]
a.append(4)        # [3, 1, 2, 4]
a.extend([5, 6])   # [3, 1, 2, 4, 5, 6]
a.insert(0, 99)    # [99, 3, 1, 2, 4, 5, 6]
a.pop()            # returns 6, list shrinks
a.remove(99)       # removes first occurrence
a.sort()           # in-place: [1, 2, 3, 4, 5]
a.reverse()        # in-place: [5, 4, 3, 2, 1]
len(a)             # 5

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[collections.deque]]
* [[sorted() and .sort()]]
* [[How do you add an item to the end of a list?]]
Q: List comprehension

A: squares = [x**2 for x in range(5)]       # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]

flat = [c for word in ["hi","yo"] for c in word]  # ['h','i','y','o']

More readable than map/filter for simple transforms.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Dict comprehension]]
* [[What is a list comprehension in Python?]]
* [[Nested comprehension]]
Q: Dict operations

A: d = {"a": 1, "b": 2}
d["c"] = 3              # add/update
d.get("z", 0)           # 0 (no KeyError)
d.pop("b")              # returns 2, removes key
d.update({"a": 10})     # merge
d.setdefault("d", 4)    # insert only if missing

for k, v in d.items():
    print(k, v)

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Unpacking (* and **)]]
* [[What is a "dictionary"?]]
* [[What does `dict | other_dict` do in Python 3.9+?]]
Q: Dict comprehension

A: squares = {x: x**2 for x in range(5)}
! {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

inverse = {v: k for k, v in squares.items()}
! {0: 0, 1: 1, 4: 2, 9: 3, 16: 4}

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[List comprehension]]
* [[What are the different comprehension types in Python?]]
* [[What is a list comprehension in Python?]]
Q: Set operations

A: a = {1, 2, 3}
b = {2, 3, 4}

a | b    # {1, 2, 3, 4}  union
a & b    # {2, 3}        intersection
a - b    # {1}           difference
a ^ b    # {1, 4}        symmetric difference

3 in a   # True (O(1) lookup)
a.add(5)
a.discard(99)  # no error if missing

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What happens when you add two `Counter` objects together?]]
* [[is / is not (identity)]]
* [[Dict operations]]
Q: Set comprehension

A: words = ["hello", "world", "hello"]
unique_lengths = {len(w) for w in words}  # {5}

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[collections.Counter]]
* [[Find the first non-repeating character in a string]]
* [[collections.defaultdict]]
Q: Tuple operations

A: t = (1, "two", 3.0)
t[0]         # 1
t[-1]        # 3.0
len(t)       # 3
a, b, c = t  # unpacking

! single-element tuple needs trailing comma
one = (42,)

! tuples are immutable — no append, no assignment
! t[0] = 99  → TypeError

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is a tuple and how does it differ from a list?]]
* [[What is "tuple unpacking"?]]
* [[String slicing]]
Q: Unpacking (* and **)

A: # Iterable unpacking
first, *rest = [1, 2, 3, 4]  # first=1, rest=[2,3,4]
a, _, b = (1, 2, 3)          # ignore middle value

! Function argument unpacking
def f(a, b, c): return a + b + c
args = [1, 2, 3]
f(*args)       # 6

kw = {"a": 1, "b": 2, "c": 3}
f(**kw)        # 6

! Merge dicts
merged = {''d1, ''d2}

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is "tuple unpacking"?]]
* [[Dict operations]]
* [[*args and **kwargs]]
Q: enumerate()

A: for i, name in enumerate(["alice", "bob", "carol"]):
    print(f"{i}: {name}")
! 0: alice
! 1: bob
! 2: carol

for i, ch in enumerate("abc", start=1):
    print(i, ch)  # 1 a, 2 b, 3 c

Replaces the manual counter pattern. Always prefer over range(len(x)).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[zip()]]
* [[What does `enumerate()` return?]]
* [[collections.defaultdict]]
Q: zip()

A: names = ["alice", "bob"]
ages = [30, 25]

for name, age in zip(names, ages):
    print(f"{name} is {age}")

dict(zip(names, ages))  # {"alice": 30, "bob": 25}

Stops at the shortest iterable. Use itertools.zip_longest to pad.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[for loop]]
* [[enumerate()]]
* [[What is a "dictionary"?]]
Q: map() and filter()

A: nums = [1, 2, 3, 4, 5]

list(map(str, nums))           # ['1','2','3','4','5']
list(filter(lambda x: x>3, nums))  # [4, 5]

Both return lazy iterators. Usually prefer comprehensions:
[str(n) for n in nums]
[n for n in nums if n > 3]

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is a list comprehension in Python?]]
* [[List comprehension]]
* [[collections.deque]]
Q: any() and all()

A: nums = [2, 4, 6, 7, 8]
any(x > 5 for x in nums)   # True  (at least one)
all(x > 0 for x in nums)   # True  (every one)
all(x % 2 == 0 for x in nums)  # False (7 is odd)

Short-circuit: any() stops at first True, all() stops at first False.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What does `any(generator_expression)` short-circuit?]]
* [[Truthy and falsy values]]
* [[What are the three logical operators?]]
Q: sorted() and .sort()

A: nums = [3, 1, 2]
sorted(nums)               # [1, 2, 3] — returns new list
nums.sort()                # in-place, returns None

words = ["banana", "apple", "cherry"]
sorted(words, key=len)             # ['apple', 'banana', 'cherry']
sorted(words, key=len, reverse=True)  # ['cherry', 'banana', 'apple']

sorted() works on any iterable. .sort() is list-only.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What does `list.sort()` vs `sorted()` return?]]
* [[List operations]]
* [[What is Timsort?]]
Q: isinstance() and type()

A: x = 42
isinstance(x, int)         # True
isinstance(x, (int, float))  # True (either type)
type(x)                    # <class 'int'>
type(x) is int             # True

Prefer isinstance() — it handles subclasses. type() is for exact type checks.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What does `type(...)` return?]]
* [[What is `typing.TypeGuard` used for?]]
* [[What is a `TYPE_CHECKING` guard?]]
Q: What function returns the data type of an object?

A: type(). 
Example: type(42) returns <class 'int'>. For checking whether an object is a specific type, prefer isinstance(obj, int) over type(obj) == int because isinstance also handles subclasses and supports tuple-of-types: isinstance(x, (int, float)).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What does `isinstance()` check that `type()` does not?]]
* [[What does `type(...)` return?]]
* [[What is `type()` with one argument vs three arguments?]]
Q: Conditional expression (ternary)

A: age = 20
status = "adult" if age >= 18 else "minor"

! In a list
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
! ['even', 'odd', 'even', 'odd', 'even']

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Truthy and falsy values]]
Q: Walrus operator (:=)

A: # Assign and test in one expression
if (n := len("hello")) > 3:
    print(f"long: {n} chars")  # long: 5 chars

! In a [[while loop]]
while (line := input("> ")) != "quit":
    print(f"you said: {line}")

! In a comprehension
results = [y for x in data if (y := expensive(x)) > threshold]

Python 3.8+. Use sparingly — readability first.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is the walrus operator in Python?]]
* [[What is the precedence of the walrus operator?]]
* [[What is the walrus operator's PEP number?]]
Q: match / case (structural pattern matching)

A: def handle(command):
    match command.split():
        case ["quit"]:
            return "bye"
        case ["go", direction]:
            return f"going {direction}"
        case ["pick", "up", item]:
            return f"picked up {item}"
        case _:
            return "unknown"

handle("go north")    # "going north"
handle("pick up key") # "picked up key"

Python 3.10+. Matches structure, not just values.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is Python's `match` statement mapping pattern?]]
* [[What is Python's `match` statement sequence pattern?]]
* [[What is the wildcard pattern in Python's match statement?]]
Q: Decorator

A: def log_calls(fn):
    def wrapper(*args, **kwargs):
        print(f"calling {fn.__name__}")
        return fn(*args, **kwargs)
    return wrapper

@log_calls
def add(a, b):
    return a + b

add(1, 2)  # prints "calling add", returns 3

@decorator is syntactic sugar for: add = log_calls(add)

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is a decorator in Python?]]
* [[How do you stack multiple decorators?]]
* [[What is a parameterized decorator?]]
Q: Closure

A: def make_counter(start=0):
    count = start
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

c = make_counter()
c()  # 1
c()  # 2
c()  # 3

The inner function captures variables from the enclosing scope. They persist after the outer function returns.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[global / nonlocal]]
* [[What is a closure in Python?]]
* [[self]]
Q: *args and **kwargs

A: def f(*args, **kwargs):
    print(args)    # tuple of positional args
    print(kwargs)  # dict of keyword args

f(1, 2, x=3, y=4)
! (1, 2)
! {'x': 3, 'y': 4}

! Keyword-only args (after *):
def g(a, b, *, verbose=False):
    pass  # verbose must be passed by name

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What are *args and **kwargs in Python functions?]]
* [[Unpacking (* and **)]]
* [[argparse]]
Q: Type hints

A: def greet(name: str, times: int = 1) -> str:
    return (f"hello {name}\
") * times

from typing import Optional
def find(lst: list[int], target: int) -> Optional[int]:
    return target if target in lst else None

Hints are not enforced at runtime. Use mypy for static checking. Python 3.9+ allows list[int] instead of List[int].

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What PEP introduced type hints to Python?]]
* [[Is Python statically or dynamically typed?]]
* [[What is `typing.get_type_hints()` used for?]]
Q: dataclass

A: from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

p = Point(1.0, 2.0)
print(p)            # Point(x=1.0, y=2.0)
p == Point(1.0, 2.0)  # True (auto __eq__)

Auto-generates __init__, __repr__, __eq__. Use frozen=True for immutable.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[__init__ and __repr__]]
* [[NamedTuple]]
* [[What is the `dataclasses.make_dataclass()` function?]]
Q: NamedTuple

A: from typing import NamedTuple

class Point(NamedTuple):
    x: float
    y: float

p = Point(1.0, 2.0)
p.x          # 1.0 (attribute access)
x, y = p     # unpacking
p[0]         # 1.0 (index access)

Immutable, lightweight, hashable. Great for simple records.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[How do you create a named tuple with `collections.namedtuple`?]]
* [[dataclass]]
* [[Dataclasses vs namedtuples — when to use which?]]
Q: Generator expression

A: # Parentheses instead of brackets → lazy evaluation
total = sum(x**2 for x in range(1000000))  # no list in memory

lines = (line.strip() for line in open("big.log"))
for line in lines:
    if "ERROR" in line:
        print(line)

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is a Python generator?]]
* [[yield (generators)]]
* [[Walrus operator (:=)]]
Q: Custom context manager

A: from contextlib import contextmanager

@contextmanager
def timer():
    import time
    start = time.time()
    yield  # code inside 'with' runs here
    print(f"elapsed: {time.time() - start:.2f}s")

with timer():
    sum(range(10**7))
! elapsed: 0.23s

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[How do you create a context manager from a generator function using `contextlib`?]]
* [[yield (generators)]]
* [[What are context variables (`contextvars`)?]]
Q: @property

A: class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def area(self):
        return 3.14159 * self._radius ** 2

c = Circle(5)
print(c.area)  # 78.53975 — no parentheses

Makes a method look like an attribute. Add @area.setter for write access.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Abstract base class (ABC)]]
* [[What is the ABC module and how do you use abstract classes?]]
* [[Explain Python's property decorator]]
Q: @staticmethod / @classmethod

A: class Date:
    def __init__(self, y, m, d):
        self.y, self.m, self.d = y, m, d

    @classmethod
    def from_str(cls, s):
        return cls(*map(int, s.split("-")))

    @staticmethod
    def is_valid(s):
        return len(s.split("-")) == 3

Date.from_str("2026-04-11")  # creates Date
Date.is_valid("2026-04-11")  # True

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[datetime]]
* [[What is the difference between `@staticmethod` and `@classmethod`?]]
* [[What is __repr__ vs __str__?]]
Q: What are class methods and static methods?

A: @classmethod receives the class as first arg (cls), @staticmethod receives no implicit arg.

class Date:
    def __init__(self, year, month, day):
        self.year, self.month, self.day = year, month, day

    @classmethod
    def from_string(cls, s):
        y, m, d = map(int, s.split('-'))
        return cls(y, m, d)  # works with subclasses too

    @staticmethod
    def is_valid(s):
        parts = s.split('-')
        return len(parts) == 3

Date.from_string('2026-04-01')  # creates Date instance
Date.is_valid('2026-04-01')     # True

Use classmethod for alternative constructors (factory methods). Use staticmethod for utility functions that don't need class/instance state but logically belong to the class.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What is the difference between `@staticmethod` and `@classmethod`?]]
* [[What is `classmethod` vs `staticmethod` when used with inheritance?]]
* [[Implement the Singleton pattern in Python (three ways)]]
Q: __init__ and __repr__

A: class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

p = Point(1, 2)
print(p)  # Point(1, 2)

__init__ sets up the instance. __repr__ controls how it prints.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[self]]
* [[class]]
* [[__slots__]]
Q: __len__ and __getitem__

A: class Deck:
    def __init__(self):
        self.cards = list(range(52))
    def __len__(self):
        return len(self.cards)
    def __getitem__(self, i):
        return self.cards[i]

d = Deck()
len(d)    # 52
d[0]      # 0
d[-1]     # 51
d[2:5]    # [2, 3, 4] — slicing works too

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is "slicing" in Python?]]
* [[What does the len() function do?]]
* [[String slicing]]
Q: __enter__ and __exit__

A: class TempDir:
    def __enter__(self):
        import tempfile
        self.path = tempfile.mkdtemp()
        return self.path
    def __exit__(self, exc_type, exc_val, exc_tb):
        import shutil
        shutil.rmtree(self.path)
        return False  # don't suppress exceptions

with TempDir() as d:
    print(d)  # /tmp/xyz — auto-cleaned up after

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[shutil]]
* [[What is `shutil.copytree()` used for?]]
* [[with (context manager)]]
Q: __add__, __eq__, __lt__ (operator overloading)

A: class Vec:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __add__(self, other):
        return Vec(self.x + other.x, self.y + other.y)
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

Vec(1,2) + Vec(3,4)   # Vec(4, 6)
Vec(1,2) == Vec(1,2)  # True

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[__init__ and __repr__]]
* [[return]]
* [[super()]]
Q: super()

A: class Base:
    def __init__(self, x):
        self.x = x

class Child(Base):
    def __init__(self, x, y):
        super().__init__(x)
        self.y = y

c = Child(1, 2)
print(c.x, c.y)  # 1 2

Delegates to the next class in the MRO. Always use super() in __init__ for cooperative [[inheritance|Inheritance]].

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is `super()` and how does it work?]]
* [[Inheritance]]
* [[Explain name mangling with double underscores]]
Q: async / await

A: import asyncio

async def fetch(url):
    await asyncio.sleep(1)  # simulate I/O
    return f"data from {url}"

async def main():
    results = await asyncio.gather(
        fetch("a.com"),
        fetch("b.com"),
    )
    print(results)  # both finish in ~1s, not 2s

asyncio.run(main())

For I/O-bound concurrency. Not parallelism — use [[multiprocessing]] for CPU-bound work.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[threading]]
* [[Blocking I/O calls freeze the asyncio event loop and all other coroutines]]
Q: Exception hierarchy

A: # Common built-in exceptions:
! BaseException
! ├── KeyboardInterrupt
! ├── SystemExit
! └── Exception
! ├── ValueError
! ├── TypeError
! ├── KeyError
! ├── IndexError
! ├── FileNotFoundError
! ├── PermissionError
! ├── AttributeError
! └── RuntimeError

! [[Custom exceptions]]:
class AppError(Exception):
    pass

class NotFoundError(AppError):
    pass

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is the exception hierarchy's root in Python?]]
* [[Why should you not catch `BaseException`?]]
* [[What is an "exception"?]]
Q: Custom exceptions

A: class ValidationError(Exception):
    def __init__(self, field, message):
        self.field = field
        super().__init__(f"{field}: {message}")

try:
    raise ValidationError("email", "invalid format")
except ValidationError as e:
    print(e)        # email: invalid format
    print(e.field)  # email

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[How do you create a custom exception?]]
* [[Exception hierarchy]]
* [[What is an "exception"?]]
Q: Nested comprehension

A: matrix = [[1,2,3], [4,5,6], [7,8,9]]

! Flatten
flat = [x for row in matrix for x in row]
! [1, 2, 3, 4, 5, 6, 7, 8, 9]

! Transpose
transpose = [[row[i] for row in matrix] for i in range(3)]
! [[1,4,7], [2,5,8], [3,6,9]]

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[List comprehension]]
* [[What is a list comprehension in Python?]]
* [[Dict comprehension]]
Q: collections.defaultdict

A: from collections import defaultdict

counts = defaultdict(int)
for word in "the cat sat on the mat".split():
    counts[word] += 1
! {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}

groups = defaultdict(list)
for name, dept in [("alice","eng"), ("bob","eng"), ("carol","hr")]:
    groups[dept].append(name)
! {'eng': ['alice','bob'], 'hr': ['carol']}

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[collections.Counter]]
* [[enumerate()]]
* [[Set comprehension]]
Q: collections.Counter

A: from collections import Counter

c = Counter("mississippi")
! Counter({'s': 4, 'i': 4, 'p': 2, 'm': 1})
c.most_common(2)  # [('s', 4), ('i', 4)]

words = "the cat sat on the mat".split()
Counter(words)  # Counter({'the': 2, 'cat': 1, ...})

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[collections.defaultdict]]
* [[Set comprehension]]
* [[enumerate()]]
Q: collections.deque

A: from collections import deque

q = deque([1, 2, 3])
q.append(4)      # right: [1, 2, 3, 4]
q.appendleft(0)  # left:  [0, 1, 2, 3, 4]
q.pop()           # 4
q.popleft()       # 0

! Fixed-size buffer (keeps last N)
buf = deque(maxlen=3)
for i in range(5):
    buf.append(i)
print(buf)  # deque([2, 3, 4])

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What does `collections.deque(maxlen=n)` do when you append beyond capacity?]]
* [[What are the advantages of `collections.deque` over a list?]]
* [[List operations]]
Q: itertools essentials

A: import itertools

! chain — flatten iterables
list(itertools.chain([1,2], [3,4]))  # [1, 2, 3, 4]

! islice — lazy head/tail
list(itertools.islice(range(100), 5))  # [0, 1, 2, 3, 4]

! groupby (must be sorted first)
from itertools import groupby
data = sorted(["aa", "ab", "ba", "bb"], key=lambda x: x[0])
for k, g in groupby(data, key=lambda x: x[0]):
    print(k, list(g))  # a ['aa','ab'], b ['ba','bb']

! product — nested loops
list(itertools.product("AB", "12"))  # [('A','1'),('A','2'),('B','1'),('B','2')]

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What does `itertools.product('AB', '12')` yield?]]
* [[What critical requirement does `itertools.groupby()` have?]]
* [[What does `itertools.groupby()` yield?]]
Q: functools essentials

A: from functools import lru_cache, partial, reduce

! lru_cache — memoization
@lru_cache(maxsize=128)
def fib(n):
    return n if n < 2 else fib(n-1) + fib(n-2)
fib(100)  # instant

! partial — fix some arguments
from functools import partial
int_from_hex = partial(int, base=16)
int_from_hex("ff")  # 255

! reduce — fold a sequence
reduce(lambda a, b: a * b, [1,2,3,4])  # 24

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[collections.deque]]
* [[continue]]
* [[yield (generators)]]
Q: pathlib basics

A: from pathlib import Path

p = Path("/var/log/syslog")
p.name       # "syslog"
p.parent     # Path("/var/log")
p.suffix     # "" (no extension)
p.exists()   # True/False
p.read_text()  # file contents as string

! Build paths with /
conf = Path.home() / ".config" / "myapp"
conf.mkdir(parents=True, exist_ok=True)

! Glob
for f in Path("/var/log").glob("*.log"):
    print(f)

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[pathlib replaces os.path for modern file operations]]
* [[logging]]
* [[What is `sys.path` and how does Python use it?]]
Q: subprocess basics

A: import subprocess

! Run a command, capture output
result = subprocess.run(
    ["ls", "-la"],
    capture_output=True, text=True, check=True,
)
print(result.stdout)

! NEVER use shell=True with user input
! Always pass args as a list

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[subprocess runs shell commands safely with argument lists]]
* [[What is the `subprocess.run()` function?]]
Q: re (regular expressions)

A: import re

! Search
m = re.search(r"(\\d+)", "error on line 42")
m.group(1)  # "42"

! Find all
re.findall(r"\\b\\w+@\\w+\\.\\w+\\b", text)

! Sub (replace)
re.sub(r"\\s+", " ", "too   many   spaces")  # "too many spaces"

! Split
re.split(r"[;,]\\s*", "a, b; c")  # ['a', 'b', 'c']

! Compile for reuse
pattern = re.compile(r"ERROR: (.+)")

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Common string methods]]
* [[Reverse words in a sentence]]
* [[Why do we use raw strings (r'...') for regex patterns in Python?]]
Q: JSON and YAML

A: import json

! JSON
data = {"name": "alice", "age": 30}
json.dumps(data)               # string
json.dumps(data, indent=2)     # pretty
json.loads('{"x": 1}')         # dict

with open("f.json") as f:
    data = json.load(f)         # from file

! YAML (pip install pyyaml)
import yaml
yaml.safe_load(open("f.yaml"))
yaml.dump(data, default_flow_style=False)

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is YAML handling in Python?]]
Q: datetime

A: from datetime import datetime, timedelta

now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))

dt = datetime.strptime("2026-04-11", "%Y-%m-%d")

tomorrow = now + timedelta(days=1)
delta = datetime(2026, 12, 31) - now
print(f"{delta.days} days left")

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Why should you avoid using `datetime.utcnow()`?]]
* [[What does `timedelta` represent?]]
* [[@staticmethod / @classmethod]]
Q: logging

A: import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger(__name__)

log.debug("details")    # hidden (below INFO)
log.info("started")     # shown
log.warning("slow")     # shown
log.error("failed")     # shown

Use logging, not print(), in production code.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Logging levels organize severity and information categories]]
* [[What are the standard logging levels in Python, from lowest to highest?]]
* [[pathlib basics]]
Q: argparse

A: import argparse

p = argparse.ArgumentParser(description="greet user")
p.add_argument("name")
p.add_argument("-n", "--count", type=int, default=1)
p.add_argument("-v", "--verbose", action="store_true")
args = p.parse_args()

for _ in range(args.count):
    print(f"hello {args.name}")

! Usage: python greet.py alice -n 3 -v

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is the standard library module for parsing command-line arguments?]]
* [[What is the difference between a parameter and an argument?]]
* [[*args and **kwargs]]
Q: threading

A: from concurrent.futures import ThreadPoolExecutor
import urllib.request

def fetch(url):
    return urllib.request.urlopen(url).read()[:100]

urls = ["https://example.com"] * 5
with ThreadPoolExecutor(max_workers=5) as pool:
    results = list(pool.map(fetch, urls))

Good for I/O-bound tasks. GIL prevents true CPU parallelism — use ProcessPoolExecutor for that.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[concurrent.futures unifies thread and process pool APIs]]
* [[multiprocessing]]
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
Q: multiprocessing

A: from concurrent.futures import ProcessPoolExecutor

def crunch(n):
    return sum(i*i for i in range(n))

with ProcessPoolExecutor(max_workers=4) as pool:
    results = list(pool.map(crunch, [10**6]*4))

Bypasses the GIL — true parallelism for CPU-bound work. Each worker is a separate process.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
* [[threading]]
* [[What is `multiprocessing.Pool` used for?]]
Q: __slots__

A: class Point:
    __slots__ = ("x", "y")
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
! p.z = 3  → AttributeError (no dynamic attrs)

~40% less memory per instance. Use when creating millions of objects.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is `__slots__` and why use it?]]
* [[__init__ and __repr__]]
* [[What parameter to `@dataclass` was added in Python 3.10 to allow slot-based instances?]]
Q: What is __slots__ and when should you use it?

A: __slots__ restricts instance attributes to a fixed set, replacing the per-instance __dict__ with a more memory-efficient structure.

class Point:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
p.z = 3  # AttributeError!

Benefits: ~40% less memory per instance, slightly faster attribute access. Use when creating millions of instances. Drawbacks: no dynamic attributes, complications with multiple [[inheritance|Inheritance]], no __dict__ for introspection. Not needed for most classes.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What parameter to `@dataclass` was added in Python 3.10 to allow slot-based instances?]]
* [[What is `__slots__` inheritance behavior?]]
* [[Class variable vs instance variable]]
Q: Abstract base class (ABC)

A: from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        ...

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14 * self.r ** 2

! Shape()   → TypeError (can't instantiate)
Circle(5).area()  # 78.5

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[@property]]
* [[What module provides abstract base classes?]]
* [[__init__ and __repr__]]
Q: What is the ABC module and how do you use abstract classes?

A: The abc module provides Abstract Base Classes — classes that can't be instantiated and enforce method implementation in subclasses.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        ...

    @abstractmethod
    def perimeter(self) -> float:
        ...

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14159 * self.r ** 2
    def perimeter(self):
        return 2 // 3.14159 // self.r

Shape()  # TypeError: Can't instantiate abstract class
Circle(5).area()  # 78.5

Use ABCs to define interfaces and ensure subclasses implement required methods. Also supports @abstractproperty (deprecated — use @property + @abstractmethod).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[@property]]
* [[What module provides abstract base classes?]]
* [[What does the `abc.abstractmethod` decorator do?]]
Q: Protocol (structural typing)

A: from typing import Protocol

class Closable(Protocol):
    def close(self) -> None: ...

def shutdown(obj: Closable) -> None:
    obj.close()

! Any object with a .close() method works
! No [[inheritance|Inheritance]] needed — duck typing + type checking
shutdown(open("/dev/null"))  # file has .close()

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What does `typing.Protocol` do?]]
* [[What is duck typing and how does Python use it?]]
* [[What is "duck typing"?]]
Q: str vs bytes

A: s = "hello"           # str (unicode text)
b = b"hello"           # bytes (raw bytes)

! Encode: str → bytes
b = s.encode("utf-8")  # b'hello'

! Decode: bytes → str
s = b.decode("utf-8")  # 'hello'

! You WILL hit this at network/file boundaries
! Always decode bytes to str as early as possible

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is `base64` encoding used for in Python?]]
* [[What does `int.to_bytes()` do?]]
* [[What is a Python "magic comment" for encoding?]]
Q: What is <html><code>str.encode()</code></html> and <html><code>bytes.decode()</code></html>?

A: <html><code>str.encode('utf-8')</code></html> converts a string to bytes. <html><code>bytes.decode('utf-8')</code></html> converts bytes to a string. The encoding defaults to UTF-8.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `base64` encoding used for in Python?]]
* [[What is the difference between `bytes` and `str` in Python 3?]]
* [[What does `int.to_bytes()` do?]]
Q: os.environ

A: import os

home = os.environ["HOME"]               # raises KeyError if missing
db = os.environ.get("DB_HOST", "localhost")  # default if missing
os.environ["MY_VAR"] = "value"           # set for this process

! List all env vars starting with AWS_
aws = {k: v for k, v in os.environ.items() if k.startswith("AWS_")}

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is `os.environ`?]]
Q: shutil

A: import shutil

shutil.copy2("a.txt", "b.txt")      # cp -p (preserves metadata)
shutil.copytree("src/", "dst/")     # cp -r
shutil.move("old.txt", "new.txt")   # mv
shutil.rmtree("/tmp/build")         # rm -rf
shutil.which("python3")             # /usr/bin/python3

usage = shutil.disk_usage("/")
print(f"{usage.free // 1e9:.0f} GB free")

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[tempfile]]
* [[__enter__ and __exit__]]
* [[pathlib replaces os.path for modern file operations]]
Q: tempfile

A: import tempfile

! Temp file (auto-deleted)
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt") as f:
    f.write("data")
    print(f.name)  # /tmp/tmpXXXX.txt

! Temp directory (auto-deleted)
with tempfile.TemporaryDirectory() as d:
    print(d)  # /tmp/tmpXXXXXX

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[shutil]]
* [[What module provides functions for working with temporary files and directories?]]
* [[Non-atomic file writes corrupt state on process termination]]
Q: secrets (secure random)

A: import secrets

! Secure token
tok = secrets.token_hex(16)    # "a3f2...d1b7" (32 hex chars)
tok = secrets.token_urlsafe(16)  # URL-safe base64

! Secure random integer
n = secrets.randbelow(100)     # 0-99

! Secure password
import string
alpha = string.ascii_letters + string.digits
pwd = "".join(secrets.choice(alpha) for _ in range(16))

Use secrets, not random, for anything security-related.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is the `secrets.token_urlsafe(nbytes)` function?]]
* [[What does the `secrets` module provide that `random` does not?]]
* [[What standard library module provides an interface to the operating system's random num…]]
Q: hashlib

A: import hashlib

h = hashlib.sha256(b"hello world").hexdigest()
! "b94d27b9934d3e08a52e52d7da7dabfa..."

! Hash a file
def file_hash(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            h.update(chunk)
    return h.hexdigest()

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What does `hashlib` provide?]]
* [[pathlib replaces os.path for modern file operations]]
* [[tempfile]]
Q: for/else and while/else

A: for n in [2, 3, 5, 7]:
    if n == 4:
        print("found 4")
        break
else:
    print("4 not found")  # ← runs because no break

The else block runs only if the loop completes without break. Useful for search patterns.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[while loop]]
* [[break]]
* [[continue]]
Q: Augmented assignment

A: x = 10
x += 5   # 15
x -= 3   # 12
x *= 2   # 24
x //= 5  # 4
x **= 3  # 64
x %= 10  # 4

Also works with strings: s = "hi"; s += "!" → "hi!"

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is "decrementing"?]]
* [[Conditional expression (ternary)]]
* [[Set comprehension]]
Q: Truthy and falsy values

A: # Falsy values:
bool(0)       # False
bool(0.0)     # False
bool("")      # False
bool([])      # False
bool({})      # False
bool(None)    # False
bool(False)   # False

! Everything else is truthy:
bool(1)       # True
bool("hi")    # True
bool([0])     # True (non-empty list)

! So you can write:
if my_list:  # instead of if len(my_list) > 0

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is the result of `bool([])`?]]
* [[What is the truthiness rule in Python?]]
* [[What is the `__bool__` method?]]
Q: LEGB scope rule

A: x = "global"

def outer():
    x = "enclosing"
    def inner():
        x = "local"
        print(x)  # local
    inner()
    print(x)      # enclosing

outer()
print(x)          # global

! Python searches: Local → Enclosing → Global → Built-in
! import builtins to see the B layer

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is the LEGB rule?]]
* [[global / nonlocal]]
* [[What is a "local variable"?]]
Q: Multi-line strings and docstrings

A: # Triple quotes for multi-line
query = """
SELECT *
FROM users
WHERE active = true
"""

! Docstrings
def add(a, b):
    """Return the sum of a and b."""
    return a + b

print(add.__doc__)  # "Return the sum of a and b."

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is `__doc__`?]]
* [[How do you write a comment in Python?]]
* [[What is the `with` statement's full syntax since Python 3.1?]]
Q: frozenset

A: a = frozenset([1, 2, 3])
! a.add(4)  → AttributeError (immutable)

! Can use as dict key or set element
cache = {frozenset([1,2]): "result"}

! Same [[set operations|Set operations]] work
a | frozenset([3, 4])  # frozenset({1, 2, 3, 4})

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is a frozenset?]]
* [[What is the result of `{} == set()`?]]
* [[Dict operations]]
Q: zip tricks

A: # Transpose a matrix
matrix = [(1,2,3), (4,5,6)]
list(zip(*matrix))  # [(1,4), (2,5), (3,6)]

! Unzip
pairs = [("a",1), ("b",2), ("c",3)]
keys, vals = zip(*pairs)
! keys = ('a','b','c'), vals = (1,2,3)

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[Nested comprehension]]
* [[Unpacking (* and **)]]
* [[List operations]]
Q: Class variable vs instance variable

A: class Dog:
    species = "canine"  # class variable (shared)

    def __init__(self, name):
        self.name = name  # instance variable (per-object)

a = Dog("rex")
b = Dog("fido")
Dog.species    # "canine"
a.name         # "rex"

! Gotcha: mutable class vars are shared!
class Bad:
    items = []  # all instances share this list

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-concepts.tsv</code></html>

''Related atoms''
* [[What is `__dict__` on a class vs an instance?]]
* [[What is __slots__ and when should you use it?]]
* [[class]]
A bare <html><code>except:</code></html> or <html><code>except Exception:</code></html> catches everything — KeyboardInterrupt, SystemExit, and programming errors like TypeError and AttributeError. Your code silently fails while you think it's working. The function swallows the signal that something is broken. Always catch the narrowest exception possible and log <html><code>exc_info=True</code></html> to see the traceback. If you don't know what exception to expect, use a bare except only as a last resort and log loudly. Better: let exceptions propagate so you see them during development. In production, catch specific exceptions at the boundaries (request handler, background job, API call) and let internal exceptions propagate as errors.

----
''Sources''
* <html><code>training/library/topics/python-debugging/footguns.md</code></html>

''Related atoms''
* [[Overly broad exception handlers hide bugs and failures]]
* [[try / except]]
A default argument is evaluated once at function definition time, not on each call. If the default is a mutable object (list, dict, set), the same object is reused and modified across all calls. Data from one invocation contaminates the next. This bug is invisible in unit tests that call the function in isolation; it appears in production when the function is called repeatedly. The symptom: results accumulate unexpectedly or old data persists. The fix: use <html><code>None</code></html> as the sentinel and create a new object inside the function. Always treat default arguments as constants; if you need mutability, create it inside the function.

----
''Sources''
* <html><code>training/library/topics/python-debugging/footguns.md</code></html>

''Related atoms''
* [[What is the mutable default argument gotcha?]]
* [[What is `unittest.mock.sentinel`?]]
* [[is checks identity; == checks value; small ints are interned]]
Code that runs at import time (database connections, starting threads, reading config files, API calls) executes whenever any module imports that file, with no way to defer or control it. Tests that import the module trigger production behavior. Missing environment variables crash during import. Circular imports crash with <html><code>ImportError</code></html> or <html><code>AttributeError: module has no attribute</code></html>, because modules are partially initialized. The fix: keep module-level code limited to constants, type definitions, and simple assignments. Defer expensive operations to function calls using lazy initialization patterns (check a module-level <html><code>_client = None</code></html>, create on first call). This makes modules safe to import in any order and test environments don't trigger production side effects.

----
''Sources''
* <html><code>training/library/topics/python-debugging/footguns.md</code></html>

''Related atoms''
* [[Circular imports produce partially-initialized modules]]
* [[Relative imports fail when modules are run directly instead of via python -m]]
* [[What is `__import__` hook?]]
Module A imports from module B, which imports from module A. Python doesn't crash immediately — instead, module A is given to B while still being initialized. B tries to access an attribute that hasn't been defined yet, yielding <html><code>AttributeError: module 'foo' has no attribute 'bar'</code></html> even though the attribute is clearly in the source. The symptom is mystifying because the code obviously contains the name. The fix: move the import inside the function (lazy import, breaks the cycle), use <html><code>if TYPE_CHECKING:</code></html> for type-only imports, or restructure to eliminate the cycle. Detecting circular imports during development requires careful code review; they're not always caught by linters.

----
''Sources''
* <html><code>training/library/topics/python-debugging/footguns.md</code></html>

''Related atoms''
* [[Import-time side effects create fragile, order-dependent loading]]
* [[Relative imports fail when modules are run directly instead of via python -m]]
* [[What is the difference between `__import__()` and `importlib.import_module()`?]]
Python buffers stdout by default. In a terminal, the buffer is line-buffered (flushes on newline). In Docker containers (no TTY), stdout is fully buffered and may not flush for minutes, even with <html><code>print()</code></html> calls. Your debugging output never reaches <html><code>docker logs</code></html>. You think the code isn't running; it is — you just can't see it. The fix: set <html><code>PYTHONUNBUFFERED=1</code></html> in the Dockerfile or run <html><code>python -u</code></html>. Alternatively, use the <html><code>logging</code></html> module, which writes to stderr (unbuffered by default). This is why production logging rarely uses <html><code>print()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-debugging/footguns.md</code></html>

''Related atoms''
* [[Introspection of Python in Docker containers]]
* [[Debugging Python encoding errors in production]]
* [[Debugging tool selection by symptom and environment]]
A <html><code>breakpoint()</code></html> or <html><code>pdb.set_trace()</code></html> in a thread (thread pool, Celery task, asyncio coroutine) tries to read from stdin, which doesn't exist in production. The thread hangs forever, holding locks or resources. Other threads waiting on those resources also hang. The entire service freezes silently. Gunicorn workers, Kubernetes pods, and async workers are particularly vulnerable. Never commit <html><code>breakpoint()</code></html> to production code. Use a pre-commit hook to catch it (<html><code>debug-statements</code></html> hook in pre-commit framework). For production debugging, use <html><code>debugpy</code></html> with remote attach or rely on structured logging.

----
''Sources''
* <html><code>training/library/topics/python-debugging/footguns.md</code></html>

''Related atoms''
* [[Debugging hung async code via debug mode and task inspection]]
* [[Debugging tool selection by symptom and environment]]
* [[Event loop blocking in async Python services]]
<html><code>is</code></html> checks whether two variables reference the same object in memory. <html><code>==</code></html> checks whether they have the same value. CPython interns small integers (-5 to 256) and some strings, so <html><code>a is b</code></html> accidentally returns <html><code>True</code></html> for <html><code>a = 256; b = 256</code></html>. With larger values, <html><code>a = 257; b = 257; a is b</code></html> returns <html><code>False</code></html> because they're separate objects with the same value. Code using <html><code>is</code></html> for value comparison works in unit tests (small test values) but fails in production (larger values). The fix: use <html><code>is</code></html> only for <html><code>None</code></html>, <html><code>True</code></html>, <html><code>False</code></html>, and sentinel objects; use <html><code>==</code></html> for all value comparisons. Python 3.8+ emits <html><code>SyntaxWarning</code></html> for <html><code>is</code></html> with literals.

----
''Sources''
* <html><code>training/library/topics/python-debugging/footguns.md</code></html>

''Related atoms''
* [[What is the difference between == and is in Python?]]
* [[What is the difference between `is` and `==` in Python?]]
* [[is / is not (identity)]]
Exceptions raised in a thread don't propagate to the main thread. The thread dies silently and work stops being processed. The main thread has no idea something failed. Hours later, a queue backs up or an error log reveals the problem. Raw <html><code>threading.Thread</code></html> provides no exception handling or visibility into worker failures. The fix: use <html><code>concurrent.futures.ThreadPoolExecutor</code></html>, which captures exceptions in <html><code>Future</code></html> objects accessible via <html><code>future.result()</code></html>. Or wrap the thread target with exception handling that logs at CRITICAL level and re-raises, ensuring failures are visible.

----
''Sources''
* <html><code>training/library/topics/python-debugging/footguns.md</code></html>

''Related atoms''
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
* [[concurrent.futures unifies thread and process pool APIs]]
* [[What is `concurrent.futures` and when was it introduced?]]
ipdb adds IPython features to pdb: tab completion, syntax highlighting, and better tracebacks. pdb++ is a drop-in replacement with sticky mode (continuously displays code), syntax highlighting, and smarter command parsing (typing foo prints the variable without requiring p foo). Both are installed via pip and activate automatically when you call breakpoint() after setting PYTHONBREAKPOINT. Choose ipdb if you want IPython integration; choose pdb++ for the sticky-mode workflow that keeps code visible while stepping through.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[pdb shipped with Python 1.0 in 1994]]
* [[What is `pdb` and how do you invoke it?]]
* [[What did `breakpoint()` (Python 3.7) replace?]]
debugpy (Microsoft's Debug Adapter Protocol server) lets you attach VS Code or any DAP-compatible client to code running in Docker containers, remote servers, or background services. Add debugpy.listen() and optionally debugpy.wait_for_client() to your application startup, expose the debug port, and configure your client to connect. For production, enable debugpy only when signaled—register a signal handler that starts the debug server on demand, then send SIGUSR1 to enable debugging without restarting the application.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[Introspection of Python in Docker containers]]
* [[All Python debuggers use sys.settrace() with measurable overhead]]
Python's logging module categorizes messages by severity: DEBUG (development diagnostics), INFO (normal operation), WARNING (unexpected but recoverable), ERROR (operation failed, app continues), CRITICAL (app cannot continue). The level you set at startup determines which messages are emitted—setting INFO silences DEBUG messages. Production systems typically run at INFO or WARNING to reduce noise while capturing problems. The basicConfig pattern sets this once at application startup, allowing both human-readable and structured formats. Logger instances inherit the configured level and can emit at appropriate severity: logger.debug() for variable traces, logger.info() for significant events, logger.warning() for deprecations or retries, logger.exception() in except blocks to auto-capture tracebacks. The pattern prevents spamming logs with noise while ensuring critical signals reach operators.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[logging]]
* [[What is the `logging` module's hierarchy?]]
* [[Multiple APIs exist for capturing and formatting exception information]]
When an exception occurs, Python provides several ways to access its details without losing the traceback. The traceback module can print a traceback to stderr or capture it as a string for logging or alerting. The sys.exc_info() function returns a tuple of (exception_type, exception_value, traceback_object), allowing programmatic inspection—the traceback object itself can be walked to examine individual frames. In exception handlers, logger.exception() automatically includes the full traceback. The point is that you can extract exception details in different contexts: format as a string for storage, inspect individual frames for debugging, or pass the traceback to alerting systems. All three approaches access the same information; choose based on what you need to do with it.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[What does the `traceback` module provide?]]
* [[What is an "exception"?]]
* [[Logging levels organize severity and information categories]]
When catching an exception and raising a different one, use the 'from' keyword to preserve the original error context. Raising 'RuntimeError("Cannot start") from original_error' creates a chain: the traceback shows both exceptions, with the original FileNotFoundError listed first as the direct cause. This prevents losing critical context—the next person debugging sees the full causal chain, not just the final error. Without chaining, 'raise RuntimeError("Cannot start")' hides the fact that a missing config file was the root cause, making the error cryptic. Chaining is a Python 3 feature; it costs nothing and always makes postmortems clearer.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[What is exception chaining in Python?]]
* [[What is an "exception"?]]
* [[What is the difference between `__cause__` and `__context__` on exceptions?]]
Assertions using assert and the __debug__ flag are tools for development—they're stripped when Python runs with the -O (optimize) flag. The __debug__ builtin is True during normal execution and False when -O is passed, allowing you to conditionally run expensive validation checks only during development. Never use assert for input validation in production code, because users won't see the AssertionError if you run the app with optimizations. Instead, use assert to document invariants you believe always hold during development—'assert isinstance(data, dict)'—and validate actual input with explicit if-checks. The pattern is: assertions catch your own bugs during development; real input validation guards against malformed user data in production.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[What is the `__debug__` built-in constant?]]
* [[What does `python -O` do?]]
The warnings module lets you issue warnings for deprecated APIs, experimental features, or conditions the caller should know about, without raising an exception and stopping execution. A function can call warnings.warn(message, DeprecationWarning) to tell callers that it's being phased out. Callers control whether warnings become errors, are suppressed, or are logged: warnings.filterwarnings('error', category=DeprecationWarning) treats deprecation warnings as exceptions, catching them early during testing. This is more lenient than raising an exception immediately—callers can suppress warnings for compatibility code or turn them into errors for strict testing. The command line also controls warnings: -W error::DeprecationWarning makes all deprecation warnings fatal, useful for CI to catch deprecated use. Warnings are the right tool for soft failures and API evolution.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[What is `DeprecationWarning` vs `PendingDeprecationWarning`?]]
Q: What is the <html><code>warnings</code></html> module?

A: It provides a mechanism for issuing warning messages (like <html><code>DeprecationWarning</code></html>) that do not stop execution. Warnings can be filtered, silenced, or turned into exceptions.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `DeprecationWarning` vs `PendingDeprecationWarning`?]]
* [[Logging levels organize severity and information categories]]
When Python crashes with a segfault—usually from a C extension or signal handling—the normal traceback is lost. Setting PYTHONFAULTHANDLER=1 or calling faulthandler.enable() dumps the Python-level stack trace to stderr when SIGSEGV, SIGABRT, or similar crash signals arrive. This lets you see where the crash happened in Python code, not just that a segmentation fault occurred. Additionally, faulthandler.register(signal.SIGUSR1) makes the process dump its stack trace on demand: 'kill -USR1 <pid>' prints the traceback without stopping the process. For stuck processes, this is invaluable—without interactive debugger access, you can fire the signal and check logs to see what Python function is hanging. The downside of a segfault is you lose the traceback; faulthandler recovers it.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[Systematic procedure to diagnose hung Python processes using live profiling and system introspection]]
Setting PYTHONFAULTHANDLER=1 or calling faulthandler.enable() makes the Python interpreter dump a traceback when it crashes from a segfault, bus error, or abort signal. Without it, a segfault in a C extension produces no diagnostic at all—the process just dies. This feature, added in Python 3.3, is invaluable for debugging crashes in numpy, pandas, and other C-extension-heavy libraries. It bridges the gap between Python-level debugging and C-level crashes.

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>

''Related atoms''
* [[Debugging segfaults in Python C extensions]]
* [[python -i flag creates post-mortem debugging environment]]
cProfile measures function-level CPU time. Run 'python -m cProfile -s cumulative script.py' to profile an entire script and sort by cumulative time (time in the function plus all functions it calls). The output shows ncalls (how many times each function was called), tottime (time in that function only), and cumtime (time including subcalls). This quickly identifies bottlenecks—a function called once but taking 90% of cumtime is where optimization matters most. For finer granularity, line_profiler profiles line-by-line execution with the @profile decorator and 'kernprof -l -v script.py', showing exactly which lines in a slow function are the culprits. Both tools answer "where is my time going?" but at different scales: cProfile is fast and broad, line_profiler is detailed and needs manual annotation. Save cProfile output with -o for analysis with pstats.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[Profiling strategies for slow FastAPI endpoints]]
* [[What is the `cProfile` module?]]
strace attaches to a running process and prints every system call it makes. 'strace -p <pid>' shows what a stuck Python process is actually waiting on. Common patterns: a process stuck on read() from a socket is waiting for a network response (DNS lookup? database? API?), stuck on futex() indicates lock contention or threading deadlock, stuck on poll() with timeout is normal for event loops. The -e flag filters to syscall categories (network, read, write) to reduce noise. For hung processes, strace answers the question debuggers can't: is this thread waiting on network I/O, filesystem I/O, or a lock? The output includes timing (-t flag), showing how long each call took. strace is a last resort when faulthandler and py-spy aren't available, but it's powerful for understanding what the kernel sees the process doing—often the truth.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>
When a Python process is unresponsive—no errors, no logs, just stuck—diagnosis requires system visibility. First, find the PID with ps or pgrep. Second, use py-spy (no restart required; attaches to the running process) to see what the call stack is doing right now—py-spy top shows a live view of which functions are consuming CPU or blocked. If the process is actually stuck (consuming no CPU), strace -p reveals what system call it's waiting on: read() from a socket means network I/O, futex() means a lock, poll() means an event loop. Check /proc for clues: /proc/<pid>/status shows thread count and memory, /proc/<pid>/fd shows open file descriptors. If all else fails, send SIGUSR1 to trigger faulthandler's signal handler (if enabled), which dumps the Python stack trace. As a last resort, gdb can extract stack traces, but it's slow. For production, enable faulthandler at startup—set PYTHONFAULTHANDLER=1 in the environment or call faulthandler.enable() and faulthandler.register(signal.SIGUSR1) in your app entrypoint.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>

''Related atoms''
* [[Debugging tool selection by symptom and environment]]
* [[faulthandler captures Python stack traces when the process crashes]]
The built-in trace module instruments Python execution without external tools. 'python -m trace --trace script.py' replays the script line-by-line, showing every line as it runs—verbose but exact. 'python -m trace --count script.py' instead counts how many times each line executed, generating .cover files showing a heatmap of hot paths. This is useful for understanding which branches get hit most often and identifying loops that run more than expected. 'python -m trace --listfuncs script.py' lists all functions called. The trace module is built-in and requires no installation; the cost is runtime overhead because you're instrumenting every line. It's slower than sampling profilers like cProfile but precise in what it measures.

----
''Sources''
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

''Related atoms''
* [[CPU profiling reveals which functions consume the most time]]
* [[All Python debuggers use sys.settrace() with measurable overhead]]
* [[Profiling strategies for slow FastAPI endpoints]]
Python services leak memory through unbounded caches, event handlers that are never unsubscribed, and logging handlers added repeatedly. The built-in <html><code>tracemalloc</code></html> module shows which code paths are allocating the most memory; add it to startup with <html><code>tracemalloc.start(25)</code></html>, then expose a debug endpoint to dump top allocators by file and line number. For questions about what types are accumulating (dicts, lists, your custom classes), <html><code>objgraph.show_growth()</code></html> highlights the culprits. Once identified, check for the common patterns: a global dict that never evicts entries, a subscribe method without an unsubscribe, or handlers appended in a loop. Fix with <html><code>functools.lru_cache(maxsize=...)</code></html>, proper cleanup in destructors, or cachetools.TTLCache for time-bounded eviction. Outside the process, monitor RSS with a simple shell loop to track growth over time and confirm your fix works.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>

''Related atoms''
* [[Memory profiling is non-deterministic due to reference counting]]
When <html><code>ModuleNotFoundError</code></html> appears despite installing a package, the mismatch is usually between which Python is running and where packages are installed. Verify with <html><code>which python3</code></html> and <html><code>python3 -m pip show mypackage</code></html> — if Location doesn't match the directory in <html><code>sys.path</code></html>, the package is in the wrong environment. Trace every import attempt with <html><code>python3 -v -c "import mypackage"</code></html>, which logs file resolution in order. In Docker, the classic mistake is a multi-stage build where packages are installed in one stage but not copied into the runtime: use <html><code>pip install --target=/install</code></html> and explicitly copy into the runtime stage's site-packages. Virtualenv can become broken if created with a different Python version than the one currently active — check <html><code>sys.prefix</code></html> to confirm the active venv matches the Python being used. Alpine Linux with pip is particularly fragile because packages are built from source rather than using pre-built wheels compiled for glibc; prefer Debian-based Python images.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>

''Related atoms''
* [[System Python must use virtualenvs to prevent package conflicts]]
* [[ModuleNotFoundError usually means wrong Python, wrong path, or inactive venv]]
* [[Never mix system and pip packages — use virtualenvs for applications]]
Encoding failures — garbled output, mojibake, or UnicodeDecodeError — usually stem from mismatch between what Python expects and what the environment provides. Check Python's encoding settings with <html><code>sys.getdefaultencoding()</code></html>, <html><code>sys.getfilesystemencoding()</code></html>, and crucially <html><code>sys.stdout.encoding</code></html>, which may be 'ascii' in minimal Docker images despite your locale. Fix Docker images by setting <html><code>LANG=C.UTF-8</code></html>, <html><code>LC_ALL=C.UTF-8</code></html>, and <html><code>PYTHONIOENCODING=utf-8</code></html>. When reading files, always specify encoding explicitly: <html><code>open(path, encoding="utf-8")</code></html>. For data from unknown sources, detect encoding with the <html><code>chardet</code></html> library; once you know the source encoding, you can fix mojibake (data decoded incorrectly once, now double-encoded) by re-encoding: <html><code>broken.encode('latin-1').decode('utf-8')</code></html>. Test encoding behavior locally before deploying to production, especially when moving between operating systems.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>

''Related atoms''
* [[Python buffers stdout; output vanishes in Docker without flags]]
* [[Diagnosing import failures in Python and Docker]]
The most common reason for hung async services is a blocking synchronous call inside an async function. When you call <html><code>db.query(Model).first()</code></html> from within a FastAPI endpoint, the entire event loop stalls waiting for the database query, and all other requests queue behind it. The fix is <html><code>loop.run_in_executor(None, blocking_function)</code></html>, which runs sync code in a thread pool so the event loop remains responsive. Detect blocking calls with <html><code>asyncio.get_event_loop().set_debug(True)</code></html>, which emits warnings when callbacks take longer than <html><code>slow_callback_duration</code></html>. List all running tasks and their stacks with <html><code>asyncio.all_tasks()</code></html> to find what the event loop is stuck on. <html><code>py-spy</code></html> is equally useful: if the process appears stuck in a single thread on a C extension or system call, that confirms a blocking operation. Never import sync database drivers directly in FastAPI handlers; use async drivers (asyncpg, motor, sqlalchemy async) or explicitly defer the sync call to a thread pool.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>

''Related atoms''
* [[Blocking in async handlers starves the entire event loop]]
* [[Debugging hung async code via debug mode and task inspection]]
* [[strace reveals system-level bottlenecks by showing process syscalls]]
When an endpoint is slow, choose your profiling tool based on what you need to know. <html><code>py-spy record</code></html> captures CPU time across the entire process in real-time and outputs a flamegraph, ideal for finding hotspots without modifying code. For line-level granularity within a specific function, use <html><code>line_profiler</code></html> with <html><code>@profile</code></html> decoration and run with <html><code>kernprof</code></html>. To time all endpoints uniformly, add a <html><code>BaseHTTPMiddleware</code></html> that records request duration and logs requests exceeding a threshold (e.g., >1 second). For profiling a specific code path isolated from request context, use <html><code>cProfile</code></html> and analyze its output with <html><code>pstats</code></html>, sorting by cumulative time. When investigating a live service, <html><code>py-spy top --pid</code></html> is non-invasive — it doesn't require restarting or modifying code and has negligible overhead. In development, enable <html><code>asyncio</code></html> debug mode to catch event loop blocking; in production, middleware-based timing catches slow paths without the overhead of full profiling.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>

''Related atoms''
* [[CPU profiling reveals which functions consume the most time]]
* [[The trace module counts execution to identify hot paths and bottlenecks]]
* [[strace reveals system-level bottlenecks by showing process syscalls]]
When Python crashes without a traceback (exit code 139, SIGSEGV), the fault is in compiled code, not Python. Enable <html><code>faulthandler</code></html> with the environment variable <html><code>PYTHONFAULTHANDLER=1</code></html> or in code with <html><code>import faulthandler; faulthandler.enable()</code></html> to generate a Python-level traceback at the crash site. If faulthandler is insufficient, use <html><code>gdb</code></html> to attach and capture the C-level backtrace: <html><code>gdb -ex run -ex bt --args python3 app.py</code></html>. Common culprits are version mismatches between Python packages and system libraries — numpy/scipy with incompatible BLAS/LAPACK, pillow missing libpng, lxml with incompatible libxml2 — and binary wheels built for glibc deployed on Alpine (which uses musl). Verify shared library dependencies with <html><code>ldd</code></html> on the <html><code>.so</code></html> file; look for "not found" entries. Alpine's use of musl and its typical workaround of building packages from source makes it fragile for packages with C extensions. Prefer Debian-based images like <html><code>python:3.11-slim</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>

''Related atoms''
* [[PYTHONFAULTHANDLER captures segfaults in C extensions]]
* [[Alpine musl libc breaks glibc wheels and DNS in Python containers]]
In production, you cannot attach a debugger or reliably reproduce failures locally. Structured logging — logs as JSON, not prose — makes errors searchable and automatable. Log every significant event with a fixed set of fields: timestamp, log level, logger name, and a JSON message containing event type and context. Include a request ID or order ID in every log so you can trace a single transaction through your system. On error, include the full exception traceback in a field. Search your logs with <html><code>jq</code></html> to find patterns: <html><code>docker logs myapp | jq 'select(.event == "payment_failed")'</code></html> returns only payment failures; <html><code>jq 'select(.order_id == "12345")'</code></html> reconstructs a single order's timeline. The upfront cost is a slightly more verbose logging setup, but it scales: you catch production failures within seconds rather than guessing from unstructured text logs.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>
<html><code>docker exec -it myapp python3</code></html> drops a Python shell into a running container where you can import your app and call functions directly. <html><code>docker exec -it myapp bash</code></html> followed by installing debugging tools on the fly lets you inspect a live process without restarting. <html><code>py-spy top --pid 1</code></html> profiles the container's main process (PID 1 in Docker) without instrumentation. <html><code>breakpoint()</code></html> works in dev with proper Docker Compose configuration — set <html><code>stdin_open: true</code></html> and <html><code>tty: true</code></html>, and add <html><code>PYTHONBREAKPOINT=ipdb.set_trace</code></html> to environment; when the process hits the breakpoint, <html><code>docker attach myapp</code></html> connects you to the debugger. Use <html><code>docker exec myapp env | sort</code></html> and <html><code>docker exec myapp python3 -c "import sys; print(sys.path)"</code></html> to verify environment settings and path configuration match your expectations. One-off debug containers with <html><code>docker run --rm -it --entrypoint bash myapp:latest</code></html> avoid modifying the running service.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>

''Related atoms''
* [[Debugging tool selection by symptom and environment]]
A Python service's failure mode determines which debugging tool fits best. A hung process with no output or logs indicates deadlock or an infinite loop — use <html><code>py-spy top --pid</code></html> for real-time stack sampling or <html><code>strace -p PID</code></html> to see system calls. Memory growing over days indicates a leak — add <html><code>tracemalloc</code></html> to your code and expose a debug endpoint, or use <html><code>objgraph.show_growth()</code></html> to identify the accumulating type. Import errors require checking the Python executable, <html><code>sys.path</code></html>, and pip's installation location with <html><code>python3 -v</code></html>. Segfaults (exit code 139, no traceback) demand <html><code>PYTHONFAULTHANDLER=1</code></html> or <html><code>gdb</code></html>. Slow endpoints profit from <html><code>py-spy record</code></html> for flamegraphs or middleware-based timing. Docker-specific issues yield to <html><code>docker exec</code></html> for introspection. Async event-loop blocking needs <html><code>asyncio.set_debug(True)</code></html> and stack traces of all running tasks. Production errors without local reproduction require structured JSON logging and <html><code>jq</code></html> queries.

----
''Sources''
* <html><code>training/library/topics/python-debugging/street_ops.md</code></html>

''Related atoms''
* [[Systematic procedure to diagnose hung Python processes using live profiling and system introspection]]
* [[Introspection of Python in Docker containers]]
* [[strace reveals system-level bottlenecks by showing process syscalls]]
Python's debugger, pdb, was present in the very first production release. It adopted gdb's command vocabulary—break, continue, step, next, print—making it familiar to C programmers. Over three decades later, pdb remains the standard Python debugger despite competition from IDE-integrated alternatives. The modern interface improved significantly: Python 3.7 introduced the breakpoint() built-in function (PEP 553), replacing the awkward import pdb; pdb.set_trace() idiom. The built-in is also customizable via sys.breakpointhook() and the PYTHONBREAKPOINT environment variable, allowing you to swap in ipdb, pudb, or disable all breakpoints at once.

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>
* <html><code>training/library/topics/python-debugging/primer.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[ipdb and pdb++ extend pdb with completion and visualization]]
* [[python -i flag creates post-mortem debugging environment]]
* [[All Python debuggers use sys.settrace() with measurable overhead]]
Q: What is <html><code>pdb</code></html> and how do you invoke it?

A: The Python debugger. Invoke it with <html><code>python -m pdb script.py</code></html>, or insert <html><code>breakpoint()</code></html> (Python 3.7+) or <html><code>import pdb; pdb.set_trace()</code></html> in code.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[python -i flag creates post-mortem debugging environment]]
* [[ipdb and pdb++ extend pdb with completion and visualization]]
* [[All Python debuggers use sys.settrace() with measurable overhead]]
Q: What did <html><code>breakpoint()</code></html> (Python 3.7) replace?

A: The verbose <html><code>import pdb; pdb.set_trace()</code></html>. The <html><code>breakpoint()</code></html> built-in is also configurable via the <html><code>PYTHONBREAKPOINT</code></html> environment variable to use different debuggers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[python -i flag creates post-mortem debugging environment]]
* [[ipdb and pdb++ extend pdb with completion and visualization]]
* [[faulthandler captures Python stack traces when the process crashes]]
When Python launched in 1991, most languages displayed cryptic error messages or numeric error codes. Python's traceback showed the full call stack with file names, line numbers, and the actual source code at each frame—an unusually clear diagnostic for its era. The format proved so effective that it influenced error reporting in Ruby, JavaScript, and other dynamic languages. This design choice—readable errors by default—is one reason Python became popular for teaching and scripting.

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>

''Related atoms''
* [[What improvement did Python 3.11 make to error messages?]]
* [[What does the `traceback` module provide?]]
* [[cgitb module provides formatted tracebacks with context]]
Python 3.11 (October 2022) introduced fine-grained error locations. Tracebacks now point to the exact expression within a line using caret markers, rather than just showing the line number. Instead of saying "AttributeError on line 42," it underlines the specific attribute access in a chained expression that failed. This precision reduces guesswork when debugging complex statements with multiple operations on a single line.

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>

''Related atoms''
* [[What improvement did Python 3.11 make to error messages?]]
* [[Python's traceback format influenced error reporting across languages]]
* [[Exception chaining preserves the original cause in the traceback]]
Every Python debugger—pdb, PyCharm's debugger, VS Code's Python extension—registers a callback via sys.settrace() that the interpreter invokes before executing each line, function call, return, and exception. This mechanism gives debuggers complete visibility into program execution but comes with a cost: running under a debugger imposes 2-10x performance overhead compared to normal execution. This overhead makes it impractical to debug high-throughput code in production; use profilers or production-safe tracing instead.

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>

''Related atoms''
* [[The trace module counts execution to identify hot paths and bottlenecks]]
* [[What is `sys.monitoring` in Python 3.12?]]
* [[Print debugging remains the most common debugging technique]]
python -m dis script.py (or dis.dis(function) programmatically) disassembles Python functions into their bytecode instructions: LOAD_FAST, BINARY_ADD, CALL_FUNCTION, RETURN_VALUE, and so on. Bytecode reveals exactly what the interpreter executes. Understanding bytecode is essential for diagnosing performance issues where the same Python expression compiles to surprisingly different instruction counts—often due to subtle differences in variable scope or control flow that the optimizer handles differently. This knowledge separates "why is this slow?" from "why is //that// slow?"

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>

''Related atoms''
* [[What is the `dis` module?]]
* [[All Python debuggers use sys.settrace() with measurable overhead]]
* [[What does `python -O` do?]]
Inserting print statements to trace program execution is called printf debugging (after C's printf function). Despite the philosophy that real programmers use debuggers, a 2017 survey found print debugging is the most commonly used technique across all experience levels. Python 3.8 made it faster with the f-string = specifier: f"{var=}" prints both the variable name and its value, reducing the friction. The technique works because it's simple, requires no setup, and produces output you can log or capture.

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>

''Related atoms''
* [[All Python debuggers use sys.settrace() with measurable overhead]]
* [[pdb shipped with Python 1.0 in 1994]]
Running python -i script.py executes the script normally, but if it raises an unhandled exception, instead of exiting, Python drops into an interactive REPL with all variables still in scope. Combined with import pdb; pdb.pm() (post-mortem debugger), you can inspect the exact state of the program at the moment of failure. This is faster than re-running the script and adding breakpoints.

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>

''Related atoms''
* [[What is `pdb` and how do you invoke it?]]
* [[pdb shipped with Python 1.0 in 1994]]
* [[What did `breakpoint()` (Python 3.7) replace?]]
Python uses reference counting (with a generational garbage collector for cycles) rather than pure tracing GC. Objects are freed immediately when their reference count hits zero, making memory profiles non-deterministic across runs—the same code may show different memory usage depending on object lifetime ordering and reference visibility. Tools like tracemalloc, objgraph, and memory_profiler each take different approaches to this problem, and no single tool gives a complete picture without the others.

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>

''Related atoms''
* [[What is the purpose of garbage collection in Python?]]
* [[Debugging memory leaks with tracemalloc and objgraph]]
* [[The trace module counts execution to identify hot paths and bottlenecks]]
The cgitb module produces colorful, structured tracebacks showing local variable values at each frame. Originally designed for CGI web scripts, it's now superseded by web frameworks' own error pages but remains useful for quick, detailed diagnostics in scripts. Enable it with cgitb.enable(format='text') for terminal output. It's most valuable in legacy codebases or one-off scripts where you need more context than the default traceback provides without reaching for a full debugger.

----
''Sources''
* <html><code>training/library/topics/python-debugging/trivia.md</code></html>

''Related atoms''
* [[What does the `traceback` module provide?]]
* [[Python's traceback format influenced error reporting across languages]]
* [[Multiple APIs exist for capturing and formatting exception information]]
A request without an explicit timeout can hang forever if the remote server is overloaded or unresponsive. In a cron job or worker process, this accumulates: one hung request blocks the worker, which spawns another job, which hangs, until you have dozens of zombie processes each holding a TCP connection and memory. All downstream systems dependent on those workers starve for available slots. Every <html><code>requests.get()</code></html>, <html><code>requests.post()</code></html>, and similar call must specify <html><code>timeout=(connect_timeout, read_timeout)</code></html>, for example <html><code>requests.get(url, timeout=(5, 30))</code></html>. Use a session with retry logic for further resilience: <html><code>requests.Session()</code></html> with <html><code>HTTPAdapter(max_retries=Retry(...))</code></html> to avoid retrying forever. In production, cron jobs and workers need even tighter timeouts (5–10 seconds) so hung jobs fail fast and the scheduler can restart them, rather than locking the entire worker pool.

----
''Sources''
* <html><code>training/library/topics/python-infra/footguns.md</code></html>

''Related atoms''
* [[requests with retries and timeout handles flaky APIs safely]]
* [[Seven common pitfalls in Python infrastructure scripts]]
Constructing a shell command with f-strings and passing it to <html><code>subprocess.run(cmd, shell=True)</code></html> opens a shell injection vulnerability. If the interpolated value (a server name, filename, or user input) contains special characters — a space, semicolon, backtick, or pipe — the shell interprets them as command separators, not literal strings. Malicious input like <html><code>host; rm -rf /</code></html> executes arbitrary commands. The fix is to pass arguments as a list and never use <html><code>shell=True</code></html>: <html><code>subprocess.run(["ping", "-c", "1", hostname])</code></html>. The subprocess module then passes the argument directly to the executable, bypassing shell parsing. If your command genuinely needs shell features like pipes or redirects, do the plumbing in Python instead: pipe subprocess output to another subprocess in the same Python process rather than asking the shell to pipe for you. Audit existing code for <html><code>shell=True</code></html> and migrate to list-based calls.

----
''Sources''
* <html><code>training/library/topics/python-infra/footguns.md</code></html>

''Related atoms''
* [[Why should you never use `shell=True` with `subprocess` when handling user input?]]
* [[What is the safer way to use `subprocess`?]]
subprocess.run() executes external programs. CRITICAL: never use shell=True with user-provided input. Shell metacharacters in user input become code: a hostname of <html><code>host; rm -rf /</code></html> executes deletion. Always pass arguments as a list: subprocess.run(['ping', '-c', '1', hostname]). Use shlex.split() only if you must parse a string (and you do not have user input in that string). capture_output=True collects stdout/stderr; text=True decodes to strings; timeout= prevents hangs; check=True raises CalledProcessError on non-zero exit. For real-time output, use Popen with a loop over stdout lines.

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>

''Related atoms''
* [[subprocess basics]]
* [[What is the safer way to use `subprocess`?]]
AWS [[list operations|List operations]] return a maximum of 1,000 (or fewer, depending on the API) results and a continuation token. If you process only the first response without checking for a <html><code>NextToken</code></html> and fetching subsequent pages, you silently lose data. A script that works perfectly on 10 EC2 instances fails silently on 2,000 instances, ignoring all instances after the first page. Your automation becomes incomplete and dangerous — security groups apply to only part of your fleet, backups run only on a subset of databases. The <html><code>boto3</code></html> paginator interface abstracts this away: <html><code>paginator = client.get_paginator('describe_instances')</code></html> followed by iteration over <html><code>paginator.paginate()</code></html> handles pagination automatically. Every AWS list operation has a corresponding paginator; use it instead of calling the base operation and assuming one response is sufficient. Test at scale — with large datasets — before deploying.

----
''Sources''
* <html><code>training/library/topics/python-infra/footguns.md</code></html>

''Related atoms''
* [[Seven common pitfalls in Python infrastructure scripts]]
* [[Generators enable streaming processing without loading entire files into memory]]
boto3 is the AWS SDK for Python. It exposes every AWS API through two interfaces: client (low-level, 1:1 with the API) and resource (high-level, object-oriented). Use client for new code; resource is in maintenance mode. boto3 reads credentials automatically from environment variables, ~/.aws/credentials profile, or EC2 instance metadata—hardcoding is never necessary. Critically, all list/describe operations return paginated results capped at 50–1000 items per call. Ignoring pagination silently truncates results. Always use get_paginator() to iterate through all pages. Error handling via ClientError lets you distinguish expected failures (instance not found) from transient failures (retry) from bugs (raise).

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>

''Related atoms''
* [[What is boto3?]]
* [[Seven common pitfalls in Python infrastructure scripts]]
* [[Diagnostic commands for Python infrastructure debugging]]
Writing a new config or data file with <html><code>open(path, 'w').write(content)</code></html> leaves a window where the process can die mid-write, leaving the file partially written and corrupted. The service reads the incomplete file, interprets it as valid, and crashes or behaves unpredictably. On Linux, <html><code>rename()</code></html> is atomic when source and destination are on the same filesystem — if the operation starts, it completes fully without interruption. Write to a temporary file in the same directory, then rename: use <html><code>tempfile.NamedTemporaryFile(dir=os.path.dirname(path), delete=False)</code></html> to create safely, flush and fsync, then <html><code>os.rename(tmp.name, path)</code></html>. This pattern ensures the original file is never partially overwritten. For additional safety, use a lock file or read-back verification to detect corruption. On other filesystems or distributed systems, atomicity may not be guaranteed; if your config system is remote or shared, use a version number or checksum.

----
''Sources''
* <html><code>training/library/topics/python-infra/footguns.md</code></html>

''Related atoms''
* [[tempfile]]
* [[pathlib replaces os.path for modern file operations]]
Overwriting a config file in place is unsafe: if the write fails partway through (disk full, process killed, power loss), the file is corrupted and the system may fail to start. The fix is to write to a temporary file first, then atomically rename it into place.

The pattern works because <html><code>rename()</code></html> is atomic on POSIX filesystems — the inode swap is a single kernel operation, so there's no window where the file is half-written. The temp file is created in the same directory as the target, ensuring the rename doesn't cross filesystem boundaries.

Before writing, the code backs up the existing file with a timestamp suffix for recovery. After writing the temp file, it copies the original file's permissions with <html><code>copystat()</code></html>, preserving ownership and mode bits. If anything fails during the write, the temp file is cleaned up, leaving the original untouched.

This pattern is essential for any daemon that auto-updates its configuration or state files. Without it, a failed update leaves the system in an unknown state. The same approach applies to updating any critical file — database snapshots, PKI certificates, deployment manifests.

----
''Sources''
* <html><code>training/library/topics/python-infra/street_ops.md</code></html>
Wrapping code in <html><code>except Exception: pass</code></html> silences every non-fatal error. A typo in a variable name raises <html><code>NameError</code></html>. A network failure raises <html><code>ConnectionError</code></html>. A JSON parsing failure raises <html><code>JSONDecodeError</code></html>. All are swallowed silently. The script reports success when it actually did nothing — the caller is none the wiser and continues depending on data that was never collected. Catch specific exceptions only: <html><code>except requests.RequestException</code></html> for HTTP failures, <html><code>except json.JSONDecodeError</code></html> for parsing, <html><code>except ClientError</code></html> for AWS errors. Unexpected exceptions propagate and crash loudly, alerting you to bugs that broad exception handlers would hide. Always log what you caught; if you do suppress an exception, include a comment explaining why. Use <html><code>logging.exception()</code></html> to capture the traceback for debugging. A failed task that crashes loudly is better than a silent, partially-complete task.

----
''Sources''
* <html><code>training/library/topics/python-infra/footguns.md</code></html>

''Related atoms''
* [[Bare except clauses hide all errors, including bugs in your code]]
* [[What is an "exception"?]]
* [[Multiple APIs exist for capturing and formatting exception information]]
Q: What is the <html><code>subprocess.run()</code></html> function?

A: The recommended way to run external commands (Python 3.5+). It returns a <html><code>CompletedProcess</code></html> with <html><code>returncode</code></html>, <html><code>stdout</code></html>, and <html><code>stderr</code></html>. Use <html><code>check=True</code></html> to raise on non-zero exit codes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `subprocess.Popen` vs `subprocess.run`?]]
* [[What is the safer way to use `subprocess`?]]
* [[subprocess basics]]
Bash is powerful for simple gluing tasks but breaks down when scripts need error handling, data structures, API integration, parallel execution, or complex logic. Python fills that gap. Every major infrastructure tool—Ansible, SaltStack, AWS CLI, Terraform providers—is written in or extensible with Python. Python's design philosophy (readability counts, one obvious way to do it) makes it ideal for infrastructure code that teams must maintain over time. This is not about replacing Bash entirely; it is about knowing when Bash has reached its limits and choosing the better tool.

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>

''Related atoms''
* [[What is Python and what makes it popular for DevOps and scripting?]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
paramiko is the standard library for SSH from Python. It runs commands on remote hosts, transfers files via SFTP, and manages SSH connections. The gotcha: SSH connections consume file descriptors. If you open connections in a loop without closing them on exception, you hit the ulimit after ~1000 hosts and everything fails. Always wrap connections in try/finally or use a context manager pattern. paramiko.AutoAddPolicy() auto-accepts unknown host keys (acceptable for infrastructure automation in controlled networks; never in production against untrusted hosts). Timeouts on connect and exec_command prevent hangs.

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>

''Related atoms''
* [[What is paramiko?]]
Click is the standard library for building command-line interfaces in Python. It handles argument parsing, help text generation, type validation, and subcommand routing. Decorators (@click.group, @click.command, @click.option, @click.argument) define structure. Click infers types from default values and [[type hints|Type hints]]. It supports confirmation prompts (confirmation_option) before destructive operations, and context objects for passing state between commands. For infrastructure tools, Click produces clean help output and validates arguments before execution, catching typos early.

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>

''Related atoms''
* [[What is Click?]]
* [[What is the standard library module for parsing command-line arguments?]]
* [[What is Typer?]]
Jinja2 is a templating engine for Python. It separates data from presentation. Loops, conditionals, and filters in templates reduce boilerplate. For infrastructure, Jinja2 generates nginx.conf, Terraform code, Kubernetes manifests, or Ansible playbooks from structured data. A template for nginx upstream blocks iterates over backend servers, interpolating IP, port, and weight. env.from_string() evaluates templates from strings; FileSystemLoader loads from files. Filters like |join, |upper, |default handle transformations without code. trim_blocks and lstrip_blocks remove extra whitespace in output.

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>
requests is the standard HTTP library for Python. Bare requests.get(url) without retries fails at the first network hiccup. Infra APIs are flaky; a single timeout or 503 should trigger a retry, not a crash. Use requests.Session with HTTPAdapter and Retry: configure total retries, backoff factor (exponential), and status_forcelist (which codes trigger retry). Always set timeout in seconds (connect_timeout, read_timeout). A session with retries and exponential backoff lets transient failures self-heal. This pattern is essential for API-driven infrastructure; without it, your script becomes fragile and unreliable.

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>

''Related atoms''
* [[Seven common pitfalls in Python infrastructure scripts]]
* [[Unmanaged HTTP request timeouts cause cascading hangs]]
* [[Exponential backoff in retries prevents service overload]]
pathlib.Path is cleaner and more expressive than os.path. Path('dir') / 'file.txt' is more readable than os.path.join('dir', 'file.txt'). Path objects have methods: mkdir(parents=True), read_text(), write_text(), glob('*.log'), rglob() for recursive glob. stat().st_size gets file size without os.stat. For atomic writes (critical for config files), write to a temp file in the same directory, then rename. This ensures the target file never contains partial data if the process crashes mid-write.

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>

''Related atoms''
* [[pathlib basics]]
* [[What is `pathlib.Path.glob()` used for?]]
* [[shutil]]
ThreadPoolExecutor runs functions in parallel. For I/O-bound tasks (API calls, SSH, health checks), threading is appropriate. Create an executor with max_workers (typically 10–50 for infrastructure work). Submit tasks, which return futures. Use as_completed() to process results as they finish, or map() for simple cases. A health check on 500 hosts takes ~500 seconds sequential but ~25 seconds with 20 workers. The trade-off: threads share Python's GIL, so CPU-bound tasks do not parallelize; use ProcessPoolExecutor instead. For infrastructure automation, ThreadPoolExecutor is almost always sufficient.

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>

''Related atoms''
* [[concurrent.futures unifies thread and process pool APIs]]
* [[threading]]
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
# Not using sessions with retries: Bare requests.get() fails at the first hiccup. Always use Session with Retry and HTTPAdapter. 2. subprocess with shell=True: Shell metacharacters in user input become code. Pass arguments as a list. 3. Blocking on SSH sequentially: 500 hosts × 1 second each = 500 seconds. Use ThreadPoolExecutor with max_workers=20. 4. Hardcoding credentials: Never put AWS keys, passwords, or tokens in code. Use environment variables, AWS profiles, or a secrets manager. 5. No timeout on HTTP requests: requests.get(url) with no timeout blocks forever if the server does not respond. Set timeout=. 6. Ignoring pagination: AWS APIs return at most 100–1000 results per call. 5000 instances + no pagination = only 1000 returned. Use get_paginator(). 7. Using os.path instead of pathlib: Path objects are cleaner, handle edge cases better, and are more readable.

----
''Sources''
* <html><code>training/library/topics/python-infra/primer.md</code></html>

''Related atoms''
* [[requests with retries and timeout handles flaky APIs safely]]
* [[Unmanaged HTTP request timeouts cause cascading hangs]]
* [[boto3 accesses AWS APIs with proper error handling and pagination]]
Quick one-liners to troubleshoot Python infra issues: python3 --version and which python3 identify the Python installation. python3 -c 'import module; print(module.__version__)' checks if a module is installed and its version. pip list shows installed packages. python3 -c 'import boto3; print(boto3.client("sts").get_caller_identity()["Arn"])' verifies AWS credentials are present and working. python3 -v -c 'import mymodule' with stderr captures import errors. python3 -m py_compile script.py checks for syntax errors without executing. python3 -m cProfile -s cumtime script.py profiles which functions consume time. These commands avoid fire-and-forget guessing when something is broken.

----
''Sources''
* <html><code>training/library/topics/python-infra/street_ops.md</code></html>

''Related atoms''
* [[Debugging tool selection by symptom and environment]]
* [[ModuleNotFoundError usually means wrong Python, wrong path, or inactive venv]]
* [[Scan Python dependencies against known vulnerabilities]]
When a service is temporarily unavailable, naive retries hammer it harder, delaying recovery. Exponential backoff spaces retries logarithmically — first retry after 2 seconds, second after 4, third after 8 — giving the service breathing room while still catching transient failures.

The pattern wraps a function with a decorator that catches specified exceptions and retries up to a limit. Each failed attempt logs the error and wait time. The backoff multiplier (2 in the example) is tunable; higher values (4, 10) suit very slow services or rate-limited APIs.

Key details: <html><code>functools.wraps</code></html> preserves the original function's name and docstring for introspection. The decorator catches only specified exception types (typically network errors like <html><code>requests.RequestException</code></html>), giving control over retry triggers. A timeout is set (10 seconds) to avoid hanging indefinitely.

This pattern is load-bearing in distributed systems. Without it, client libraries and scripts become unreliable during brief outages. Jitter can be added — sleep a random offset instead of exact exponential delay — to prevent thundering herd when many clients retry simultaneously.

----
''Sources''
* <html><code>training/library/topics/python-infra/street_ops.md</code></html>
Running operations sequentially across dozens or hundreds of hosts is slow. Threading parallelizes the work while keeping memory use fixed — the thread pool size is capped, unlike creating a thread per host.

The pattern submits a function to run on each host, then collects results as they complete. The <html><code>as_completed()</code></html> iterator fires callbacks immediately after each task finishes, so you see results in real time rather than waiting for all tasks to finish. This also enables <html><code>fail_fast</code></html>: if any host fails, you can cancel remaining work instead of completing pointless operations.

Results are bucketed into success and failed lists, making it easy to report on the job: how many succeeded, which failed, and what error occurred on each. The <html><code>max_workers</code></html> parameter (typically 20–30) bounds concurrency. Too few and you're not parallelizing; too many and you overwhelm the network or API rate limits.

One caveat: if the operation modifies state (deploys code, changes config), parallel execution can cause race conditions. Use a distributed lock or ensure operations are idempotent.

----
''Sources''
* <html><code>training/library/topics/python-infra/street_ops.md</code></html>

''Related atoms''
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
* [[Threading pools coordinate I/O-bound work with shared memory and locks]]
* [[Workload type determines the optimal concurrency model]]
Loading a 10 GB file into memory with <html><code>readlines()</code></html> will OOM. The fix is generators: iterate over lines one at a time, process each, and discard it. Only one line is in memory at any moment.

The <html><code>grep_file</code></html> generator yields line number and content as they're read, making it easy to build tools that search or filter without buffering. The same pattern applies to AWS API results: instead of fetching all objects into a list with <html><code>list_objects_v2()</code></html>, use the paginator and yield objects one page at a time.

This approach trades sequential CPU access for memory — you scan the file once linearly rather than random-accessing a loaded list — but the tradeoff is almost always worthwhile for large datasets. It also makes code more composable: you can chain generators together (filter → transform → aggregate) and they stay memory-efficient end-to-end.

The <html><code>enumerate()</code></html> function provides line numbers without extra bookkeeping. The generator stops reading as soon as you stop iterating, making partial reads efficient. This is not optional for production scripts that handle user data — size for worst-case and ensure your script handles 100 GB inputs.

----
''Sources''
* <html><code>training/library/topics/python-infra/street_ops.md</code></html>

''Related atoms''
* [[AWS API pagination limits cause silent data loss]]
* [[boto3 accesses AWS APIs with proper error handling and pagination]]
By default, <html><code>requests</code></html> and <html><code>boto3</code></html> verify that a server's SSL certificate is signed by a trusted certificate authority. In corporate environments with internal CAs (issuing certificates for internal services), this verification fails because the public CA list doesn't include your internal CA. The error is typically <html><code>SSL: CERTIFICATE_VERIFY_FAILED</code></html>.

The fix is to tell the library where to find the CA certificate — usually a PEM file in <html><code>/etc/ssl/certs/</code></html>. Pass the path with <html><code>verify=</code></html> (for requests) or set <html><code>AWS_CA_BUNDLE</code></html> (for boto3). The library adds it to the verification chain.

Disabling verification entirely (<html><code>verify=False</code></html>) is a dangerous shortcut that leaves you vulnerable to MITM attacks, especially on internal networks where an attacker could intercept traffic. Only use it for debugging. The environment variable approach sets it globally so all calls in the process inherit it — useful for containers or CI runners that operate behind internal proxies.

Docker images in corporate environments often need to COPY the internal CA certificate into the image and set the environment variable in the Dockerfile.

----
''Sources''
* <html><code>training/library/topics/python-infra/street_ops.md</code></html>
Q: Why is the language called "Python"?

A: Guido van Rossum named it after "Monty Python's Flying Circus," the British comedy group, not the snake.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Jupyter's name derived from?]]
* [[What language was Python's direct predecessor at CWI Amsterdam?]]
* [[Where do "spam" and "eggs" come from as Python variable names?]]
Q: When did Guido van Rossum start working on Python?

A: Late December 1989, during Christmas vacation at CWI in Amsterdam. He was looking for a hobby programming project to keep him occupied.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Where has Guido van Rossum worked?]]
* [[What language was Python's direct predecessor at CWI Amsterdam?]]
* [[When was Python 0.9.0 first released publicly?]]
Q: What language was Python's direct predecessor at CWI Amsterdam?

A: ABC — Guido worked on the ABC language at CWI and Python was partly inspired by it, borrowing ideas like indentation-based syntax, high-level data types, and interactive use.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is CWI?]]
* [[When did Guido van Rossum start working on Python?]]
* [[What did Python 3.7 add?]]
Q: When was Python 0.9.0 first released publicly?

A: February 20, 1991, posted to the alt.sources Usenet newsgroup.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was Python 1.0 released?]]
* [[What features did Python 0.9.0 already include?]]
* [[When was Python 3.0 released?]]
Q: What features did Python 0.9.0 already include?

A: Classes with [[inheritance|Inheritance]], exception handling, functions, the core data types (list, dict, str), and a module system. It was remarkably complete for a first public release.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.9?]]
* [[When was Python 1.0 released?]]
* [[When was Python 0.9.0 first released publicly?]]
Q: When was Python 1.0 released?

A: January 1994. It added lambda, map, filter, and reduce — functional programming features inspired by Lisp.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was Python 0.9.0 first released publicly?]]
* [[When was Python 2.0 released and what did it add?]]
* [[What features did Python 0.9.0 already include?]]
Q: When was Python 2.0 released and what did it add?

A: October 16, 2000. It introduced list comprehensions (PEP 202) and a cycle-detecting garbage collector.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What did Python 2.7 introduce?]]
* [[When was Python 1.0 released?]]
* [[When did Python 2 reach end of life?]]
Q: What did Python 2.2 introduce?

A: New-style classes (unifying types and classes), iterators, generators (PEP 255), and the <html><code>__future__</code></html> mechanism. It was one of the most significant Python 2.x releases.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What did Python 2.7 introduce?]]
* [[What did Python 3.7 add?]]
* [[What features did Python 0.9.0 already include?]]
Q: When was Python 3.0 released?

A: December 3, 2008. It was intentionally backward-incompatible to fix fundamental design issues like the print statement vs function, integer division, and Unicode handling.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What were the main breaking changes in Python 3.0?]]
* [[When was Python 1.0 released?]]
* [[What did Python 2.6 introduce?]]
Q: What were the main breaking changes in Python 3.0?

A: <html><code>print</code></html> became a function, <html><code>/</code></html> does true division by default, all strings are Unicode, <html><code>range()</code></html> returns an iterator, <html><code>dict.keys()</code></html>/<html><code>values()</code></html>/<html><code>items()</code></html> return views, and many functions return iterators instead of lists.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was Python 3.0 released?]]
* [[What did Python 3.7 add?]]
* [[What major features were added in Python 3.9?]]
Q: When did Python 2 reach end of life?

A: January 1, 2020. Python 2.7.18 (April 2020) was the absolute final release.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was Python 2.0 released and what did it add?]]
* [[When was Python 3.0 released?]]
* [[When was Python 1.0 released?]]
Q: Why was the Python 2 to 3 migration so painful?

A: The breaking changes were extensive, many popular libraries were slow to port, the <html><code>2to3</code></html> tool was imperfect, and organizations had millions of lines of Python 2 code. The migration took over a decade.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What did Python 2.6 introduce?]]
* [[When was Python 3.0 released?]]
* [[When did Python 2 reach end of life?]]
Q: What is the "six" library?

A: A Python 2/3 compatibility library by Benjamin Peterson, named because 2 x 3 = 6. It provided utilities to write code that worked on both Python 2 and 3 during the long migration.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What did Python 2.6 introduce?]]
* [[What is the significance of Python 3.6?]]
* [[What did Python 2.7 introduce?]]
Q: What does BDFL stand for, and who held that title?

A: Benevolent Dictator For Life — Guido van Rossum, Python's creator. He held this title until July 2018 when he stepped down after the contentious PEP 572 (walrus operator) debate.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why was PEP 572 (walrus operator) controversial?]]
* [[What governance model replaced the BDFL?]]
* [[What caused Guido to resign as BDFL?]]
Q: What caused Guido to resign as BDFL?

A: The bitter debate over PEP 572 (the walrus operator <html><code>:=</code></html>). Guido was tired of fighting for the PEP and facing personal attacks, so he stepped down in July 2018.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why was PEP 572 (walrus operator) controversial?]]
* [[What does BDFL stand for, and who held that title?]]
* [[What did Guido work on at Google?]]
Q: What governance model replaced the BDFL?

A: The Steering Council — a group of 5 people elected by core developers, established by PEP 13. They are re-elected after each major Python release.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What PEP established the Steering Council governance model?]]
* [[What does BDFL stand for, and who held that title?]]
Q: What PEP established the Steering Council governance model?

A: PEP 13, "Python Language Governance," adopted in late 2018.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What governance model replaced the BDFL?]]
* [[What is a PEP?]]
* [[What PEP defines the Python style guide?]]
Q: Where has Guido van Rossum worked?

A: CWI Amsterdam (1980s-1995), CNRI (1995-2000), BeOpen (2000), Zope/Digital Creations (2001-2003), Elemental Security (2003-2005), Google (2005-2012), Dropbox (2013-2019), retired briefly, then Microsoft (2020-present).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When did Guido van Rossum start working on Python?]]
* [[What year did Guido van Rossum receive the Award for the Advancement of Free Software f…]]
* [[What did Guido work on at Dropbox?]]
Q: What did Guido work on at Google?

A: He spent half his time on Python and half on internal Google tools. He helped with the internal code review tool Mondrian and worked on App Engine.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What did Guido work on at Dropbox?]]
* [[Why did Guido join Microsoft in 2020?]]
* [[Where has Guido van Rossum worked?]]
Q: What did Guido work on at Dropbox?

A: He helped improve Dropbox's Python codebase and was involved with type checking and mypy adoption.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What did Guido work on at Google?]]
* [[Why did Guido join Microsoft in 2020?]]
* [[Where has Guido van Rossum worked?]]
Q: Why did Guido join Microsoft in 2020?

A: To work on improving CPython performance. Microsoft funded the "Faster CPython" project that led to significant speed improvements in Python 3.11+.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What performance improvement was made in Python 3.11?]]
* [[Who is the current fastest growing Python web framework (as of 2025)?]]
* [[What did Guido work on at Google?]]
Q: What does PSF stand for?

A: Python Software Foundation — the non-profit organization that manages the Python programming language, owns its intellectual property, and supports the community.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is PyCon US?]]
* [[What is Python and what makes it popular for DevOps and scripting?]]
* [[What does PyPI stand for?]]
Q: What is a PEP?

A: Python Enhancement Proposal — a design document providing information or describing a new feature for Python. Key PEPs include PEP 8 (style guide), PEP 20 (Zen of Python), and PEP 484 ([[type hints|Type hints]]).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What PEP defines the Python style guide?]]
* [[What PEP introduced type hints to Python?]]
* [[What is PEP 8 and why does it matter for Python code?]]
Q: What PEP defines the Python style guide?

A: PEP 8, "Style Guide for Python Code," originally written by Guido van Rossum, Barry Warsaw, and Alyssa Coghlan.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a PEP?]]
* [[What is PEP 8 and why does it matter for Python code?]]
* [[What PEP established the Steering Council governance model?]]
Q: What PEP number is "The Zen of Python"?

A: PEP 20.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `python -m this`?]]
* [[Who wrote The Zen of Python?]]
* [[What is the walrus operator's PEP number?]]
Q: What is the PEP process for proposing language changes?

A: Write a PEP draft, submit it, get a PEP editor to assign a number, discuss it on Python-Dev/Discourse, revise based on feedback, and the Steering Council (or a delegate) accepts, rejects, or defers it.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a PEP?]]
* [[What PEP established the Steering Council governance model?]]
* [[What PEP introduced type hints to Python?]]
Q: How does someone become a Python core developer?

A: By sustained contributions to CPython, typically over months or years. An existing core developer nominates them, and the Steering Council votes. Core developers get commit access to the CPython repository.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is CPython?]]
* [[What is Python and what makes it popular for DevOps and scripting?]]
* [[When was Python 2.0 released and what did it add?]]
Q: What is PyCon US?

A: The largest annual gathering for the Python community, organized by the PSF. It includes talks, tutorials, sprints, and an expo hall. It typically attracts 3,000-4,000 attendees.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Where was PyCon US first held?]]
* [[What is EuroPython?]]
* [[What does PSF stand for?]]
Q: Where was PyCon US first held?

A: Washington, D.C. in 2003.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is PyCon US?]]
* [[When was Python 0.9.0 first released publicly?]]
* [[What does PyPI stand for?]]
Q: What is EuroPython?

A: The largest Python conference in Europe, held annually since 2002. It rotates between European cities.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is PyCon US?]]
* [[What is Cython?]]
* [[What is MicroPython?]]
Q: What is PyData?

A: A conference series (with events worldwide) focused on data science, machine learning, and analytics in the Python ecosystem. Organized by NumFOCUS.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `pydoc` module?]]
* [[What does PyPI stand for?]]
* [[What Python library has become the standard for data validation and settings management?]]
Q: What are "sprints" at Python conferences?

A: Multi-day coding sessions after the main conference where attendees collaborate on open-source projects, fix bugs, and contribute to Python itself.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are Python "lightning talks"?]]
* [[What is PyCon US?]]
* [[What is EuroPython?]]
Q: What are Python "lightning talks"?

A: Very short (typically 5-minute) presentations given at Python conferences, often humorous or covering niche topics.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are "sprints" at Python conferences?]]
* [[What is PyCon US?]]
* [[What is Python Fire?]]
Q: What is CPython?

A: The reference implementation of Python, written in C. When people say "Python," they usually mean CPython.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is CPython bytecode?]]
* [[What is Jupyter's name derived from?]]
* [[What is a PEP?]]
Q: Name five alternative Python implementations.

A: PyPy (JIT-compiled, faster), Jython (runs on JVM), IronPython (runs on .NET), GraalPython (on GraalVM), and MicroPython (for microcontrollers).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is PyPy and why is it significant?]]
* [[Name three Python static type checkers besides mypy.]]
* [[What is Python and what makes it popular for DevOps and scripting?]]
Q: What is PyPy and why is it significant?

A: A Python implementation with a Just-In-Time (JIT) compiler that can be 4-10x faster than CPython for long-running programs. It is written in RPython (a restricted subset of Python).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Name five alternative Python implementations.]]
* [[What does PyPI stand for?]]
* [[What is Cython?]]
Q: What is MicroPython?

A: A lean Python 3 implementation designed to run on microcontrollers and constrained environments. It implements a subset of the standard library optimized for embedded systems.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Name five alternative Python implementations.]]
* [[What is Cython?]]
* [[What is PyPy and why is it significant?]]
Q: What is Timsort?

A: The sorting algorithm used by Python's <html><code>sorted()</code></html> and <html><code>list.sort()</code></html>. Designed by Tim Peters in 2002, it is a hybrid merge sort/insertion sort with O(n log n) worst case and O(n) best case for partially sorted data. Adopted by Java, Android, and other platforms.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `list.sort()` vs `sorted()` return?]]
* [[What does `sorted()` guarantee about equal elements?]]
Q: What was Python 1.5 notable for?

A: Released in 1998, it was the version that really established Python's popularity and was the standard for many years. It introduced the <html><code>re</code></html> module replacing the older <html><code>regex</code></html> module.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What features did Python 0.9.0 already include?]]
* [[When was Python 1.0 released?]]
* [[When was Python 2.0 released and what did it add?]]
Q: What did Python 2.5 introduce?

A: The <html><code>with</code></html> statement (PEP 343), conditional expressions (<html><code>x if cond else y</code></html>), and <html><code>try/except/finally</code></html> as a single statement.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What did Python 2.7 introduce?]]
* [[What is the `with` statement's full syntax since Python 3.1?]]
* [[What is the `except*` syntax?]]
Q: What did Python 2.6 introduce?

A: It served as a transition release toward Python 3, adding many Python 3 features with backward compatibility. It introduced the <html><code>multiprocessing</code></html> module and the <html><code>-3</code></html> flag for warnings about Python 3 incompatibilities.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the significance of Python 3.6?]]
* [[When was Python 3.0 released?]]
* [[What is the "six" library?]]
Q: What did Python 2.7 introduce?

A: The final Python 2 release. It added set literals <html><code>{1, 2, 3}</code></html>, dict comprehensions, <html><code>OrderedDict</code></html>, <html><code>Counter</code></html>, and the <html><code>argparse</code></html> module.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was Python 2.0 released and what did it add?]]
* [[What did Python 2.2 introduce?]]
* [[What features did Python 0.9.0 already include?]]
Q: What is the significance of Python 3.6?

A: It added f-strings (PEP 498), variable annotations (PEP 526), underscores in numeric literals, the <html><code>secrets</code></html> module, async generators, and dict ordering as an implementation detail.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.12?]]
* [[What did Python 2.6 introduce?]]
* [[What is PEP 649 about?]]
Q: What did Python 3.7 add?

A: <html><code>dataclasses</code></html>, <html><code>breakpoint()</code></html>, <html><code>asyncio.run()</code></html>, <html><code>contextvars</code></html>, postponed evaluation of annotations (PEP 563 as <html><code>__future__</code></html>), and dict ordering became a language guarantee.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When did dict ordering become a language guarantee?]]
* [[What were the main breaking changes in Python 3.0?]]
* [[What major features were added in Python 3.13?]]
Q: What year did Guido van Rossum receive the Award for the Advancement of Free Software from the FSF?

A: 2001.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When did Guido van Rossum start working on Python?]]
* [[Where has Guido van Rossum worked?]]
Q: What is CWI?

A: Centrum Wiskunde & Informatica (Center for Mathematics and Computer Science) in Amsterdam, the Netherlands. This is where Guido created Python.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What language was Python's direct predecessor at CWI Amsterdam?]]
* [[When did Guido van Rossum start working on Python?]]
* [[What does PyPI stand for?]]
Q: What was the "Python 3000" or "Py3k" initiative?

A: The long-term project to create Python 3, which was known as "Python 3000" during development. The name was a tongue-in-cheek suggestion that it would take until the year 3000 to finish.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was Python 3.0 released?]]
* [[What did Python 2.6 introduce?]]
* [[What did Python 3.7 add?]]
Q: What is the difference between <html><code>is</code></html> and <html><code>==</code></html> in Python?

A: <html><code>is</code></html> checks identity (same object in memory). <html><code>==</code></html> checks equality (same value). Due to integer caching, <html><code>a is b</code></html> might be True for small integers but this should never be relied upon.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[is / is not (identity)]]
* [[What is the difference between `is` and `==` for `None`?]]
* [[is checks identity; == checks value; small ints are interned]]
Q: What is the difference between == and is in Python?

A: == checks value equality (whether two objects have equal values), while is checks identity (whether they are the same object in memory). 
Gotcha: small integers (-5 to 256) and short strings are cached/interned by CPython, so is may appear to work but is unreliable for value comparison. Always use == for values; reserve is for None checks (x is None).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[is checks identity; == checks value; small ints are interned]]
* [[is / is not (identity)]]
* [[What does `f'{value=}'` do, introduced in Python 3.8?]]
Q: What integers does CPython cache (intern)?

A: Integers from -5 to 256 inclusive. These are pre-allocated singleton objects, so <html><code>a = 256; b = 256; a is b</code></html> is True, but <html><code>a = 257; b = 257; a is b</code></html> may be False.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `id()` return?]]
* [[What is the result of `() is ()`?]]
* [[What is `__cached__` on a module?]]
Q: What is the small integer cache in CPython?

A: CPython pre-allocates integers from -5 to 256 as singleton objects. Any code that creates an integer in this range gets a reference to the same object, saving memory and time.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a "free list" in CPython?]]
* [[What is `__cached__` on a module?]]
* [[What is CPython's memory allocator?]]
Q: Does Python intern strings?

A: CPython interns some strings automatically (like identifiers and string literals that look like identifiers). You can also explicitly intern with <html><code>sys.intern()</code></html>. Interning allows <html><code>is</code></html> comparison instead of <html><code>==</code></html> for speed.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `str.isidentifier()`?]]
* [[What is the surprising behavior of `is` with short strings?]]
* [[is checks identity; == checks value; small ints are interned]]
Q: What is string interning?

A: A technique where identical strings share the same object in memory. CPython automatically interns strings that look like identifiers. You can manually intern with <html><code>sys.intern()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `import __hello__` do?]]
* [[What does `id()` return?]]
* [[What integers does CPython cache (intern)?]]
Q: What is "duck typing"?

A: "If it walks like a duck and quacks like a duck, it's a duck." Python checks behavior (methods/attributes) rather than explicit type, enabling polymorphism without [[inheritance|Inheritance]].

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `typing.Protocol` do?]]
* [[What is the `type` statement in Python 3.12?]]
* [[What is the `typing.Self` type, and when was it introduced?]]
Q: What is duck typing and how does Python use it?

A: 'If it walks like a duck and quacks like a duck, it's a duck.' Python checks behavior (methods/attributes) rather than type.

def get_length(obj):
    return len(obj)  # works with str, list, dict, any object with __len__

get_length('hello')  # 5
get_length([1,2,3])  # 3

Protocol classes (Python 3.8+) formalize this:
from typing import Protocol

class Sized(Protocol):
    def __len__(self) -> int: ...

def f(x: Sized) -> int:
    return len(x)

Duck typing enables polymorphism without [[inheritance|Inheritance]]. The typing.Protocol class adds optional static checking while preserving runtime duck typing.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[Protocol (structural typing)]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What does the len() function do?]]
Q: What is "EAFP" in Python?

A: "Easier to Ask Forgiveness than Permission" — a coding style that tries an operation and handles exceptions rather than checking preconditions. Contrasted with "LBYL" (Look Before You Leap).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the LBYL coding style?]]
* [[What does `python -c "expr"` do?]]
* [[What is the `except*` syntax?]]
Q: What is the LEGB rule?

A: The variable scoping rule in Python: Local, Enclosing, Global, Built-in. Python searches for names in this order.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[LEGB scope rule]]
* [[What are variables in Python and how are they defined?]]
* [[What is name mangling in Python?]]
Q: What is a [[list comprehension|List comprehension]] and when was it introduced?

A: A concise syntax for creating lists: <html><code>[x**2 for x in range(10)]</code></html>. Introduced in Python 2.0 (PEP 202), inspired by Haskell.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are the different comprehension types in Python?]]
* [[What is the difference between a list comprehension and a generator expression?]]
* [[What did Python 2.7 introduce?]]
Q: What is a [[list comprehension|List comprehension]] in Python?

A: A concise way to create a new list by iterating over an iterable and optionally filtering. 
Example: [x**2 for x in range(5) if x % 2 == 0] creates [0, 4, 16]. Also supports nested loops and can be turned into generator expressions with parentheses for memory efficiency. Prefer comprehensions over map/filter for readability.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What are the different comprehension types in Python?]]
* [[What is the difference between a list comprehension and a generator expression?]]
* [[List comprehension]]
Q: What are the different comprehension types in Python?

A: List <html><code>[x for x in items]</code></html>, set <html><code>{x for x in items}</code></html>, dict <html><code>{k: v for k, v in pairs}</code></html>, and [[generator expression|Generator expression]] <html><code>(x for x in items)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a list comprehension in Python?]]
* [[What is a list comprehension and when was it introduced?]]
* [[What is the difference between a list comprehension and a generator expression?]]
Q: What is the difference between a [[list comprehension|List comprehension]] and a [[generator expression|Generator expression]]?

A: A list comprehension <html><code>[x for x in items]</code></html> creates the entire list in memory. A generator expression <html><code>(x for x in items)</code></html> produces values lazily, one at a time, using much less memory for large sequences.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are the different comprehension types in Python?]]
* [[What is a list comprehension in Python?]]
* [[What is a Python generator?]]
Q: What is the result of <html><code>bool([])</code></html>?

A: <html><code>False</code></html>. Empty sequences (list, tuple, string, dict, set) are falsy.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `[] is []`?]]
* [[What is the `__bool__` method?]]
* [[What does `any([])` return?]]
Q: What is the result of <html><code>True + True</code></html>?

A: <html><code>2</code></html>. In Python, <html><code>bool</code></html> is a subclass of <html><code>int</code></html>, where <html><code>True</code></html> is <html><code>1</code></html> and <html><code>False</code></html> is <html><code>0</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the truthiness rule in Python?]]
* [[What does `isinstance(True, int)` return?]]
* [[What is a Boolean data type and how is it used in programming?]]
Q: Why is <html><code>True + True == 2</code></html>?

A: Because <html><code>bool</code></html> is a subclass of <html><code>int</code></html>, <html><code>True</code></html> equals <html><code>1</code></html>, so <html><code>True + True</code></html> evaluates to <html><code>1 + 1 = 2</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `isinstance(True, int)` return?]]
* [[What is a Boolean data type and how is it used in programming?]]
* [[What is the `__bool__` method?]]
Q: What does <html><code>isinstance(True, int)</code></html> return?

A: <html><code>True</code></html>, because <html><code>bool</code></html> is a subclass of <html><code>int</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `True + True`?]]
* [[Why is `True + True == 2`?]]
* [[What function returns the data type of an object?]]
Q: What is the truthiness rule in Python?

A: Objects are truthy by default. The following are falsy: <html><code>None</code></html>, <html><code>False</code></html>, zero of any numeric type (<html><code>0</code></html>, <html><code>0.0</code></html>, <html><code>0j</code></html>, <html><code>Decimal(0)</code></html>, <html><code>Fraction(0, 1)</code></html>), empty sequences/mappings (<html><code>''</code></html>, <html><code>()</code></html>, <html><code>[]</code></html>, <html><code>{}</code></html>, <html><code>set()</code></html>, <html><code>range(0)</code></html>), and objects whose <html><code>__bool__</code></html> returns False or <html><code>__len__</code></html> returns 0.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `True + True`?]]
* [[What is the result of `bool([])`?]]
* [[Truthy and falsy values]]
Q: What is the <html><code>__bool__</code></html> method?

A: It defines the truth value of an object. If not defined, Python falls back to <html><code>__len__</code></html> (0 is falsy), then defaults to <html><code>True</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `bool([])`?]]
* [[What is `__len__` used for?]]
* [[What is a Boolean data type and how is it used in programming?]]
Q: What is <html><code>__all__</code></html> used for in a module?

A: It defines the public API — the list of names exported when someone does <html><code>from module import *</code></html>. If not defined, all names not starting with underscore are exported.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__name__` set to when a module is imported?]]
* [[What does the `import` statement do in Python?]]
* [[What is `sys.modules`?]]
Q: What does <html><code>__all__</code></html> in <html><code>__init__.py</code></html> control?

A: What is exported when <html><code>from package import *</code></html> is used. It also serves as documentation of the package's public API.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__init__.py` file for?]]
* [[What does the `import` statement do in Python?]]
* [[What is the `__main__.py` file for?]]
Q: What is <html><code>sys.path</code></html> and how does Python use it?

A: A list of directories that Python searches when importing modules. It includes the script's directory, <html><code>PYTHONPATH</code></html> environment variable entries, and default library paths.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Inspect sys.path and site-packages to understand module resolution]]
* [[What is `sysconfig` used for?]]
* [[What is the `site` module responsible for?]]
Q: What is the <html><code>PYTHONPATH</code></html> environment variable?

A: A colon-separated (semicolon on Windows) list of directories added to <html><code>sys.path</code></html> before the default entries.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.executable`?]]
* [[What is the `PYTHONDONTWRITEBYTECODE` environment variable?]]
Q: What is the <html><code>nonlocal</code></html> keyword used for?

A: It declares that a variable in an inner function refers to a variable in the enclosing (non-global) scope, allowing it to be modified. Without <html><code>nonlocal</code></html>, the inner function would create a new local variable.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[global / nonlocal]]
* [[What is the `global` keyword used for?]]
* [[What is a "local variable"?]]
Q: What is the <html><code>global</code></html> keyword used for?

A: It declares that a variable inside a function refers to the global (module-level) scope, allowing it to be read and modified.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a "local variable"?]]
* [[What is the `nonlocal` keyword used for?]]
* [[global / nonlocal]]
Q: What is monkey patching?

A: Dynamically modifying a class or module at runtime. For example, replacing a method on an existing class. It is powerful but can make code hard to debug.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `pytest.monkeypatch`?]]
* [[What is `unittest.mock.patch` used for?]]
* [[What is `object.__new__`?]]
Q: What does <html><code>id()</code></html> return?

A: The identity of an object — an integer guaranteed to be unique for that object during its lifetime. In CPython, it is the memory address.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What integers does CPython cache (intern)?]]
* [[What is the small integer cache in CPython?]]
* [[What is the result of `() is ()`?]]
Q: What is the <html><code>del</code></html> statement?

A: It unbinds a name from an object: <html><code>del x</code></html> removes <html><code>x</code></html> from the local namespace. For lists, <html><code>del lst[i]</code></html> removes an element. <html><code>del</code></html> does not directly free memory — it just decrements the reference count.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__del__` used for?]]
* [[del (delete)]]
* [[What is `__setitem__` and `__delitem__`?]]
Q: What is the maximum recursion depth in Python by default?

A: 1000. It can be changed with <html><code>sys.setrecursionlimit()</code></html>, but deep recursion is discouraged due to stack overflow risk.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.getrecursionlimit()` return?]]
* [[Is there a limit to integer size in Python 3?]]
* [[What are the standard logging levels in Python, from lowest to highest?]]
Q: What is the <html><code>Ellipsis</code></html> object (<html><code>...</code></html>) used for in Python?

A: As a placeholder in stubs/protocols (<html><code>def method(self) -&gt; None: ...</code></html>), in NumPy for advanced slicing (<html><code>array[..., 0]</code></html>), and in [[type hints|Type hints]] (<html><code>tuple[int, ...]</code></html> for variable-length tuples).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is "slicing" in Python?]]
* [[What does the len() function do?]]
* [[What is "tuple unpacking"?]]
Q: What does <html><code>type(...)</code></html> return?

A: <html><code>&lt;class 'ellipsis'&gt;</code></html>. The <html><code>...</code></html> literal is the singleton <html><code>Ellipsis</code></html> object.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What function returns the data type of an object?]]
* [[What is `type()` with one argument vs three arguments?]]
* [[What does `isinstance()` check that `type()` does not?]]
Q: What is the <html><code>NotImplemented</code></html> singleton used for?

A: Rich comparison methods return <html><code>NotImplemented</code></html> to indicate they don't support comparison with the given type, allowing Python to try the reflected operation on the other operand. It is NOT the same as <html><code>NotImplementedError</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `is` and `==` for `None`?]]
* [[How do you check for `None` in Python?]]
* [[What is `typing.runtime_checkable` used for?]]
Q: What is <html><code>NotImplemented</code></html> vs <html><code>NotImplementedError</code></html>?

A: <html><code>NotImplemented</code></html> is a singleton value returned by rich comparison methods to signal the comparison is not implemented for those types. <html><code>NotImplementedError</code></html> is an exception raised to indicate an abstract method needs to be overridden.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.runtime_checkable` used for?]]
* [[What does `isinstance()` check that `type()` does not?]]
* [[What is the difference between `is` and `==` for `None`?]]
Q: What does the <html><code>__future__</code></html> module do?

A: It enables features from future Python versions in the current version. For example, <html><code>from __future__ import annotations</code></html> (PEP 563) makes all annotations strings by default (lazy evaluation).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is the significance of Python 3.6?]]
* [[What is the `__annotations__` attribute?]]
* [[What is `typing.get_type_hints()` used for?]]
Q: What is the Python REPL's <html><code>_</code></html> variable?

A: In the interactive interpreter, <html><code>_</code></html> holds the result of the last expression evaluated. For example, after typing <html><code>2 + 3</code></html>, <html><code>_</code></html> equals <html><code>5</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is name mangling in Python?]]
* [[What is the difference between `__str__` and `__repr__`?]]
* [[What is the walrus operator in Python?]]
Q: What does <html><code>sorted()</code></html> guarantee about equal elements?

A: The sort is stable — elements that compare equal retain their original relative order.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `list.sort()` vs `sorted()` return?]]
* [[What is Timsort?]]
Q: What does <html><code>[1, 2, 3][::-1]</code></html> return?

A: <html><code>[3, 2, 1]</code></html> — a reversed copy of the list. The <html><code>[::-1]</code></html> slice reverses any sequence.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is "slicing" in Python?]]
* [[What does `reversed()` require?]]
* [[What is the difference between `list.copy()` and `list[:]`?]]
Q: What is the result of <html><code>"hello" * 3</code></html>?

A: <html><code>'hellohellohello'</code></html>. String (and sequence) multiplication repeats the sequence.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Python's `match` statement sequence pattern?]]
* [[What does the `%` operator do with strings in Python?]]
* [[What does `string.ascii_letters` contain?]]
Q: What does <html><code>any([])</code></html> return?

A: <html><code>False</code></html>. <html><code>any</code></html> of an empty iterable is <html><code>False</code></html>. <html><code>all([])</code></html> returns <html><code>True</code></html> (vacuous truth).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `bool([])`?]]
* [[What does `itertools.pairwise()` return for an empty or single-element iterable?]]
* [[What does `any(generator_expression)` short-circuit?]]
Q: Why does <html><code>all([])</code></html> return <html><code>True</code></html>?

A: It follows the mathematical convention of vacuous truth — the statement "all elements satisfy the condition" is trivially true when there are no elements.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `[] is []`?]]
* [[What is the result of `bool([])`?]]
* [[What is the WAT moment with `[] == False`?]]
Q: What does <html><code>string.ascii_letters</code></html> contain?

A: All ASCII letters: <html><code>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `str.encode()` and `bytes.decode()`?]]
* [[What is the `unicodedata` module?]]
* [[What does `chr()` and `ord()` do?]]
Q: What is the difference between <html><code>a += b</code></html> and <html><code>a = a + b</code></html> for lists?

A: For lists, <html><code>+=</code></html> modifies the list in-place (calls <html><code>__iadd__</code></html>), while <html><code>a = a + b</code></html> creates a new list. This matters when other variables reference the same list.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__iadd__`?]]
* [[What is the difference between == and is in Python?]]
* [[What is the `operator` module?]]
Q: What does <html><code>enumerate()</code></html> return?

A: An iterator of <html><code>(index, element)</code></html> tuples. It accepts an optional <html><code>start</code></html> parameter: <html><code>enumerate(items, start=1)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.count(start=0, step=1)` do?]]
* [[What does `Counter.elements()` return?]]
* [[What is a tuple and how does it differ from a list?]]
Q: What is the <html><code>zip()</code></html> function's strict mode?

A: Added in Python 3.10 (PEP 618): <html><code>zip(*iterables, strict=True)</code></html> raises <html><code>ValueError</code></html> if the iterables have different lengths.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `python -m zipapp` used for?]]
* [[What is `itertools.repeat()` commonly used with?]]
* [[What is `zipimport`?]]
Q: What does <html><code>itertools.zip_longest()</code></html> do differently from <html><code>zip()</code></html>?

A: <html><code>zip()</code></html> stops at the shortest iterable. <html><code>zip_longest()</code></html> continues until the longest iterable is exhausted, filling missing values with a <html><code>fillvalue</code></html> (default <html><code>None</code></html>).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.compress(data, selectors)` do?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
* [[What does `itertools.islice()` do?]]
Q: What is the walrus operator in Python?

A: The <html><code>:=</code></html> assignment expression operator, introduced in Python 3.8 (PEP 572). It assigns a value to a variable as part of an expression.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the walrus operator's PEP number?]]
* [[What is the precedence of the walrus operator?]]
* [[Walrus operator (:=)]]
Q: What is the <html><code>walrus operator</code></html> officially called?

A: Assignment expression.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the walrus operator's PEP number?]]
* [[Can the walrus operator be used in all expression contexts?]]
* [[What is the precedence of the walrus operator?]]
Q: Give a common use case for the walrus operator.

A: In while loops reading input: <html><code>while (line := input()) != 'quit': process(line)</code></html>. Or in list comprehensions for filtering: <html><code>[y for x in data if (y := f(x)) &gt; 0]</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the walrus operator in Python?]]
* [[What is the precedence of the walrus operator?]]
* [[What is a list comprehension in Python?]]
Q: Why was PEP 572 (walrus operator) controversial?

A: It sparked intense debate about readability and Pythonic style. The contentious discussion led to Guido van Rossum resigning as BDFL in July 2018, stating he was tired of fighting for the PEP and facing personal attacks.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What caused Guido to resign as BDFL?]]
* [[What does BDFL stand for, and who held that title?]]
* [[What is the walrus operator's PEP number?]]
Q: Can the walrus operator be used in all expression contexts?

A: No. It cannot be used as a top-level statement (use regular <html><code>=</code></html> instead). It also has restrictions in comprehension scoping and augmented assignments.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `walrus operator` officially called?]]
* [[What is the walrus operator in Python?]]
* [[What is the precedence of the walrus operator?]]
Q: What is the precedence of the walrus operator?

A: It has very low precedence — lower than most operators. Parentheses are often needed: <html><code>if (n := len(data)) &gt; 10:</code></html> requires the parentheses around the assignment.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the walrus operator in Python?]]
* [[What is the walrus operator's PEP number?]]
* [[What is the `walrus operator` officially called?]]
Q: What is the difference between <html><code>bytes</code></html> and <html><code>str</code></html> in Python 3?

A: <html><code>str</code></html> holds Unicode text, <html><code>bytes</code></html> holds raw binary data. They are distinct types and cannot be mixed without explicit encoding/decoding.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `__str__` and `__repr__`?]]
* [[What is `str.encode()` and `bytes.decode()`?]]
* [[What is `base64` encoding used for in Python?]]
Q: What encoding does Python 3 use for source files by default?

A: UTF-8 (since Python 3.0). Python 2 defaulted to ASCII.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.getdefaultencoding()` return in Python 3?]]
* [[What is `str.encode()` and `bytes.decode()`?]]
* [[What is `base64` encoding used for in Python?]]
Q: What is a <html><code>bytearray</code></html> and how does it differ from <html><code>bytes</code></html>?

A: <html><code>bytearray</code></html> is a mutable sequence of bytes, while <html><code>bytes</code></html> is immutable. <html><code>bytearray</code></html> supports in-place modification.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `int.to_bytes()` do?]]
* [[What is `io.BytesIO` used for?]]
* [[What is the difference between `bytes` and `str` in Python 3?]]
Q: What does <html><code>pass</code></html> do in Python?

A: It is a null operation — a placeholder that does nothing. It is used where a statement is syntactically required but no action is needed (empty class bodies, stubs, etc.).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[pass]]
* [[What is a closure in Python?]]
* [[What does the `*` separator in function parameters do?]]
Q: What is the difference between <html><code>None</code></html> and <html><code>False</code></html>?

A: <html><code>None</code></html> is the singleton representing absence of a value (NoneType). <html><code>False</code></html> is a boolean. Both are falsy, but <html><code>None is not False</code></html> evaluates to <html><code>True</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[How do you check for `None` in Python?]]
* [[What is the difference between `is` and `==` for `None`?]]
* [[What is a Boolean data type and how is it used in programming?]]
Q: How do you check for <html><code>None</code></html> in Python?

A: Always use <html><code>is None</code></html> or <html><code>is not None</code></html>, never <html><code>== None</code></html>. The <html><code>is</code></html> operator checks identity, which is correct since <html><code>None</code></html> is a singleton.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[is / is not (identity)]]
* [[What is the difference between `None` and `False`?]]
* [[None]]
Q: What are the advantages of <html><code>collections.deque</code></html> over a list?

A: O(1) append and pop from both ends (lists are O(n) for <html><code>insert(0, x)</code></html> and <html><code>pop(0)</code></html>). Deques also support a <html><code>maxlen</code></html> parameter for fixed-size buffers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[collections.deque]]
* [[What does `list.extend()` do vs `list.append()`?]]
* [[What is the time complexity of `list.append()`?]]
Q: What does <html><code>collections.deque(maxlen=n)</code></html> do when you append beyond capacity?

A: It automatically discards elements from the opposite end. Appending to the right discards from the left, and vice versa. This creates a bounded buffer.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[collections.deque]]
* [[What does `list.extend()` do vs `list.append()`?]]
* [[What does `itertools.tee(iterable, n=2)` return?]]
Q: What does <html><code>deque.rotate(n)</code></html> do?

A: Rotates the deque n steps to the right. If n is negative, it rotates to the left. For example, <html><code>deque([1,2,3]).rotate(1)</code></html> gives <html><code>deque([3,1,2])</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `[1, 2, 3][::-1]` return?]]
* [[What does `reversed()` require?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
Q: What does <html><code>collections.Counter</code></html> return when you access a key that doesn't exist?

A: It returns <html><code>0</code></html> (not a <html><code>KeyError</code></html>), because Counter is a subclass of <html><code>dict</code></html> that overrides <html><code>__missing__</code></html> to return zero.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__missing__` used for?]]
* [[What is `collections.UserDict` for?]]
* [[What happens if you create a `defaultdict` with no argument (i.e., `defaultdict()`)?]]
Q: What does <html><code>Counter.most_common(n)</code></html> return?

A: A list of the n most common elements and their counts, as <html><code>(element, count)</code></html> tuples, sorted from most common to least.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `Counter.elements()` return?]]
* [[collections.Counter]]
* [[What happens when you add two `Counter` objects together?]]
Q: What happens when you add two <html><code>Counter</code></html> objects together?

A: Their counts are summed element-wise. Subtraction (<html><code>-</code></html>) subtracts counts and drops zero/negative results. The <html><code>&amp;</code></html> operator gives element-wise minimums (intersection) and <html><code>|</code></html> gives maximums (union).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `collections.Counter.subtract()` do differently from `-`?]]
* [[What does `Counter.elements()` return?]]
* [[What does `Counter.most_common(n)` return?]]
Q: What does <html><code>Counter.elements()</code></html> return?

A: An iterator over elements, each repeated as many times as its count. Elements with zero or negative counts are excluded.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.count(start=0, step=1)` do?]]
* [[What happens when you add two `Counter` objects together?]]
* [[What does `collections.Counter.subtract()` do differently from `-`?]]
Q: What does <html><code>collections.Counter.subtract()</code></html> do differently from <html><code>-</code></html>?

A: <html><code>subtract()</code></html> subtracts counts in-place and allows negative results. The <html><code>-</code></html> operator drops zero and negative results.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What happens when you add two `Counter` objects together?]]
* [[What does `Counter.elements()` return?]]
* [[What does `collections.Counter` return when you access a key that doesn't exist?]]
Q: What is the default value returned by a <html><code>defaultdict(list)</code></html> for a missing key?

A: An empty list <html><code>[]</code></html>. The argument to <html><code>defaultdict</code></html> is a factory function called with no arguments to produce default values.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__missing__` used for?]]
* [[What is `dict.setdefault(key, default)`?]]
* [[What does `collections.Counter` return when you access a key that doesn't exist?]]
Q: What happens if you create a <html><code>defaultdict</code></html> with no argument (i.e., <html><code>defaultdict()</code></html>)?

A: Accessing a missing key raises a <html><code>KeyError</code></html>, just like a regular dict, because the <html><code>default_factory</code></html> is <html><code>None</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `dict.setdefault(key, default)`?]]
* [[What does `collections.Counter` return when you access a key that doesn't exist?]]
* [[What is a "dictionary"?]]
Q: What method does <html><code>defaultdict</code></html> call to produce a default value?

A: It calls the <html><code>default_factory</code></html> attribute, which is the callable passed to the constructor. This is invoked from the <html><code>__missing__</code></html> method.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__missing__` used for?]]
* [[What is `dict.setdefault(key, default)`?]]
* [[In `dataclasses`, what does the `field()` function's `default_factory` parameter do?]]
Q: Is <html><code>OrderedDict</code></html> still useful now that regular dicts maintain insertion order (since Python 3.7)?

A: Yes. <html><code>OrderedDict</code></html> supports <html><code>move_to_end()</code></html>, equality comparisons consider order (unlike regular dicts), and it has a different <html><code>__eq__</code></html> behavior: two OrderedDicts with the same items in different order are not equal, while two regular dicts would be.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When did dict ordering become a language guarantee?]]
* [[What does `OrderedDict.move_to_end(key, last=True)` do?]]
* [[What is the `collections.OrderedDict` `popitem(last=True)` method?]]
Q: What does <html><code>OrderedDict.move_to_end(key, last=True)</code></html> do?

A: It moves an existing key to either end of the ordered dict. With <html><code>last=True</code></html> (default) it moves to the right end; with <html><code>last=False</code></html> to the beginning.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Is `OrderedDict` still useful now that regular dicts maintain insertion order (since Py…]]
* [[What is `dict.setdefault(key, default)`?]]
* [[What does `dict | other_dict` do in Python 3.9+?]]
Q: What is <html><code>collections.ChainMap</code></html> used for?

A: It groups multiple dicts into a single mapping view. Lookups search the underlying maps in order. It is commonly used for managing nested scopes like configuration layers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.abc.MutableMapping`?]]
* [[When you set a value on a `ChainMap`, which underlying dict is modified?]]
Q: When you set a value on a <html><code>ChainMap</code></html>, which underlying dict is modified?

A: Only the first (frontmost) mapping in the chain. Lookups search all maps, but mutations only affect <html><code>maps[0]</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.ChainMap` used for?]]
* [[What is a `mappingproxy`?]]
* [[What does `dict | other_dict` do in Python 3.9+?]]
Q: How do you create a named tuple with <html><code>collections.namedtuple</code></html>?

A: <html><code>Point = namedtuple('Point', ['x', 'y'])</code></html> or equivalently with a space-separated string <html><code>'x y'</code></html>. Instances are immutable tuples with named fields.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[NamedTuple]]
* [[What is `typing.NamedTuple` and how does it compare to `collections.namedtuple`?]]
* [[What method on a namedtuple returns a regular dictionary?]]
Q: What method on a [[namedtuple|NamedTuple]] returns a regular dictionary?

A: <html><code>._asdict()</code></html>. Despite the leading underscore, it is part of the public API — the underscore prevents name conflicts with field names.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is name mangling in Python?]]
* [[What method on a namedtuple creates a new instance with some fields replaced?]]
* [[What is `typing.NamedTuple` and how does it compare to `collections.namedtuple`?]]
Q: What method on a [[namedtuple|NamedTuple]] creates a new instance with some fields replaced?

A: <html><code>._replace(**kwargs)</code></html>. It returns a new instance since namedtuples are immutable.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What method on a namedtuple returns a regular dictionary?]]
* [[How do you create a named tuple with `collections.namedtuple`?]]
* [[Dataclasses vs namedtuples — when to use which?]]
Q: What is <html><code>collections.UserDict</code></html> for?

A: It is a wrapper around a regular dict (stored as <html><code>.data</code></html>) designed to be subclassed. It is easier to subclass than <html><code>dict</code></html> because you only need to override the methods you want without worrying about internal C optimizations.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.abc` and how does it differ from `collections`?]]
* [[What is a "dictionary"?]]
* [[What does the `dataclasses.asdict()` function do?]]
Q: What is <html><code>collections.abc</code></html> and how does it differ from <html><code>collections</code></html>?

A: <html><code>collections.abc</code></html> contains abstract base classes for containers (like <html><code>Mapping</code></html>, <html><code>Sequence</code></html>, <html><code>Iterable</code></html>, <html><code>MutableSet</code></html>). These were moved from <html><code>collections</code></html> in Python 3.3 and accessing them from <html><code>collections</code></html> directly was deprecated in 3.9 and removed in 3.10.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.abc.Iterator` vs `collections.abc.Iterable`?]]
* [[What is `collections.abc.MutableMapping`?]]
* [[What is `collections.UserDict` for?]]
Q: Can a tuple be a dictionary key?

A: Only if all its elements are hashable. <html><code>(1, 2, 3)</code></html> can be a key, but <html><code>(1, [2, 3])</code></html> cannot because lists are unhashable.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a tuple and how does it differ from a list?]]
* [[What's the difference between a list and a tuple in Python?]]
* [[What is a "dictionary"?]]
Q: What is a frozenset?

A: An immutable version of <html><code>set</code></html>. Since it is hashable, it can be used as a dictionary key or as an element of another set.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[frozenset]]
* [[What does `@dataclass(frozen=True)` do?]]
* [[What is the result of `{} == set()`?]]
Q: What is the result of <html><code>{} == set()</code></html>?

A: <html><code>False</code></html>. <html><code>{}</code></html> creates an empty dict, not an empty set. To create an empty set, you must use <html><code>set()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the type of `{}`?]]
* [[What is `dict.setdefault(key, default)`?]]
* [[What is the result of `bool([])`?]]
Q: What is the type of <html><code>{}</code></html>?

A: <html><code>dict</code></html>. This is a common gotcha — empty curly braces create a dict, not a set.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `{} == set()`?]]
* [[What does `type(...)` return?]]
* [[What is `dict.setdefault(key, default)`?]]
Q: What is the time complexity of Python's <html><code>dict</code></html> lookup?

A: Average O(1), worst case O(n) due to hash collisions. Python uses open addressing with random probing for collision resolution.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the time complexity of `in` for lists vs sets?]]
* [[What is a "dictionary"?]]
* [[How does CPython implement dicts internally?]]
Q: When did dict ordering become a language guarantee?

A: Python 3.7 (it was an implementation detail in CPython 3.6). Dicts maintain insertion order as part of the language spec.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Is `OrderedDict` still useful now that regular dicts maintain insertion order (since Py…]]
* [[What did Python 3.7 add?]]
* [[What did Python 2.7 introduce?]]
Q: How does CPython implement dicts internally?

A: Using a compact hash table with two arrays: a sparse index array and a dense key-value array. This design (introduced in CPython 3.6) saves 20-25% memory compared to the old implementation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `dis.dis()` do?]]
* [[What is a "dictionary"?]]
* [[What does `dict | other_dict` do in Python 3.9+?]]
Q: What is the time complexity of <html><code>list.append()</code></html>?

A: Amortized O(1). Lists over-allocate memory, so most appends are O(1), with occasional O(n) resizes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `list.extend()` do vs `list.append()`?]]
* [[What is the time complexity of `bisect.insort()` for inserting into a sorted list?]]
* [[What is the time complexity of `in` for lists vs sets?]]
Q: What is the time complexity of <html><code>list.insert(0, x)</code></html>?

A: O(n), because all existing elements must be shifted right.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the time complexity of `in` for lists vs sets?]]
* [[What are the advantages of `collections.deque` over a list?]]
* [[What is the time complexity of Python's `dict` lookup?]]
Q: What is the time complexity of <html><code>in</code></html> for lists vs sets?

A: O(n) for lists (linear scan), O(1) average for sets (hash lookup).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the time complexity of Python's `dict` lookup?]]
* [[What is the time complexity of `list.insert(0, x)`?]]
* [[What is the time complexity of `list.append()`?]]
Q: What is the <html><code>array</code></html> module used for?

A: It provides space-efficient arrays of uniform C-style types (like <html><code>'i'</code></html> for int, <html><code>'f'</code></html> for float). More memory-efficient than lists for large homogeneous numeric data, but less flexible.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is NumPy's `dtype`?]]
* [[What is the "math" module?]]
* [[What is a list data type and how is it used?]]
Q: What does <html><code>sys.getsizeof(())</code></html> vs <html><code>sys.getsizeof([])</code></html> show?

A: Empty tuples are smaller than empty lists in memory. An empty tuple is about 40 bytes; an empty list is about 56 bytes (on 64-bit CPython), because lists have extra overhead for mutability (over-allocation buffer).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.getsizeof(1)` return approximately?]]
* [[Why are tuples slightly faster than lists?]]
* [[What does the len() function do?]]
Q: Why are tuples slightly faster than lists?

A: Tuples are immutable, so CPython can optimize their storage (contiguous memory, no over-allocation). Small tuples (up to length 20) are also cached and reused by the free-list allocator.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What's the difference between a list and a tuple in Python?]]
* [[What is a "free list" in CPython?]]
* [[What is a tuple and how does it differ from a list?]]
Q: What does <html><code>list.sort()</code></html> vs <html><code>sorted()</code></html> return?

A: <html><code>list.sort()</code></html> sorts in-place and returns <html><code>None</code></html>. <html><code>sorted()</code></html> returns a new sorted list and works on any iterable.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sorted()` guarantee about equal elements?]]
* [[sorted() and .sort()]]
Q: What does the <html><code>*</code></html> separator in function parameters do?

A: Parameters after <html><code>*</code></html> are keyword-only: <html><code>def f(a, *, b):</code></html> means <html><code>b</code></html> must be passed as a keyword argument. Added in Python 3.0.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `/` separator in function parameters do?]]
* [[What are *args and **kwargs in Python functions?]]
Q: What does the <html><code>/</code></html> separator in function parameters do?

A: Introduced in Python 3.8 (PEP 570), parameters before <html><code>/</code></html> are positional-only: <html><code>def f(a, /, b):</code></html> means <html><code>a</code></html> must be passed positionally.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `*` separator in function parameters do?]]
* [[What does the `%` operator do with strings in Python?]]
* [[What is `__format__` used for?]]
Q: What is a closure in Python?

A: A function that captures variables from its enclosing scope. The inner function "closes over" the variables, retaining access even after the enclosing function has returned.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Closure]]
* [[What is the late binding closures gotcha?]]
* [[What is `contextlib.closing()` used for?]]
Q: What is the mutable default argument gotcha?

A: Default arguments are evaluated once at function definition time, not each call. So <html><code>def f(x=[]):</code></html> shares the same list across all calls. Use <html><code>None</code></html> and create the list inside the function instead.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Mutable default arguments are shared across all function calls]]
* [[What is the default value returned by a `defaultdict(list)` for a missing key?]]
* [[In `dataclasses`, what does the `field()` function's `default_factory` parameter do?]]
Q: What is the late binding closures gotcha?

A: Closures capture variables by reference, not value. In a loop <html><code>for i in range(3): funcs.append(lambda: i)</code></html>, all lambdas return <html><code>2</code></html> (the final value of <html><code>i</code></html>). Fix with default arguments: <html><code>lambda i=i: i</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a closure in Python?]]
* [[Closure]]
* [[What is the mutable default argument gotcha?]]
Q: What is a lambda function?

A: An anonymous inline function limited to a single expression: <html><code>lambda x, y: x + y</code></html>. It cannot contain statements or annotations.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[lambda (anonymous function)]]
* [[What is `operator.methodcaller()` used for?]]
Q: What are first-class functions?

A: In Python, functions are objects — they can be assigned to variables, passed as arguments, returned from other functions, and stored in data structures.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[def (function definition)]]
* [[What is the `dataclasses.make_dataclass()` function?]]
* [[What is a code object in Python?]]
Q: What is a higher-order function?

A: A function that takes another function as an argument or returns a function. <html><code>map()</code></html>, <html><code>filter()</code></html>, <html><code>sorted()</code></html> (with <html><code>key</code></html>), and decorators are examples.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What built-in functions are considered functional-style?]]
* [[What is the `operator` module?]]
* [[What are first-class functions?]]
Q: How do you stack multiple decorators?

A: Apply them one above another: <html><code>@decorator1</code></html> then <html><code>@decorator2</code></html> above <html><code>def func</code></html>. This is equivalent to <html><code>func = decorator1(decorator2(func))</code></html> — the bottommost decorator is applied first.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a decorator in Python?]]
* [[Decorator]]
* [[What is a parameterized decorator?]]
Q: What is a parameterized decorator?

A: A decorator that takes arguments: <html><code>@retry(max_attempts=3)</code></html>. It is implemented as a function that returns a decorator, creating a three-level nesting pattern (decorator factory -> decorator -> wrapper).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a decorator in Python?]]
* [[Decorator]]
* [[What does `functools.wraps` do?]]
Q: What does <html><code>functools.wraps</code></html> do?

A: It is a decorator for wrapper functions that copies metadata (like <html><code>__name__</code></html>, <html><code>__doc__</code></html>, <html><code>__module__</code></html>, <html><code>__qualname__</code></html>, <html><code>__annotations__</code></html>, and <html><code>__dict__</code></html>) from the wrapped function to the wrapper, preserving introspection.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 3 source atoms.//

''Related atoms''
* [[What is a decorator in Python?]]
* [[What is `ParamSpec` used for?]]
* [[What does `functools.partialmethod` do?]]
Q: What does <html><code>__init__</code></html> vs <html><code>__new__</code></html> do?

A: <html><code>__new__</code></html> creates and returns a new instance (it is a static method on the class). <html><code>__init__</code></html> initializes the instance after creation. <html><code>__new__</code></html> is called first and is rarely overridden except for immutable types or singletons.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__init_subclass__` used for?]]
* [[Implement the Singleton pattern in Python (three ways)]]
* [[What is `__init_subclass__` vs a metaclass?]]
Q: What is <html><code>object.__new__</code></html>?

A: The static method that actually allocates memory for a new instance. All classes inherit it from <html><code>object</code></html>. It is called before <html><code>__init__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `object.__subclasses__()` return?]]
* [[What does `object.__repr__` return by default?]]
* [[What is `__slots__` and why use it?]]
Q: What is <html><code>__slots__</code></html> and why use it?

A: A class variable that explicitly declares instance attributes, replacing <html><code>__dict__</code></html>. It saves memory (no per-instance dict) and slightly speeds up attribute access. Instances cannot have attributes not listed in <html><code>__slots__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is `__dict__` on a class vs an instance?]]
* [[__slots__]]
* [[What is `object.__new__`?]]
Q: What is <html><code>__slots__</code></html> [[inheritance|Inheritance]] behavior?

A: <html><code>__slots__</code></html> in a subclass only adds the slots defined in that class — it does not replace parent slots. If any class in the hierarchy lacks <html><code>__slots__</code></html>, instances will still have <html><code>__dict__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What parameter to `@dataclass` was added in Python 3.10 to allow slot-based instances?]]
* [[What is __slots__ and when should you use it?]]
* [[What is `__dict__` on a class vs an instance?]]
Q: What is a data descriptor vs a non-data descriptor?

A: A data descriptor defines both <html><code>__get__</code></html> and <html><code>__set__</code></html> (or <html><code>__delete__</code></html>). A non-data descriptor defines only <html><code>__get__</code></html>. Data descriptors take priority over instance <html><code>__dict__</code></html>, while non-data descriptors do not.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are descriptors in Python?]]
* [[What is `__missing__` used for?]]
* [[What is `__dict__` on a class vs an instance?]]
Q: What is the MRO in Python?

A: Method Resolution Order — the order in which base classes are searched when looking up a method. Python uses the C3 linearization algorithm. You can see it with <html><code>ClassName.__mro__</code></html> or <html><code>ClassName.mro()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is C3 linearization?]]
* [[What does `python -O` do?]]
* [[What is `super()` and how does it work?]]
Q: What is C3 linearization?

A: The algorithm Python uses to determine MRO for multiple [[inheritance|Inheritance]]. It preserves local precedence order and monotonicity, ensuring a consistent and predictable method resolution.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the MRO in Python?]]
* [[Explain Python's Method Resolution Order (MRO)]]
* [[What is `scipy.optimize.minimize()`?]]
Q: What is a metaclass?

A: A class whose instances are themselves classes. <html><code>type</code></html> is the default metaclass in Python. Metaclasses control class creation and can customize the behavior of class statements.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are metaclasses and when would you use them?]]
* [[What is the `abc.ABCMeta` metaclass?]]
* [[What is __init_subclass__ and how does it replace metaclasses?]]
Q: What is the relationship between <html><code>type</code></html> and <html><code>object</code></html>?

A: <html><code>object</code></html> is the base class of all classes (including <html><code>type</code></html>), and <html><code>type</code></html> is the metaclass of all classes (including <html><code>object</code></html>). So <html><code>type</code></html> is an instance of itself, and <html><code>object</code></html> is an instance of <html><code>type</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `type(...)` return?]]
* [[What is `type()` with one argument vs three arguments?]]
* [[What function returns the data type of an object?]]
Q: What is the difference between <html><code>@staticmethod</code></html> and <html><code>@classmethod</code></html>?

A: <html><code>@staticmethod</code></html> receives no implicit first argument — it is just a regular function namespaced to the class. <html><code>@classmethod</code></html> receives the class as its first argument (<html><code>cls</code></html>), so it can access class-level data and be properly inherited.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are class methods and static methods?]]
* [[What does `functools.partialmethod` do?]]
* [[What is `@dataclass` an example of in terms of Python internals?]]
Q: What is <html><code>classmethod</code></html> vs <html><code>staticmethod</code></html> when used with [[inheritance|Inheritance]]?

A: <html><code>classmethod</code></html> receives the actual subclass as <html><code>cls</code></html>, enabling factory methods that return the correct subclass type. <html><code>staticmethod</code></html> has no access to the class, so it behaves identically regardless of which class calls it.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `__subclasshook__` do?]]
* [[What does the `abc.abstractmethod` decorator do?]]
* [[What are class methods and static methods?]]
Q: What is <html><code>__init_subclass__</code></html> used for?

A: A hook method called when a class is subclassed. It allows the parent class to customize subclass creation without a metaclass. Added in Python 3.6 (PEP 487).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `__subclasshook__` do?]]
* [[What is `__class_getitem__` used for?]]
* [[What is the `__init__.py` file for?]]
Q: What is <html><code>__init_subclass__</code></html> vs a metaclass?

A: <html><code>__init_subclass__</code></html> is simpler and covers many use cases (registering subclasses, validating class attributes). Metaclasses are more powerful but harder to compose — use <html><code>__init_subclass__</code></html> when possible.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are metaclasses and when would you use them?]]
* [[What does `__subclasshook__` do?]]
* [[What does `__init__` vs `__new__` do?]]
Q: What is __init_subclass__ and how does it replace metaclasses?

A: __init_subclass__ is a hook called when a class is subclassed, added in Python 3.6. It covers many metaclass use cases more simply.

class Plugin:
    registry = {}
    def __init_subclass__(cls, name=None, **kwargs):
        super().__init_subclass__(**kwargs)
        Plugin.registry[name or cls.__name__] = cls

class PDF(Plugin, name='pdf'):
    pass

class CSV(Plugin, name='csv'):
    pass

print(Plugin.registry)  # {'pdf': PDF, 'csv': CSV}

This auto-registers subclasses without metaclasses. Use for plugin systems, validation on subclass creation, or enforcing class-level constraints. Simpler to understand and compose than metaclasses.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What are metaclasses and when would you use them?]]
* [[What does `__subclasshook__` do?]]
* [[What is a metaclass?]]
Q: What is <html><code>__class_getitem__</code></html> used for?

A: It enables the subscript syntax for classes: <html><code>MyClass[int]</code></html>. Used to make classes generic without metaclasses. Added in Python 3.7 (PEP 560).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__getitem__` used for?]]
* [[What is `__init_subclass__` used for?]]
* [[What is `__missing__` used for?]]
Q: What is <html><code>__class_getitem__</code></html> vs <html><code>__getitem__</code></html>?

A: <html><code>__class_getitem__</code></html> handles <html><code>MyClass[item]</code></html> (class-level subscript, used for generics). <html><code>__getitem__</code></html> handles <html><code>instance[item]</code></html> (instance-level subscript).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__getitem__` used for?]]
* [[What is `__setitem__` and `__delitem__`?]]
* [[What does `object.__subclasses__()` return?]]
Q: What is name mangling in Python?

A: Attributes starting with <html><code>__</code></html> (double underscore) but not ending with <html><code>__</code></html> are name-mangled: <html><code>__attr</code></html> in class <html><code>MyClass</code></html> becomes <html><code>_MyClass__attr</code></html>. This provides a limited form of name privacy to avoid accidental name clashes in subclasses.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Explain name mangling with double underscores]]
* [[What is `__set_name__` used for?]]
* [[What is the `__qualname__` attribute?]]
Q: What module provides abstract base classes?

A: The <html><code>abc</code></html> module, with <html><code>ABC</code></html> as a base class and <html><code>@abstractmethod</code></html> as a decorator.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `abc.abstractmethod` decorator do?]]
* [[What is the `abc.ABCMeta` metaclass?]]
* [[What is the ABC module and how do you use abstract classes?]]
Q: What does <html><code>@dataclass</code></html> generate automatically?

A: By default, <html><code>__init__</code></html>, <html><code>__repr__</code></html>, and <html><code>__eq__</code></html> methods. With additional parameters it can generate <html><code>__hash__</code></html>, ordering methods, and use <html><code>__slots__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `@dataclass(kw_only=True)` do, introduced in Python 3.10?]]
* [[What parameter to `@dataclass` was added in Python 3.10 to allow slot-based instances?]]
* [[What does `@dataclass(frozen=True)` do?]]
Q: What is <html><code>@dataclass</code></html> an example of in terms of Python internals?

A: A class decorator that uses code generation — it inspects annotations and generates <html><code>__init__</code></html>, <html><code>__repr__</code></html>, <html><code>__eq__</code></html>, and other methods at class definition time.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `@typing.dataclass_transform` decorator?]]
* [[What parameter to `@dataclass` was added in Python 3.10 to allow slot-based instances?]]
* [[What is the `dataclasses.make_dataclass()` function?]]
Q: What does <html><code>@dataclass(frozen=True)</code></html> do?

A: It makes instances of the dataclass immutable (read-only). Attempting to assign to fields after creation raises <html><code>FrozenInstanceError</code></html>. Frozen dataclasses are also hashable by default.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `@dataclass(order=True)` do?]]
* [[What does `@dataclass` generate automatically?]]
* [[What does `@dataclass(kw_only=True)` do, introduced in Python 3.10?]]
Q: What parameter to <html><code>@dataclass</code></html> was added in Python 3.10 to allow slot-based instances?

A: <html><code>slots=True</code></html>. When set, the generated class uses <html><code>__slots__</code></html> instead of <html><code>__dict__</code></html>, resulting in faster attribute access and less memory usage.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__slots__` inheritance behavior?]]
* [[What is __slots__ and when should you use it?]]
* [[What is `@dataclass` an example of in terms of Python internals?]]
Q: What does <html><code>@dataclass(kw_only=True)</code></html> do, introduced in Python 3.10?

A: It makes all fields keyword-only in the generated <html><code>__init__</code></html>, so they cannot be passed as positional arguments.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `@dataclass` generate automatically?]]
* [[What does `@dataclass(order=True)` do?]]
* [[What parameter to `@dataclass` was added in Python 3.10 to allow slot-based instances?]]
Q: What method can you define on a dataclass to customize how it is initialized after <html><code>__init__</code></html>?

A: <html><code>__post_init__()</code></html>. It is called automatically after the generated <html><code>__init__</code></html> and is useful for validation or computing derived fields.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `@dataclass` generate automatically?]]
* [[What does `__init__` vs `__new__` do?]]
* [[What is `__init_subclass__` used for?]]
Q: What does the <html><code>dataclasses.asdict()</code></html> function do?

A: It recursively converts a dataclass instance into a dictionary. There is also <html><code>astuple()</code></html> for converting to a tuple.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `dataclasses.make_dataclass()` function?]]
* [[What is `collections.UserDict` for?]]
* [[What is `__dict__` on a class vs an instance?]]
Q: In <html><code>dataclasses</code></html>, what does the <html><code>field()</code></html> function's <html><code>default_factory</code></html> parameter do?

A: It provides a zero-argument callable that creates the default value for the field. This is necessary for mutable defaults like lists or dicts to avoid the shared mutable default argument problem.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What method does `defaultdict` call to produce a default value?]]
* [[What is the `dataclasses.field()` metadata parameter for?]]
* [[What is the `dataclasses.make_dataclass()` function?]]
Q: What is the <html><code>dataclasses.field()</code></html> metadata parameter for?

A: It is a mapping that stores arbitrary user-defined data on the field. It is not used by dataclasses itself but can be consumed by third-party libraries or custom processing.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `dataclasses.make_dataclass()` function?]]
* [[In `dataclasses`, what does the `field()` function's `default_factory` parameter do?]]
* [[What does `@dataclass` generate automatically?]]
Q: What does <html><code>@dataclass(order=True)</code></html> do?

A: It generates <html><code>__lt__</code></html>, <html><code>__le__</code></html>, <html><code>__gt__</code></html>, and <html><code>__ge__</code></html> methods that compare instances as if they were tuples of their fields (in order of definition).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `@dataclass(frozen=True)` do?]]
* [[What does `@dataclass(kw_only=True)` do, introduced in Python 3.10?]]
* [[What is `@dataclass` an example of in terms of Python internals?]]
Q: What is <html><code>typing.NamedTuple</code></html> and how does it compare to <html><code>collections.namedtuple</code></html>?

A: <html><code>typing.NamedTuple</code></html> is a class-based syntax for named tuples that supports type annotations: <html><code>class Point(NamedTuple): x: int; y: int</code></html>. It is more readable and type-checker-friendly than the functional <html><code>namedtuple()</code></html> form.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.TypedDict` used for?]]
* [[How do you create a named tuple with `collections.namedtuple`?]]
Q: What is the <html><code>match</code></html> statement's <html><code>__match_args__</code></html> attribute used for?

A: It defines the positional pattern matching order for a class. For example, <html><code>__match_args__ = ('x', 'y')</code></html> allows <html><code>case Point(1, 2)</code></html> instead of requiring <html><code>case Point(x=1, y=2)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Python's `match` statement OR pattern?]]
* [[What is the wildcard pattern in Python's match statement?]]
* [[What is the `match` statement guard clause?]]
Q: What is <html><code>__set_name__</code></html> used for?

A: Called on descriptors when a class is created, it receives the owner class and the attribute name. This allows descriptors to know what name they were assigned to without the user specifying it explicitly. Added in Python 3.6.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is name mangling in Python?]]
* [[What is the `__qualname__` attribute?]]
* [[What are descriptors in Python?]]
Q: What is the <html><code>property</code></html> built-in?

A: A descriptor that lets you define getter, setter, and deleter methods for an attribute. It provides a Pythonic alternative to Java-style getter/setter methods: <html><code>@property</code></html> for the getter, <html><code>@attr.setter</code></html> for the setter.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Explain Python's property decorator]]
* [[What is `__set_name__` used for?]]
* [[What is `operator.attrgetter()` used for?]]
Q: What does <html><code>@property</code></html> do under the hood?

A: It creates a data descriptor with <html><code>__get__</code></html>, <html><code>__set__</code></html>, and <html><code>__delete__</code></html> methods. The getter is passed to <html><code>property()</code></html>, and setter/deleter are added via <html><code>.setter</code></html> and <html><code>.deleter</code></html> decorators.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `functools.cached_property` do?]]
* [[What is `__set_name__` used for?]]
* [[What does `@dataclass` generate automatically?]]
Q: What is the <html><code>@property</code></html> deleter?

A: The third component of a property: <html><code>@attr.deleter</code></html> defines what happens when <html><code>del obj.attr</code></html> is called. All three (getter, setter, deleter) are optional.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `operator.attrgetter()` used for?]]
* [[What is the `del` statement?]]
* [[What is `__del__` used for?]]
Q: What is <html><code>yield from</code></html> used for?

A: Introduced in Python 3.3 (PEP 380), it delegates to a sub-generator: <html><code>yield from iterable</code></html> is equivalent to <html><code>for item in iterable: yield item</code></html> but also properly handles <html><code>send()</code></html>, <html><code>throw()</code></html>, and return values.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a Python generator?]]
* [[What does `itertools.product('AB', '12')` yield?]]
* [[What does `itertools.groupby()` yield?]]
Q: What does the <html><code>__iter__</code></html> method return?

A: An iterator object (which must implement <html><code>__next__</code></html>). If a class defines <html><code>__iter__</code></html> and <html><code>__next__</code></html>, its instances are iterators. If it only defines <html><code>__iter__</code></html>, it is iterable.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__iter__` vs `__getitem__` for iteration?]]
* [[What does `itertools.chain(*iterables)` do?]]
* [[What does `itertools.cycle(iterable)` do?]]
Q: What is the iterator protocol?

A: An object must implement <html><code>__iter__()</code></html> (returning itself) and <html><code>__next__()</code></html> (returning the next value or raising <html><code>StopIteration</code></html>).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.abc.Iterator` vs `collections.abc.Iterable`?]]
* [[What is `__aiter__` and `__anext__`?]]
* [[What is `__iter__` vs `__getitem__` for iteration?]]
Q: What does <html><code>itertools.chain(*iterables)</code></html> do?

A: It chains multiple iterables together into a single lazy iterator, yielding all elements from the first iterable, then the second, and so on.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.starmap(func, iterable)` do?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
* [[What does `itertools.dropwhile(predicate, iterable)` do?]]
Q: What does <html><code>itertools.cycle(iterable)</code></html> do?

A: It creates an infinite iterator that cycles through the elements of the iterable. For example, <html><code>cycle('ABC')</code></html> yields <html><code>A, B, C, A, B, C, A, ...</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.repeat(elem, times=None)` do?]]
* [[What does `itertools.batched()` do, and when was it added?]]
* [[What does `itertools.tee(iterable, n=2)` return?]]
Q: What is the difference between <html><code>itertools.chain()</code></html> and <html><code>itertools.chain.from_iterable()</code></html>?

A: <html><code>chain()</code></html> takes multiple iterables as separate arguments: <html><code>chain([1,2], [3,4])</code></html>. <html><code>chain.from_iterable()</code></html> takes a single iterable of iterables: <html><code>chain.from_iterable([[1,2], [3,4]])</code></html>. The latter is useful when you have a generator of iterables.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.cycle(iterable)` do?]]
* [[What is `collections.abc.Iterator` vs `collections.abc.Iterable`?]]
* [[What does `itertools.tee(iterable, n=2)` return?]]
Q: What does <html><code>itertools.combinations('ABCD', 2)</code></html> return?

A: An iterator of 2-element tuples containing all unique combinations without repetition: <html><code>('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `itertools.pairwise()` and when was it added?]]
* [[What does `itertools.batched()` do, and when was it added?]]
* [[What does `itertools.product('AB', '12')` yield?]]
Q: What is the difference between <html><code>combinations</code></html> and <html><code>combinations_with_replacement</code></html>?

A: <html><code>combinations</code></html> does not allow repeated elements, while <html><code>combinations_with_replacement</code></html> does. For example, <html><code>combinations_with_replacement('AB', 2)</code></html> yields <html><code>('A','A'), ('A','B'), ('B','B')</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.combinations('ABCD', 2)` return?]]
* [[What does `itertools.product('AB', '12')` yield?]]
* [[What is `itertools.product` with the `repeat` parameter?]]
Q: How many items does <html><code>itertools.permutations('ABC', 2)</code></html> yield?

A: 6 items: <html><code>('A','B'), ('A','C'), ('B','A'), ('B','C'), ('C','A'), ('C','B')</code></html> — all ordered arrangements of 2 elements from 3. The formula is P(3,2) = 3!/(3-2)! = 6.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.combinations('ABCD', 2)` return?]]
* [[What does `itertools.product('AB', '12')` yield?]]
* [[Generate all permutations of a string]]
Q: What does <html><code>itertools.product('AB', '12')</code></html> yield?

A: The Cartesian product: <html><code>('A','1'), ('A','2'), ('B','1'), ('B','2')</code></html>. It is equivalent to nested for loops.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.combinations('ABCD', 2)` return?]]
* [[How do you use `itertools.product` to get the equivalent of a triple nested loop?]]
* [[What does `itertools.groupby()` yield?]]
Q: What is <html><code>itertools.product</code></html> with the <html><code>repeat</code></html> parameter?

A: It computes the Cartesian product of an iterable with itself: <html><code>product('AB', repeat=2)</code></html> is equivalent to <html><code>product('AB', 'AB')</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is `itertools.repeat()` commonly used with?]]
* [[What does `itertools.repeat(elem, times=None)` do?]]
* [[How do you use `itertools.product` to get the equivalent of a triple nested loop?]]
Q: How do you use <html><code>itertools.product</code></html> to get the equivalent of a triple nested loop?

A: <html><code>itertools.product(range(3), range(3), range(3))</code></html> yields all 27 triples, equivalent to three nested <html><code>for</code></html> loops.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.product('AB', '12')` yield?]]
* [[What is `itertools.product` with the `repeat` parameter?]]
* [[What is `itertools.pairwise()` and when was it added?]]
Q: What critical requirement does <html><code>itertools.groupby()</code></html> have?

A: The input must be sorted (or at least grouped) by the key function. <html><code>groupby</code></html> only groups consecutive elements with the same key. If the data is not pre-sorted, elements with the same key will appear in separate groups.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Pandas `groupby()` used for?]]
* [[itertools essentials]]
* [[What does `itertools.count(start=0, step=1)` do?]]
Q: What does <html><code>itertools.groupby()</code></html> yield?

A: Pairs of <html><code>(key, group_iterator)</code></html> where the group iterator yields all consecutive elements with that key. The group iterators share the underlying iterator, so you must consume each group before advancing to the next.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.cycle(iterable)` do?]]
* [[What does `itertools.chain(*iterables)` do?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
Q: What does <html><code>itertools.starmap(func, iterable)</code></html> do?

A: It applies <html><code>func</code></html> to each element of the iterable using argument unpacking. For example, <html><code>starmap(pow, [(2,3), (3,2)])</code></html> yields <html><code>8, 9</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.chain(*iterables)` do?]]
* [[What is `itertools.repeat()` commonly used with?]]
* [[What does `itertools.cycle(iterable)` do?]]
Q: What does <html><code>itertools.tee(iterable, n=2)</code></html> return?

A: n independent iterators from a single iterable. Once teed, the original iterator should not be used. Note: it can consume significant memory if one copy advances far ahead of the others.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.cycle(iterable)` do?]]
* [[What does `itertools.repeat(elem, times=None)` do?]]
* [[What does `itertools.pairwise()` return for an empty or single-element iterable?]]
Q: What does <html><code>itertools.count(start=0, step=1)</code></html> do?

A: It creates an infinite iterator that yields evenly spaced values starting from <html><code>start</code></html>. For example, <html><code>count(10, 2)</code></html> yields <html><code>10, 12, 14, 16, ...</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.repeat(elem, times=None)` do?]]
* [[What does `itertools.accumulate()` do?]]
* [[What does `itertools.chain(*iterables)` do?]]
Q: What does <html><code>itertools.repeat(elem, times=None)</code></html> do?

A: It yields <html><code>elem</code></html> over and over, either infinitely (if times is None) or the specified number of times.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.count(start=0, step=1)` do?]]
* [[What does `itertools.cycle(iterable)` do?]]
* [[What does `itertools.accumulate()` do?]]
Q: What does <html><code>itertools.islice()</code></html> do?

A: It slices an iterator lazily, similar to sequence slicing but works on any iterable and doesn't support negative indices. <html><code>islice(iterable, stop)</code></html> or <html><code>islice(iterable, start, stop, step)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.chain(*iterables)` do?]]
* [[What does `itertools.tee(iterable, n=2)` return?]]
* [[What does `itertools.cycle(iterable)` do?]]
Q: What does <html><code>itertools.dropwhile(predicate, iterable)</code></html> do?

A: It drops elements from the beginning of the iterable as long as the predicate is true, then yields all remaining elements (even if the predicate becomes true again later).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What does `itertools.chain(*iterables)` do?]]
* [[What does `itertools.cycle(iterable)` do?]]
* [[What does `itertools.tee(iterable, n=2)` return?]]
Q: What does <html><code>itertools.accumulate()</code></html> do?

A: It yields running totals (or running results of any binary function). For example, <html><code>accumulate([1,2,3,4])</code></html> yields <html><code>1, 3, 6, 10</code></html>. You can pass a function like <html><code>operator.mul</code></html> for running products.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.count(start=0, step=1)` do?]]
* [[What does `itertools.repeat(elem, times=None)` do?]]
* [[What does `itertools.batched()` do, and when was it added?]]
Q: What does <html><code>itertools.compress(data, selectors)</code></html> do?

A: It filters data by returning only the elements where the corresponding selector is truthy. For example, <html><code>compress('ABCDEF', [1,0,1,0,1,1])</code></html> yields <html><code>A, C, E, F</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.filterfalse(predicate, iterable)` do?]]
* [[What does `itertools.zip_longest()` do differently from `zip()`?]]
* [[What does `itertools.batched()` do, and when was it added?]]
Q: What does <html><code>itertools.filterfalse(predicate, iterable)</code></html> do?

A: It yields elements for which the predicate returns false — the opposite of the built-in <html><code>filter()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.chain(*iterables)` do?]]
* [[What does `itertools.compress(data, selectors)` do?]]
* [[What does `itertools.cycle(iterable)` do?]]
Q: What is <html><code>itertools.pairwise()</code></html> and when was it added?

A: Added in Python 3.10, it yields consecutive overlapping pairs from an iterable. <html><code>pairwise('ABCD')</code></html> yields <html><code>('A','B'), ('B','C'), ('C','D')</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.combinations('ABCD', 2)` return?]]
* [[What does `itertools.batched()` do, and when was it added?]]
* [[What is `itertools.repeat()` commonly used with?]]
Q: What does <html><code>itertools.pairwise()</code></html> return for an empty or single-element iterable?

A: An empty iterator — there are no pairs to form.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.tee(iterable, n=2)` return?]]
* [[What does `itertools.cycle(iterable)` do?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
Q: What does <html><code>itertools.batched()</code></html> do, and when was it added?

A: Added in Python 3.12, it yields non-overlapping batches (tuples) of a given size from an iterable. <html><code>batched('ABCDEFG', 3)</code></html> yields <html><code>('A','B','C'), ('D','E','F'), ('G',)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.cycle(iterable)` do?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
* [[What does `itertools.combinations('ABCD', 2)` return?]]
Q: What does <html><code>functools.lru_cache</code></html> do?

A: It is a decorator that caches the results of a function using a Least Recently Used eviction policy. By default, it caches up to 128 results. Use <html><code>@lru_cache(maxsize=None)</code></html> for unbounded caching.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `functools.cached_property` do?]]
* [[What is the `lru_cache` maximum size by default?]]
* [[When was `functools.cached_property` introduced?]]
Q: What is the difference between <html><code>functools.lru_cache</code></html> and <html><code>functools.cache</code></html>?

A: <html><code>functools.cache</code></html> (added in Python 3.9) is equivalent to <html><code>lru_cache(maxsize=None)</code></html> — an unbounded cache with no LRU eviction. It is simpler and slightly faster when you don't need size limits.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `@functools.lru_cache` memory leak risk?]]
* [[What method on an `lru_cache`-decorated function shows cache performance?]]
* [[When was `functools.cached_property` introduced?]]
Q: What method on an <html><code>lru_cache</code></html>-decorated function shows cache performance?

A: <html><code>.cache_info()</code></html> returns a named tuple with <html><code>hits</code></html>, <html><code>misses</code></html>, <html><code>maxsize</code></html>, and <html><code>currsize</code></html>. You can also call <html><code>.cache_clear()</code></html> to reset the cache.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `functools.lru_cache` and `functools.cache`?]]
* [[What is the `lru_cache` maximum size by default?]]
* [[Why must arguments to an `lru_cache`-decorated function be hashable?]]
Q: Why must arguments to an <html><code>lru_cache</code></html>-decorated function be hashable?

A: Because the cache uses a dictionary internally, and dictionary keys must be hashable. Passing unhashable arguments like lists will raise a <html><code>TypeError</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `functools.lru_cache` and `functools.cache`?]]
* [[What does `functools.lru_cache` do?]]
* [[What method on an `lru_cache`-decorated function shows cache performance?]]
Q: What is the <html><code>lru_cache</code></html> maximum size by default?

A: 128 entries.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `functools.lru_cache` do?]]
* [[What is the difference between `functools.lru_cache` and `functools.cache`?]]
* [[What method on an `lru_cache`-decorated function shows cache performance?]]
Q: What does <html><code>functools.partial</code></html> do?

A: It creates a new callable with some arguments of the original function pre-filled. For example, <html><code>int_from_binary = partial(int, base=2)</code></html> creates a function that parses binary strings.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `functools.singledispatch` do?]]
* [[What does `functools.wraps` do?]]
* [[What does `functools.cmp_to_key` do?]]
Q: What does <html><code>functools.partialmethod</code></html> do?

A: Like <html><code>partial</code></html> but for methods in a class. It creates a partial version of a method that can be used as a descriptor.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `functools.wraps` do?]]
* [[What does `functools.singledispatch` do?]]
* [[What does `functools.cached_property` do?]]
Q: What does <html><code>functools.reduce</code></html> do?

A: It applies a two-argument function cumulatively to the items of an iterable, reducing it to a single value. For example, <html><code>reduce(operator.add, [1,2,3,4])</code></html> returns 10.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.accumulate()` do?]]
* [[What does `itertools.dropwhile(predicate, iterable)` do?]]
* [[What does `functools.cmp_to_key` do?]]
Q: What is <html><code>functools.reduce</code></html> with an initial value?

A: <html><code>reduce(func, iterable, initializer)</code></html> starts accumulation from the initializer instead of the first element. Without it, an empty iterable raises <html><code>TypeError</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why was `reduce` moved from builtins to `functools` in Python 3?]]
* [[What does `itertools.dropwhile(predicate, iterable)` do?]]
* [[What does `functools.singledispatch` do?]]
Q: Why was <html><code>reduce</code></html> moved from builtins to <html><code>functools</code></html> in Python 3?

A: Guido van Rossum argued that <html><code>reduce()</code></html> is confusing and rarely needed. He preferred explicit loops for clarity. It was moved to <html><code>functools</code></html> to discourage casual use.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `functools.reduce` with an initial value?]]
* [[When was `functools.cached_property` introduced?]]
* [[What does `functools.cmp_to_key` do?]]
Q: What does <html><code>functools.singledispatch</code></html> do?

A: It provides single-dispatch generic functions — function overloading based on the type of the first argument. You register implementations for different types using <html><code>@func.register(type)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 3 source atoms.//

''Related atoms''
* [[What does `functools.partialmethod` do?]]
* [[What does `functools.partial` do?]]
* [[What is `functools.reduce` with an initial value?]]
Q: What does <html><code>functools.cached_property</code></html> do?

A: It transforms a method into a property that is computed once and then cached as a normal attribute. Unlike <html><code>@property</code></html>, the computation only runs on the first access.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `functools.lru_cache` do?]]
* [[What does `@property` do under the hood?]]
* [[What is the difference between `functools.lru_cache` and `functools.cache`?]]
Q: When was <html><code>functools.cached_property</code></html> introduced?

A: Python 3.8.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `functools.lru_cache` and `functools.cache`?]]
* [[What does `functools.lru_cache` do?]]
* [[What is `__cached__` on a module?]]
Q: What does <html><code>functools.cmp_to_key</code></html> do?

A: It converts an old-style comparison function (that returns -1, 0, or 1) into a key function suitable for <html><code>sorted()</code></html>, <html><code>min()</code></html>, <html><code>max()</code></html>, etc. This bridges the gap from Python 2's <html><code>cmp</code></html> parameter.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `functools.reduce` do?]]
* [[What does `functools.total_ordering` require you to define?]]
* [[Why was `reduce` moved from builtins to `functools` in Python 3?]]
Q: What does <html><code>functools.total_ordering</code></html> require you to define?

A: You must define <html><code>__eq__</code></html> and one of the other comparison methods (<html><code>__lt__</code></html>, <html><code>__le__</code></html>, <html><code>__gt__</code></html>, or <html><code>__ge__</code></html>). The decorator fills in the rest.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What does `functools.cmp_to_key` do?]]
* [[What are `__lt__`, `__le__`, `__gt__`, `__ge__`?]]
* [[What is `__eq__` and `__ne__`?]]
Q: What is <html><code>operator.itemgetter()</code></html> used for?

A: It creates a callable that retrieves items by index or key: <html><code>itemgetter(1)</code></html> is equivalent to <html><code>lambda x: x[1]</code></html>. Commonly used as a <html><code>key</code></html> function for <html><code>sorted()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `operator.attrgetter()` used for?]]
* [[What is `operator.methodcaller()` used for?]]
* [[What is `__getitem__` used for?]]
Q: What is <html><code>operator.attrgetter()</code></html> used for?

A: Similar to <html><code>itemgetter</code></html> but for attributes: <html><code>attrgetter('name')</code></html> is equivalent to <html><code>lambda x: x.name</code></html>. Supports dotted names for nested attributes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `operator.itemgetter()` used for?]]
* [[What is `getattr(obj, name, default)` used for?]]
* [[What is the `__qualname__` attribute?]]
Q: What is <html><code>operator.methodcaller()</code></html> used for?

A: It creates a callable that calls a method: <html><code>methodcaller('lower')</code></html> is equivalent to <html><code>lambda x: x.lower()</code></html>. Can also pass arguments.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `operator.itemgetter()` used for?]]
* [[What is `operator.attrgetter()` used for?]]
* [[What is the `operator` module?]]
Q: What built-in functions are considered functional-style?

A: <html><code>map()</code></html>, <html><code>filter()</code></html>, <html><code>zip()</code></html>, <html><code>enumerate()</code></html>, <html><code>sorted()</code></html>, <html><code>reversed()</code></html>, <html><code>min()</code></html>, <html><code>max()</code></html>, <html><code>sum()</code></html>, <html><code>any()</code></html>, <html><code>all()</code></html>.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a higher-order function?]]
* [[What is the `operator` module?]]
* [[What is a lambda function?]]
Q: What is the order of clauses in a try statement?

A: <html><code>try</code></html> -> <html><code>except</code></html> (zero or more) -> <html><code>else</code></html> (optional, runs if no exception) -> <html><code>finally</code></html> (optional, always runs). The <html><code>else</code></html> block executes only when no exception was raised in <html><code>try</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Does `finally` always execute?]]
Q: When does the <html><code>else</code></html> clause of a <html><code>try</code></html> block execute?

A: Only when no exception was raised in the <html><code>try</code></html> block. It is useful for code that should run only on success, keeping the <html><code>try</code></html> block minimal.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Does `finally` always execute?]]
Q: Does <html><code>finally</code></html> always execute?

A: Yes, even if there is a <html><code>return</code></html>, <html><code>break</code></html>, or <html><code>continue</code></html> in the <html><code>try</code></html> or <html><code>except</code></html> blocks. The only exception is if the process is killed by the OS or <html><code>os._exit()</code></html> is called.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `os._exit()` and when is it used?]]
* [[When does the `else` clause of a `try` block execute?]]
* [[What is the order of clauses in a try statement?]]
Q: What is exception chaining in Python?

A: When an exception is raised inside an <html><code>except</code></html> block, the original exception is stored in <html><code>__context__</code></html>. You can explicitly chain with <html><code>raise NewException() from original</code></html> which sets <html><code>__cause__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Exception chaining preserves the original cause in the traceback]]
* [[What is the `except*` syntax?]]
* [[How do you suppress exception chaining?]]
Q: What is an "exception"?

A: An error raised during execution that disrupts normal program flow. Python has a hierarchy of built-in exceptions (ValueError, TypeError, KeyError, etc.) all inheriting from BaseException. Handle with try/except/finally blocks. You can define [[custom exceptions|Custom exceptions]] by subclassing Exception. Unhandled exceptions produce a traceback and crash the program.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is the `except*` syntax?]]
* [[How do you create a custom exception?]]
* [[Multiple APIs exist for capturing and formatting exception information]]
Q: What is the difference between <html><code>__cause__</code></html> and <html><code>__context__</code></html> on exceptions?

A: <html><code>__cause__</code></html> is set explicitly via <html><code>raise X from Y</code></html> (explicit chaining). <html><code>__context__</code></html> is set automatically when an exception is raised during exception handling (implicit chaining).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[How do you suppress exception chaining?]]
* [[Exception chaining preserves the original cause in the traceback]]
* [[What are exception groups, introduced in Python 3.11?]]
Q: How do you suppress exception chaining?

A: Use <html><code>raise NewException() from None</code></html>. This sets <html><code>__cause__</code></html> to <html><code>None</code></html> and <html><code>__suppress_context__</code></html> to <html><code>True</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is exception chaining in Python?]]
* [[What is the difference between `__cause__` and `__context__` on exceptions?]]
* [[How do you create a custom exception?]]
Q: What is the [[exception hierarchy|Exception hierarchy]]'s root in Python?

A: <html><code>BaseException</code></html>. It has four direct subclasses: <html><code>SystemExit</code></html>, <html><code>KeyboardInterrupt</code></html>, <html><code>GeneratorExit</code></html>, and <html><code>Exception</code></html>. User code should generally catch/subclass <html><code>Exception</code></html>, not <html><code>BaseException</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Exception hierarchy]]
* [[What is exception chaining in Python?]]
* [[Why should you not catch `BaseException`?]]
Q: Why should you not catch <html><code>BaseException</code></html>?

A: Because it would catch <html><code>SystemExit</code></html> (preventing clean exit), <html><code>KeyboardInterrupt</code></html> (preventing Ctrl+C), and <html><code>GeneratorExit</code></html>. Catch <html><code>Exception</code></html> instead for general error handling.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Exception hierarchy]]
* [[What is the exception hierarchy's root in Python?]]
* [[What does `sys.exit()` actually raise?]]
Q: What are exception groups, introduced in Python 3.11?

A: <html><code>ExceptionGroup</code></html> and <html><code>BaseExceptionGroup</code></html> allow raising and handling multiple unrelated exceptions simultaneously. They are caught with the new <html><code>except*</code></html> syntax.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Exception hierarchy]]
* [[What is the difference between `__cause__` and `__context__` on exceptions?]]
* [[What major features were added in Python 3.11?]]
Q: What is the <html><code>except*</code></html> syntax?

A: Introduced in Python 3.11, it handles exception groups. <html><code>except* ValueError as eg:</code></html> catches all <html><code>ValueError</code></html> instances from an exception group while letting other exceptions propagate.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is exception chaining in Python?]]
* [[What is an "exception"?]]
* [[try / except]]
Q: What is the LBYL coding style?

A: "Look Before You Leap" — checking preconditions before an operation (e.g., <html><code>if key in dict: dict[key]</code></html>). Python generally prefers EAFP, but LBYL is sometimes clearer for non-exceptional conditions.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is "EAFP" in Python?]]
* [[What is `dict.setdefault(key, default)`?]]
* [[What is the `__bool__` method?]]
Q: How do you create a custom exception?

A: Subclass <html><code>Exception</code></html> (or a more specific built-in exception): <html><code>class MyError(Exception): pass</code></html>. You can add custom attributes in <html><code>__init__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Custom exceptions]]
* [[What is an "exception"?]]
* [[How do you suppress exception chaining?]]
Q: What does <html><code>raise</code></html> without an argument do?

A: It re-raises the current exception being handled. It can only be used inside an <html><code>except</code></html> block.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `pytest.raises`?]]
* [[What is exception chaining in Python?]]
* [[What is the difference between `__cause__` and `__context__` on exceptions?]]
Q: What improvement did Python 3.11 make to error messages?

A: Much more precise error locations. Tracebacks now point to the exact expression that caused the error, not just the line. For example, in <html><code>a['x']['y']['z']</code></html>, the traceback highlights which dictionary access failed.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Python 3.11 shows exact expression locations in tracebacks]]
* [[Python's traceback format influenced error reporting across languages]]
* [[What major features were added in Python 3.11?]]
Q: What module provides functions to maintain a list in sorted order without having to sort the list after each insertion?

A: The <html><code>bisect</code></html> module. It uses binary search via <html><code>bisect.insort()</code></html> and <html><code>bisect.bisect()</code></html> to efficiently insert into and search sorted lists.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the time complexity of `bisect.insort()` for inserting into a sorted list?]]
* [[What is the difference between `bisect.bisect_left()` and `bisect.bisect_right()`?]]
* [[What does `list.sort()` vs `sorted()` return?]]
Q: What is the time complexity of <html><code>bisect.insort()</code></html> for inserting into a sorted list?

A: O(n) overall — O(log n) for the binary search to find the insertion point, but O(n) for the actual insertion due to shifting elements in the list.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module provides functions to maintain a list in sorted order without having to sor…]]
* [[What is the time complexity of `list.append()`?]]
* [[What is the time complexity of `in` for lists vs sets?]]
Q: What is the difference between <html><code>bisect.bisect_left()</code></html> and <html><code>bisect.bisect_right()</code></html>?

A: <html><code>bisect_left()</code></html> returns the leftmost position where an element can be inserted to keep the list sorted (before any existing equal elements), while <html><code>bisect_right()</code></html> returns the rightmost position (after existing equal elements). <html><code>bisect()</code></html> is an alias for <html><code>bisect_right()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module provides functions to maintain a list in sorted order without having to sor…]]
* [[What is the difference between `list.copy()` and `list[:]`?]]
* [[What does `list.sort()` vs `sorted()` return?]]
Q: Which standard library module provides a min-heap implementation?

A: The <html><code>heapq</code></html> module. Python's heapq only implements a min-heap natively; for a max-heap you negate values or use a wrapper.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What function in `heapq` merges multiple sorted inputs into a single sorted output?]]
* [[What Python library has become the standard for data validation and settings management?]]
Q: How do you implement a max-heap using Python's <html><code>heapq</code></html> module?

A: By negating the values before pushing and after popping, e.g., <html><code>heapq.heappush(heap, -value)</code></html> and <html><code>-heapq.heappop(heap)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What function in `heapq` merges multiple sorted inputs into a single sorted output?]]
* [[What is `sys.maxsize`?]]
Q: What does <html><code>heapq.nlargest(n, iterable)</code></html> do, and when is it more efficient than sorting?

A: It returns the n largest elements from an iterable. It is more efficient than full sorting when n is small relative to the iterable size, using a min-heap of size n internally.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `list.sort()` vs `sorted()` return?]]
* [[What function in `heapq` merges multiple sorted inputs into a single sorted output?]]
* [[What is Timsort?]]
Q: What function in <html><code>heapq</code></html> merges multiple sorted inputs into a single sorted output?

A: <html><code>heapq.merge(*iterables)</code></html>. It returns a lazy iterator, making it memory-efficient for merging sorted streams.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Merge two sorted arrays]]
* [[What does `heapq.nlargest(n, iterable)` do, and when is it more efficient than sorting?]]
* [[Which standard library module provides a min-heap implementation?]]
Q: What does <html><code>contextlib.suppress()</code></html> do?

A: It is a context manager that suppresses specified exceptions. For example, <html><code>with contextlib.suppress(FileNotFoundError): os.remove('file')</code></html> silently ignores the error if the file doesn't exist.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `contextlib.closing()` used for?]]
* [[What is the `contextlib.nullcontext()` used for?]]
* [[What is the `contextlib.aclosing()` context manager?]]
Q: What is <html><code>contextlib.ExitStack</code></html> used for?

A: It is a context manager that manages a dynamic collection of other context managers and cleanup functions. It is useful when you don't know at coding time how many context managers you need.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `contextlib.aclosing()` context manager?]]
* [[What is the `contextlib.nullcontext()` used for?]]
* [[What is `os._exit()` and when is it used?]]
Q: What is <html><code>contextlib.closing()</code></html> used for?

A: It wraps an object that has a <html><code>.close()</code></html> method but does not implement the context manager protocol, ensuring <html><code>.close()</code></html> is called when exiting the <html><code>with</code></html> block.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `contextlib.aclosing()` context manager?]]
* [[What is the `contextlib.nullcontext()` used for?]]
* [[What does `contextlib.suppress()` do?]]
Q: How do you create a context manager from a generator function using <html><code>contextlib</code></html>?

A: Use the <html><code>@contextlib.contextmanager</code></html> decorator on a generator function that yields exactly once. Code before the yield is the setup (<html><code>__enter__</code></html>), and code after is the teardown (<html><code>__exit__</code></html>).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `contextlib.asynccontextmanager` decorator for?]]
* [[What is the `contextlib.aclosing()` context manager?]]
* [[What is a context manager protocol?]]
Q: What does <html><code>contextlib.redirect_stdout()</code></html> do?

A: It temporarily redirects <html><code>sys.stdout</code></html> to another file-like object within a <html><code>with</code></html> block. There is also <html><code>redirect_stderr()</code></html> for standard error.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.stdin`, `sys.stdout`, `sys.stderr`?]]
* [[What does `contextlib.suppress()` do?]]
Q: What is the <html><code>contextlib.asynccontextmanager</code></html> decorator for?

A: It is the async equivalent of <html><code>@contextmanager</code></html>, allowing you to create async context managers from async generator functions that yield once.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `contextlib.aclosing()` context manager?]]
* [[How do you create a context manager from a generator function using `contextlib`?]]
* [[What are context variables (`contextvars`)?]]
Q: What is the <html><code>contextlib.nullcontext()</code></html> used for?

A: It is a no-op context manager, useful as a stand-in when a context manager is expected but none is needed. Added in Python 3.7.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `contextlib.closing()` used for?]]
* [[What is the `contextlib.aclosing()` context manager?]]
* [[What are context variables (`contextvars`)?]]
Q: What is the <html><code>enum.auto()</code></html> function used for?

A: It automatically generates values for enum members, typically incrementing integers starting from 1. The behavior can be customized by overriding <html><code>_generate_next_value_()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `enum.unique` used for?]]
* [[What is the `enum.nonmember()` function added in Python 3.11?]]
* [[What is the `enum.verify` decorator added in Python 3.11?]]
Q: What is the difference between <html><code>enum.Enum</code></html> and <html><code>enum.IntEnum</code></html>?

A: <html><code>IntEnum</code></html> members are also integers and can be compared with plain ints and used anywhere an int is expected. <html><code>Enum</code></html> members are not comparable with ints — they can only be compared with other members of the same enum.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `enum.unique` used for?]]
* [[What is the `enum.auto()` function used for?]]
* [[What `Enum` subclass was introduced in Python 3.11 to ensure members are valid strings?]]
Q: What <html><code>Enum</code></html> subclass was introduced in Python 3.11 to ensure members are valid strings?

A: <html><code>enum.StrEnum</code></html>. Its members are also strings and can be used wherever strings are expected.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `enum.verify` decorator added in Python 3.11?]]
* [[What is the `enum.auto()` function used for?]]
* [[What is `enum.unique` used for?]]
Q: What does the <html><code>enum.Flag</code></html> class allow?

A: It supports bitwise operations (|, &, ^, ~) on enum members, allowing them to be combined as bit flags.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `enum.nonmember()` function added in Python 3.11?]]
* [[What `Enum` subclass was introduced in Python 3.11 to ensure members are valid strings?]]
* [[What is the `enum.verify` decorator added in Python 3.11?]]
Q: What is <html><code>enum.unique</code></html> used for?

A: It is a decorator that ensures no two enum members have the same value. Without it, duplicate values create aliases to the first member with that value.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `enum.verify` decorator added in Python 3.11?]]
* [[What is the `enum.auto()` function used for?]]
* [[What is the `enum.nonmember()` function added in Python 3.11?]]
Q: What is the <html><code>enum.nonmember()</code></html> function added in Python 3.11?

A: It wraps a value to explicitly exclude it from being an enum member: <html><code>x = nonmember(42)</code></html>. Similarly, <html><code>member()</code></html> forces inclusion.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `enum.verify` decorator added in Python 3.11?]]
* [[What is `enum.unique` used for?]]
* [[What is the `enum.auto()` function used for?]]
Q: What module lets you pack and unpack binary data in C struct format?

A: The <html><code>struct</code></html> module. It uses format strings like <html><code>'&lt;I'</code></html> (little-endian unsigned int) to pack/unpack bytes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `struct.pack('>I', 1024)` return?]]
* [[What is the `struct` module's byte order prefixes?]]
* [[What is the `array` module used for?]]
Q: What does <html><code>struct.pack('&gt;I', 1024)</code></html> return?

A: It returns <html><code>b'\x00\x00\x04\x00'</code></html> — the integer 1024 packed as a big-endian unsigned 32-bit integer.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module lets you pack and unpack binary data in C struct format?]]
* [[What does `int.to_bytes()` do?]]
* [[What is the `struct` module's byte order prefixes?]]
Q: What module provides memory-mapped file access?

A: The <html><code>mmap</code></html> module. It maps a file into memory, allowing file I/O via memory operations, which can be significantly faster for large files.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `io` module?]]
Q: What is the <html><code>shelve</code></html> module used for?

A: It provides a persistent dictionary-like object backed by a database file (using <html><code>dbm</code></html>). Keys must be strings, but values can be any picklable Python object.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `ast` module used for?]]
* [[What is the `dis` module?]]
* [[What is the `__bool__` method?]]
Q: Why is unpickling data from untrusted sources a security risk?

A: Because <html><code>pickle.loads()</code></html> can execute arbitrary code during deserialization. A malicious pickle payload can use the <html><code>__reduce__</code></html> method to run arbitrary commands.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What safer alternatives to pickle exist for data serialization?]]
* [[How can you restrict what classes can be unpickled for security?]]
* [[What is `exec()` dangerous for?]]
Q: How can you restrict what classes can be unpickled for security?

A: By subclassing <html><code>pickle.Unpickler</code></html> and overriding the <html><code>find_class()</code></html> method to whitelist allowed modules and classes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why is unpickling data from untrusted sources a security risk?]]
* [[Explain name mangling with double underscores]]
Q: What safer alternatives to pickle exist for data serialization?

A: JSON (for simple data), <html><code>msgpack</code></html>, Protocol Buffers, or <html><code>marshal</code></html> (limited to Python-internal types). For untrusted data, JSON is strongly preferred.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why is unpickling data from untrusted sources a security risk?]]
* [[What is `marshal` and how does it differ from `pickle`?]]
* [[What is the `pickle` protocol version?]]
Q: What is the <html><code>pickle</code></html> protocol version?

A: Pickle has protocol versions 0-5. Higher versions are more efficient. Protocol 5 (Python 3.8) added out-of-band data support for large buffers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What safer alternatives to pickle exist for data serialization?]]
* [[What is `marshal` and how does it differ from `pickle`?]]
* [[What does `typing.Protocol` do?]]
Q: What is <html><code>marshal</code></html> and how does it differ from <html><code>pickle</code></html>?

A: <html><code>marshal</code></html> is used internally by Python to read/write <html><code>.pyc</code></html> files. It is faster than pickle but only supports basic Python types, is not meant for general serialization, and its format can change between Python versions.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What safer alternatives to pickle exist for data serialization?]]
* [[What is the `pickle` protocol version?]]
Q: What module provides functions for working with temporary files and directories?

A: The <html><code>tempfile</code></html> module, with <html><code>NamedTemporaryFile</code></html>, <html><code>TemporaryDirectory</code></html>, <html><code>mkstemp()</code></html>, and <html><code>mkdtemp()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[tempfile]]
Q: What does the <html><code>secrets</code></html> module provide that <html><code>random</code></html> does not?

A: Cryptographically secure random numbers suitable for passwords, tokens, and security-sensitive operations. The <html><code>random</code></html> module uses a Mersenne Twister PRNG that is predictable and not suitable for security.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[secrets (secure random)]]
* [[What standard library module provides an interface to the operating system's random num…]]
* [[What is the `secrets.token_urlsafe(nbytes)` function?]]
Q: What standard library module provides an interface to the operating system's random number generator?

A: <html><code>os.urandom()</code></html> provides raw random bytes. The <html><code>secrets</code></html> module (added in Python 3.6) wraps this in a more convenient API.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `secrets` module provide that `random` does not?]]
Q: What is the <html><code>secrets.token_urlsafe(nbytes)</code></html> function?

A: It generates a random URL-safe text string. With <html><code>nbytes=32</code></html>, it generates approximately 43 characters. Used for generating secure tokens.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[secrets (secure random)]]
* [[What does the `secrets` module provide that `random` does not?]]
* [[What is `urllib.parse.urlparse()` used for?]]
Q: What does <html><code>sys.getsizeof()</code></html> return?

A: The size of an object in bytes, including the garbage collector overhead but not the size of objects it references (it is shallow, not deep).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is `sys.getrefcount(obj)`?]]
* [[What is `sys.maxsize`?]]
* [[What does `int.to_bytes()` do?]]
Q: What does <html><code>sys.getsizeof(1)</code></html> return approximately?

A: About 28 bytes on a 64-bit system. Even small integers have significant overhead due to the object header.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.getsizeof(())` vs `sys.getsizeof([])` show?]]
* [[What is `sys.maxsize`?]]
* [[What does `int.bit_length()` return?]]
Q: What is the <html><code>weakref</code></html> module used for?

A: It creates weak references to objects that don't prevent garbage collection. Useful for caches and observer patterns where you don't want to keep objects alive.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__del__` used for?]]
* [[What is the purpose of garbage collection in Python?]]
* [[What does `object.__repr__` return by default?]]
Q: What is the <html><code>__weakref__</code></html> attribute?

A: A slot that allows weak references to an object. Objects with <html><code>__slots__</code></html> need to explicitly include <html><code>__weakref__</code></html> to support weak references.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__slots__` and why use it?]]
* [[What is `__slots__` inheritance behavior?]]
* [[What does `object.__repr__` return by default?]]
Q: What standard library module can you use to measure execution time of small code snippets?

A: The <html><code>timeit</code></html> module, which runs code multiple times and reports the execution time, disabling the garbage collector during timing by default.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Profiling strategies for slow FastAPI endpoints]]
Q: What does <html><code>copy.deepcopy()</code></html> do differently from <html><code>copy.copy()</code></html>?

A: <html><code>copy()</code></html> creates a shallow copy (new container but same references to contained objects). <html><code>deepcopy()</code></html> recursively copies all contained objects, creating fully independent copies.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `list.copy()` and `list[:]`?]]
* [[What is `shutil.copytree()` used for?]]
Q: What standard library module provides support for generating universally unique identifiers?

A: The <html><code>uuid</code></html> module, supporting UUID versions 1, 3, 4, and 5.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What standard library module provides an interface to the operating system's random num…]]
* [[What is `enum.unique` used for?]]
Q: What is the <html><code>pathlib</code></html> module and when was it introduced?

A: Introduced in Python 3.4, <html><code>pathlib</code></html> provides object-oriented filesystem paths via the <html><code>Path</code></html> class, offering a more Pythonic alternative to <html><code>os.path</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `pathlib.Path.glob()` used for?]]
* [[What is `sys.path` and how does Python use it?]]
* [[What is the `PYTHONPATH` environment variable?]]
Q: What does the <html><code>statistics</code></html> module provide?

A: Basic statistical functions: <html><code>mean()</code></html>, <html><code>median()</code></html>, <html><code>mode()</code></html>, <html><code>stdev()</code></html>, <html><code>variance()</code></html>, <html><code>quantiles()</code></html>, and more. Added in Python 3.4.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `statistics.NormalDist` used for?]]
Q: What is <html><code>statistics.NormalDist</code></html> used for?

A: Added in Python 3.8, it represents a normal (Gaussian) distribution and provides methods for CDF, PDF, quantiles, overlap with other distributions, and more.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `statistics` module provide?]]
Q: What does <html><code>os.scandir()</code></html> return and why is it preferred over <html><code>os.listdir()</code></html>?

A: It returns an iterator of <html><code>DirEntry</code></html> objects that include file metadata (type, stat info) cached from the directory scan. This avoids extra system calls, making it faster than <html><code>listdir()</code></html> followed by <html><code>os.stat()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `os.walk()` used for?]]
* [[What is the "os" module primarily used for?]]
Q: What is <html><code>shutil.copytree()</code></html> used for?

A: Recursively copying an entire directory tree. It supports <html><code>ignore</code></html> patterns and <html><code>dirs_exist_ok</code></html> (Python 3.8+) to copy into an existing directory.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `copy.deepcopy()` do differently from `copy.copy()`?]]
* [[What is `os.walk()` used for?]]
Q: What does <html><code>json.dumps(obj, default=str)</code></html> do?

A: It serializes <html><code>obj</code></html> to JSON, using <html><code>str()</code></html> as a fallback for objects that are not JSON-serializable. This is a common trick for handling <html><code>datetime</code></html> objects.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `json` module's `cls` parameter?]]
* [[What does `python -m json.tool` do?]]
Q: What is <html><code>inspect.signature()</code></html> used for?

A: It returns a <html><code>Signature</code></html> object describing the parameters of a callable, including their names, default values, annotations, and kinds.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.settrace()` do?]]
Q: What does <html><code>dis.dis()</code></html> do?

A: It disassembles Python bytecode, showing the low-level instructions that CPython executes. Useful for understanding performance and how Python compiles your code.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[How does CPython implement dicts internally?]]
* [[What does `python -O` do?]]
* [[What is CPython bytecode?]]
Q: What is the <html><code>dis</code></html> module?

A: The disassembler module that converts Python bytecode into human-readable form. Useful for understanding CPython internals.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[dis module reveals Python bytecode and optimization patterns]]
* [[What is the `difflib` module?]]
* [[How does CPython implement dicts internally?]]
Q: What is the <html><code>ast</code></html> module used for?

A: It parses Python source code into an Abstract Syntax Tree (AST), which can be inspected, modified, and compiled. Used by linters, code formatters, and metaprogramming tools.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is mypy?]]
* [[What is the `dis` module?]]
* [[What is the significance of Python 3.6?]]
Q: What is <html><code>importlib</code></html> used for?

A: Programmatic control of Python's import system — importing modules by name string, reloading modules, finding loaders, and customizing import behavior.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__import__` hook?]]
* [[What is `__name__` set to when a module is imported?]]
* [[What does `import __hello__` do?]]
Q: What is the <html><code>logging</code></html> module's hierarchy?

A: Loggers form a hierarchy based on dot-separated names (e.g., <html><code>app.database</code></html> is a child of <html><code>app</code></html>). Messages propagate up to parent loggers. The root logger is the ancestor of all loggers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Logging levels organize severity and information categories]]
Q: What are the standard logging levels in Python, from lowest to highest?

A: <html><code>DEBUG</code></html> (10), <html><code>INFO</code></html> (20), <html><code>WARNING</code></html> (30), <html><code>ERROR</code></html> (40), <html><code>CRITICAL</code></html> (50). The default level is <html><code>WARNING</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[logging]]
Q: What is the <html><code>graphlib</code></html> module?

A: Added in Python 3.9, it provides <html><code>TopologicalSorter</code></html> for topological sorting of directed acyclic graphs. Useful for dependency resolution.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.9?]]
* [[Implement DFS and BFS for a graph]]
* [[What is the `pathlib` module and when was it introduced?]]
Q: What does <html><code>math.prod()</code></html> do, and when was it added?

A: Added in Python 3.8, it computes the product of all elements in an iterable: <html><code>math.prod([1, 2, 3, 4])</code></html> returns <html><code>24</code></html>. It is the multiplication equivalent of <html><code>sum()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `itertools.accumulate()` do?]]
* [[What does `itertools.product('AB', '12')` yield?]]
* [[What does `math.lcm()` compute, and when was it added?]]
Q: What is the <html><code>reprlib</code></html> module used for?

A: It provides a version of <html><code>repr()</code></html> that limits output length for large or recursive data structures. <html><code>reprlib.repr([1]*1000)</code></html> gives a truncated representation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `object.__repr__` return by default?]]
* [[What does `re.sub(pattern, repl, string)` do?]]
* [[What is the difference between `__str__` and `__repr__`?]]
Q: What is <html><code>atexit</code></html> used for?

A: Registering cleanup functions to be called when the interpreter exits normally. <html><code>atexit.register(func)</code></html> ensures <html><code>func</code></html> is called at shutdown.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `os._exit()` and when is it used?]]
* [[What is `contextlib.ExitStack` used for?]]
* [[What is `__del__` used for?]]
Q: What does the <html><code>traceback</code></html> module provide?

A: Functions for extracting, formatting, and printing stack traces. Useful for logging exceptions without re-raising them.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.exc_info()` used for?]]
* [[Multiple APIs exist for capturing and formatting exception information]]
* [[cgitb module provides formatted tracebacks with context]]
Q: What does <html><code>sys.intern(string)</code></html> do?

A: It interns the string, ensuring only one copy exists in memory. Subsequent equal strings will be the same object, enabling <html><code>is</code></html> comparisons instead of <html><code>==</code></html> for performance.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the surprising behavior of `is` with short strings?]]
* [[What is the difference between == and is in Python?]]
* [[What does `copy.deepcopy()` do differently from `copy.copy()`?]]
Q: What is the <html><code>site</code></html> module responsible for?

A: It is automatically imported during Python startup and adds site-specific paths (like <html><code>site-packages</code></html>) to <html><code>sys.path</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Inspect sys.path and site-packages to understand module resolution]]
* [[What is `sys.path` and how does Python use it?]]
* [[What is the `PYTHONPATH` environment variable?]]
Q: What does <html><code>python -m site</code></html> do?

A: It prints the site-packages paths, user site-packages path, and other configuration details.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m venv myenv` do?]]
* [[Inspect sys.path and site-packages to understand module resolution]]
* [[What is the `__main__.py` file for?]]
Q: What are <html><code>.pth</code></html> files?

A: Path configuration files in <html><code>site-packages</code></html> that contain paths to add to <html><code>sys.path</code></html> at startup.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.path` and how does Python use it?]]
* [[What is the `site` module responsible for?]]
Q: What is the <html><code>PYTHONDONTWRITEBYTECODE</code></html> environment variable?

A: When set, it prevents Python from creating <html><code>__pycache__</code></html> directories and <html><code>.pyc</code></html> files. Equivalent to the <html><code>-B</code></html> flag.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `PYTHONPATH` environment variable?]]
* [[What is `__cached__` on a module?]]
* [[What is `sys.path` and how does Python use it?]]
Q: What does the <html><code>gc</code></html> module do?

A: It provides an interface to Python's garbage collector. You can trigger collection with <html><code>gc.collect()</code></html>, get referrers with <html><code>gc.get_referrers()</code></html>, and tune collection thresholds.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the purpose of garbage collection in Python?]]
* [[What is Flask's `g` object?]]
* [[Memory profiling is non-deterministic due to reference counting]]
Q: What does <html><code>sys.getrecursionlimit()</code></html> return?

A: The current recursion limit. The default is 1000 on most platforms.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the maximum recursion depth in Python by default?]]
* [[What is `sys.getrefcount(obj)`?]]
Q: What is the default recursion limit?

A: 1000 (check with <html><code>sys.getrecursionlimit()</code></html>, change with <html><code>sys.setrecursionlimit()</code></html>).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
Q: What is the <html><code>http.server</code></html> module used for?

A: A simple HTTP server: <html><code>python -m http.server 8000</code></html> serves the current directory. It is intended for development only, not production.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Quick HTTP server from any directory with Python]]
* [[What is the `requests` library?]]
Q: What does <html><code>python -m json.tool</code></html> do?

A: It reads JSON from stdin and pretty-prints it. Useful as a command-line JSON formatter.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m py_compile script.py` do?]]
* [[What is the `json` module's `cls` parameter?]]
Q: What is <html><code>python -m zipapp</code></html> used for?

A: It creates executable Python ZIP applications (<html><code>.pyz</code></html> files). A ZIP file with a <html><code>__main__.py</code></html> entry point can be executed directly by Python.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__main__.py` file for?]]
* [[What is `zipimport`?]]
* [[What is the `zip()` function's strict mode?]]
Q: What does <html><code>python -m calendar</code></html> do?

A: It prints a calendar for the current year (or a specified year/month) to the terminal.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `calendar` module?]]
* [[What does `python -m site` do?]]
* [[What does `python -m json.tool` do?]]
Q: What is the difference between a "naive" and "aware" datetime in Python?

A: A naive datetime has no timezone information (<html><code>tzinfo</code></html> is <html><code>None</code></html>). An aware datetime has timezone info attached. Comparing naive and aware datetimes raises a <html><code>TypeError</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why should you avoid using `datetime.utcnow()`?]]
* [[What is the epoch in Python's `time` module?]]
* [[What does `datetime.datetime.fromisoformat()` parse?]]
Q: Why should you avoid using <html><code>datetime.utcnow()</code></html>?

A: It returns a naive datetime (no timezone info) representing UTC time, which can be confused with local time. Use <html><code>datetime.now(timezone.utc)</code></html> instead. <html><code>utcnow()</code></html> was deprecated in Python 3.12.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between a "naive" and "aware" datetime in Python?]]
* [[What is the epoch in Python's `time` module?]]
* [[What does `datetime.datetime.fromisoformat()` parse?]]
Q: What is the <html><code>zoneinfo</code></html> module?

A: Added in Python 3.9, it provides IANA timezone support: <html><code>ZoneInfo('America/New_York')</code></html>. It replaced the need for the third-party <html><code>pytz</code></html> library.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why was `pytz` problematic?]]
* [[Why should you avoid using `datetime.utcnow()`?]]
* [[What does `datetime.datetime.fromisoformat()` parse?]]
Q: Why was <html><code>pytz</code></html> problematic?

A: <html><code>pytz</code></html> had a non-standard API — you had to use <html><code>localize()</code></html> instead of <html><code>replace()</code></html> to attach timezones. Using <html><code>replace()</code></html> with <html><code>pytz</code></html> gave wrong results for DST transitions. <html><code>zoneinfo</code></html> uses the standard <html><code>datetime</code></html> API.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `zoneinfo` module?]]
* [[Why should you avoid using `datetime.utcnow()`?]]
* [[What does `datetime.datetime.fromisoformat()` parse?]]
Q: What is the epoch in Python's <html><code>time</code></html> module?

A: January 1, 1970, 00:00:00 UTC on most systems. <html><code>time.time()</code></html> returns seconds since the epoch.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `datetime.datetime.fromisoformat()` parse?]]
* [[What is the maximum date Python's `datetime` can represent?]]
Q: What does <html><code>timedelta</code></html> represent?

A: A duration — the difference between two dates or datetimes. It stores days, seconds, and microseconds internally.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the epoch in Python's `time` module?]]
Q: What is the maximum date Python's <html><code>datetime</code></html> can represent?

A: <html><code>datetime.datetime.max</code></html> is <html><code>9999-12-31 23:59:59.999999</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the epoch in Python's `time` module?]]
* [[Why should you avoid using `datetime.utcnow()`?]]
* [[What does `datetime.datetime.fromisoformat()` parse?]]
Q: What does <html><code>datetime.datetime.fromisoformat()</code></html> parse?

A: ISO 8601 formatted strings. In Python 3.11, it was expanded to handle many more ISO 8601 formats including the <html><code>Z</code></html> suffix for UTC.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the epoch in Python's `time` module?]]
* [[Why should you avoid using `datetime.utcnow()`?]]
* [[What is `__format__` used for?]]
Q: What module was added in Python 3.11 for parsing TOML files?

A: <html><code>tomllib</code></html> — a read-only TOML parser in the standard library. For writing TOML, you still need a third-party library like <html><code>tomli-w</code></html>.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What tool is the modern standard for building Python packages?]]
* [[Multiple dependency declaration files create inconsistent builds]]
* [[What major features were added in Python 3.11?]]
Q: What are the three string formatting approaches in Python?

A: %-formatting (<html><code>'%s' % val</code></html>), <html><code>str.format()</code></html> (<html><code>'{}'.format(val)</code></html>), and f-strings (<html><code>f'{val}'</code></html>). F-strings (Python 3.6+) are generally preferred for readability and performance.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__format__` used for?]]
* [[What major feature did Python 3.12 change regarding f-strings?]]
* [[f-string (formatted string literal)]]
Q: What does <html><code>f'{value=}'</code></html> do, introduced in Python 3.8?

A: The <html><code>=</code></html> specifier in f-strings shows both the expression text and its value. For example, <html><code>x=42; f'{x=}'</code></html> produces <html><code>"x=42"</code></html>. It is useful for debugging.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between == and is in Python?]]
* [[What major feature did Python 3.12 change regarding f-strings?]]
* [[What is `typing.Literal` used for?]]
Q: Can f-strings contain the backslash character?

A: Before Python 3.12, f-string expressions could not contain backslashes. In Python 3.12+, this restriction was lifted and backslashes are allowed in f-string expressions.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why do we use raw strings (r'...') for regex patterns in Python?]]
* [[What does `f'{value=}'` do, introduced in Python 3.8?]]
* [[f-string (formatted string literal)]]
Q: What major feature did Python 3.12 change regarding f-strings?

A: F-strings were completely reformulated with a new parser, removing many previous limitations. They can now contain any valid Python expression, including nested f-strings and backslashes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the significance of Python 3.6?]]
* [[What were the main breaking changes in Python 3.0?]]
* [[What does `f'{value=}'` do, introduced in Python 3.8?]]
Q: What is <html><code>string.Template</code></html> and when would you use it?

A: <html><code>string.Template</code></html> uses <html><code>$</code></html>-based substitution (<html><code>$name</code></html> or <html><code>${name}</code></html>). It is simpler and safer for user-provided templates because it doesn't allow arbitrary expression evaluation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
Q: What does <html><code>textwrap.dedent()</code></html> do?

A: It removes common leading whitespace from all lines in a multi-line string, useful for writing indented string literals that should not have leading whitespace in the output.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `textwrap.fill()` do?]]
* [[What is the `textwrap` module useful for?]]
* [[What does `str.removeprefix()` do, and when was it added?]]
Q: What does <html><code>textwrap.fill()</code></html> do?

A: It wraps a single paragraph of text to a given width and returns a single string with newlines inserted. <html><code>textwrap.wrap()</code></html> returns a list of lines instead.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `textwrap` module useful for?]]
* [[What does `textwrap.dedent()` do?]]
* [[What does `functools.wraps` do?]]
Q: What does the <html><code>str.partition(sep)</code></html> method return?

A: A 3-tuple: <html><code>(before, sep, after)</code></html>. If the separator is not found, it returns <html><code>(string, '', '')</code></html>. There is also <html><code>rpartition()</code></html> which splits at the last occurrence.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
* [[What is "slicing" in Python?]]
* [[What is `shlex.split()` used for?]]
Q: What is the difference between <html><code>str.join()</code></html> and concatenation with <html><code>+</code></html>?

A: <html><code>str.join()</code></html> is O(n) — it preallocates memory for the final string. Repeated <html><code>+</code></html> concatenation is O(n^2) because each concatenation creates a new string. Always prefer <html><code>join()</code></html> for combining many strings.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.Union` used for?]]
* [[Merge two sorted arrays]]
Q: What does <html><code>str.removeprefix()</code></html> do, and when was it added?

A: Added in Python 3.9, it removes the specified prefix if the string starts with it, otherwise returns the string unchanged. Similarly <html><code>removesuffix()</code></html> for suffixes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -O` do?]]
* [[What does `str.translate()` do?]]
Q: What is the difference between <html><code>str.strip()</code></html> and <html><code>str.removeprefix()</code></html>/<html><code>str.removesuffix()</code></html>?

A: <html><code>strip()</code></html> removes individual characters from both ends. <html><code>removeprefix()</code></html>/<html><code>removesuffix()</code></html> removes a specific substring. <html><code>'Arthur'.lstrip('Art')</code></html> gives <html><code>'hur'</code></html> (strips characters), while <html><code>'Arthur'.removeprefix('Art')</code></html> gives <html><code>'hur'</code></html> (removes exact prefix).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `str.translate()` do?]]
* [[What is the difference between `__str__` and `__repr__`?]]
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
Q: What does the <html><code>%</code></html> operator do with strings in Python?

A: It performs old-style C-like string formatting: <html><code>'Hello %s, you are %d' % ('Alice', 30)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are the three string formatting approaches in Python?]]
* [[What does `python -c "expr"` do?]]
* [[What is the Python REPL's `_` variable?]]
Q: What format spec would you use in an f-string to display a float with exactly 2 decimal places?

A: <html><code>f'{value:.2f}'</code></html>. The <html><code>.2f</code></html> means 2 decimal places with fixed-point notation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `decimal.Decimal` vs `float` for financial calculations?]]
* [[How do you format a number with thousands separators in an f-string?]]
* [[What is the output of `print(0.1 + 0.2)`?]]
Q: How do you format a number with thousands separators in an f-string?

A: <html><code>f'{1000000:,}'</code></html> produces <html><code>'1,000,000'</code></html>. You can also use <html><code>_</code></html> as a separator: <html><code>f'{1000000:_}'</code></html> gives <html><code>'1_000_000'</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[f-string (formatted string literal)]]
* [[What format spec would you use in an f-string to display a float with exactly 2 decimal…]]
* [[What is `__format__` used for?]]
Q: What does <html><code>str.zfill(width)</code></html> do?

A: It pads the string with leading zeros to the specified width. It handles a leading sign correctly: <html><code>'-42'.zfill(5)</code></html> gives <html><code>'-0042'</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `textwrap.fill()` do?]]
* [[What does `str.removeprefix()` do, and when was it added?]]
Q: What does <html><code>str.casefold()</code></html> do differently from <html><code>str.lower()</code></html>?

A: <html><code>casefold()</code></html> is more aggressive for case-insensitive comparisons. For example, the German <html><code>'SS'.casefold()</code></html> gives <html><code>'ss'</code></html>, which correctly matches the lowercase form of <html><code>'ß'</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does case-sensitivity mean in Python?]]
* [[What does the `re.IGNORECASE` (or `re.I`) flag do?]]
* [[What is the wildcard pattern in Python's match statement?]]
Q: What does <html><code>str.translate()</code></html> do?

A: It maps characters using a translation table created by <html><code>str.maketrans()</code></html>. It is the fastest way to replace or delete multiple characters at once.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `chr()` and `ord()` do?]]
* [[What does `str.format_map()` do?]]
Q: Why do we use raw strings (r'...') for regex patterns in Python?

A: Raw strings prevent Python from interpreting backslash sequences before the regex engine sees them. Without <html><code>r</code></html>, <html><code>\b</code></html> would be a backspace character rather than a word boundary.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `re.escape(string)` do?]]
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
* [[What does `re.sub(pattern, repl, string)` do?]]
Q: What is the difference between <html><code>re.search()</code></html> and <html><code>re.fullmatch()</code></html>?

A: <html><code>re.search()</code></html> finds a match anywhere in the string. <html><code>re.fullmatch()</code></html> (added in Python 3.4) requires the entire string to match the pattern.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What does `re.findall()` return when the pattern contains groups?]]
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
Q: What does <html><code>re.compile()</code></html> return and why use it?

A: It returns a compiled regular expression pattern object. Compiling is useful when you reuse the same pattern many times. Python caches recently used patterns internally.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `compile()` built-in?]]
* [[What is `compileall` used for?]]
* [[What does `re.sub(pattern, repl, string)` do?]]
Q: What do parentheses <html><code>()</code></html> do in a regex pattern?

A: They create capturing groups. Matched text can be retrieved via <html><code>group(n)</code></html> on the match object.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a non-capturing group in regex?]]
* [[What are named groups in regex and how do you use them?]]
* [[What is a named group backreference in regex?]]
Q: What is a non-capturing group in regex?

A: <html><code>(?:...)</code></html> groups the pattern for alternation or quantification but does not capture the matched text. It is more efficient when you don't need the captured group.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What do parentheses `()` do in a regex pattern?]]
* [[What is a named group backreference in regex?]]
* [[What are named groups in regex and how do you use them?]]
Q: What is a positive lookahead in regex?

A: <html><code>(?=...)</code></html> asserts that what follows matches the pattern, without consuming any characters. For example, <html><code>foo(?=bar)</code></html> matches <html><code>foo</code></html> only if followed by <html><code>bar</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a positive lookbehind?]]
* [[What is a negative lookbehind?]]
* [[What is a non-capturing group in regex?]]
Q: What is a negative lookahead?

A: <html><code>(?!...)</code></html> asserts that what follows does NOT match the pattern. For example, <html><code>foo(?!bar)</code></html> matches <html><code>foo</code></html> only if NOT followed by <html><code>bar</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a positive lookbehind?]]
* [[What is a non-capturing group in regex?]]
Q: What is a positive lookbehind?

A: <html><code>(?&lt;=...)</code></html> asserts that what precedes the current position matches the pattern.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a positive lookahead in regex?]]
* [[What is a negative lookahead?]]
* [[What is the `match` statement's `__match_args__` attribute used for?]]
Q: What is a negative lookbehind?

A: <html><code>(?&lt;!...)</code></html> asserts that what precedes does NOT match. For example, <html><code>(?&lt;!un)happy</code></html> matches <html><code>happy</code></html> but not <html><code>unhappy</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a positive lookahead in regex?]]
* [[What limitation do lookbehinds have in Python's `re` module?]]
* [[What is the `match` statement's `__match_args__` attribute used for?]]
Q: What limitation do lookbehinds have in Python's <html><code>re</code></html> module?

A: Lookbehinds must be fixed-width — they cannot contain quantifiers like <html><code>*</code></html>, <html><code>+</code></html>, or <html><code>{m,n}</code></html> (variable-length). The <html><code>regex</code></html> third-party module removes this limitation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `re.search()` and `re.fullmatch()`?]]
* [[What does the `re.VERBOSE` (or `re.X`) flag do?]]
* [[What does the `re.MULTILINE` (or `re.M`) flag do?]]
Q: What does the <html><code>re.IGNORECASE</code></html> (or <html><code>re.I</code></html>) flag do?

A: It makes the pattern case-insensitive, matching both uppercase and lowercase letters.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `re.DOTALL` (or `re.S`) flag do?]]
* [[What does the `re.VERBOSE` (or `re.X`) flag do?]]
Q: What does the <html><code>re.MULTILINE</code></html> (or <html><code>re.M</code></html>) flag do?

A: It makes <html><code>^</code></html> and <html><code>$</code></html> match the start and end of each line (after/before a newline), not just the start and end of the entire string.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `re.VERBOSE` (or `re.X`) flag do?]]
* [[What does `re.escape(string)` do?]]
* [[What does the `re.IGNORECASE` (or `re.I`) flag do?]]
Q: What does the <html><code>re.DOTALL</code></html> (or <html><code>re.S</code></html>) flag do?

A: It makes the <html><code>.</code></html> metacharacter match any character including newlines. Without it, <html><code>.</code></html> matches everything except <html><code>\n</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `re.VERBOSE` (or `re.X`) flag do?]]
* [[What does `re.escape(string)` do?]]
* [[What does the `re.IGNORECASE` (or `re.I`) flag do?]]
Q: What does the <html><code>re.VERBOSE</code></html> (or <html><code>re.X</code></html>) flag do?

A: It allows you to write multi-line regexes with comments and whitespace for readability. Unescaped whitespace and <html><code>#</code></html> comments are ignored in the pattern.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `re.MULTILINE` (or `re.M`) flag do?]]
* [[What does the `re.DOTALL` (or `re.S`) flag do?]]
* [[What does `re.escape(string)` do?]]
Q: What does <html><code>re.findall()</code></html> return when the pattern contains groups?

A: It returns a list of the groups (or tuples of groups if multiple groups exist), not the full matches. If there are no groups, it returns the full matches.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `re.search()` and `re.fullmatch()`?]]
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
* [[What is a non-capturing group in regex?]]
Q: What does <html><code>re.sub(pattern, repl, string)</code></html> do?

A: It replaces all occurrences of the pattern in the string with <html><code>repl</code></html>. <html><code>repl</code></html> can be a string (with backreferences like <html><code>\1</code></html>) or a callable that receives the match object.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `re.subn()` return differently from `re.sub()`?]]
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
* [[What does `re.escape(string)` do?]]
Q: What does <html><code>re.split(pattern, string)</code></html> do differently from <html><code>str.split()</code></html>?

A: <html><code>re.split()</code></html> splits on a regex pattern. If the pattern contains capturing groups, the matched separators are included in the result list.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `re.sub(pattern, repl, string)` do?]]
* [[What does `re.escape(string)` do?]]
* [[What is the difference between `re.search()` and `re.fullmatch()`?]]
Q: What are named groups in regex and how do you use them?

A: <html><code>(?P&lt;name&gt;...)</code></html> creates a named group accessible via <html><code>match.group('name')</code></html> or <html><code>match.groupdict()</code></html>. Backreferences use <html><code>(?P=name)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a non-capturing group in regex?]]
* [[What do parentheses `()` do in a regex pattern?]]
* [[What does `re.findall()` return when the pattern contains groups?]]
Q: What is a named group backreference in regex?

A: <html><code>(?P=name)</code></html> in the pattern references a previously captured named group. For example, <html><code>(?P&lt;word&gt;\w+)\s+(?P=word)</code></html> matches repeated words.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a non-capturing group in regex?]]
* [[What do parentheses `()` do in a regex pattern?]]
* [[What is a positive lookahead in regex?]]
Q: What does <html><code>re.escape(string)</code></html> do?

A: It escapes all non-alphanumeric characters in the string, making it safe to use as a literal pattern in a regex.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `re.sub(pattern, repl, string)` do?]]
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
* [[What does the `re.DOTALL` (or `re.S`) flag do?]]
Q: What does <html><code>re.subn()</code></html> return differently from <html><code>re.sub()</code></html>?

A: <html><code>re.subn()</code></html> returns a tuple <html><code>(new_string, number_of_substitutions_made)</code></html>, while <html><code>re.sub()</code></html> returns just the new string.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `re.sub(pattern, repl, string)` do?]]
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
* [[What does `re.compile()` return and why use it?]]
Q: Is there a limit to integer size in Python 3?

A: No. Python 3 integers have arbitrary precision — they can be as large as your memory allows. There is no overflow.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What happened to `long` in Python 3?]]
* [[What is `sys.maxsize`?]]
* [[What is `int.as_integer_ratio()` added in Python 3.8?]]
Q: What happened to <html><code>long</code></html> in Python 3?

A: Python 2 had both <html><code>int</code></html> (fixed-size) and <html><code>long</code></html> (arbitrary precision). Python 3 unified them into a single <html><code>int</code></html> type with arbitrary precision.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Is there a limit to integer size in Python 3?]]
* [[What did Python 3.7 add?]]
* [[What is `sys.maxsize`?]]
Q: What does <html><code>float('inf')</code></html> represent?

A: Positive infinity, per IEEE 754. It is greater than any other number. <html><code>float('-inf')</code></html> is negative infinity. <html><code>float('nan')</code></html> is Not a Number.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `hash(float('inf'))` return?]]
* [[What is the surprising result of `float('nan') == float('nan')`?]]
* [[What is `sys.float_info`?]]
Q: What is <html><code>math.inf</code></html> equal to?

A: <html><code>float('inf')</code></html>. It represents positive infinity.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `hash(float('inf'))` return?]]
* [[What is `sys.float_info`?]]
* [[What is `int.as_integer_ratio()` added in Python 3.8?]]
Q: What is the surprising result of <html><code>float('nan') == float('nan')</code></html>?

A: <html><code>False</code></html>. NaN is not equal to anything, including itself. This is per the IEEE 754 standard. To check for NaN, use <html><code>math.isnan()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `float('inf')` represent?]]
* [[Why does `0.1 + 0.2 != 0.3` in Python?]]
Q: Why does <html><code>0.1 + 0.2 != 0.3</code></html> in Python?

A: Because floating-point numbers use IEEE 754 binary representation, and 0.1 and 0.2 cannot be represented exactly in binary. The result is <html><code>0.30000000000000004</code></html>. Use <html><code>math.isclose()</code></html> or <html><code>decimal.Decimal</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the output of `print(0.1 + 0.2)`?]]
* [[What is the output of `round(0.5)` and `round(1.5)` in Python 3?]]
* [[What is `pytest.approx()` used for?]]
Q: What is the output of <html><code>print(0.1 + 0.2)</code></html>?

A: <html><code>0.30000000000000004</code></html> due to IEEE 754 floating-point representation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why does `0.1 + 0.2 != 0.3` in Python?]]
* [[What is the output of `round(0.5)` and `round(1.5)` in Python 3?]]
Q: What module provides arbitrary-precision decimal arithmetic?

A: The <html><code>decimal</code></html> module with its <html><code>Decimal</code></html> class. It avoids the floating-point representation issues of <html><code>float</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `decimal.Decimal` vs `float` for financial calculations?]]
* [[What module allows exact arithmetic with fractions?]]
* [[What is the `decimal` module's `ROUND_HALF_EVEN` rounding mode?]]
Q: How do you set the precision for <html><code>decimal.Decimal</code></html> operations?

A: Via <html><code>decimal.getcontext().prec = n</code></html>. The default precision is 28 significant digits.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module provides arbitrary-precision decimal arithmetic?]]
* [[What is `decimal.Decimal` vs `float` for financial calculations?]]
Q: What module allows exact arithmetic with fractions?

A: The <html><code>fractions</code></html> module with its <html><code>Fraction</code></html> class. For example, <html><code>Fraction(1, 3) + Fraction(1, 6)</code></html> gives <html><code>Fraction(1, 2)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module provides arbitrary-precision decimal arithmetic?]]
* [[What is the `numbers` module?]]
* [[What is the `fractions.Fraction.limit_denominator()` method?]]
Q: Does Python have native support for complex numbers?

A: Yes. Use <html><code>j</code></html> or <html><code>J</code></html> for the imaginary part: <html><code>z = 3 + 4j</code></html>. Access parts with <html><code>z.real</code></html> and <html><code>z.imag</code></html>. The <html><code>cmath</code></html> module provides math functions for complex numbers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the "math" module?]]
* [[Is there a limit to integer size in Python 3?]]
* [[What happened to `long` in Python 3?]]
Q: What does <html><code>divmod(a, b)</code></html> return?

A: A tuple <html><code>(a // b, a % b)</code></html> — the quotient and remainder. It is more efficient than computing them separately.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Which operator gives the remainder of division?]]
* [[What is an "integer division" operator?]]
* [[What does the `/` separator in function parameters do?]]
Q: What is <html><code>math.isclose(a, b)</code></html> used for?

A: Comparing floating-point numbers for approximate equality, with configurable relative tolerance (<html><code>rel_tol</code></html>, default 1e-9) and absolute tolerance (<html><code>abs_tol</code></html>, default 0.0).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the "math" module?]]
* [[Why does `0.1 + 0.2 != 0.3` in Python?]]
* [[What is `pytest.approx()` used for?]]
Q: What does <html><code>int.bit_length()</code></html> return?

A: The number of bits needed to represent the integer (excluding sign and leading zeros). For example, <html><code>(255).bit_length()</code></html> returns 8.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `int.to_bytes()` do?]]
* [[What does `struct.pack('>I', 1024)` return?]]
* [[What does `sys.getsizeof(1)` return approximately?]]
Q: What does <html><code>int.to_bytes()</code></html> do?

A: Converts an integer to a bytes representation. For example, <html><code>(1024).to_bytes(2, byteorder='big')</code></html> returns <html><code>b'\x04\x00'</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What does `int.bit_length()` return?]]
* [[What does `struct.pack('>I', 1024)` return?]]
* [[What is `str.encode()` and `bytes.decode()`?]]
Q: What is the <html><code>numbers</code></html> module?

A: It defines abstract base classes for numeric types: <html><code>Number</code></html>, <html><code>Complex</code></html>, <html><code>Real</code></html>, <html><code>Rational</code></html>, <html><code>Integral</code></html>. It forms a numeric tower for type checking.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `types` module?]]
* [[What module provides arbitrary-precision decimal arithmetic?]]
* [[What is the "math" module?]]
Q: What is reference counting in CPython?

A: The primary memory management mechanism. Each object tracks how many references point to it. When the count reaches zero, the memory is freed immediately. The cyclic garbage collector handles reference cycles.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the purpose of garbage collection in Python?]]
* [[What is CPython's memory allocator?]]
* [[What is the small integer cache in CPython?]]
Q: Why does the GIL exist?

A: To protect CPython's reference counting from race conditions. Without the GIL, every reference count update would need its own lock, adding significant overhead.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[The GIL does not make individual operations atomic; protect shared state with locks]]
* [[What did Python 3.12 do with the GIL?]]
* [[The Global Interpreter Lock constrains Python threading to I/O concurrency]]
Q: What is CPython bytecode?

A: The intermediate representation that Python source code is compiled to before execution. Each <html><code>.py</code></html> file is compiled to bytecode (stored in <html><code>.pyc</code></html> files) which the CPython virtual machine interprets.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m py_compile script.py` do?]]
* [[What is a code object in Python?]]
* [[What is the `__pycache__` directory?]]
Q: What is the <html><code>__pycache__</code></html> directory?

A: A directory Python creates to store compiled bytecode (<html><code>.pyc</code></html> files). It avoids recompiling modules that haven't changed. The files are named with the Python version, like <html><code>module.cpython-312.pyc</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m py_compile script.py` do?]]
* [[What is the `__init__.py` file for?]]
* [[What is the `__main__.py` file for?]]
Q: What is <html><code>__cached__</code></html> on a module?

A: The path to the compiled bytecode file (<html><code>.pyc</code></html>) for the module.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__spec__` in a module?]]
* [[What is the `PYTHONDONTWRITEBYTECODE` environment variable?]]
* [[What is `__file__` in a module?]]
Q: What does <html><code>python -O</code></html> do?

A: Runs Python with basic optimizations: removes <html><code>assert</code></html> statements and sets <html><code>__debug__</code></html> to <html><code>False</code></html>. <html><code>-OO</code></html> also removes docstrings.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__debug__` built-in constant?]]
* [[What does `dis.dis()` do?]]
* [[What does `python -v` do?]]
Q: What is the <html><code>__debug__</code></html> built-in constant?

A: It is <html><code>True</code></html> under normal execution and <html><code>False</code></html> when Python runs with the <html><code>-O</code></html> flag. <html><code>assert</code></html> statements are only executed when <html><code>__debug__</code></html> is True.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -O` do?]]
* [[Assertions are development aids, removed in production with -O]]
Q: How does CPython's garbage collector handle circular references?

A: It uses a generational garbage collector with three generations. Objects that survive collection are promoted to older generations, which are collected less frequently. It detects unreachable cycles by tracking container objects.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are the three generations in CPython's garbage collector?]]
* [[What is the purpose of garbage collection in Python?]]
Q: What are the three generations in CPython's garbage collector?

A: Generation 0 (youngest, collected most frequently), generation 1 (middle), and generation 2 (oldest, collected least frequently). New objects start in generation 0.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[How does CPython's garbage collector handle circular references?]]
* [[What is reference counting in CPython?]]
* [[What is a Python generator?]]
Q: What is the peephole optimizer in CPython?

A: A bytecode optimizer that performs simple optimizations like constant folding (<html><code>1 + 2</code></html> becomes <html><code>3</code></html>), dead code elimination, and converting operations to more efficient forms.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What performance improvement was made in Python 3.11?]]
* [[What is CPython's memory allocator?]]
* [[What is `scipy.optimize.minimize()`?]]
Q: What is <html><code>sys.maxsize</code></html>?

A: The largest positive integer supported by the platform's <html><code>Py_ssize_t</code></html> type (typically 2^63 - 1 on 64-bit). It is NOT the maximum integer Python can handle, but is the maximum size for containers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[Is there a limit to integer size in Python 3?]]
* [[What does `sys.getsizeof(1)` return approximately?]]
* [[What is `sys.float_info`?]]
Q: What does <html><code>sys.version_info</code></html> return?

A: A named tuple with <html><code>major</code></html>, <html><code>minor</code></html>, <html><code>micro</code></html>, <html><code>releaselevel</code></html>, and <html><code>serial</code></html> fields.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.exc_info()` used for?]]
Q: What does <html><code>sys.platform</code></html> return on Linux, macOS, and Windows?

A: <html><code>'linux'</code></html>, <html><code>'darwin'</code></html>, and <html><code>'win32'</code></html> respectively.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is the `platform` module?]]
* [[What is the "os" module primarily used for?]]
Q: What is the difference between concurrency and parallelism in Python?

A: Concurrency (doing multiple things by switching between them) is achieved with <html><code>asyncio</code></html> or threading. Parallelism (doing multiple things simultaneously) requires <html><code>multiprocessing</code></html> due to the GIL.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[GIL prevents CPU parallelism but releases during I/O]]
* [[The Global Interpreter Lock constrains Python threading to I/O concurrency]]
* [[Multiprocessing achieves true CPU parallelism with separate interpreters]]
Q: What is <html><code>async</code></html>/<html><code>await</code></html> in Python?

A: Syntax for asynchronous programming introduced in Python 3.5 (PEP 492). <html><code>async def</code></html> defines a coroutine, and <html><code>await</code></html> suspends execution until an awaitable completes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `asyncio.run()` used for?]]
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
* [[What is `asyncio.Queue`?]]
Q: What is <html><code>asyncio.run()</code></html> used for?

A: It is the main entry point for running async code from synchronous code. It creates an event loop, runs the coroutine, and closes the loop. Added in Python 3.7.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `asyncio.create_task()` vs `await`?]]
* [[What is `asyncio.Queue`?]]
* [[What is `asyncio.sleep()` vs `time.sleep()`?]]
Q: What is <html><code>asyncio.to_thread()</code></html> added in Python 3.9?

A: It runs a synchronous function in a separate thread: <html><code>await asyncio.to_thread(blocking_io_func)</code></html>. This prevents blocking the event loop.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[What is `asyncio.wait_for()` used for?]]
* [[What is the `TaskGroup` in Python 3.11's asyncio?]]
Q: What is <html><code>multiprocessing.Pool</code></html> used for?

A: It creates a pool of worker processes for parallel execution, with methods like <html><code>map()</code></html>, <html><code>apply_async()</code></html>, and <html><code>starmap()</code></html> to distribute work across CPU cores.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Multiprocessing achieves true CPU parallelism with separate interpreters]]
* [[What is `multiprocessing.Queue` vs `queue.Queue`?]]
* [[multiprocessing]]
Q: What is the <html><code>TaskGroup</code></html> in Python 3.11's asyncio?

A: <html><code>asyncio.TaskGroup</code></html> provides structured concurrency — a context manager that runs multiple tasks and ensures all are completed (or cancelled) before exiting the block.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
* [[What is `asyncio.run()` used for?]]
* [[What is `asyncio.create_task()` vs `await`?]]
Q: What is the difference between <html><code>asyncio.gather()</code></html> and <html><code>TaskGroup</code></html>?

A: <html><code>gather()</code></html> runs coroutines concurrently but has error-handling issues — if one task fails, others may be left running. <html><code>TaskGroup</code></html> (3.11) provides structured concurrency: if any task fails, all others are cancelled and the group raises an <html><code>ExceptionGroup</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `asyncio.create_task()` vs `await`?]]
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[What is `asyncio.run()` used for?]]
Q: What are context variables (<html><code>contextvars</code></html>)?

A: Introduced in Python 3.7, the <html><code>contextvars</code></html> module provides context-local variables similar to thread-local storage but works correctly with <html><code>asyncio</code></html> tasks. Used for things like request-scoped state.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `contextlib.nullcontext()` used for?]]
* [[What is the `contextlib.aclosing()` context manager?]]
Q: What is the GIL's impact on I/O-bound vs CPU-bound threading?

A: I/O-bound threading works well because the GIL is released during I/O operations (network, file). CPU-bound threading is ineffective because only one thread can execute Python bytecode at a time.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the per-interpreter GIL in Python 3.12?]]
* [[Why does the GIL exist?]]
* [[Workload type determines the optimal concurrency model]]
Q: What is <html><code>threading.Lock</code></html> used for?

A: A primitive lock for mutual exclusion. Only one thread can hold the lock at a time. Use <html><code>with lock:</code></html> for safe acquisition and release.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `threading.Condition`?]]
* [[What is `threading.Event`?]]
* [[The GIL does not make individual operations atomic; protect shared state with locks]]
Q: What is a daemon thread?

A: A thread that runs in the background and is automatically killed when all non-daemon threads exit. Set with <html><code>thread.daemon = True</code></html> before starting.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
Q: What is <html><code>asyncio.Queue</code></html>?

A: An async-safe queue for producer-consumer patterns in asyncio code. Unlike <html><code>queue.Queue</code></html> (for threads), it uses <html><code>await</code></html> for <html><code>get()</code></html> and <html><code>put()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `asyncio.run()` used for?]]
* [[What is `asyncio.wait_for()` used for?]]
* [[What is `asyncio.Semaphore` used for?]]
Q: What is <html><code>asyncio.Semaphore</code></html> used for?

A: Limiting the number of concurrent coroutines accessing a shared resource — for example, limiting concurrent HTTP connections to avoid overwhelming a server.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Semaphore limits concurrent operations without blocking new submissions]]
* [[What is `asyncio.Queue`?]]
* [[What is `asyncio.run()` used for?]]
Q: What PEP introduced [[type hints|Type hints]] to Python?

A: PEP 484, accepted in Python 3.5. It introduced the <html><code>typing</code></html> module.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.get_type_hints()` used for?]]
* [[What is `typing.Annotated` used for?]]
* [[What is `typing.TypeVarTuple` used for?]]
Q: What does <html><code>typing.Protocol</code></html> do?

A: Introduced in Python 3.8 (PEP 544), it enables structural subtyping (duck typing for type checkers). A class satisfies a Protocol if it has the required methods/attributes, without explicitly inheriting from it.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Protocol (structural typing)]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.TypeGuard` used for?]]
Q: What is <html><code>TypeVar</code></html> used for?

A: Defining generic type variables. For example, <html><code>T = TypeVar('T')</code></html> allows writing <html><code>def first(items: list[T]) -&gt; T</code></html> to indicate the return type matches the list element type.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.ClassVar` used for?]]
* [[What is the `type` statement in Python 3.12?]]
* [[What is `typing.TypeGuard` used for?]]
Q: What is <html><code>typing.TypeVarTuple</code></html> used for?

A: Added in Python 3.11 (PEP 646), it represents a variadic number of types. Used for typing functions that accept variable numbers of arguments of different types, like tensor shapes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypedDict` used for?]]
* [[What is `typing.ClassVar` used for?]]
* [[What is `typing.get_type_hints()` used for?]]
Q: What is <html><code>ParamSpec</code></html> used for?

A: Introduced in Python 3.10 (PEP 612), it captures the parameter types of a callable, enabling accurate typing of decorators that preserve the wrapped function's signature.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `pytest.mark.parametrize` used for?]]
* [[What does `functools.wraps` do?]]
Q: What is <html><code>TypeAlias</code></html> used for?

A: Explicitly declaring a type alias: <html><code>Vector: TypeAlias = list[float]</code></html>. Added in Python 3.10. In Python 3.12, the <html><code>type</code></html> statement replaced it.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.TypeGuard` used for?]]
* [[What is `TypeVar` used for?]]
Q: What is the <html><code>type</code></html> statement in Python 3.12?

A: A new syntax for defining type aliases: <html><code>type Vector = list[float]</code></html>. It is lazily evaluated and supports generic type parameters inline.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `TypeVar` used for?]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What new generic syntax was introduced in Python 3.12?]]
Q: What new generic syntax was introduced in Python 3.12?

A: PEP 695 introduced <html><code>def func[T](x: T) -&gt; T:</code></html> and <html><code>class MyClass[T]:</code></html> syntax, replacing the verbose <html><code>TypeVar</code></html> pattern with inline generic parameters.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `TypeVar` used for?]]
* [[What is the `type` statement in Python 3.12?]]
* [[What is `typing.TypeVarTuple` used for?]]
Q: What is <html><code>typing.Literal</code></html> used for?

A: Introduced in Python 3.8, it restricts values to specific literal values: <html><code>def set_mode(mode: Literal['r', 'w', 'a']) -&gt; None</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.Union` used for?]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.TypeGuard` used for?]]
Q: What is <html><code>typing.TypeGuard</code></html> used for?

A: Added in Python 3.10, it narrows types in conditional branches. A function returning <html><code>TypeGuard[X]</code></html> tells the type checker that if the function returns True, the argument is of type X.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.get_type_hints()` used for?]]
* [[What is `TypeVar` used for?]]
* [[What is `typing.cast()` used for?]]
Q: What is <html><code>typing.TypedDict</code></html> used for?

A: Defining the expected structure of a dictionary with specific keys and their types: <html><code>class Movie(TypedDict): title: str; year: int</code></html>. Added in Python 3.8.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.Required` and `typing.NotRequired` for TypedDict?]]
* [[What is `typing.TypeGuard` used for?]]
Q: What is <html><code>typing.overload</code></html> used for?

A: Declaring multiple type signatures for a single function, allowing type checkers to determine the return type based on the argument types. The decorated stubs are for type checking only.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.Final` used for?]]
* [[What is `typing.cast()` used for?]]
Q: What is <html><code>typing.Final</code></html> used for?

A: Declaring that a variable should not be reassigned: <html><code>MAX_SIZE: Final = 100</code></html>. A type checker will flag any subsequent reassignment.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.overload` used for?]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.Union` used for?]]
Q: What is <html><code>typing.Never</code></html> (Python 3.11) or <html><code>typing.NoReturn</code></html> used for?

A: <html><code>NoReturn</code></html> annotates functions that never return (they always raise an exception or run forever). <html><code>Never</code></html> (Python 3.11) is the bottom type — it also works for variables that should never have a value.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypeGuard` used for?]]
* [[What is `typing.get_type_hints()` used for?]]
* [[What is `typing.Annotated` used for?]]
Q: Can you use built-in types as generics since Python 3.9?

A: Yes. PEP 585 (Python 3.9) allows <html><code>list[int]</code></html>, <html><code>dict[str, int]</code></html>, <html><code>tuple[int, ...]</code></html> directly, making <html><code>typing.List</code></html>, <html><code>typing.Dict</code></html>, etc. redundant.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `type` statement in Python 3.12?]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What new generic syntax was introduced in Python 3.12?]]
Q: What is <html><code>typing.Annotated</code></html> used for?

A: Added in Python 3.9 (PEP 593), it attaches arbitrary metadata to [[type hints|Type hints]]: <html><code>Annotated[int, ValueRange(0, 100)]</code></html>. Libraries like Pydantic and FastAPI use this for validation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__annotations__` attribute?]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What PEP introduced type hints to Python?]]
Q: What is <html><code>typing.get_type_hints()</code></html> used for?

A: It resolves string annotations to actual types, handling forward references and <html><code>from __future__ import annotations</code></html>. More reliable than accessing <html><code>__annotations__</code></html> directly.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What PEP introduced type hints to Python?]]
* [[What is `typing.TypeGuard` used for?]]
* [[What is `typing.TypeVarTuple` used for?]]
Q: What is the <html><code>typing.Self</code></html> type, and when was it introduced?

A: Added in Python 3.11 (PEP 673), <html><code>Self</code></html> is used in method return annotations to indicate the method returns an instance of the enclosing class.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.Annotated` used for?]]
* [[What is `typing.get_type_hints()` used for?]]
Q: What does <html><code>typing.Unpack</code></html> do?

A: Added in Python 3.11, it is used for typing variadic generics with <html><code>TypeVarTuple</code></html>, enabling typed variable-length tuple types and <html><code>**kwargs</code></html> typing.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `TypeVar` used for?]]
* [[What is `typing.get_type_hints()` used for?]]
* [[What is `typing.TypeGuard` used for?]]
Q: What is <html><code>typing.runtime_checkable</code></html> used for?

A: It is a decorator for <html><code>Protocol</code></html> classes that allows <html><code>isinstance()</code></html> checks at runtime.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a `TYPE_CHECKING` guard?]]
* [[What is `typing.Callable` used for?]]
* [[What does `isinstance()` check that `type()` does not?]]
Q: What is PEP 649 about?

A: "Deferred Evaluation of Annotations" — an alternative to PEP 563 that evaluates annotations lazily on access rather than converting them to strings. Accepted for Python 3.14.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the significance of Python 3.6?]]
* [[What is `typing.Annotated` used for?]]
* [[What is the `__annotations__` attribute?]]
Q: What does PyPI stand for?

A: Python Package Index — the official repository for third-party Python packages, hosted at pypi.org.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[How do you install a package in Python?]]
* [[What is PyPy and why is it significant?]]
* [[What are historically the most downloaded packages on PyPI?]]
Q: Approximately how many packages are on PyPI as of 2025?

A: Over 500,000 packages.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are historically the most downloaded packages on PyPI?]]
* [[What does PyPI stand for?]]
* [[How do you install a package in Python?]]
Q: What are historically the most downloaded packages on PyPI?

A: <html><code>boto3</code></html>, <html><code>urllib3</code></html>, <html><code>botocore</code></html>, <html><code>requests</code></html>, <html><code>setuptools</code></html>, <html><code>certifi</code></html>, <html><code>charset-normalizer</code></html>, <html><code>idna</code></html>, <html><code>pip</code></html>, and <html><code>python-dateutil</code></html> are consistently among the top.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does PyPI stand for?]]
* [[What tool is the modern standard for building Python packages?]]
* [[How do you install a package in Python?]]
Q: What was the original name of <html><code>pip</code></html>?

A: <html><code>pip</code></html> is a recursive acronym: "pip installs packages" (originally "pip installs Python"). It replaced <html><code>easy_install</code></html> from <html><code>setuptools</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was `pip` first released?]]
* [[What is `pip install -e .` (editable install)?]]
* [[What is `pipx`?]]
Q: When was <html><code>pip</code></html> first released?

A: In 2008, created by Ian Bicking.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What was the original name of `pip`?]]
* [[What is `pip freeze` used for?]]
* [[What is `pipx`?]]
Q: What tool is the modern standard for building Python packages?

A: <html><code>build</code></html> (as in <html><code>python -m build</code></html>), using a <html><code>pyproject.toml</code></html> configuration. <html><code>setuptools</code></html> remains the most common build backend.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What file replaced `setup.py` and `setup.cfg` as the modern Python project configuratio…]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
* [[Multiple dependency declaration files create inconsistent builds]]
Q: What file replaced <html><code>setup.py</code></html> and <html><code>setup.cfg</code></html> as the modern Python project configuration standard?

A: <html><code>pyproject.toml</code></html>, standardized by PEP 518 (build system requirements) and PEP 621 (project metadata).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What tool is the modern standard for building Python packages?]]
* [[Multiple dependency declaration files create inconsistent builds]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
Q: What is <html><code>virtualenv</code></html> and why is it important?

A: It creates isolated Python environments with their own packages, preventing dependency conflicts between projects.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Never mix system and pip packages — use virtualenvs for applications]]
* [[System Python must use virtualenvs to prevent package conflicts]]
Q: What is a virtual environment in Python and why use it?

A: An isolated Python environment with its own installed packages, avoiding dependency conflicts between projects. Create with python -m venv .venv, activate with source .venv/bin/activate. Each venv has its own site-packages. Essential for reproducible builds — without one, pip install affects the system Python and can break other projects.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is the difference between `venv` and `virtualenv`?]]
* [[System Python must use virtualenvs to prevent package conflicts]]
* [[Never mix system and pip packages — use virtualenvs for applications]]
Q: What is the difference between <html><code>venv</code></html> and <html><code>virtualenv</code></html>?

A: <html><code>venv</code></html> is in the standard library but has fewer features. <html><code>virtualenv</code></html> is faster, supports more Python versions, has more configuration options, and can create environments for different interpreters.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a virtual environment in Python and why use it?]]
* [[What does `python -m venv myenv` do?]]
Q: What is <html><code>conda</code></html> and how does it differ from <html><code>pip</code></html>?

A: <html><code>conda</code></html> is a cross-platform package and environment manager that handles non-Python dependencies (C libraries, etc.). <html><code>pip</code></html> only manages Python packages.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `pipx`?]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
* [[What is `pip freeze` used for?]]
Q: What is <html><code>uv</code></html> in the Python ecosystem?

A: <html><code>uv</code></html> is an extremely fast Python package installer and resolver written in Rust by Astral (the makers of Ruff). It is a drop-in replacement for <html><code>pip</code></html> and <html><code>pip-tools</code></html>, often 10-100x faster.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `uvloop`?]]
* [[What ASGI server is commonly used with FastAPI?]]
* [[What does `python -O` do?]]
Q: What is <html><code>ruff</code></html>?

A: An extremely fast Python linter and code formatter written in Rust, created by Charlie Marsh / Astral. It aims to replace Flake8, isort, pyupgrade, and Black in a single tool.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `isort`?]]
* [[What is `uv` in the Python ecosystem?]]
* [[What is `maturin`?]]
Q: What is the <html><code>wheel</code></html> format?

A: A built distribution format (<html><code>.whl</code></html> files) introduced by PEP 427. Wheels are pre-built and install faster than source distributions because they don't require a build step.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Wheels are pre-built, sdists are source distributions]]
* [[What is the `wheel` filename convention?]]
Q: What is Black?

A: An opinionated Python code formatter that enforces a consistent style with minimal configuration. Its motto is "the uncompromising code formatter."

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[How does Python define code blocks?]]
* [[What is `__format__` used for?]]
* [[What is a Python "magic comment" for encoding?]]
Q: What is a PEP 517 build backend?

A: A system that builds Python packages according to the standard defined in PEP 517. Examples include <html><code>setuptools</code></html>, <html><code>flit-core</code></html>, <html><code>hatchling</code></html>, and <html><code>maturin</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What tool is the modern standard for building Python packages?]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
* [[What is PEP 703 (free-threading)?]]
Q: What is <html><code>pyenv</code></html>?

A: A tool for managing multiple Python versions on the same machine. It lets you install and switch between different Python versions per-project or globally.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m venv myenv` do?]]
* [[What is `virtualenv` and why is it important?]]
* [[What is a virtual environment in Python and why use it?]]
<html><code>pyenv</code></html> is the standard tool for dev machines: install multiple Python versions and set a global default or per-project version via <html><code>.python-version</code></html> in the project root. On servers without pyenv, use <html><code>update-alternatives</code></html> (Debian/Ubuntu) to configure <html><code>python3</code></html> to point to different installed versions, or add newer versions from the deadsnakes PPA if the distro default is too old. Once multiple versions are available, create virtualenvs for the specific version needed: <html><code>python3.12 -m venv .venv312</code></html>. The key pattern: install multiple Python versions at the system level, then always use virtualenvs for isolated project dependencies. This avoids polluting system Python and allows different projects to target different versions without interference. CI pipelines can test against multiple versions by installing all needed versions and running tests in each venv. Version management becomes transparent when paired with virtualenvs—projects can declare their requirements without affecting other projects.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>

''Related atoms''
* [[System Python must use virtualenvs to prevent package conflicts]]
* [[Mixing system packages and pip creates version conflicts]]
* [[Never mix system and pip packages — use virtualenvs for applications]]
Q: What is <html><code>pipx</code></html>?

A: A tool for installing Python CLI applications in isolated environments. Each application gets its own virtualenv, preventing dependency conflicts between tools.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
* [[What is a virtual environment in Python and why use it?]]
* [[System Python must use virtualenvs to prevent package conflicts]]
Q: What is <html><code>poetry</code></html>?

A: A Python dependency management and packaging tool that uses <html><code>pyproject.toml</code></html>, provides deterministic builds via a lock file, and manages virtual environments.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is YAML handling in Python?]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
* [[What does `python -v` do?]]
Q: What is <html><code>hatch</code></html>?

A: A modern Python project manager and build backend. It manages environments, builds packages, publishes to PyPI, and runs scripts.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a PEP 517 build backend?]]
* [[What does PyPI stand for?]]
* [[What is the `pydoc` module?]]
Q: What is <html><code>maturin</code></html>?

A: A build tool for Rust-based Python extensions (PyO3/cffi). It compiles Rust code into Python-installable wheels.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a PEP 517 build backend?]]
* [[What is `hatch`?]]
* [[What is `cffi` (C Foreign Function Interface)?]]
Q: What is <html><code>isort</code></html>?

A: A tool that automatically sorts Python imports alphabetically and separates them into sections (stdlib, third-party, local). Now largely superseded by ruff.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `ruff`?]]
* [[What module provides functions to maintain a list in sorted order without having to sor…]]
* [[What does `datetime.datetime.fromisoformat()` parse?]]
Q: What is <html><code>pre-commit</code></html>?

A: A framework for managing and running git pre-commit hooks. It can run linters, formatters, and other checks automatically before each commit.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
Q: What is pytest's key advantage over unittest?

A: Simpler syntax — tests are plain functions with <html><code>assert</code></html> statements instead of requiring classes and <html><code>self.assertEqual()</code></html> methods. It also has a powerful fixture system and plugin ecosystem.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `pytest.fixture` do?]]
* [[What is `pytest.approx()` used for?]]
* [[What are pytest marks?]]
Q: What does <html><code>pytest.fixture</code></html> do?

A: It defines reusable test setup/teardown functions that are injected into test functions by name. Fixtures can have different scopes (function, class, module, session).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is pytest's `tmp_path` fixture?]]
* [[What is `conftest.py` in pytest?]]
* [[What is pytest's key advantage over unittest?]]
Q: What is <html><code>pytest.mark.parametrize</code></html> used for?

A: Running the same test with multiple sets of inputs: <html><code>@pytest.mark.parametrize("input,expected", [(1,2), (3,4)])</code></html> runs the test twice with different arguments.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are pytest marks?]]
* [[What is `ParamSpec` used for?]]
* [[What does the `*` separator in function parameters do?]]
Q: What is Hypothesis?

A: A property-based testing library for Python (inspired by Haskell's QuickCheck). It generates random test inputs based on strategies and finds edge cases automatically.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `coverage.py` used for?]]
* [[What does if __name__ == "__main__": do?]]
* [[What is PyData?]]
Q: What is tox?

A: A tool for automating testing across multiple Python versions and environments. It creates virtualenvs and runs test commands in each.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is nox?]]
* [[What is `pipx`?]]
* [[What is a virtual environment in Python and why use it?]]
Q: What is nox?

A: Similar to tox but uses Python scripts instead of INI configuration files for defining test sessions. Created by Thea Flowers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is tox?]]
Q: What is <html><code>unittest.mock.patch</code></html> used for?

A: Temporarily replacing an object with a mock during testing. It can be used as a decorator or context manager: <html><code>@patch('module.ClassName')</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `unittest.mock.MagicMock`?]]
* [[What is `unittest.mock.sentinel`?]]
* [[What is `unittest.TestCase.setUp()` vs `setUpClass()`?]]
Q: What is <html><code>unittest.mock.MagicMock</code></html>?

A: A mock object that implements most magic methods automatically. It records calls and allows you to set return values and assert how it was used.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `unittest.mock.patch` used for?]]
* [[What is `unittest.mock.sentinel`?]]
* [[What is `unittest.TestCase.setUp()` vs `setUpClass()`?]]
Q: What is doctest?

A: A module that tests code examples embedded in docstrings by running them and comparing output. It serves double duty as documentation and tests.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__doc__`?]]
Q: What is <html><code>coverage.py</code></html> used for?

A: Measuring code coverage — what percentage of your code is executed during testing. It can report line coverage, branch coverage, and generate HTML reports.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m py_compile script.py` do?]]
* [[What is the `__main__.py` file for?]]
* [[What is `conftest.py` in pytest?]]
Q: What are pytest marks?

A: Decorators that categorize tests: <html><code>@pytest.mark.slow</code></html>, <html><code>@pytest.mark.skip</code></html>, <html><code>@pytest.mark.xfail</code></html>. Custom marks allow running subsets of tests with <html><code>-m</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `pytest.mark.parametrize` used for?]]
* [[What is pytest's key advantage over unittest?]]
* [[What is pytest's `tmp_path` fixture?]]
Q: What is <html><code>conftest.py</code></html> in pytest?

A: A special file where you define fixtures, hooks, and plugins that are automatically available to all tests in the same directory and subdirectories. No import needed.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is pytest's `tmp_path` fixture?]]
* [[What does `pytest.fixture` do?]]
Q: What is pytest's <html><code>tmp_path</code></html> fixture?

A: A built-in fixture that provides a temporary directory unique to each test invocation. It returns a <html><code>pathlib.Path</code></html> object.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `pytest.fixture` do?]]
* [[What is `conftest.py` in pytest?]]
* [[What are pytest marks?]]
Q: What is <html><code>pytest.raises</code></html>?

A: A context manager that asserts an exception is raised: <html><code>with pytest.raises(ValueError):</code></html>. It also allows inspecting the exception via <html><code>excinfo.value</code></html>.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `raise` without an argument do?]]
* [[What is exception chaining in Python?]]
* [[What are exception groups, introduced in Python 3.11?]]
Q: What is Django's primary design philosophy?

A: "The web framework for perfectionists with deadlines." It follows the "batteries included" philosophy with an ORM, admin interface, authentication, templating, and more built-in.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the Django admin?]]
* [[What design pattern does Django follow?]]
* [[What template engine does Django use by default?]]
Q: What design pattern does Django follow?

A: Model-Template-View (MTV), which is Django's variation of MVC. Models define data, Templates handle presentation, and Views contain business logic.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What template engine does Django use by default?]]
* [[What is Django's primary design philosophy?]]
* [[What are metaclasses and when would you use them?]]
Q: What is Django's ORM?

A: An Object-Relational Mapper that lets you define database models as Python classes and query databases using Python code instead of raw SQL.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the Django admin?]]
* [[What is Django's `manage.py`?]]
* [[What are metaclasses and when would you use them?]]
Q: When was Django first released?

A: July 2005. It was originally developed at the Lawrence Journal-World newspaper in Lawrence, Kansas.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Who created Django?]]
* [[When was Python 0.9.0 first released publicly?]]
* [[When was Python 1.0 released?]]
Q: Who created Django?

A: Adrian Holovaty and Simon Willison at the Lawrence Journal-World, a newspaper in Lawrence, Kansas.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was Django first released?]]
* [[What is the Django admin?]]
* [[What is Django's primary design philosophy?]]
Q: What does Flask call itself?

A: A "micro" web framework. It provides the core (routing, request/response handling, templating via Jinja2) but leaves choices like ORM and authentication to extensions.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What WSGI toolkit does Flask use under the hood?]]
* [[What is Jinja2?]]
* [[What is Flask's `g` object?]]
Q: Who created Flask?

A: Armin Ronacher, as part of the Pallets project. It was originally an April Fools' joke in 2010 that became wildly popular.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does Flask call itself?]]
* [[What WSGI toolkit does Flask use under the hood?]]
* [[What is Click?]]
Q: What WSGI toolkit does Flask use under the hood?

A: Werkzeug (German for "tool") for WSGI utilities and request/response handling.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does Flask call itself?]]
* [[What is Gunicorn?]]
* [[What template engine does Django use by default?]]
Q: What is FastAPI's key distinguishing feature?

A: Automatic API documentation (Swagger UI and ReDoc) generated from Python [[type hints|Type hints]], along with automatic request validation using Pydantic models.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What framework is FastAPI built on top of?]]
* [[What is `typing.Annotated` used for?]]
* [[What is Pydantic v2's key change from v1?]]
Q: What ASGI server is commonly used with FastAPI?

A: Uvicorn, which is based on <html><code>uvloop</code></html> and <html><code>httptools</code></html> for high performance.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What framework is FastAPI built on top of?]]
* [[Who is the current fastest growing Python web framework (as of 2025)?]]
* [[What is Starlette?]]
Q: What is the difference between WSGI and ASGI?

A: WSGI (Web Server Gateway Interface) is synchronous — one request per thread. ASGI (Asynchronous Server Gateway Interface) supports async, WebSockets, and long-lived connections.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What WSGI toolkit does Flask use under the hood?]]
* [[What ASGI server is commonly used with FastAPI?]]
* [[What is the difference between concurrency and parallelism in Python?]]
Q: What framework is FastAPI built on top of?

A: Starlette (for the web parts) and Pydantic (for data validation).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Who is the current fastest growing Python web framework (as of 2025)?]]
* [[What is Starlette?]]
* [[What is FastAPI's key distinguishing feature?]]
Q: What is Tornado known for?

A: Being one of the first Python async web frameworks (originally from FriendFeed/Facebook, released 2009). It has its own event loop and is designed for long-polling and WebSockets.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `asyncio.run()` used for?]]
* [[What are Python "lightning talks"?]]
* [[What does Flask call itself?]]
Q: What is Bottle's claim to fame?

A: It is a single-file micro web framework with no dependencies outside the standard library — the entire framework is one Python file.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does Flask call itself?]]
* [[Who is the current fastest growing Python web framework (as of 2025)?]]
* [[Who created Flask?]]
Q: What is AIOHTTP?

A: An async HTTP client/server framework built on <html><code>asyncio</code></html>. It serves as both a web server framework and an HTTP client library.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `aiofiles`?]]
* [[What is `asyncio.Semaphore` used for?]]
* [[What is `asyncio.Queue`?]]
Q: What is Sanic?

A: An async Python web framework designed for speed, similar to Flask's API but fully async.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is MicroPython?]]
* [[What is `asyncio.create_task()` vs `await`?]]
* [[Who is the current fastest growing Python web framework (as of 2025)?]]
Q: What is Litestar (formerly Starlite)?

A: A high-performance ASGI framework with an emphasis on being opinionated, having built-in dependency injection, and supporting multiple serialization libraries beyond Pydantic.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Starlette?]]
* [[What framework is FastAPI built on top of?]]
* [[What ASGI server is commonly used with FastAPI?]]
Q: Who is the current fastest growing Python web framework (as of 2025)?

A: FastAPI, created by Sebastian Ramirez in 2018. It became one of the most starred Python frameworks on GitHub within a few years.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What framework is FastAPI built on top of?]]
* [[What ASGI server is commonly used with FastAPI?]]
* [[What performance improvement was made in Python 3.11?]]
Q: What is Gunicorn?

A: A popular WSGI HTTP server for Unix. It uses a pre-fork worker model and is commonly deployed with Django or Flask behind Nginx.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What WSGI toolkit does Flask use under the hood?]]
* [[What is Django's `manage.py`?]]
* [[What template engine does Django use by default?]]
Q: What is the Django admin?

A: An automatically generated web-based admin interface for managing data. It introspects your models and creates CRUD pages with minimal configuration.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Django's `manage.py`?]]
* [[What is Django's primary design philosophy?]]
* [[What is Django's ORM?]]
Q: What does NumPy stand for?

A: Numerical Python.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does SciPy provide that NumPy does not?]]
* [[What is NumPy's `dtype`?]]
* [[What is broadcasting in NumPy?]]
Q: What is the core data structure in NumPy?

A: The <html><code>ndarray</code></html> (n-dimensional array), a fixed-size, homogeneous, contiguous block of memory that enables fast vectorized operations.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does SciPy provide that NumPy does not?]]
* [[Why are NumPy operations faster than Python loops?]]
* [[What is NumPy's `dtype`?]]
Q: Why are NumPy operations faster than Python loops?

A: NumPy operations are implemented in C and operate on contiguous memory arrays, avoiding Python's per-element type checking and interpreter overhead. This is called vectorization.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does SciPy provide that NumPy does not?]]
* [[What does NumPy stand for?]]
* [[Why are tuples slightly faster than lists?]]
Q: What is broadcasting in NumPy?

A: A set of rules that allows NumPy to perform operations on arrays of different shapes by automatically expanding the smaller array.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does NumPy stand for?]]
* [[What does SciPy provide that NumPy does not?]]
* [[What is the difference between NumPy's `np.array()` and `np.asarray()`?]]
Q: What is a Pandas DataFrame?

A: A 2D labeled data structure with columns of potentially different types, similar to a spreadsheet or SQL table.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `pandas.read_csv()` do?]]
* [[What is Pandas `groupby()` used for?]]
* [[What does `pandas.DataFrame.merge()` do?]]
Q: What is a Pandas Series?

A: A 1D labeled array — essentially a single column of a DataFrame. It can hold any data type.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Pandas `groupby()` used for?]]
* [[What does `pandas.read_csv()` do?]]
* [[What is the `apply()` method in Pandas?]]
Q: What does <html><code>pandas.read_csv()</code></html> do?

A: It reads a CSV file into a DataFrame. It has dozens of parameters for handling different delimiters, encodings, missing values, data types, and more.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `csv` module?]]
* [[What is a Pandas DataFrame?]]
* [[What does `pandas.DataFrame.merge()` do?]]
Q: What is Matplotlib's <html><code>pyplot</code></html> interface?

A: A MATLAB-like procedural interface for creating plots, accessed as <html><code>matplotlib.pyplot</code></html> (commonly imported as <html><code>plt</code></html>).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Who created Matplotlib and why?]]
* [[What is seaborn?]]
* [[What is the `graphlib` module?]]
Q: Who created Matplotlib and why?

A: John D. Hunter created it in 2003 to emulate MATLAB's plotting capabilities in Python, so he could do his epilepsy research without a MATLAB license.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Matplotlib's `pyplot` interface?]]
* [[What is seaborn?]]
* [[What is the `pathlib` module and when was it introduced?]]
Q: What is seaborn?

A: A statistical data visualization library built on top of Matplotlib that provides a higher-level interface for creating attractive statistical graphics.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Matplotlib's `pyplot` interface?]]
* [[Who created Matplotlib and why?]]
* [[What does the `statistics` module provide?]]
Q: What does SciPy provide that NumPy does not?

A: Higher-level scientific computing algorithms: optimization, integration, interpolation, signal processing, linear algebra decompositions, sparse matrices, spatial data structures, and statistics.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does NumPy stand for?]]
* [[Why are NumPy operations faster than Python loops?]]
* [[What is `scipy.optimize.minimize()`?]]
Q: What is scikit-learn?

A: The most widely used Python machine learning library, providing consistent APIs for classification, regression, clustering, dimensionality reduction, model selection, and preprocessing.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What API convention does scikit-learn follow?]]
* [[What does SciPy provide that NumPy does not?]]
* [[What is Python Fire?]]
Q: What API convention does scikit-learn follow?

A: The <html><code>fit</code></html>/<html><code>predict</code></html>/<html><code>transform</code></html> pattern: <html><code>model.fit(X_train, y_train)</code></html> trains, <html><code>model.predict(X_test)</code></html> predicts, and transformers use <html><code>transform()</code></html> or <html><code>fit_transform()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is scikit-learn?]]
* [[What is the `@typing.dataclass_transform` decorator?]]
* [[What does the `__future__` module do?]]
Q: What is Jupyter's name derived from?

A: The three core programming languages it supports: ''Ju''lia, ''Py''thon, and ''R''. It evolved from IPython Notebook.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a Jupyter kernel?]]
* [[Why is the language called "Python"?]]
* [[What is CPython?]]
Q: What Python library has become the standard for data validation and settings management?

A: Pydantic, which uses Python type annotations for runtime data validation, serialization, and deserialization.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Name three Python static type checkers besides mypy.]]
* [[Name five alternative Python implementations.]]
* [[What tool is the modern standard for building Python packages?]]
Q: What is Polars?

A: A fast DataFrame library written in Rust with a Python interface. It is designed as a more performant alternative to Pandas, with lazy evaluation and better multi-threaded performance.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a Pandas DataFrame?]]
* [[What is seaborn?]]
* [[What is a Pandas Series?]]
Q: What is the difference between Pandas and Polars?

A: Pandas uses NumPy arrays internally and runs single-threaded. Polars uses Apache Arrow memory format, supports lazy evaluation, and automatically parallelizes operations across CPU cores.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a Pandas DataFrame?]]
* [[What is a Pandas Series?]]
* [[What is the difference between concurrency and parallelism in Python?]]
Q: What happens when you run <html><code>import this</code></html> in Python?

A: It prints "The Zen of Python" — 19 aphorisms by Tim Peters that capture Python's design philosophy.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why does `import this` have 19 aphorisms when The Zen of Python was supposed to have 20?]]
* [[What does `import __hello__` do?]]
* [[What does the `import` statement do in Python?]]
Q: What is <html><code>python -m this</code></html>?

A: It prints The Zen of Python, same as <html><code>import this</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__main__.py` file for?]]
* [[What PEP number is "The Zen of Python"?]]
* [[What does `python -m py_compile script.py` do?]]
Q: Who wrote The Zen of Python?

A: Tim Peters, a major early contributor to Python and author of the Timsort algorithm.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What PEP number is "The Zen of Python"?]]
* [[What is `python -m this`?]]
* [[What are all 19 aphorisms of The Zen of Python?]]
Q: Why does <html><code>import this</code></html> have 19 aphorisms when The Zen of Python was supposed to have 20?

A: Tim Peters intentionally left the 20th aphorism blank for Guido to fill in — he never did.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What happens when you run `import this` in Python?]]
* [[What is `python -m this`?]]
* [[What PEP number is "The Zen of Python"?]]
Q: What is the Easter egg hidden in the source code of the <html><code>this</code></html> module?

A: The Zen text is stored as a ROT13-encoded string and decoded at import time. The module itself is a playful example of obfuscated code — contradicting the very principles it espouses.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What happens when you run `import this` in Python?]]
* [[What is `python -m this`?]]
Q: What are all 19 aphorisms of The Zen of Python?

A: 1. Beautiful is better than ugly. 2. Explicit is better than implicit. 3. Simple is better than complex. 4. Complex is better than complicated. 5. Flat is better than nested. 6. Sparse is better than dense. 7. Readability counts. 8. Special cases aren't special enough to break the rules. 9. Although practicality beats purity. 10. Errors should never pass silently. 11. Unless explicitly silenced. 12. In the face of ambiguity, refuse the temptation to guess. 13. There should be one -- and preferably only one -- obvious way to do it. 14. Although that way may not be obvious at first unless you're Dutch. 15. Now is better than never. 16. Although never is often better than //right// now. 17. If the implementation is hard to explain, it's a bad idea. 18. If the implementation is easy to explain, it may be a good idea. 19. Namespaces are one honking great idea -- let's do more of those!

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Which Zen aphorism is often cited to argue against Java-style getter/setter methods in …]]
* [[Why does `import this` have 19 aphorisms when The Zen of Python was supposed to have 20?]]
* [[Who wrote The Zen of Python?]]
Q: Which Zen aphorism is often cited to argue against Java-style getter/setter methods in Python?

A: "Simple is better than complex" and "There should be one -- and preferably only one -- obvious way to do it."

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are all 19 aphorisms of The Zen of Python?]]
* [[What is the `property` built-in?]]
* [[Who wrote The Zen of Python?]]
Q: Which Zen aphorism is the "Dutch" one a reference to?

A: "Although that way may not be obvious at first unless you're Dutch" — a reference to Guido van Rossum being Dutch.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Which Zen aphorism is often cited to argue against Java-style getter/setter methods in …]]
* [[Why does `import this` have 19 aphorisms when The Zen of Python was supposed to have 20?]]
* [[What are all 19 aphorisms of The Zen of Python?]]
Q: What is the significance of <html><code>antigravity</code></html> in Python?

A: <html><code>import antigravity</code></html> opens the classic XKCD comic #353 about Python in a web browser.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `antigravity` module's geohash feature?]]
* [[What is the significance of Python 3.6?]]
* [[What Monty Python references exist in the Python stdlib?]]
Q: What does <html><code>import __hello__</code></html> do?

A: It prints "Hello world!".

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `import` statement do in Python?]]
* [[What is `__import__` hook?]]
* [[What is `__name__` set to when a module is imported?]]
Q: What happens if you type <html><code>from __future__ import braces</code></html> in Python?

A: You get <html><code>SyntaxError: not a chance</code></html> — a humorous rejection of curly-brace syntax.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `__future__` module do?]]
* [[What happens when you run `import this` in Python?]]
* [[What is a "Syntax Error"?]]
Q: What happens when you multiply a list: <html><code>[[]] * 3</code></html>?

A: You get <html><code>[[], [], []]</code></html>, but all three inner lists are the SAME object. Modifying one modifies all: <html><code>a = [[]] * 3; a[0].append(1)</code></html> gives <html><code>[[1], [1], [1]]</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `[] is []`?]]
* [[What does `[1, 2, 3][::-1]` return?]]
* [[What is the difference between `list.copy()` and `list[:]`?]]
Q: What is the output of <html><code>round(0.5)</code></html> and <html><code>round(1.5)</code></html> in Python 3?

A: <html><code>round(0.5)</code></html> gives <html><code>0</code></html> and <html><code>round(1.5)</code></html> gives <html><code>2</code></html>. Python 3 uses "banker's rounding" (round half to even).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why does `0.1 + 0.2 != 0.3` in Python?]]
* [[What is the output of `print(0.1 + 0.2)`?]]
* [[What is `decimal.Decimal` vs `float` for financial calculations?]]
Q: What is the <html><code>decimal</code></html> module's <html><code>ROUND_HALF_EVEN</code></html> rounding mode?

A: Banker's rounding — rounds to the nearest even number when the value is exactly halfway. This is the default rounding mode for <html><code>Decimal</code></html> and Python's built-in <html><code>round()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module provides arbitrary-precision decimal arithmetic?]]
* [[Which operator gives the remainder of division?]]
* [[Why does `0.1 + 0.2 != 0.3` in Python?]]
Q: What is the WAT moment with <html><code>hash(-1)</code></html> and <html><code>hash(-2)</code></html> in CPython?

A: <html><code>hash(-1) == hash(-2)</code></html> is <html><code>True</code></html>. CPython's hash function maps -1 to -2 internally because -1 is used as an error indicator in the C implementation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `hash(float('inf'))` return?]]
* [[What is the WAT moment with tuple addition?]]
* [[What is the small integer cache in CPython?]]
Q: What does <html><code>hash(-1)</code></html> return in CPython?

A: <html><code>-2</code></html>. CPython's C-level hash function uses -1 as an error indicator, so it maps the hash value -1 to -2.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `hash(float('inf'))` return?]]
* [[What is the small integer cache in CPython?]]
* [[What does `__hash__` need to be consistent with?]]
Q: What is the WAT moment with <html><code>[] == False</code></html>?

A: <html><code>[] == False</code></html> is <html><code>False</code></html>. An empty list is falsy (<html><code>bool([])</code></html> is <html><code>False</code></html>), but <html><code>==</code></html> compares by value, and a list does not equal a boolean.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `bool([])`?]]
* [[What is the result of `[] is []`?]]
* [[Truthy and falsy values]]
Q: What is the <html><code>antigravity</code></html> module's geohash feature?

A: <html><code>antigravity.geohash(lat, lon, date)</code></html> generates a random location using the XKCD geohashing algorithm (comic #426). It was added as a secondary Easter egg.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the significance of `antigravity` in Python?]]
* [[What does `math.gcd()` compute?]]
Q: What does <html><code>import __phello__</code></html> do in Python 3.12+?

A: It prints "Hello world!" — a frozen "hello world" package added as part of the frozen module infrastructure.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `import` statement do in Python?]]
* [[What is `__import__` hook?]]
* [[What happens when you run `import this` in Python?]]
Q: What is the WAT moment with tuple addition?

A: <html><code>() + ()</code></html> gives <html><code>()</code></html>. But <html><code>(1,) + (2,)</code></html> gives <html><code>(1, 2)</code></html>. The trailing comma is required for single-element tuples: <html><code>(1)</code></html> is just the integer <html><code>1</code></html>, not a tuple.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Tuple operations]]
* [[What is a tuple and how does it differ from a list?]]
* [[What is the WAT moment with `[] == False`?]]
Q: What is the surprising behavior of <html><code>is</code></html> with short strings?

A: Due to string interning, <html><code>a = 'hello'; b = 'hello'; a is b</code></html> is <html><code>True</code></html>. But <html><code>a = 'hello world'; b = 'hello world'; a is b</code></html> may be <html><code>False</code></html> because strings with spaces are not automatically interned.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.intern(string)` do?]]
* [[What is the difference between `is` and `==` in Python?]]
* [[Does Python intern strings?]]
Q: What is boto3?

A: The official AWS SDK for Python. It provides low-level client interfaces and higher-level resource interfaces for AWS services.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between boto3 client and resource interfaces?]]
* [[boto3 accesses AWS APIs with proper error handling and pagination]]
* [[Diagnostic commands for Python infrastructure debugging]]
Q: What is the difference between boto3 client and resource interfaces?

A: Client provides a low-level, 1:1 mapping to AWS API operations. Resource provides a higher-level, object-oriented interface. Client is more complete; resource is more Pythonic.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is boto3?]]
* [[boto3 accesses AWS APIs with proper error handling and pagination]]
Q: What is paramiko?

A: A Python library implementing SSHv2. It provides both client and server functionality for SSH connections, file transfers (SFTP), and remote command execution.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[paramiko enables SSH automation with connection lifecycle management]]
* [[What is Fabric?]]
Q: What is Fabric?

A: A library for executing shell commands remotely over SSH. Built on top of paramiko and Invoke, it is commonly used for deployment automation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is paramiko?]]
Q: What is Invoke?

A: A task execution library — a Pythonic replacement for Make. It provides a clean API for running shell commands and organizing task functions.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `subprocess.run()` function?]]
Q: What is Click?

A: A Python package by the Pallets Project (same team as Flask) for creating command-line interfaces using decorators.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Click structures CLI tools with validation and subcommands]]
* [[What WSGI toolkit does Flask use under the hood?]]
* [[What is Typer?]]
Q: What is Typer?

A: A CLI library by Sebastian Ramirez (FastAPI author) built on top of Click that uses Python [[type hints|Type hints]] for argument parsing.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.get_type_hints()` used for?]]
* [[What PEP introduced type hints to Python?]]
* [[What is `typing.TypeVarTuple` used for?]]
Q: What is Python Fire?

A: A Google library that automatically generates CLI interfaces from any Python object (function, class, module, dict).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Python and what makes it popular for DevOps and scripting?]]
* [[What are first-class functions?]]
* [[What is a code object in Python?]]
Q: What is the standard library module for parsing command-line arguments?

A: <html><code>argparse</code></html> (since Python 3.2, replacing the older <html><code>optparse</code></html>).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Click structures CLI tools with validation and subcommands]]
* [[What is `argparse.FileType`?]]
* [[What does `sys.argv` contain?]]
Q: What does <html><code>argparse.ArgumentParser.add_subparsers()</code></html> do?

A: Creates subcommands (like <html><code>git commit</code></html>, <html><code>git push</code></html>), where each subcommand has its own set of arguments.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `argparse.FileType`?]]
* [[What does `sys.argv` contain?]]
* [[What is the standard library module for parsing command-line arguments?]]
Q: What is Rich?

A: A Python library for rich text and formatting in the terminal. It provides syntax highlighting, tables, progress bars, tracebacks, markdown rendering, and more.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Python and what makes it popular for DevOps and scripting?]]
* [[What new REPL was introduced in Python 3.13?]]
* [[What major features were added in Python 3.13?]]
Q: What is httpx?

A: A modern HTTP client for Python that supports both sync and async requests, HTTP/2, and has an API similar to <html><code>requests</code></html>. It is the async-capable successor to <html><code>requests</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `requests` library?]]
* [[What is the `http.server` module used for?]]
Q: What is the <html><code>requests</code></html> library?

A: The most popular Python HTTP client library, known for its simple API: <html><code>requests.get(url)</code></html>. Created by Kenneth Reitz.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is httpx?]]
* [[What is the `http.server` module used for?]]
* [[What is `urllib.parse.urlencode()` used for?]]
Q: Why should you never use <html><code>shell=True</code></html> with <html><code>subprocess</code></html> when handling user input?

A: It enables shell injection attacks. User input could contain shell metacharacters that execute arbitrary commands. Always pass arguments as a list instead.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the safer way to use `subprocess`?]]
* [[Passing interpolated strings to shell=True allows command injection]]
Q: What is the safer way to use <html><code>subprocess</code></html>?

A: Use <html><code>subprocess.run(['cmd', 'arg1', 'arg2'])</code></html> with a list of arguments instead of a shell string. This avoids shell injection vulnerabilities.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why should you never use `shell=True` with `subprocess` when handling user input?]]
* [[What is the `subprocess.run()` function?]]
Q: What is Jinja2?

A: A template engine for Python used by Flask, Ansible, and many other tools. It supports template [[inheritance|Inheritance]], macros, filters, and auto-escaping.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What template engine does Django use by default?]]
* [[What does Flask call itself?]]
Q: What is <html><code>shlex.split()</code></html> used for?

A: Splitting a shell command string into a list of arguments using shell-like syntax. Useful for converting <html><code>"cmd --flag 'arg with spaces'"</code></html> into <html><code>['cmd', '--flag', 'arg with spaces']</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
Q: What is YAML handling in Python?

A: The <html><code>pyyaml</code></html> library is the standard. Use <html><code>yaml.safe_load()</code></html> (not <html><code>yaml.load()</code></html>) to avoid arbitrary code execution from untrusted YAML.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[JSON and YAML]]
Q: What is <html><code>ansible-runner</code></html>?

A: A Python library that provides a programmatic interface for running Ansible playbooks, roles, and tasks from Python code.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
Q: What is the difference between <html><code>__str__</code></html> and <html><code>__repr__</code></html>?

A: <html><code>__repr__</code></html> should return an unambiguous string representation (ideally valid Python to recreate the object). <html><code>__str__</code></html> should return a readable, user-friendly string. <html><code>__repr__</code></html> is used in the REPL; <html><code>__str__</code></html> is used by <html><code>print()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `bytes` and `str` in Python 3?]]
* [[What is __repr__ vs __str__?]]
* [[What is the Python REPL's `_` variable?]]
Q: What is <html><code>__format__</code></html> used for?

A: It is called by <html><code>format()</code></html> and f-strings to customize how an object is formatted. For example, <html><code>datetime</code></html> objects use it to support format codes like <html><code>f'{dt:%Y-%m-%d}'</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are the three string formatting approaches in Python?]]
* [[What does `str.format_map()` do?]]
* [[What is the `__annotations__` attribute?]]
Q: What does <html><code>__hash__</code></html> need to be consistent with?

A: <html><code>__eq__</code></html>. Objects that compare equal must have the same hash. If you define <html><code>__eq__</code></html>, Python sets <html><code>__hash__</code></html> to <html><code>None</code></html> (making instances unhashable) unless you also define <html><code>__hash__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.abc.Hashable`?]]
* [[What is the difference between == and is in Python?]]
Q: What is <html><code>__getattr__</code></html> vs <html><code>__getattribute__</code></html>?

A: <html><code>__getattribute__</code></html> is called for every attribute access. <html><code>__getattr__</code></html> is only called when normal attribute lookup fails. Overriding <html><code>__getattribute__</code></html> is risky and can easily cause infinite recursion.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `getattr(obj, name, default)` used for?]]
* [[What is `hasattr(obj, name)` equivalent to?]]
* [[Explain name mangling with double underscores]]
Q: What is <html><code>__missing__</code></html> used for?

A: It is called by <html><code>dict.__getitem__()</code></html> when a key is not found. <html><code>defaultdict</code></html> uses this to generate default values. You can override it in dict subclasses.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the default value returned by a `defaultdict(list)` for a missing key?]]
* [[What method does `defaultdict` call to produce a default value?]]
* [[What is `dict.setdefault(key, default)`?]]
Q: What is the <html><code>__contains__</code></html> method?

A: It implements the <html><code>in</code></html> operator: <html><code>x in obj</code></html> calls <html><code>obj.__contains__(x)</code></html>. If not defined, Python falls back to iterating through <html><code>__iter__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `__iter__` method return?]]
* [[What is `str.isidentifier()`?]]
* [[What is `__iter__` vs `__getitem__` for iteration?]]
Q: What method makes an object callable?

A: <html><code>__call__</code></html>. If a class defines <html><code>__call__</code></html>, its instances can be called like functions: <html><code>obj()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.Callable` used for?]]
* [[What is `object.__new__`?]]
* [[What is a code object in Python?]]
Q: What is <html><code>__len__</code></html> used for?

A: It implements <html><code>len(obj)</code></html>. It should return a non-negative integer. An object with <html><code>__len__</code></html> is also considered falsy if <html><code>__len__</code></html> returns 0 (unless <html><code>__bool__</code></html> is defined).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__bool__` method?]]
* [[What is the truthiness rule in Python?]]
* [[What is `__format__` used for?]]
Q: What does the len() function do?

A: Returns the number of items in an object — works on strings, lists, tuples, dicts, sets, and any object implementing __len__. 
Example: len("hello") returns 5, len([1,2,3]) returns 
# Calling len on an object that does not support it raises TypeError.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What does `sys.getsizeof(())` vs `sys.getsizeof([])` show?]]
* [[What is the `Ellipsis` object (`...`) used for in Python?]]
* [[What is duck typing and how does Python use it?]]
Q: What is a context manager protocol?

A: Any object that implements <html><code>__enter__</code></html> and <html><code>__exit__</code></html> methods. <html><code>__enter__</code></html> is called at the start of a <html><code>with</code></html> block, and <html><code>__exit__</code></html> is called at the end.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `contextlib.closing()` used for?]]
* [[What is the `__aenter__` and `__aexit__` protocol?]]
* [[What is `contextlib.ExitStack` used for?]]
Q: What arguments does <html><code>__exit__</code></html> receive?

A: Three arguments: <html><code>exc_type</code></html>, <html><code>exc_val</code></html>, and <html><code>exc_tb</code></html> (exception type, value, and traceback). If no exception occurred, all are <html><code>None</code></html>. Returning <html><code>True</code></html> suppresses the exception.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.exc_info()` used for?]]
* [[What does `sys.exit()` actually raise?]]
Q: What is a <html><code>__fspath__</code></html> method?

A: Added in Python 3.6, it allows objects to represent filesystem paths. <html><code>os.fspath()</code></html> calls it. <html><code>pathlib.Path</code></html> implements it.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `os.walk()` used for?]]
* [[What is `pathlib.Path.glob()` used for?]]
* [[What is the `pathlib` module and when was it introduced?]]
Q: What is <html><code>__del__</code></html> used for?

A: It is a finalizer called when an object is about to be garbage collected. It is unreliable for cleanup because you cannot predict when (or if) it will be called. Use context managers instead.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `del` statement?]]
* [[What is `contextlib.ExitStack` used for?]]
Q: What is <html><code>__eq__</code></html> and <html><code>__ne__</code></html>?

A: <html><code>__eq__</code></html> implements <html><code>==</code></html>, <html><code>__ne__</code></html> implements <html><code>!=</code></html>. By default, <html><code>__ne__</code></html> delegates to <html><code>__eq__</code></html> and negates the result.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `is` and `==` for `None`?]]
* [[What does `functools.total_ordering` require you to define?]]
* [[What is `__setitem__` and `__delitem__`?]]
Q: What are <html><code>__lt__</code></html>, <html><code>__le__</code></html>, <html><code>__gt__</code></html>, <html><code>__ge__</code></html>?

A: Rich comparison methods: less-than, less-or-equal, greater-than, greater-or-equal. They enable custom comparison logic and are used by <html><code>sorted()</code></html> and comparison operators.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `functools.total_ordering` require you to define?]]
* [[How do you check if two values are equal?]]
* [[What does `sorted()` guarantee about equal elements?]]
Q: What is <html><code>__add__</code></html> vs <html><code>__radd__</code></html>?

A: <html><code>__add__</code></html> handles <html><code>self + other</code></html>. <html><code>__radd__</code></html> (reflected add) handles <html><code>other + self</code></html> when the left operand's <html><code>__add__</code></html> returns <html><code>NotImplemented</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__iadd__`?]]
* [[What is the difference between `a += b` and `a = a + b` for lists?]]
* [[What does `__init__` vs `__new__` do?]]
Q: What is <html><code>__iadd__</code></html>?

A: The in-place add method, called by <html><code>+=</code></html>. For mutable objects (like lists), it modifies in-place. For immutable objects (like tuples), it creates a new object.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__add__` vs `__radd__`?]]
* [[What is the difference between `a += b` and `a = a + b` for lists?]]
* [[What is `object.__new__`?]]
Q: What is <html><code>__getitem__</code></html> used for?

A: It implements <html><code>obj[key]</code></html>. For sequences, the key is an integer index. For mappings, it can be any hashable key. It also enables iteration as a fallback if <html><code>__iter__</code></html> is not defined.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__iter__` vs `__getitem__` for iteration?]]
* [[What is `__class_getitem__` used for?]]
* [[What is `__class_getitem__` vs `__getitem__`?]]
Q: What is <html><code>__setitem__</code></html> and <html><code>__delitem__</code></html>?

A: <html><code>__setitem__</code></html> implements <html><code>obj[key] = value</code></html>. <html><code>__delitem__</code></html> implements <html><code>del obj[key]</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__getitem__` used for?]]
* [[What is `__class_getitem__` vs `__getitem__`?]]
* [[What is `collections.abc.MutableMapping`?]]
Q: What is <html><code>__iter__</code></html> vs <html><code>__getitem__</code></html> for iteration?

A: Python first tries <html><code>__iter__</code></html> for iteration. If not defined, it falls back to calling <html><code>__getitem__</code></html> with increasing integer indices starting from 0, stopping at <html><code>IndexError</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__getitem__` used for?]]
* [[What does the `__iter__` method return?]]
* [[What is the iterator protocol?]]
Q: What major features were added in Python 3.8?

A: The walrus operator <html><code>:=</code></html> (PEP 572), positional-only parameters <html><code>/</code></html> (PEP 570), f-string <html><code>=</code></html> for debugging, <html><code>functools.cached_property</code></html>, <html><code>typing.Literal</code></html>, <html><code>typing.Protocol</code></html>, <html><code>math.prod()</code></html>, and <html><code>statistics.NormalDist</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.13?]]
* [[What is the significance of Python 3.6?]]
* [[What features did Python 0.9.0 already include?]]
Q: What major features were added in Python 3.9?

A: Dict merge operator <html><code>|</code></html> (PEP 584), <html><code>str.removeprefix()</code></html>/<html><code>removesuffix()</code></html>, <html><code>zoneinfo</code></html> module, built-in generic types (<html><code>list[int]</code></html> instead of <html><code>typing.List[int]</code></html>), <html><code>graphlib.TopologicalSorter</code></html>, and <html><code>functools.cache</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What features did Python 0.9.0 already include?]]
* [[What major features were added in Python 3.11?]]
* [[What major features were added in Python 3.13?]]
Q: What major features were added in Python 3.10?

A: Structural pattern matching <html><code>match</code></html>/<html><code>case</code></html> (PEP 634), <html><code>TypeGuard</code></html>, <html><code>ParamSpec</code></html>, <html><code>pairwise()</code></html> in itertools, <html><code>zip(strict=True)</code></html>, and better error messages.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.13?]]
* [[What features did Python 0.9.0 already include?]]
* [[What is the significance of Python 3.6?]]
Q: What major features were added in Python 3.11?

A: Exception groups and <html><code>except*</code></html>, <html><code>asyncio.TaskGroup</code></html>, <html><code>tomllib</code></html>, <html><code>typing.Self</code></html>, 10-60% speed improvement, much better error messages with precise locations, <html><code>StrEnum</code></html>, and <html><code>typing.Never</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.9?]]
* [[What features did Python 0.9.0 already include?]]
* [[What performance improvement was made in Python 3.11?]]
Q: What major features were added in Python 3.12?

A: F-string improvements (any expression allowed), <html><code>type</code></html> statement (PEP 695), per-interpreter GIL (PEP 684), <html><code>sys.monitoring</code></html> (PEP 669), <html><code>itertools.batched()</code></html>, Linux <html><code>perf</code></html> profiler support, and deprecated <html><code>distutils</code></html> removal.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the significance of Python 3.6?]]
* [[What is the `perf` profiler support added in Python 3.12?]]
* [[What features did Python 0.9.0 already include?]]
Q: What major features were added in Python 3.13?

A: Free-threading experimental build (<html><code>--disable-gil</code></html>, PEP 703), new interactive REPL with multiline editing and color, PEP 649 deferred annotations (experimental), and an experimental JIT compiler.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.10?]]
* [[What major features were added in Python 3.8?]]
* [[What is the significance of Python 3.6?]]
Q: What is PEP 703 (free-threading)?

A: It removes the GIL as an experimental opt-in build option in Python 3.13. It enables true multi-threaded parallelism but requires significant changes to C extensions.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the per-interpreter GIL in Python 3.12?]]
* [[Threads do not parallelize CPU-bound work; the GIL serializes operations]]
* [[The Global Interpreter Lock constrains Python threading to I/O concurrency]]
Q: What is the per-interpreter GIL in Python 3.12?

A: PEP 684 allows each sub-interpreter to have its own GIL, enabling true parallelism between interpreters without the complexity of free-threading.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is PEP 703 (free-threading)?]]
* [[The Global Interpreter Lock constrains Python threading to I/O concurrency]]
* [[What is the GIL's full name?]]
Q: What did Python 3.12 do with the GIL?

A: Python 3.12 began the work for per-interpreter GIL (PEP 684), allowing each sub-interpreter to have its own GIL.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why does the GIL exist?]]
* [[What is the GIL's full name?]]
* [[What major features were added in Python 3.12?]]
Q: What is <html><code>sys.monitoring</code></html> in Python 3.12?

A: A new API for monitoring Python execution (PEP 669), designed for debuggers and profilers. It is much lower overhead than the previous <html><code>sys.settrace</code></html> approach.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.setprofile()` used for?]]
* [[All Python debuggers use sys.settrace() with measurable overhead]]
* [[What is `sys.executable`?]]
Q: What does <html><code>sys.settrace()</code></html> do?

A: It registers a trace function called for each line of Python execution. Used by debuggers and profilers. Replaced by the lower-overhead <html><code>sys.monitoring</code></html> in Python 3.12.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.exc_info()` used for?]]
* [[The trace module counts execution to identify hot paths and bottlenecks]]
Q: What performance improvement was made in Python 3.11?

A: CPython 3.11 is 10-60% faster than 3.10 thanks to the "Faster CPython" project (led by Mark Shannon, funded by Microsoft). Key optimizations include adaptive specialization of bytecode.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.11?]]
* [[What major features were added in Python 3.13?]]
* [[Why did Guido join Microsoft in 2020?]]
Q: What is the <html><code>perf</code></html> profiler support added in Python 3.12?

A: Python 3.12 added support for the Linux <html><code>perf</code></html> profiler, allowing Python function names to appear in <html><code>perf</code></html> output for system-level profiling.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.12?]]
* [[What is the `profile` module vs `cProfile`?]]
Q: What new REPL was introduced in Python 3.13?

A: A new interactive REPL with multi-line editing, color support, and better paste handling, replacing the basic readline-based REPL.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the significance of Python 3.6?]]
* [[What is the difference between `__str__` and `__repr__`?]]
* [[What did Python 3.7 add?]]
Q: What is the <html><code>match</code></html> statement guard clause?

A: An <html><code>if</code></html> condition added to a <html><code>case</code></html> pattern: <html><code>case [x, y] if x &gt; 0:</code></html> only matches if the pattern matches AND the guard condition is true.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[What is Python's `match` statement OR pattern?]]
* [[What is the wildcard pattern in Python's match statement?]]
Q: What PEPs define structural pattern matching?

A: PEP 634 (specification), PEP 635 (motivation and rationale), and PEP 636 (tutorial).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[What is a PEP?]]
* [[What PEP defines the Python style guide?]]
Q: Can you match against object attributes in Python's pattern matching?

A: Yes. Class patterns like <html><code>case Point(x=0, y=y)</code></html> can destructure objects by matching against their attributes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[What is Python's `match` statement mapping pattern?]]
* [[What is the wildcard pattern in Python's match statement?]]
Q: What is the wildcard pattern in Python's match statement?

A: <html><code>case _:</code></html> matches anything (like a default case). The <html><code>_</code></html> is a special pattern that never binds a variable.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Python's `match` statement mapping pattern?]]
* [[What is Python's `match` statement sequence pattern?]]
* [[What is the `match` statement's `__match_args__` attribute used for?]]
Q: What is the experimental JIT compiler in Python 3.13?

A: A copy-and-patch JIT compiler that generates machine code for hot Python bytecode. It is an early-stage feature that lays groundwork for future performance improvements.

----

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What major features were added in Python 3.13?]]
* [[Name five alternative Python implementations.]]
* [[What is CPython bytecode?]]
Q: What is the walrus operator's PEP number?

A: PEP 572 — "Assignment Expressions."

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the walrus operator in Python?]]
* [[What is the `walrus operator` officially called?]]
* [[What is the precedence of the walrus operator?]]
Q: Where do "spam" and "eggs" come from as Python variable names?

A: From Monty Python's famous "Spam" sketch, where everything on the menu contains spam. They replace the traditional "foo" and "bar" in Python examples.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What Monty Python references exist in the Python stdlib?]]
* [[What is name mangling in Python?]]
* [[What are variables in Python and how are they defined?]]
Q: What Monty Python references exist in the Python stdlib?

A: The <html><code>spam</code></html> module (C extension example), spam/eggs in examples throughout documentation, the <html><code>antigravity</code></html> Easter egg (references XKCD which often features Python), and the "Spanish Inquisition" references in some test suites.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Where do "spam" and "eggs" come from as Python variable names?]]
* [[Name three Python static type checkers besides mypy.]]
* [[What is the significance of `antigravity` in Python?]]
Q: What is Cython?

A: A superset of Python that compiles to C for performance. It allows adding C type declarations to Python code for dramatic speedups.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is PyPy and why is it significant?]]
* [[What is MicroPython?]]
* [[What is EuroPython?]]
Q: What is <html><code>mypyc</code></html>?

A: A compiler that uses mypy type annotations to compile Python modules to C extensions. It powers mypy's own speedup.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m py_compile script.py` do?]]
* [[Name three Python static type checkers besides mypy.]]
* [[What is CPython bytecode?]]
Q: What is PyInstaller?

A: A tool that packages Python applications into standalone executables, bundling the interpreter and all dependencies.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__main__.py` file for?]]
* [[What is `pyenv`?]]
* [[What is PyPy and why is it significant?]]
Q: What is mypy?

A: The original static type checker for Python, created by Jukka Lehtosalo. It checks type annotations without running the code.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Name three Python static type checkers besides mypy.]]
* [[Is Python statically or dynamically typed?]]
* [[What is `typing.Annotated` used for?]]
Q: Name three Python static type checkers besides mypy.

A: Pyright (Microsoft, used by Pylance in VS Code), pytype (Google), and Pyre (Facebook/Meta).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is mypy?]]
* [[What major features were added in Python 3.10?]]
* [[Name five alternative Python implementations.]]
Q: What is the GIL's full name?

A: Global Interpreter Lock.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What did Python 3.12 do with the GIL?]]
* [[What is the per-interpreter GIL in Python 3.12?]]
* [[Why does the GIL exist?]]
Q: What year did Python first appear on the TIOBE index top 3?

A: Python first reached the #1 spot on TIOBE in October 2021, though it had been in the top 3 since around 2018.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was Python 0.9.0 first released publicly?]]
* [[When was Python 3.0 released?]]
* [[When was Python 1.0 released?]]
Q: How many keywords does Python 3.12 have?

A: 35 keywords. You can see them with <html><code>import keyword; print(keyword.kwlist)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are the different comprehension types in Python?]]
* [[What major features were added in Python 3.12?]]
* [[What is a "dictionary"?]]
Q: What is <html><code>__name__</code></html> set to when a module is imported?

A: The module's name (e.g., <html><code>'mymodule'</code></html>). When run as a script, it is set to <html><code>'__main__'</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does the `import` statement do in Python?]]
* [[What is the difference between `__import__()` and `importlib.import_module()`?]]
* [[What is `__all__` used for in a module?]]
Q: What does <html><code>sys.getdefaultencoding()</code></html> return in Python 3?

A: <html><code>'utf-8'</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What encoding does Python 3 use for source files by default?]]
* [[What is a Python "magic comment" for encoding?]]
* [[What is `str.encode()` and `bytes.decode()`?]]
Q: What is <html><code>__file__</code></html> in a module?

A: The path to the file from which the module was loaded. It is not defined for C extensions or built-in modules.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__name__` set to when a module is imported?]]
* [[What is `__cached__` on a module?]]
Q: What is <html><code>__spec__</code></html> in a module?

A: A <html><code>ModuleSpec</code></html> object (added in Python 3.4) containing metadata about how the module was loaded, including its name, loader, and origin.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__cached__` on a module?]]
* [[What is `__name__` set to when a module is imported?]]
Q: What does <html><code>python -c "expr"</code></html> do?

A: Executes the given Python expression directly from the command line.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -O` do?]]
* [[What is the `compile()` built-in?]]
* [[What is the `subprocess.run()` function?]]
Q: What is <html><code>PYTHONSTARTUP</code></html>?

A: An environment variable pointing to a Python file that is executed when the interactive interpreter starts. Useful for setting up custom helpers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__main__.py` file for?]]
* [[What is the `__init__.py` file for?]]
Q: What is <html><code>sys.executable</code></html>?

A: The path to the Python interpreter binary currently running.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `PYTHONPATH` environment variable?]]
* [[What is `sysconfig` used for?]]
Q: What is the <html><code>compile()</code></html> built-in?

A: It compiles a string of Python code into a code object that can be executed with <html><code>exec()</code></html> or <html><code>eval()</code></html>. It accepts <html><code>'exec'</code></html>, <html><code>'eval'</code></html>, or <html><code>'single'</code></html> mode.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `compileall` used for?]]
* [[What does `python -m py_compile script.py` do?]]
* [[What does `re.compile()` return and why use it?]]
Q: What is the difference between <html><code>exec()</code></html> and <html><code>eval()</code></html>?

A: <html><code>eval()</code></html> evaluates a single expression and returns its value. <html><code>exec()</code></html> executes arbitrary statements but always returns <html><code>None</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `exec()` dangerous for?]]
* [[What is the `compile()` built-in?]]
Q: What is <html><code>getattr(obj, name, default)</code></html> used for?

A: It retrieves an attribute by name string. If the attribute does not exist, it returns the default (or raises <html><code>AttributeError</code></html> if no default is given).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__getattr__` vs `__getattribute__`?]]
* [[What is `operator.attrgetter()` used for?]]
* [[What is `__set_name__` used for?]]
Q: What is <html><code>hasattr(obj, name)</code></html> equivalent to?

A: Calling <html><code>getattr(obj, name)</code></html> and catching <html><code>AttributeError</code></html>. It returns <html><code>True</code></html> if the attribute exists.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__getattr__` vs `__getattribute__`?]]
* [[What is `operator.attrgetter()` used for?]]
* [[What is the `__qualname__` attribute?]]
Q: What is <html><code>vars(obj)</code></html> equivalent to?

A: <html><code>obj.__dict__</code></html> — it returns the <html><code>__dict__</code></html> attribute of the object. Without an argument, <html><code>vars()</code></html> returns <html><code>locals()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
Q: What is <html><code>dir()</code></html> used for?

A: It returns a list of names in the current scope (no argument) or a list of valid attributes for an object. It calls <html><code>__dir__()</code></html> if defined.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `os.walk()` used for?]]
* [[What is `pathlib.Path.glob()` used for?]]
* [[What is `sys.path` and how does Python use it?]]
Q: What is <html><code>type()</code></html> with one argument vs three arguments?

A: With one argument, <html><code>type(obj)</code></html> returns the type of the object. With three arguments, <html><code>type(name, bases, dict)</code></html> dynamically creates a new class.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What function returns the data type of an object?]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What does `type(...)` return?]]
Q: What is <html><code>super()</code></html> and how does it work?

A: <html><code>super()</code></html> returns a proxy object that delegates method calls to a parent or sibling class in the MRO. In Python 3, <html><code>super()</code></html> with no arguments works inside methods.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[super()]]
* [[Explain Python's Method Resolution Order (MRO)]]
* [[What is `operator.methodcaller()` used for?]]
Q: How does super() work in Python 3?

A: super() returns a proxy object that delegates method calls to the next class in the MRO.

class A:
    def greet(self):
        return 'A'

class B(A):
    def greet(self):
        return 'B->' + super().greet()

class C(A):
    def greet(self):
        return 'C->' + super().greet()

class D(B, C):
    def greet(self):
        return 'D->' + super().greet()

D().greet()  # 'D->B->C->A'

Python 3 super() needs no args (uses __class__ cell). It follows MRO, not parent — crucial for cooperative multiple [[inheritance|Inheritance]]. Always call super().__init__() in __init__ for MI to work correctly.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[Inheritance]]
* [[Explain name mangling with double underscores]]
* [[Implement the Singleton pattern in Python (three ways)]]
Q: What is the <html><code>__init__.py</code></html> file for?

A: It marks a directory as a Python package. It can be empty or contain initialization code. Since Python 3.3, namespace packages allow packages without <html><code>__init__.py</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[__init__.py is required for directories to be importable as packages]]
* [[What are namespace packages?]]
* [[What does `__all__` in `__init__.py` control?]]
Q: What are namespace packages?

A: Packages without <html><code>__init__.py</code></html> (PEP 420, Python 3.3). They allow a single logical package to be split across multiple directories or even distributions.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__init__.py` file for?]]
* [[What is a Python namespace?]]
* [[__init__.py is required for directories to be importable as packages]]
Q: What is the result of <html><code>[] is []</code></html>?

A: <html><code>False</code></html>. Each <html><code>[]</code></html> creates a new list object with a different identity.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the result of `bool([])`?]]
* [[Why does `all([])` return `True`?]]
* [[What happens when you multiply a list: `[[]] * 3`?]]
Q: What is the result of <html><code>() is ()</code></html>?

A: <html><code>True</code></html> in CPython. Empty tuples are cached as singletons because they are immutable and commonly used.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `is` and `==` for `None`?]]
* [[What is the result of `bool([])`?]]
* [[How do you check for `None` in Python?]]
Q: What is the difference between <html><code>__import__()</code></html> and <html><code>importlib.import_module()</code></html>?

A: Both import modules by name, but <html><code>importlib.import_module()</code></html> is the recommended approach. <html><code>__import__()</code></html> is the low-level function called by the <html><code>import</code></html> statement.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__name__` set to when a module is imported?]]
* [[What is `__import__` hook?]]
* [[What does `import __hello__` do?]]
Q: What does the <html><code>import</code></html> statement do in Python?

A: Loads a module (or specific names from it) into the current namespace so you can use its functions, classes, and variables. Variants: import math (full module), from math import sqrt (single name), from math import 
* (all names — discouraged, pollutes namespace). Python caches imports in sys.modules.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is `__import__` hook?]]
* [[What is `__name__` set to when a module is imported?]]
* [[What does `import __hello__` do?]]
Q: What does <html><code>isinstance()</code></html> check that <html><code>type()</code></html> does not?

A: <html><code>isinstance()</code></html> checks the entire [[inheritance|Inheritance]] chain (including virtual subclasses registered with ABCs). <html><code>type()</code></html> only returns the exact type.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What function returns the data type of an object?]]
* [[What does `type(...)` return?]]
* [[What is a virtual subclass in Python's ABC framework?]]
Q: What is CPython's memory allocator?

A: CPython uses a custom memory allocator called <html><code>pymalloc</code></html> for small objects (up to 512 bytes). It uses memory pools and arenas to reduce fragmentation and improve performance.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a "free list" in CPython?]]
* [[What is the small integer cache in CPython?]]
* [[What is reference counting in CPython?]]
Q: What is a "free list" in CPython?

A: A cache of recently deallocated objects of a specific type (like floats, tuples, lists) that can be reused instead of calling <html><code>malloc()</code></html>. This speeds up creation of frequently used objects.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Why are tuples slightly faster than lists?]]
* [[What is CPython's memory allocator?]]
* [[What is the purpose of garbage collection in Python?]]
Q: What is <html><code>sys.getrefcount(obj)</code></html>?

A: Returns the reference count for an object. The count is always at least 1 higher than expected because the function argument itself creates a temporary reference.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.getrecursionlimit()` return?]]
* [[What does `sys.getsizeof()` return?]]
* [[self]]
Q: What is the <html><code>__annotations__</code></html> attribute?

A: A dictionary storing the annotations of a function, class, or module. For example, <html><code>def f(x: int) -&gt; str:</code></html> results in <html><code>f.__annotations__ == {'x': int, 'return': str}</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.Annotated` used for?]]
* [[What is `typing.get_type_hints()` used for?]]
* [[What is PEP 649 about?]]
Q: What is a code object in Python?

A: An immutable object containing compiled bytecode, constants, variable names, and metadata for a function or module. Accessed via <html><code>function.__code__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[How does Python define code blocks?]]
* [[What is CPython bytecode?]]
* [[What method makes an object callable?]]
Q: What does <html><code>sys.argv</code></html> contain?

A: A list of command-line arguments passed to the script. <html><code>sys.argv[0]</code></html> is the script name.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.executable`?]]
* [[What is `argparse.FileType`?]]
* [[What is `sys.flags`?]]
Q: What is <html><code>os.environ</code></html>?

A: A mapping object representing the environment variables. Changes to it affect the current process and any child processes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the "os" module primarily used for?]]
Q: What is the <html><code>__prepare__</code></html> method in metaclasses?

A: A classmethod on the metaclass that returns the namespace dict to use during class body execution. It allows custom namespace objects (like <html><code>OrderedDict</code></html>) for tracking definition order.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are metaclasses and when would you use them?]]
* [[What is `__dict__` on a class vs an instance?]]
* [[What is a metaclass?]]
Q: What does the <html><code>abc.abstractmethod</code></html> decorator do?

A: It marks a method as abstract, preventing the class from being instantiated unless the method is overridden. The containing class must inherit from <html><code>ABC</code></html> or use <html><code>ABCMeta</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module provides abstract base classes?]]
* [[What is the `abc.ABCMeta` metaclass?]]
* [[What is a decorator in Python?]]
Q: What is <html><code>collections.abc.Hashable</code></html>?

A: An abstract base class for objects that support <html><code>hash()</code></html>. You can check <html><code>isinstance(obj, Hashable)</code></html> to test if an object is hashable.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.abc` and how does it differ from `collections`?]]
* [[What does `__hash__` need to be consistent with?]]
* [[What is `collections.abc.MutableMapping`?]]
Q: What is the <html><code>textwrap</code></html> module useful for?

A: Wrapping and formatting plain text: <html><code>wrap()</code></html>, <html><code>fill()</code></html>, <html><code>dedent()</code></html>, <html><code>indent()</code></html>, and <html><code>shorten()</code></html> for truncating text with a placeholder.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `textwrap.fill()` do?]]
* [[What does `textwrap.dedent()` do?]]
* [[What does `functools.wraps` do?]]
Q: What does <html><code>os.path.expanduser('~')</code></html> return?

A: The current user's home directory path.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `os.walk()` used for?]]
* [[What is the `PYTHONPATH` environment variable?]]
Q: What is the <html><code>platform</code></html> module?

A: It provides portable access to platform-identifying data: <html><code>platform.system()</code></html> returns <html><code>'Linux'</code></html>, <html><code>'Darwin'</code></html>, or <html><code>'Windows'</code></html>. Also <html><code>platform.python_version()</code></html>, <html><code>platform.machine()</code></html>, etc.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.platform` return on Linux, macOS, and Windows?]]
* [[What is the "os" module primarily used for?]]
Q: What is <html><code>sys.stdin</code></html>, <html><code>sys.stdout</code></html>, <html><code>sys.stderr</code></html>?

A: File objects corresponding to the interpreter's standard input, output, and error streams. They can be redirected.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `contextlib.redirect_stdout()` do?]]
Q: What does <html><code>python -m venv myenv</code></html> do?

A: Creates a virtual environment in the <html><code>myenv</code></html> directory with its own Python binary and isolated <html><code>site-packages</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `venv` and `virtualenv`?]]
* [[What does `python -m site` do?]]
* [[What does `python -v` do?]]
Q: What is <html><code>pip freeze</code></html> used for?

A: It outputs a list of installed packages and their versions in <html><code>requirements.txt</code></html> format, suitable for recreating the environment.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[When was `pip` first released?]]
* [[What was the original name of `pip`?]]
* [[What is a `requirements.txt` file?]]
Q: What is a <html><code>requirements.txt</code></html> file?

A: A text file listing Python package dependencies, one per line, with optional version specifiers. Used by <html><code>pip install -r requirements.txt</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `pip freeze` used for?]]
* [[How do you install a package in Python?]]
Q: What is the <html><code>wheel</code></html> filename convention?

A: <html><code>{name}-{version}(-{build})?-{python}-{abi}-{platform}.whl</code></html>. For example: <html><code>numpy-1.24.0-cp311-cp311-manylinux_2_17_x86_64.whl</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a Python wheel's tag format?]]
* [[What is `py3-none-any` in a wheel filename?]]
* [[What is the `wheel` format?]]
Q: What is <html><code>manylinux</code></html>?

A: A tag for Linux wheel files indicating compatibility across many Linux distributions. It defines a set of allowed system libraries, enabling portable binary wheels.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a Python wheel's tag format?]]
* [[What is the `wheel` filename convention?]]
Q: What is <html><code>sdist</code></html> in Python packaging?

A: Source distribution — a tarball (<html><code>.tar.gz</code></html>) containing the source code and build instructions. Unlike wheels, sdists require building during installation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Wheels are pre-built, sdists are source distributions]]
Q: What is the <html><code>__main__.py</code></html> file for?

A: It makes a package executable with <html><code>python -m package</code></html>. The <html><code>__main__.py</code></html> file is executed when the package is run as a script.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m py_compile script.py` do?]]
* [[What is `python -m zipapp` used for?]]
* [[What does if __name__ == "__main__": do?]]
Q: What is the <html><code>struct</code></html> module's byte order prefixes?

A: <html><code>&gt;</code></html> for big-endian, <html><code>&lt;</code></html> for little-endian, <html><code>=</code></html> for native, <html><code>!</code></html> for network (big-endian), <html><code>@</code></html> for native with native size.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `struct.pack('>I', 1024)` return?]]
* [[What module lets you pack and unpack binary data in C struct format?]]
Q: What is the difference between <html><code>is</code></html> and <html><code>==</code></html> for <html><code>None</code></html>?

A: Always use <html><code>is None</code></html> because <html><code>None</code></html> is a singleton. <html><code>== None</code></html> would call <html><code>__eq__</code></html> which could be overridden to return <html><code>True</code></html> for non-None objects.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `is` and `==` in Python?]]
* [[What is the difference between `None` and `False`?]]
* [[is / is not (identity)]]
Q: What is <html><code>sys.flags</code></html>?

A: A named tuple containing the settings of command-line flags like <html><code>-O</code></html>, <html><code>-B</code></html>, <html><code>-v</code></html>, etc.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.argv` contain?]]
* [[What is `sys.monitoring` in Python 3.12?]]
* [[What is `sysconfig` used for?]]
Q: What does <html><code>python -v</code></html> do?

A: Verbose mode — prints a message each time a module is imported, showing which file is loaded.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m venv myenv` do?]]
* [[What does `python -O` do?]]
* [[What does if __name__ == "__main__": do?]]
Q: What is <html><code>sys.modules</code></html>?

A: A dictionary mapping module names to already-loaded module objects. It serves as a cache to prevent re-importing modules.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__spec__` in a module?]]
* [[What is `__name__` set to when a module is imported?]]
* [[What is `__cached__` on a module?]]
Q: What is the <html><code>types</code></html> module?

A: It provides access to special type objects like <html><code>FunctionType</code></html>, <html><code>MethodType</code></html>, <html><code>ModuleType</code></html>, <html><code>GeneratorType</code></html>, and <html><code>SimpleNamespace</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `type(...)` return?]]
* [[What is the `numbers` module?]]
* [[What is `type()` with one argument vs three arguments?]]
Q: What is <html><code>types.SimpleNamespace</code></html>?

A: A simple class that allows attribute access on an object: <html><code>ns = SimpleNamespace(x=1, y=2); ns.x</code></html> returns <html><code>1</code></html>. Useful as a lightweight alternative to classes or dicts.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a Python namespace?]]
* [[What is `getattr(obj, name, default)` used for?]]
* [[What is `type()` with one argument vs three arguments?]]
Q: What does <html><code>object.__subclasses__()</code></html> return?

A: A list of all immediate subclasses of the class that are still alive in memory.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `object.__new__`?]]
* [[What does `__subclasshook__` do?]]
* [[What does `object.__repr__` return by default?]]
Q: What is <html><code>__dict__</code></html> on a class vs an instance?

A: A class's <html><code>__dict__</code></html> contains its methods and class attributes (as a <html><code>mappingproxy</code></html>). An instance's <html><code>__dict__</code></html> contains only its instance attributes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a `mappingproxy`?]]
* [[What is `__slots__` and why use it?]]
* [[Class variable vs instance variable]]
Q: What is a <html><code>mappingproxy</code></html>?

A: A read-only view of a dictionary, used for class <html><code>__dict__</code></html> to prevent accidental modification of the class namespace through the dict interface.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__dict__` on a class vs an instance?]]
* [[What is `collections.abc.MutableMapping`?]]
* [[What is `collections.ChainMap` used for?]]
Q: What is the <html><code>@functools.lru_cache</code></html> memory leak risk?

A: If the cached function receives large objects as arguments, those objects are kept alive by the cache even if no other references exist. Use <html><code>maxsize</code></html> to limit cache size.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `functools.lru_cache` and `functools.cache`?]]
* [[Why must arguments to an `lru_cache`-decorated function be hashable?]]
* [[What is the `lru_cache` maximum size by default?]]
Q: What does <html><code>hash(float('inf'))</code></html> return?

A: <html><code>314159</code></html> in CPython — a reference to pi.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `float('inf')` represent?]]
* [[What does `hash(-1)` return in CPython?]]
* [[What is `math.inf` equal to?]]
Q: What is the time module's <html><code>perf_counter()</code></html> vs <html><code>time()</code></html>?

A: <html><code>perf_counter()</code></html> returns a high-resolution monotonic timer for measuring short durations. <html><code>time()</code></html> returns wall-clock time (epoch seconds) which can jump due to NTP adjustments.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `time.monotonic()`?]]
* [[What is the epoch in Python's `time` module?]]
Q: What is <html><code>time.monotonic()</code></html>?

A: A clock that cannot go backwards, even if system time is adjusted. Useful for measuring elapsed time.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the time module's `perf_counter()` vs `time()`?]]
* [[What is the epoch in Python's `time` module?]]
Q: What is the <html><code>calendar</code></html> module?

A: It provides calendar-related functions: printing calendars, determining leap years, and iterating over months and weeks.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m calendar` do?]]
* [[What does `calendar.isleap(year)` check?]]
Q: What does <html><code>calendar.isleap(year)</code></html> check?

A: Whether the given year is a leap year according to the Gregorian calendar.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `calendar` module?]]
* [[What does `python -m calendar` do?]]
Q: What is <html><code>str.isidentifier()</code></html>?

A: It returns <html><code>True</code></html> if the string is a valid Python identifier. Use <html><code>keyword.iskeyword()</code></html> to additionally check if it is a reserved keyword.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__bool__` method?]]
* [[What is the `__contains__` method?]]
* [[What is the difference between `is` and `==` in Python?]]
Q: What does <html><code>chr()</code></html> and <html><code>ord()</code></html> do?

A: <html><code>chr(n)</code></html> returns the string character for Unicode code point <html><code>n</code></html>. <html><code>ord(c)</code></html> returns the Unicode code point for a single character string <html><code>c</code></html>. They are inverses.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `str.translate()` do?]]
* [[What does `string.ascii_letters` contain?]]
Q: What is the <html><code>collections.OrderedDict</code></html> <html><code>popitem(last=True)</code></html> method?

A: It removes and returns a <html><code>(key, value)</code></html> pair. With <html><code>last=True</code></html> (default), it removes from the end (LIFO). With <html><code>last=False</code></html>, it removes from the beginning (FIFO).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[Is `OrderedDict` still useful now that regular dicts maintain insertion order (since Py…]]
* [[What is `collections.UserDict` for?]]
* [[What is the default value returned by a `defaultdict(list)` for a missing key?]]
Q: What is <html><code>dict.setdefault(key, default)</code></html>?

A: If <html><code>key</code></html> is in the dict, return its value. If not, insert <html><code>key</code></html> with <html><code>default</code></html> and return <html><code>default</code></html>. It is atomic (thread-safe in CPython due to the GIL).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What method does `defaultdict` call to produce a default value?]]
* [[What happens if you create a `defaultdict` with no argument (i.e., `defaultdict()`)?]]
* [[What is `__missing__` used for?]]
Q: What does <html><code>dict | other_dict</code></html> do in Python 3.9+?

A: It creates a new dict with merged key-value pairs. Values from <html><code>other_dict</code></html> override those in <html><code>dict</code></html> for shared keys. <html><code>|=</code></html> does the merge in-place.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `dict.setdefault(key, default)`?]]
* [[What is a "dictionary"?]]
Q: What is the difference between <html><code>list.copy()</code></html> and <html><code>list[:]</code></html>?

A: They both create a shallow copy. <html><code>list.copy()</code></html> was added in Python 3.3 and is more readable. <html><code>list[:]</code></html> uses slice syntax for the same effect.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `copy.deepcopy()` do differently from `copy.copy()`?]]
* [[What does `[1, 2, 3][::-1]` return?]]
* [[What is "slicing" in Python?]]
Q: What does <html><code>reversed()</code></html> require?

A: Either a sequence (with <html><code>__len__</code></html> and <html><code>__getitem__</code></html>) or an object with a <html><code>__reversed__</code></html> method. It returns a reverse iterator.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `[1, 2, 3][::-1]` return?]]
* [[What does the `__iter__` method return?]]
* [[What is the iterator protocol?]]
Q: What is the <html><code>locale</code></html> module?

A: It provides access to locale-specific formatting for numbers, currency, and dates. <html><code>locale.setlocale()</code></html> changes the locale for the current process.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
Q: What is <html><code>decimal.Decimal</code></html> vs <html><code>float</code></html> for financial calculations?

A: <html><code>Decimal</code></html> provides exact decimal arithmetic without floating-point rounding errors, making it essential for financial calculations where exactness matters.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module provides arbitrary-precision decimal arithmetic?]]
* [[How do you set the precision for `decimal.Decimal` operations?]]
* [[What format spec would you use in an f-string to display a float with exactly 2 decimal…]]
Q: What is <html><code>math.factorial()</code></html> used for?

A: Computing factorials: <html><code>math.factorial(5)</code></html> returns <html><code>120</code></html>. It raises <html><code>ValueError</code></html> for negative numbers.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `operator.methodcaller()` used for?]]
* [[Why does `0.1 + 0.2 != 0.3` in Python?]]
Q: What does <html><code>math.gcd()</code></html> compute?

A: The greatest common divisor. Since Python 3.9, it accepts multiple arguments: <html><code>math.gcd(12, 18, 24)</code></html> returns <html><code>6</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `math.lcm()` compute, and when was it added?]]
* [[What does `math.prod()` do, and when was it added?]]
* [[What is the "math" module?]]
Q: What does <html><code>math.lcm()</code></html> compute, and when was it added?

A: The least common multiple. Added in Python 3.9, it accepts multiple arguments: <html><code>math.lcm(4, 6, 10)</code></html> returns <html><code>60</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `math.gcd()` compute?]]
* [[What does `math.prod()` do, and when was it added?]]
* [[What is the "math" module?]]
Q: What is <html><code>DeprecationWarning</code></html> vs <html><code>PendingDeprecationWarning</code></html>?

A: <html><code>DeprecationWarning</code></html> is for features scheduled for removal. <html><code>PendingDeprecationWarning</code></html> is for features that may be deprecated in the future. By default, <html><code>DeprecationWarning</code></html> is shown in <html><code>__main__</code></html> but hidden in imported modules.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[The warnings module signals deprecations and issues separately from exceptions]]
* [[What is the `warnings` module?]]
Q: What is <html><code>sys.float_info</code></html>?

A: A named tuple containing information about the <html><code>float</code></html> type: <html><code>max</code></html> (largest representable float), <html><code>min</code></html> (smallest positive normalized float), <html><code>epsilon</code></html> (smallest difference between 1.0 and the next float), etc.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `float('inf')` represent?]]
* [[What is `sys.maxsize`?]]
* [[What is NumPy's `dtype`?]]
Q: What is <html><code>math.inf</code></html> vs <html><code>sys.float_info.max</code></html>?

A: <html><code>math.inf</code></html> is positive infinity (a special IEEE 754 value). <html><code>sys.float_info.max</code></html> is the largest finite representable float (approximately 1.8e+308).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `hash(float('inf'))` return?]]
* [[What is `sys.maxsize`?]]
* [[What does `sys.getsizeof(1)` return approximately?]]
Q: What is a Python "magic comment" for encoding?

A: A comment like <html><code># -*- coding: utf-8 -*-</code></html> or <html><code># coding: utf-8</code></html> on the first or second line of a source file. It declares the source encoding. Not needed in Python 3 (UTF-8 is default).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.getdefaultencoding()` return in Python 3?]]
* [[What is `base64` encoding used for in Python?]]
* [[What is `str.encode()` and `bytes.decode()`?]]
Q: What is <html><code>__doc__</code></html>?

A: The docstring attribute of a function, class, or module. It is set from the first string literal in the body.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is doctest?]]
* [[What is the `__annotations__` attribute?]]
* [[Multi-line strings and docstrings]]
Q: What is the <html><code>help()</code></html> built-in?

A: It invokes the interactive help system. <html><code>help(obj)</code></html> displays the docstring and other information about the object. It uses the <html><code>pydoc</code></html> module internally.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `pydoc` module?]]
* [[What is `__doc__`?]]
Q: What is the <html><code>__qualname__</code></html> attribute?

A: The qualified name of a class or function, showing the path from the module level. For a nested class method: <html><code>Outer.Inner.method</code></html>. Added in Python 3.3.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is name mangling in Python?]]
* [[What is `__set_name__` used for?]]
* [[What is `__name__` set to when a module is imported?]]
Q: What is <html><code>memoryview</code></html> used for?

A: It creates a view of the memory of a bytes-like object without copying. Useful for zero-copy slicing of large binary data like <html><code>bytes</code></html>, <html><code>bytearray</code></html>, or <html><code>array.array</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module provides memory-mapped file access?]]
* [[What is `io.BytesIO` used for?]]
* [[What is the purpose of garbage collection in Python?]]
Q: What is the <html><code>with</code></html> statement's full syntax since Python 3.1?

A: Multiple context managers in one statement: <html><code>with open('a') as f1, open('b') as f2:</code></html>. Python 3.10 also allows parenthesized multi-line form.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What did Python 2.5 introduce?]]
* [[What is the `contextlib.nullcontext()` used for?]]
* [[What is the `__contains__` method?]]
Q: What is <html><code>os.walk()</code></html> used for?

A: It generates <html><code>(dirpath, dirnames, filenames)</code></html> tuples for each directory in a tree, enabling recursive directory traversal.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the "os" module primarily used for?]]
* [[What is `pathlib.Path.glob()` used for?]]
* [[What does `os.scandir()` return and why is it preferred over `os.listdir()`?]]
Q: What is <html><code>pathlib.Path.glob()</code></html> used for?

A: Pattern matching for files within a directory tree: <html><code>Path('.').glob('**/*.py')</code></html> finds all Python files recursively.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is the `pathlib` module and when was it introduced?]]
* [[What is `os.walk()` used for?]]
* [[What is `sys.path` and how does Python use it?]]
Q: What is <html><code>pathlib.Path.resolve()</code></html> used for?

A: It returns the absolute path with all symlinks resolved and <html><code>..</code></html> components eliminated.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.path` and how does Python use it?]]
* [[What is `pathlib.Path.glob()` used for?]]
Q: What does <html><code>any(generator_expression)</code></html> short-circuit?

A: Yes. <html><code>any()</code></html> stops iterating as soon as it finds a truthy value, and <html><code>all()</code></html> stops at the first falsy value. This makes them efficient for large iterables.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[any() and all()]]
* [[What does `any([])` return?]]
* [[What does `itertools.dropwhile(predicate, iterable)` do?]]
Q: What is <html><code>itertools.repeat()</code></html> commonly used with?

A: As a constant argument source for <html><code>map()</code></html> and <html><code>zip()</code></html>: <html><code>list(map(pow, range(5), itertools.repeat(2)))</code></html> gives <html><code>[0, 1, 4, 9, 16]</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `itertools.product` with the `repeat` parameter?]]
* [[What does `itertools.starmap(func, iterable)` do?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
Q: What does <html><code>str.format_map()</code></html> do?

A: Like <html><code>str.format(**mapping)</code></html> but takes a mapping directly without unpacking. Useful with <html><code>defaultdict</code></html> to handle missing keys gracefully.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__format__` used for?]]
* [[What does `str.translate()` do?]]
Q: What is the <html><code>abc.ABCMeta</code></html> metaclass?

A: The metaclass used by <html><code>ABC</code></html>. It enables <html><code>register()</code></html> for virtual subclasses and tracks which abstract methods need implementation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a virtual subclass in Python's ABC framework?]]
* [[What does the `abc.abstractmethod` decorator do?]]
* [[What module provides abstract base classes?]]
Q: What is a virtual subclass in Python's ABC framework?

A: A class registered with <html><code>MyABC.register(SomeClass)</code></html> that passes <html><code>isinstance()</code></html> and <html><code>issubclass()</code></html> checks for the ABC without actually inheriting from it.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `__subclasshook__` do?]]
* [[What is the `abc.ABCMeta` metaclass?]]
* [[What does `isinstance()` check that `type()` does not?]]
Q: What does <html><code>__subclasshook__</code></html> do?

A: An ABC classmethod that customizes <html><code>issubclass()</code></html> behavior. It can return <html><code>True</code></html>, <html><code>False</code></html>, or <html><code>NotImplemented</code></html> to override the default subclass check.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a virtual subclass in Python's ABC framework?]]
* [[What is `__init_subclass__` used for?]]
* [[What does `object.__subclasses__()` return?]]
Q: What is the <html><code>io</code></html> module?

A: It provides Python's main I/O implementation with text streams (<html><code>TextIOWrapper</code></html>), binary streams (<html><code>BufferedReader</code></html>, <html><code>BufferedWriter</code></html>), and raw I/O (<html><code>FileIO</code></html>).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `io.StringIO` used for?]]
* [[What module provides memory-mapped file access?]]
Q: What is <html><code>io.StringIO</code></html> used for?

A: An in-memory text stream that behaves like a file object. Useful for testing or capturing output: <html><code>buf = StringIO(); print('hello', file=buf); buf.getvalue()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `io` module?]]
Q: What is <html><code>io.BytesIO</code></html> used for?

A: An in-memory binary stream. Useful for working with binary data using file-like APIs without actual files.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `int.to_bytes()` do?]]
Q: What does <html><code>object.__repr__</code></html> return by default?

A: Something like <html><code>&lt;ClassName object at 0x7f...&gt;</code></html> — the class name and memory address.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `object.__subclasses__()` return?]]
* [[What is the difference between `__str__` and `__repr__`?]]
* [[What is `object.__new__`?]]
Q: What is <html><code>typing.Required</code></html> and <html><code>typing.NotRequired</code></html> for TypedDict?

A: Added in Python 3.11, they mark individual fields in a <html><code>TypedDict</code></html> as required or optional, allowing mixed required/optional fields in a single <html><code>total=True</code></html> or <html><code>total=False</code></html> TypedDict.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypedDict` used for?]]
* [[What is `typing.Optional[X]` equivalent to?]]
* [[What is `typing.Never` (Python 3.11) or `typing.NoReturn` used for?]]
Q: What is the <html><code>@typing.dataclass_transform</code></html> decorator?

A: Added in Python 3.11 (PEP 681), it tells type checkers that a decorator or base class creates dataclass-like classes, enabling proper type checking for ORMs and similar frameworks.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `@dataclass` an example of in terms of Python internals?]]
* [[What is `typing.ClassVar` used for?]]
* [[What is a decorator in Python?]]
Q: What does <html><code>sys.exit()</code></html> actually raise?

A: <html><code>SystemExit</code></html> exception. It does not immediately terminate — it can be caught by <html><code>except BaseException</code></html> or <html><code>except SystemExit</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `os._exit()` and when is it used?]]
* [[What arguments does `__exit__` receive?]]
* [[What is `sys.exc_info()` used for?]]
Q: What is <html><code>os._exit()</code></html> and when is it used?

A: It exits immediately without cleanup (no <html><code>atexit</code></html> handlers, no flushing buffers, no <html><code>finally</code></html> blocks). Used in child processes after <html><code>os.fork()</code></html> to avoid running parent cleanup code.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `sys.exit()` actually raise?]]
* [[Does `finally` always execute?]]
Q: What is the <html><code>signal</code></html> module used for?

A: Handling Unix signals in Python: <html><code>signal.signal(signal.SIGTERM, handler)</code></html> registers a handler for graceful shutdown.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
Q: What is <html><code>multiprocessing.Queue</code></html> vs <html><code>queue.Queue</code></html>?

A: <html><code>queue.Queue</code></html> is thread-safe for use between threads. <html><code>multiprocessing.Queue</code></html> works across processes using pipes and serialization.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `multiprocessing.Pool` used for?]]
* [[Multiprocessing achieves true CPU parallelism with separate interpreters]]
* [[What is the difference between concurrency and parallelism in Python?]]
Q: What is <html><code>threading.Event</code></html>?

A: A synchronization primitive where one thread signals an event and other threads wait for it: <html><code>event.set()</code></html>, <html><code>event.wait()</code></html>, <html><code>event.clear()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `threading.Condition`?]]
* [[What is `threading.Lock` used for?]]
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
Q: What is <html><code>threading.Condition</code></html>?

A: A synchronization primitive combining a lock with the ability to wait for a condition: <html><code>condition.wait()</code></html>, <html><code>condition.notify()</code></html>, <html><code>condition.notify_all()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `threading.Lock` used for?]]
* [[What is `threading.Event`?]]
Q: What is <html><code>asyncio.sleep()</code></html> vs <html><code>time.sleep()</code></html>?

A: <html><code>asyncio.sleep()</code></html> is non-blocking — it yields control back to the event loop. <html><code>time.sleep()</code></html> blocks the entire thread, including the event loop.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `asyncio.run()` used for?]]
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[What is `asyncio.Queue`?]]
Q: What is <html><code>aiofiles</code></html>?

A: A third-party library providing async file I/O for asyncio, since the standard library's file operations are all synchronous and would block the event loop.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
* [[What is `asyncio.sleep()` vs `time.sleep()`?]]
* [[What is `asyncio.run()` used for?]]
Q: What is <html><code>sys.setprofile()</code></html> used for?

A: It registers a profiling function called on function calls and returns. Less granular than <html><code>settrace()</code></html> but lower overhead.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.monitoring` in Python 3.12?]]
* [[What is `sys.exc_info()` used for?]]
Q: What is the <html><code>cProfile</code></html> module?

A: A deterministic profiler that records how many times each function is called and how long each call takes. Invoke with <html><code>python -m cProfile script.py</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[CPU profiling reveals which functions consume the most time]]
* [[What is the `perf` profiler support added in Python 3.12?]]
* [[What is `sys.setprofile()` used for?]]
Q: What is the <html><code>profile</code></html> module vs <html><code>cProfile</code></html>?

A: Both are deterministic profilers with the same API. <html><code>cProfile</code></html> is a C extension (faster, recommended). <html><code>profile</code></html> is pure Python (can be extended more easily).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[CPU profiling reveals which functions consume the most time]]
* [[What is the `perf` profiler support added in Python 3.12?]]
Q: What does <html><code>python -m py_compile script.py</code></html> do?

A: It compiles a Python source file to bytecode (<html><code>.pyc</code></html>), useful for syntax checking without executing the code.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `__main__.py` file for?]]
* [[What is CPython bytecode?]]
* [[What is the `compile()` built-in?]]
Q: What is <html><code>compileall</code></html> used for?

A: <html><code>python -m compileall directory</code></html> compiles all <html><code>.py</code></html> files in a directory tree to <html><code>.pyc</code></html> files. Used when deploying to ensure bytecode is pre-compiled.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `compile()` built-in?]]
* [[What does `re.compile()` return and why use it?]]
* [[What is the `__main__.py` file for?]]
Q: What is the <html><code>linecache</code></html> module?

A: It reads lines from Python source files, with caching. Used internally by the <html><code>traceback</code></html> module to display source lines in tracebacks.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `__cached__` on a module?]]
* [[What is the `__pycache__` directory?]]
Q: What is <html><code>fnmatch</code></html> used for?

A: Unix filename pattern matching: <html><code>fnmatch.fnmatch('file.py', '*.py')</code></html> returns <html><code>True</code></html>. It supports <html><code>*</code></html>, <html><code>?</code></html>, <html><code>[seq]</code></html>, and <html><code>[!seq]</code></html> patterns.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the wildcard pattern in Python's match statement?]]
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[What is Python's `match` statement OR pattern?]]
Q: What is the <html><code>subprocess.PIPE</code></html> constant?

A: It indicates that a pipe should be created for stdin, stdout, or stderr, allowing the parent process to communicate with the child process.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `subprocess.run()` function?]]
* [[What is `subprocess.Popen` vs `subprocess.run`?]]
Q: What is <html><code>subprocess.Popen</code></html> vs <html><code>subprocess.run</code></html>?

A: <html><code>run()</code></html> is a high-level convenience function that waits for completion. <html><code>Popen</code></html> is the low-level class for more control: non-blocking execution, streaming I/O, and process management.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `subprocess.run()` function?]]
* [[What is the `subprocess.PIPE` constant?]]
Q: What is the <html><code>select</code></html> module?

A: It provides I/O multiplexing: monitoring multiple file descriptors for readability/writability. It wraps <html><code>select()</code></html>, <html><code>poll()</code></html>, and <html><code>epoll()</code></html> system calls.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `selectors` module?]]
* [[What is the `io` module?]]
Q: What is <html><code>selectors</code></html> module?

A: A higher-level I/O multiplexing library (Python 3.4+) that wraps <html><code>select</code></html>, providing a simpler API and automatically choosing the best available implementation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `select` module?]]
* [[What is `__class_getitem__` used for?]]
* [[What is `__spec__` in a module?]]
Q: What is the <html><code>socket</code></html> module?

A: Low-level networking: creating TCP/UDP sockets, binding, listening, connecting, sending, and receiving data.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
Q: What is <html><code>ssl.create_default_context()</code></html> for?

A: It creates an SSL context with secure default settings (certificate verification, modern TLS versions). Always use it instead of bare <html><code>ssl.SSLContext()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `contextlib.nullcontext()` used for?]]
* [[What is `contextlib.closing()` used for?]]
* [[What is `dict.setdefault(key, default)`?]]
Q: What is <html><code>urllib.parse.urlencode()</code></html> used for?

A: Converting a dictionary to a URL-encoded query string: <html><code>urlencode({'q': 'python', 'page': '1'})</code></html> returns <html><code>'q=python&amp;page=1'</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `base64` encoding used for in Python?]]
* [[What is the `requests` library?]]
* [[What does `sys.getdefaultencoding()` return in Python 3?]]
Q: What is <html><code>urllib.parse.urlparse()</code></html> used for?

A: Parsing a URL into its components: scheme, netloc, path, params, query, and fragment.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `pathlib.Path.glob()` used for?]]
* [[What is `pathlib.Path.resolve()` used for?]]
Q: What is the <html><code>email</code></html> module?

A: It provides tools for parsing, creating, and sending email messages, including MIME multipart messages with attachments.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `smtplib` used for?]]
Q: What is <html><code>smtplib</code></html> used for?

A: Sending emails via SMTP: creating an SMTP connection, authenticating, and sending messages.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `email` module?]]
* [[What is `importlib` used for?]]
Q: What is <html><code>sqlite3</code></html> in the standard library?

A: A built-in interface to SQLite databases. It requires no separate server and stores the entire database in a single file. Included since Python 2.5.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `shelve` module used for?]]
* [[What is the `__init__.py` file for?]]
Q: What is a Python wheel's tag format?

A: <html><code>{python tag}-{abi tag}-{platform tag}</code></html>. For example, <html><code>cp311-cp311-manylinux_2_17_x86_64</code></html> means CPython 3.11, CPython 3.11 ABI, 64-bit Linux.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `wheel` filename convention?]]
* [[What is `py3-none-any` in a wheel filename?]]
Q: What is <html><code>py3-none-any</code></html> in a wheel filename?

A: A pure Python wheel: works with any Python 3 version, no ABI dependency, any platform. Example: <html><code>requests-2.31.0-py3-none-any.whl</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `wheel` filename convention?]]
* [[What is a Python wheel's tag format?]]
Q: What is <html><code>pip install -e .</code></html> (editable install)?

A: It installs a package in development mode — the package is linked (not copied) so changes to source code take effect immediately without reinstalling.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What was the original name of `pip`?]]
* [[What is `pipx`?]]
* [[PYTHONPATH prepends to sys.path globally — prefer pip install -e instead]]
<html><code>pip install -e .</code></html> installs your package in editable (development) mode. Rather than copying code into <html><code>site-packages</code></html>, pip creates a <html><code>.pth</code></html> file or egg-link that points to your source directory. Any changes you make to the source files take effect immediately — no reinstall needed. Useful during development when you're iterating quickly. You can also specify extras: <html><code>pip install -e ".[dev]"</code></html> installs the package plus development dependencies listed in your <html><code>pyproject.toml</code></html> or <html><code>setup.py</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-packaging/primer.md</code></html>

''Related atoms''
* [[Multiple dependency declaration files create inconsistent builds]]
* [[Unpinned dependencies make builds non-reproducible and fragile]]
* [[Build and publish internal Python packages to private indexes]]
Q: What is <html><code>__import__</code></html> hook?

A: Python's import system can be customized by adding finder objects to <html><code>sys.meta_path</code></html> or <html><code>sys.path_hooks</code></html>. These hooks intercept import statements and can load modules from custom sources.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `importlib` used for?]]
* [[What does the `import` statement do in Python?]]
* [[What does `import __hello__` do?]]
Q: What is a Python namespace?

A: A mapping from names to objects. Examples: the set of built-in names, global names in a module, and local names in a function. Namespaces are implemented as dictionaries.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What are namespace packages?]]
* [[What is name mangling in Python?]]
Q: What is <html><code>exec()</code></html> dangerous for?

A: It executes arbitrary Python code from a string, which is a security risk if the string comes from untrusted input. It also makes code harder to analyze and debug.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between `exec()` and `eval()`?]]
Q: What is the <html><code>operator</code></html> module?

A: It provides function equivalents of Python operators: <html><code>operator.add(a, b)</code></html> is equivalent to <html><code>a + b</code></html>. Useful as arguments to <html><code>map()</code></html>, <html><code>reduce()</code></html>, and <html><code>sorted()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `operator.itemgetter()` used for?]]
* [[What is `operator.methodcaller()` used for?]]
* [[What is the walrus operator in Python?]]
Q: What is <html><code>typing.ClassVar</code></html> used for?

A: Marking an annotation as a class variable (not an instance variable) in dataclasses and type-checked code: <html><code>count: ClassVar[int] = 0</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `TypeVar` used for?]]
* [[What is the `@typing.dataclass_transform` decorator?]]
Q: What is <html><code>typing.Optional[X]</code></html> equivalent to?

A: <html><code>Union[X, None]</code></html> or <html><code>X | None</code></html> (Python 3.10+). It indicates the value can be of type X or <html><code>None</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.Union` used for?]]
* [[What is `typing.TypeGuard` used for?]]
* [[What is `typing.Never` (Python 3.11) or `typing.NoReturn` used for?]]
Q: What is <html><code>typing.Union</code></html> used for?

A: Expressing that a value can be one of several types: <html><code>Union[int, str]</code></html>. In Python 3.10+, the <html><code>|</code></html> syntax replaces it: <html><code>int | str</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.Optional[X]` equivalent to?]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.Literal` used for?]]
Q: What is <html><code>typing.Any</code></html>?

A: A special type that is compatible with every type. Variables annotated with <html><code>Any</code></html> are not type-checked. It is the "escape hatch" from the type system.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.TypeGuard` used for?]]
* [[What is `typing.Never` (Python 3.11) or `typing.NoReturn` used for?]]
Q: What is <html><code>typing.cast()</code></html> used for?

A: Telling the type checker to treat a value as a specific type without any runtime effect: <html><code>cast(int, some_value)</code></html>. It is purely a hint for static analysis.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.TypeGuard` used for?]]
* [[What is `typing.Callable` used for?]]
* [[What is `typing.TypeVarTuple` used for?]]
Q: What is "type casting"?

A: Manually converting a value from one data type to another using built-in constructors: int("42"), float(3), str(100), list("abc"). Also called type conversion. Implicit conversion happens automatically in some cases (int + float yields float). Failed casts raise ValueError or TypeError — always handle these in user-facing code.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is the `type` statement in Python 3.12?]]
* [[What function returns the data type of an object?]]
* [[What is `TypeAlias` used for?]]
Q: What is a <html><code>TYPE_CHECKING</code></html> guard?

A: <html><code>if TYPE_CHECKING:</code></html> is a block that only runs during type checking, not at runtime. Used for importing types needed only for annotations, avoiding circular imports.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.runtime_checkable` used for?]]
* [[What does `isinstance()` check that `type()` does not?]]
* [[What is `typing.cast()` used for?]]
Q: What is <html><code>typing.Callable</code></html> used for?

A: Annotating callable objects: <html><code>Callable[[int, str], bool]</code></html> describes a function taking an int and str and returning bool.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.runtime_checkable` used for?]]
* [[What is `typing.cast()` used for?]]
* [[What is `typing.TypeVarTuple` used for?]]
Q: What is <html><code>typing.Awaitable</code></html>?

A: A type hint for objects that can be <html><code>await</code></html>ed: coroutines, tasks, futures.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.AsyncIterator`?]]
* [[What is `async`/`await` in Python?]]
* [[What is `asyncio.create_task()` vs `await`?]]
Q: What is <html><code>typing.AsyncIterator</code></html>?

A: A type hint for async iterators — objects implementing <html><code>__aiter__</code></html> and <html><code>__anext__</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `typing.Awaitable`?]]
* [[What is `typing.get_type_hints()` used for?]]
* [[What is `typing.Any`?]]
Q: What is the <html><code>pydoc</code></html> module?

A: It generates documentation from Python modules: <html><code>python -m pydoc module_name</code></html> displays documentation, and <html><code>python -m pydoc -b</code></html> starts a documentation server.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m py_compile script.py` do?]]
* [[What is the `help()` built-in?]]
* [[What is the `__main__.py` file for?]]
Q: What is <html><code>unittest.TestCase.setUp()</code></html> vs <html><code>setUpClass()</code></html>?

A: <html><code>setUp()</code></html> runs before every test method. <html><code>setUpClass()</code></html> (a classmethod) runs once before all tests in the class — useful for expensive setup like database connections.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `unittest.mock.patch` used for?]]
* [[What is `unittest.mock.MagicMock`?]]
* [[What is `unittest.mock.sentinel`?]]
Q: What is <html><code>pytest.approx()</code></html> used for?

A: Comparing floating-point numbers in assertions: <html><code>assert 0.1 + 0.2 == pytest.approx(0.3)</code></html>. It handles floating-point imprecision.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is pytest's key advantage over unittest?]]
* [[Why does `0.1 + 0.2 != 0.3` in Python?]]
* [[What is the output of `print(0.1 + 0.2)`?]]
Q: What is <html><code>unittest.mock.sentinel</code></html>?

A: Unique objects useful as placeholders in tests: <html><code>sentinel.some_value</code></html> creates a unique object that can only be equal to itself.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `unittest.mock.patch` used for?]]
* [[What is `unittest.mock.MagicMock`?]]
* [[What is `unittest.TestCase.setUp()` vs `setUpClass()`?]]
Q: What is <html><code>pytest.monkeypatch</code></html>?

A: A built-in fixture for safely modifying objects, dictionaries, and environment variables during tests: <html><code>monkeypatch.setattr()</code></html>, <html><code>monkeypatch.setenv()</code></html>, etc.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is monkey patching?]]
* [[What is `pytest.raises`?]]
* [[What does `pytest.fixture` do?]]
Q: What is Django's migration system?

A: An automated system that tracks database schema changes. <html><code>makemigrations</code></html> detects model changes and creates migration files. <html><code>migrate</code></html> applies them to the database.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Django's `manage.py`?]]
* [[What is the Django admin?]]
* [[What is Django's ORM?]]
Q: What is Django's <html><code>manage.py</code></html>?

A: A command-line utility for Django projects: <html><code>python manage.py runserver</code></html>, <html><code>python manage.py migrate</code></html>, <html><code>python manage.py createsuperuser</code></html>, etc.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the Django admin?]]
* [[What is Django's migration system?]]
* [[What is the `__main__.py` file for?]]
Q: What template engine does Django use by default?

A: The Django Template Language (DTL), though it also supports Jinja2 as an alternative backend.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Jinja2?]]
* [[What design pattern does Django follow?]]
Q: What is Flask's <html><code>g</code></html> object?

A: A per-request global namespace for storing data during a request lifecycle. It is reset between requests.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does Flask call itself?]]
* [[What does the `gc` module do?]]
* [[What WSGI toolkit does Flask use under the hood?]]
Q: What is Pydantic v2's key change from v1?

A: Pydantic v2 rewrote the core validation engine in Rust (pydantic-core), making it 5-50x faster than v1. It also uses <html><code>model_validate()</code></html> instead of <html><code>parse_obj()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is FastAPI's key distinguishing feature?]]
* [[What performance improvement was made in Python 3.11?]]
Q: What is Starlette?

A: A lightweight ASGI framework that provides routing, middleware, WebSocket support, and background tasks. FastAPI is built on top of it.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What framework is FastAPI built on top of?]]
* [[What is Litestar (formerly Starlite)?]]
* [[What ASGI server is commonly used with FastAPI?]]
Q: What is <html><code>uvloop</code></html>?

A: A fast, drop-in replacement for asyncio's event loop, written in Cython and based on libuv. It can make asyncio 2-4x faster.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `uv` in the Python ecosystem?]]
* [[What is `asyncio.run()` used for?]]
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
Q: What NumPy function creates an array of zeros?

A: <html><code>np.zeros(shape)</code></html> creates an array filled with zeros. <html><code>np.ones(shape)</code></html> for ones, <html><code>np.empty(shape)</code></html> for uninitialized memory.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the difference between NumPy's `np.array()` and `np.asarray()`?]]
* [[What does NumPy stand for?]]
Q: What is the difference between NumPy's <html><code>np.array()</code></html> and <html><code>np.asarray()</code></html>?

A: <html><code>np.array()</code></html> always creates a new array. <html><code>np.asarray()</code></html> only creates a new array if the input is not already an ndarray, avoiding unnecessary copies.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What NumPy function creates an array of zeros?]]
* [[What is the core data structure in NumPy?]]
* [[What does NumPy stand for?]]
Q: What is NumPy's <html><code>dtype</code></html>?

A: The data type of array elements: <html><code>np.float64</code></html>, <html><code>np.int32</code></html>, <html><code>np.bool_</code></html>, etc. It determines storage size and behavior.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does NumPy stand for?]]
* [[What is `ctypes` used for?]]
* [[What is `sys.float_info`?]]
Q: What is Pandas <html><code>groupby()</code></html> used for?

A: Splitting a DataFrame into groups based on column values, applying a function to each group, and combining results — the "split-apply-combine" pattern.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `apply()` method in Pandas?]]
* [[What critical requirement does `itertools.groupby()` have?]]
* [[What is a Pandas DataFrame?]]
Q: What is the <html><code>apply()</code></html> method in Pandas?

A: It applies a function along an axis of a DataFrame or to each element of a Series. It is flexible but slower than vectorized operations.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Pandas `groupby()` used for?]]
* [[What is a Pandas Series?]]
* [[What is a Pandas DataFrame?]]
Q: What does <html><code>pandas.DataFrame.merge()</code></html> do?

A: SQL-style joins between DataFrames on columns or indexes. Supports <html><code>inner</code></html>, <html><code>outer</code></html>, <html><code>left</code></html>, and <html><code>right</code></html> join types.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `pandas.read_csv()` do?]]
* [[What is a Pandas DataFrame?]]
* [[What is Pandas `groupby()` used for?]]
Q: What is <html><code>scipy.optimize.minimize()</code></html>?

A: A function for finding the minimum of a scalar function, supporting multiple algorithms (Nelder-Mead, BFGS, L-BFGS-B, etc.).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does SciPy provide that NumPy does not?]]
* [[What does NumPy stand for?]]
* [[What is the peephole optimizer in CPython?]]
Q: What is a Jupyter kernel?

A: The computation engine that executes code in a notebook. Each kernel runs a specific language (IPython for Python). Multiple kernels can be installed for different languages or environments.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is Jupyter's name derived from?]]
* [[What is CPython bytecode?]]
Q: What is the <html><code>json</code></html> module's <html><code>cls</code></html> parameter?

A: It specifies a custom <html><code>JSONEncoder</code></html> subclass for serializing objects that are not JSON-serializable by default: <html><code>json.dumps(obj, cls=CustomEncoder)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `json.dumps(obj, default=str)` do?]]
* [[What does `python -m json.tool` do?]]
* [[What is `json.JSONDecodeError`?]]
Q: What is <html><code>json.JSONDecodeError</code></html>?

A: The exception raised when <html><code>json.loads()</code></html> or <html><code>json.load()</code></html> encounters invalid JSON. It is a subclass of <html><code>ValueError</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `json` module's `cls` parameter?]]
* [[What does `json.dumps(obj, default=str)` do?]]
* [[What does `python -m json.tool` do?]]
Q: What does <html><code>hashlib</code></html> provide?

A: Secure hash functions: <html><code>hashlib.sha256(data).hexdigest()</code></html>. It supports MD5, SHA-1, SHA-256, SHA-512, BLAKE2, and more.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[hashlib]]
* [[What is `hmac` module used for?]]
Q: What is <html><code>hmac</code></html> module used for?

A: Creating keyed-hash message authentication codes for verifying message integrity and authenticity: <html><code>hmac.new(key, message, hashlib.sha256).hexdigest()</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `hashlib` provide?]]
* [[What is the `shelve` module used for?]]
Q: What is <html><code>base64</code></html> encoding used for in Python?

A: Encoding binary data as ASCII text: <html><code>base64.b64encode(data)</code></html>. Commonly used for embedding binary data in JSON, URLs, or email.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `str.encode()` and `bytes.decode()`?]]
* [[str vs bytes]]
* [[What is a Python "magic comment" for encoding?]]
Q: What is <html><code>collections.abc.MutableMapping</code></html>?

A: An abstract base class for dict-like objects. Implementing <html><code>__getitem__</code></html>, <html><code>__setitem__</code></html>, <html><code>__delitem__</code></html>, <html><code>__len__</code></html>, and <html><code>__iter__</code></html> gives you the full mapping API for free.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.abc` and how does it differ from `collections`?]]
* [[What is `__getitem__` used for?]]
* [[What is `collections.ChainMap` used for?]]
Q: What is <html><code>zipimport</code></html>?

A: A built-in importer that allows importing Python modules directly from ZIP files. It is used by <html><code>python -m zipapp</code></html> and is how Ansible's Ansiballz module transfer works.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the Ansiballz framework?]]
* [[What is `python -m zipapp` used for?]]
* [[What is `importlib` used for?]]
Q: What does <html><code>python -m ensurepip</code></html> do?

A: It bootstraps <html><code>pip</code></html> into a Python installation that does not have it. Useful for minimal Python installations.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `python -m py_compile script.py` do?]]
* [[What is `python -m zipapp` used for?]]
* [[What does `python -m site` do?]]
Q: What is <html><code>sysconfig</code></html> used for?

A: Accessing Python's configuration: installation paths, compiler flags, platform tags. <html><code>sysconfig.get_paths()</code></html> returns where packages are installed.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sys.path` and how does Python use it?]]
* [[What is `sys.setprofile()` used for?]]
* [[What is the `PYTHONPATH` environment variable?]]
Q: What is the <html><code>dataclasses.make_dataclass()</code></html> function?

A: Dynamically creates a dataclass from a name and list of fields: <html><code>Point = make_dataclass('Point', ['x', 'y'])</code></html>. Useful for runtime dataclass generation.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `dataclasses.field()` metadata parameter for?]]
* [[What is `@dataclass` an example of in terms of Python internals?]]
* [[What does `@dataclass` generate automatically?]]
Q: What is <html><code>collections.abc.Iterator</code></html> vs <html><code>collections.abc.Iterable</code></html>?

A: <html><code>Iterable</code></html> defines <html><code>__iter__()</code></html>. <html><code>Iterator</code></html> defines both <html><code>__iter__()</code></html> and <html><code>__next__()</code></html>. All iterators are iterable, but not all iterables are iterators (e.g., lists are iterable but not iterators).

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.abc` and how does it differ from `collections`?]]
* [[What is the iterator protocol?]]
* [[What does `itertools.chain(*iterables)` do?]]
Q: What is the <html><code>fractions.Fraction.limit_denominator()</code></html> method?

A: It finds the closest rational approximation with a denominator at most <html><code>max_denominator</code></html>: <html><code>Fraction(3.141592653).limit_denominator(100)</code></html> gives <html><code>Fraction(311, 99)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What module allows exact arithmetic with fractions?]]
* [[What is `int.as_integer_ratio()` added in Python 3.8?]]
* [[What is the `decimal` module's `ROUND_HALF_EVEN` rounding mode?]]
Q: What is <html><code>int.as_integer_ratio()</code></html> added in Python 3.8?

A: It returns a pair of integers <html><code>(numerator, denominator)</code></html> equal to the integer with a positive denominator: <html><code>(10).as_integer_ratio()</code></html> returns <html><code>(10, 1)</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `decimal` module's `ROUND_HALF_EVEN` rounding mode?]]
* [[Is there a limit to integer size in Python 3?]]
* [[What is an "integer division" operator?]]
Q: What is the <html><code>unicodedata</code></html> module?

A: It provides access to the Unicode Character Database: <html><code>unicodedata.name('A')</code></html> returns <html><code>'LATIN CAPITAL LETTER A'</code></html>, and <html><code>unicodedata.normalize()</code></html> handles Unicode normalization forms.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `locale` module?]]
* [[What does `string.ascii_letters` contain?]]
* [[What does `sys.getdefaultencoding()` return in Python 3?]]
Q: What is Python's <html><code>match</code></html> statement OR pattern?

A: Use <html><code>|</code></html> to match multiple patterns: <html><code>case 200 | 201 | 202:</code></html> matches any of those status codes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[What is the `match` statement guard clause?]]
* [[What is `fnmatch` used for?]]
Q: What is Python's <html><code>match</code></html> statement mapping pattern?

A: <html><code>case {"status": 200, "body": body}:</code></html> matches dictionaries with specific keys and captures values. Extra keys are allowed.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the wildcard pattern in Python's match statement?]]
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[match / case (structural pattern matching)]]
Q: What is Python's <html><code>match</code></html> statement sequence pattern?

A: <html><code>case [first, *rest]:</code></html> matches sequences, capturing the first element and remaining elements in a list.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the wildcard pattern in Python's match statement?]]
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[What is the `match` statement guard clause?]]
Q: What does <html><code>sys.getswitchinterval()</code></html> return?

A: The thread switch interval in seconds (default 0.005 = 5ms). This controls how often the GIL is released to allow other threads to run.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the GIL's impact on I/O-bound vs CPU-bound threading?]]
* [[What does `sys.settrace()` do?]]
Q: What is <html><code>ctypes</code></html> used for?

A: Calling functions in C shared libraries from Python without writing C extension code. It provides C-compatible data types and function prototypes.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `cffi` (C Foreign Function Interface)?]]
* [[What is NumPy's `dtype`?]]
* [[What is `typing.TypeVarTuple` used for?]]
Q: What is <html><code>cffi</code></html> (C Foreign Function Interface)?

A: A third-party library for calling C code from Python. It is more Pythonic than <html><code>ctypes</code></html> and is used by PyPy for C extension compatibility.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `ctypes` used for?]]
* [[What is `mypyc`?]]
Q: What is the <html><code>difflib</code></html> module?

A: It provides tools for comparing sequences: <html><code>unified_diff()</code></html> and <html><code>context_diff()</code></html> for text comparisons, <html><code>SequenceMatcher</code></html> for computing similarity ratios.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `difflib.get_close_matches()` used for?]]
Q: What is <html><code>difflib.get_close_matches()</code></html> used for?

A: Finding strings similar to a target: <html><code>get_close_matches('appel', ['apple', 'ape', 'maple'])</code></html> returns <html><code>['apple', 'maple']</code></html>. Useful for "did you mean?" suggestions.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the `difflib` module?]]
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[What is `contextlib.closing()` used for?]]
Q: What is the <html><code>csv</code></html> module?

A: Reading and writing CSV files with <html><code>csv.reader()</code></html>, <html><code>csv.writer()</code></html>, <html><code>csv.DictReader()</code></html>, and <html><code>csv.DictWriter()</code></html>. It handles quoting, escaping, and different dialects.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `pandas.read_csv()` do?]]
* [[What is the `dis` module?]]
Q: What is <html><code>configparser</code></html> used for?

A: Reading and writing INI-style configuration files with sections, keys, and values. Similar to Windows <html><code>.ini</code></html> files.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `sysconfig` used for?]]
* [[What is `argparse.FileType`?]]
Q: What is <html><code>argparse.FileType</code></html>?

A: A factory for <html><code>argparse</code></html> that opens files: <html><code>parser.add_argument('input', type=argparse.FileType('r'))</code></html> automatically opens the file for reading.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What does `argparse.ArgumentParser.add_subparsers()` do?]]
* [[What does `sys.argv` contain?]]
* [[What is the standard library module for parsing command-line arguments?]]
Q: What is the <html><code>concurrent.futures.as_completed()</code></html> function?

A: It yields <html><code>Future</code></html> objects as they complete, regardless of submission order. Useful for processing results as they become available.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `concurrent.futures` and when was it introduced?]]
* [[concurrent.futures unifies thread and process pool APIs]]
* [[What is `asyncio.create_task()` vs `await`?]]
Q: What is <html><code>asyncio.wait_for()</code></html> used for?

A: Wrapping a coroutine with a timeout: <html><code>await asyncio.wait_for(coro, timeout=5.0)</code></html> raises <html><code>asyncio.TimeoutError</code></html> if the coroutine does not complete in time.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
* [[What is `asyncio.Queue`?]]
Q: What is <html><code>asyncio.create_task()</code></html> vs <html><code>await</code></html>?

A: <html><code>await coro()</code></html> runs and waits for a single coroutine. <html><code>asyncio.create_task(coro())</code></html> schedules it to run concurrently without waiting, returning a <html><code>Task</code></html> that can be awaited later.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `asyncio.run()` used for?]]
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[Debugging hung async code via debug mode and task inspection]]
Q: What is the <html><code>__aenter__</code></html> and <html><code>__aexit__</code></html> protocol?

A: The async context manager protocol, used with <html><code>async with</code></html>. <html><code>__aenter__</code></html> is an async method called on entry, <html><code>__aexit__</code></html> on exit.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is a context manager protocol?]]
* [[What is `__aiter__` and `__anext__`?]]
* [[What is the `contextlib.aclosing()` context manager?]]
Q: What is <html><code>__aiter__</code></html> and <html><code>__anext__</code></html>?

A: The async iterator protocol. <html><code>__aiter__</code></html> returns the async iterator, <html><code>__anext__</code></html> returns an awaitable that yields the next value or raises <html><code>StopAsyncIteration</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is the iterator protocol?]]
* [[What does the `__iter__` method return?]]
* [[What is the `__aenter__` and `__aexit__` protocol?]]
Q: What is <html><code>collections.abc.Coroutine</code></html>?

A: An abstract base class for coroutine objects (those created by <html><code>async def</code></html> functions). It defines <html><code>send()</code></html>, <html><code>throw()</code></html>, and <html><code>close()</code></html> methods.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `collections.abc` and how does it differ from `collections`?]]
* [[What is `asyncio.wait_for()` used for?]]
Q: What is <html><code>sys.exc_info()</code></html> used for?

A: Returns a tuple <html><code>(type, value, traceback)</code></html> of the exception currently being handled. Returns <html><code>(None, None, None)</code></html> if no exception is being handled.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What arguments does `__exit__` receive?]]
* [[What does the `traceback` module provide?]]
* [[What does `sys.exit()` actually raise?]]
Q: What is the <html><code>contextlib.aclosing()</code></html> context manager?

A: Added in Python 3.10, it calls <html><code>aclose()</code></html> on an async generator when exiting the <html><code>async with</code></html> block, ensuring cleanup.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What is `contextlib.closing()` used for?]]
* [[What is the `contextlib.asynccontextmanager` decorator for?]]
* [[What is the `contextlib.nullcontext()` used for?]]
Q: What is the <html><code>enum.verify</code></html> decorator added in Python 3.11?

A: It validates enum classes according to named rules: <html><code>@verify(UNIQUE)</code></html> ensures no duplicate values, <html><code>@verify(CONTINUOUS)</code></html> ensures no gaps in integer values.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[What `Enum` subclass was introduced in Python 3.11 to ensure members are valid strings?]]
* [[What is `enum.unique` used for?]]
* [[What is the `enum.nonmember()` function added in Python 3.11?]]
Q: What does <html><code>list.extend()</code></html> do vs <html><code>list.append()</code></html>?

A: <html><code>append(x)</code></html> adds x as a single element. <html><code>extend(iterable)</code></html> adds each element of the iterable individually. <html><code>lst.append([1,2])</code></html> adds one list element; <html><code>lst.extend([1,2])</code></html> adds two integer elements.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

''Related atoms''
* [[How do you add an item to the end of a list?]]
* [[What is the time complexity of `list.append()`?]]
* [[What are the advantages of `collections.deque` over a list?]]
Q: What are metaclasses and when would you use them?

A: A metaclass is the class of a class — it controls how classes themselves are created. The default metaclass is <html><code>type</code></html>.

class Meta(type):
    def __new__(mcs, name, bases, namespace):
        # modify class before creation
        namespace['created_by'] = 'Meta'
        return super().__new__(mcs, name, bases, namespace)

class MyClass(metaclass=Meta):
    pass

print(MyClass.created_by)  # 'Meta'

Use cases: ORMs (Django models), API registration, enforcing interfaces. In practice, __init_subclass__ or class decorators cover most use cases more simply.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What is a metaclass?]]
* [[What is `__init_subclass__` vs a metaclass?]]
* [[What is __init_subclass__ and how does it replace metaclasses?]]
Q: Implement the Singleton pattern in Python (three ways)

A: 1. Module-level instance (Pythonic):
_instance = MyClass()

# __new__ override:
class Singleton:
    _instance = None
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

# Metaclass:
class SingletonMeta(type):
    _instances = {}
    def __call__(cls, *args, **kw):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kw)
        return cls._instances[cls]

The module-level approach is simplest and most Pythonic. Use __new__ for classes that need lazy initialization.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What does `__init__` vs `__new__` do?]]
* [[What are metaclasses and when would you use them?]]
* [[What is __init_subclass__ and how does it replace metaclasses?]]
Q: What is currying in Python?

A: Currying transforms a function with multiple arguments into a sequence of functions each taking one argument.

from functools import partial

def multiply(x, y):
    return x * y

double = partial(multiply, 2)
print(double(5))  # 10

! Manual currying:
def curry_multiply(x):
    def inner(y):
        return x * y
    return inner

triple = curry_multiply(3)
print(triple(5))  # 15

functools.partial is the standard way to do partial application in Python. True currying (auto-currying) isn't built-in but libraries like toolz provide it.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What does `functools.partialmethod` do?]]
* [[What does `functools.partial` do?]]
* [[What are *args and **kwargs in Python functions?]]
Q: Explain Python's Method Resolution Order (MRO)

A: MRO determines the order in which base classes are searched when calling a method. Python uses the C3 linearization algorithm.

class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass

print(D.__mro__)  # (D, B, C, A, object)

Rules: (1) children before parents, (2) left-to-right order preserved, (3) each class appears once. Use ClassName.mro() or ClassName.__mro__ to inspect. super() follows the MRO, not just the immediate parent — critical for cooperative multiple [[inheritance|Inheritance]].

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What is `super()` and how does it work?]]
* [[What is C3 linearization?]]
* [[Explain name mangling with double underscores]]
Q: What are descriptors in Python?

A: A descriptor is any object that defines __get__, __set__, or __delete__. They control attribute access on classes.

class Validator:
    def __set_name__(self, owner, name):
        self.name = name
    def __get__(self, obj, objtype=None):
        return obj.__dict__.get(self.name)
    def __set__(self, obj, value):
        if not isinstance(value, int):
            raise TypeError(f'{self.name} must be int')
        obj.__dict__[self.name] = value

class Order:
    quantity = Validator()

Property, classmethod, staticmethod are all implemented as descriptors. Data descriptors (with __set__) take priority over instance __dict__; non-data descriptors don't.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is a data descriptor vs a non-data descriptor?]]
* [[What is `__set_name__` used for?]]
* [[What is `__dict__` on a class vs an instance?]]
Q: Dataclasses vs namedtuples — when to use which?

A: Both reduce boilerplate for data-holding classes but differ in mutability and features.

from dataclasses import dataclass
from typing import [[NamedTuple]]

@dataclass
class PointDC:
    x: float
    y: float

class PointNT(NamedTuple):
    x: float
    y: float

NamedTuple: immutable, hashable, tuple-compatible, lighter memory. Use for simple records, dict keys, function returns.

Dataclass: mutable by default (frozen=True for immutable), supports default_factory, __post_init__, [[inheritance|Inheritance]], field metadata. Use for domain objects needing methods or validation.

Rule of thumb: NamedTuple for simple data, dataclass for everything else.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[NamedTuple]]
* [[What is the `dataclasses.make_dataclass()` function?]]
* [[What is `typing.NamedTuple` and how does it compare to `collections.namedtuple`?]]
Q: Explain name mangling with double underscores

A: Python mangles attributes starting with __ (double underscore) by prepending _ClassName to prevent accidental override in subclasses.

class Parent:
    def __init__(self):
        self.__secret = 42

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.__secret = 99  # different attribute!

c = Child()
print(c._Parent__secret)  # 42
print(c._Child__secret)   # 99

This is NOT access control — it's name collision avoidance. Single underscore (_name) is the convention for 'private'. Use __ only when you need to prevent subclass attribute clashes.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What is name mangling in Python?]]
* [[What is `__set_name__` used for?]]
* [[What is the `__qualname__` attribute?]]
Q: Explain Python's property decorator

A: @property creates managed attributes with getter/setter/deleter methods.

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32

    @fahrenheit.setter
    def fahrenheit(self, value):
        self._celsius = (value - 32) * 5/9

t = Temperature(100)
print(t.fahrenheit)    # 212.0
t.fahrenheit = 32
print(t._celsius)      # 0.0

Properties are descriptors under the hood. Use them to add validation, computed attributes, or to migrate from public attributes to managed access without breaking the API.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What is the `property` built-in?]]
* [[@property]]
* [[What does `@property` do under the hood?]]
Q: What is __repr__ vs __str__?

A: __repr__ is for developers (unambiguous), __str__ is for users (readable).

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    def __repr__(self):
        return f'Point({self.x}, {self.y})'  # eval-able if possible
    def __str__(self):
        return f'({self.x}, {self.y})'

p = Point(1, 2)
repr(p)  # 'Point(1, 2)'
str(p)   # '(1, 2)'
print(p) # calls __str__: (1, 2)

If only one is defined, implement __repr__ — str() falls back to __repr__, but not vice versa. f-strings and print() call __str__; the REPL and containers call __repr__.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python-oop.tsv</code></html>

''Related atoms''
* [[What is the difference between `__str__` and `__repr__`?]]
* [[What is the `__annotations__` attribute?]]
* [[def (function definition)]]
Time pressure creates a cascade of shortcuts, each seemingly small, each making the next easier to justify. Skipping documentation to move fast leads to repeating a mistake the docs warn against; 4 hours wasted. Making changes without a rollback plan leads to a 6-hour manual recovery instead of one command when things break. Testing in staging would have caught the error, but skipping it for speed causes a 2-hour production outage. Having only one person understand the system means an incident becomes 5x harder to resolve when that person is unavailable. By the third shortcut, the pressure has compounded into critical mass: the system burns, pages fire, and a war room full of people scramble to understand what went wrong. The pattern is that no single shortcut is catastrophic — but cutting caution at each step creates a risk profile where failure becomes likely, not exceptional. Read the documentation. Have a rollback plan. Test in staging. Document and cross-train. These practices aren't bureaucratic overhead; they're the only reliable path through firefighting.

----
''Sources''
* <html><code>training/library/topics/python-packaging/anti_primer.md</code></html>
Running <html><code>pip install</code></html> in the system Python (e.g., <html><code>/usr/bin/python3</code></html>) installs packages into the system's <html><code>site-packages</code></html> directory, where they can interfere with system tools. For example, installing a newer version of PyYAML can break <html><code>apt</code></html> if the system version of apt depends on an older one. Modern pip (23.0+) blocks this with <html><code>externally-managed-environment</code></html> error for exactly this reason.

The fix is always to use a virtualenv: <html><code>python3 -m venv .venv</code></html>, then activate it, then pip install inside it. The virtualenv isolates your packages into a separate directory, leaving the system Python untouched.

Never use <html><code>--break-system-packages</code></html> to bypass this restriction unless you have a very specific reason and understand the consequences. Even then, document why so the next person knows it's intentional.

This rule applies to every Python tool and script, including infrastructure automation. If you're deploying a tool via CI, run it inside a virtualenv or container, never directly in system Python. The only exception is system packages installed via apt or yum, which manage their own dependencies correctly.

----
''Sources''
* <html><code>training/library/topics/python-packaging/footguns.md</code></html>

''Related atoms''
* [[Diagnosing import failures in Python and Docker]]
* [[Manage multiple Python versions for different projects]]
On Linux, Python packages come from two sources: system packages in <html><code>/usr/lib/python3/dist-packages/</code></html> (managed by apt, dnf, yum) and pip packages in <html><code>/usr/local/lib/</code></html> or <html><code>.venv/lib/</code></html> (managed by pip). System packages are for system tools — the package manager that uses them. Application dependencies always go in virtualenvs. PEP 668 (Python 3.11+) enforces this by raising an "externally-managed-environment" error when you try to <html><code>pip install</code></html> outside a venv — this is intentional and correct. The error was introduced because Ubuntu and Debian users were breaking system Python by installing application packages globally. If you see that error: activate a venv and try again. Never use <html><code>pip install --user</code></html> or system-wide installs for applications.

----
''Sources''
* <html><code>training/library/topics/python-packaging/primer.md</code></html>

''Related atoms''
* [[Diagnosing import failures in Python and Docker]]
* [[Recover broken virtualenvs through targeted repair methods]]
* [[What is a virtual environment in Python and why use it?]]
Writing <html><code>requests</code></html> in <html><code>requirements.txt</code></html> instead of <html><code>requests==2.31.0</code></html> means your build gets whatever version is on PyPI right now. If a new version is released with a breaking change, your build silently installs it and fails at runtime. Worse, if the change is subtle (a behavior shift, a deprecated API), you might not notice until production.

The fix is to pin every dependency to a specific version. Use <html><code>pip-compile</code></html> from <html><code>pip-tools</code></html> to generate pinned requirements from a loose spec file. It resolves the entire dependency tree, outputs exact versions and hashes for every package (including transitive dependencies), and locks them down.

Pinned requirements are reproducible: the same <html><code>requirements.txt</code></html> installs the exact same packages every time, across every machine. Without pinning, the same file might install different versions on Monday and Friday, making builds unreproducible.

For packages with known security vulnerabilities, update the version and regenerate the pinned file. For major version upgrades, update the loose spec and repin. This gives you control over when and how you upgrade.

----
''Sources''
* <html><code>training/library/topics/python-packaging/footguns.md</code></html>

''Related atoms''
* [[Version pinning strategy depends on whether you're a library or application]]
* [[Diagnose dependency conflicts with pipdeptree]]
* [[Multiple dependency declaration files create inconsistent builds]]
<html><code>pip-compile</code></html> (from pip-tools) locks all dependencies to exact versions with cryptographic hashes. Start with <html><code>requirements.in</code></html> declaring only top-level dependencies. Run <html><code>pip-compile --generate-hashes -o requirements.txt requirements.in</code></html> to generate a fully pinned <html><code>requirements.txt</code></html> with SHA-256 hashes for every package and transitive dependency. Install with <html><code>pip-sync requirements.txt</code></html>, which installs exactly what's locked and removes anything extra. To upgrade, edit <html><code>requirements.in</code></html> or run <html><code>pip-compile --upgrade requirements.in</code></html> to refresh hashes. For dev tools, create <html><code>requirements-dev.in</code></html> referencing the main lock file with <html><code>-c requirements.txt</code></html>, then compile dev dependencies separately. In CI, run <html><code>pip install --require-hashes -r requirements.txt</code></html>—if hashes mismatch (poisoned packages, MITM), installation fails. This workflow provides strong reproducibility guarantees and supply-chain security, ensuring every deployment runs identical code.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>

''Related atoms''
* [[Scan Python dependencies against known vulnerabilities]]
* [[Diagnose dependency conflicts with pipdeptree]]
* [[Version pinning strategy depends on whether you're a library or application]]
If <html><code>apt install python3-numpy</code></html> puts numpy in <html><code>/usr/lib/python3/dist-packages/</code></html>, and then <html><code>pip install numpy --upgrade</code></html> installs a newer version in <html><code>/usr/local/lib/python3.11/dist-packages/</code></html>, Python's <html><code>sys.path</code></html> will load one or the other depending on path order. This creates confusion: which numpy did you get? Additionally, <html><code>apt autoremove</code></html> might delete files that pip depends on, breaking the pip-installed version.

The root problem is that apt and pip manage the same Python environment but don't coordinate. They have no way to know about each other's packages.

The solution is strict separation: let apt manage system tools and their Python dependencies, and let pip manage application dependencies inside virtualenvs. Never install a Python package both ways in the same Python path.

If you need a library both as a system tool and in your application, install it via pip in a virtualenv for your app. For system tools, use apt, and accept that they may be outdated. If you need a specific version that apt doesn't have, consider installing the system tool in a container or virtualenv instead of in system Python.

----
''Sources''
* <html><code>training/library/topics/python-packaging/footguns.md</code></html>

''Related atoms''
* [[Manage multiple Python versions for different projects]]
* [[Diagnosing import failures in Python and Docker]]
* [[PYTHONPATH prepends to sys.path globally — prefer pip install -e instead]]
If both <html><code>setup.py</code></html> and <html><code>pyproject.toml</code></html> exist with different metadata, some tools read one and some read the other. <html><code>pip install .</code></html> might read from <html><code>pyproject.toml</code></html> while <html><code>python -m build</code></html> reads from <html><code>setup.py</code></html>, resulting in different dependencies being installed depending on how the package is built.

This is a legacy problem from Python's transition to standardized packaging. Older tools relied on <html><code>setup.py</code></html>; newer ones use <html><code>pyproject.toml</code></html> (PEP 621). During the transition, projects ended up with both, and they diverged over time.

The solution for new projects is to use <html><code>pyproject.toml</code></html> exclusively and delete <html><code>setup.py</code></html> and <html><code>setup.cfg</code></html>. Define all project metadata there: name, version, dependencies, extras, build system. For very old projects that must support ancient tooling, keep <html><code>setup.py</code></html> in sync with <html><code>pyproject.toml</code></html>, but document that they must be identical.

The single source of truth prevents confusion and makes builds reproducible. Modern tooling (pip, build, setuptools) all support <html><code>pyproject.toml</code></html>, and the ecosystem has largely moved over.

----
''Sources''
* <html><code>training/library/topics/python-packaging/footguns.md</code></html>

''Related atoms''
* [[What file replaced `setup.py` and `setup.cfg` as the modern Python project configuratio…]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
* [[Unpinned dependencies make builds non-reproducible and fragile]]
A directory without <html><code>__init__.py</code></html> is not a Python package, even if it contains <html><code>.py</code></html> files. Trying to <html><code>from mypackage.utils.helpers import format_date</code></html> fails with <html><code>ModuleNotFoundError: No module named 'mypackage.utils'</code></html> if <html><code>utils/</code></html> lacks <html><code>__init__.py</code></html>.

The <html><code>__init__.py</code></html> file can be empty; its mere presence tells Python "this directory is a package." Modern Python (3.3+) supports namespace packages (PEP 420), which don't require <html><code>__init__.py</code></html>, but they change import semantics and are rarely needed outside of plugin systems.

The issue is especially confusing because code works when run from the project directory (Python adds the current directory to <html><code>sys.path</code></html>) but fails after installation. Running with <html><code>python -m mypackage.module</code></html> often masks the problem because the module is found in the current directory rather than via the import system.

Tools like <html><code>setuptools</code></html> with <html><code>find_packages()</code></html> silently skip directories without <html><code>__init__.py</code></html>, so your package installs incomplete without any warning. Always use <html><code>__init__.py</code></html>, even if empty. If you need namespace packages, use <html><code>find_namespace_packages()</code></html> and understand the tradeoffs.

----
''Sources''
* <html><code>training/library/topics/python-packaging/footguns.md</code></html>

''Related atoms''
* [[What is the `__init__.py` file for?]]
* [[What are namespace packages?]]
* [[PYTHONPATH prepends to sys.path globally — prefer pip install -e instead]]
Code using relative imports (<html><code>from ..utils import helper</code></html>) works when installed as a package, but fails if you run the module directly with <html><code>python mypackage/module.py</code></html>. Python can't resolve the relative import because there's no package context. The error is <html><code>ImportError: attempted relative import with no known parent package</code></html>.

Conversely, absolute imports (<html><code>from mypackage.utils import helper</code></html>) fail if the package isn't on <html><code>sys.path</code></html>, which happens when you run a module directly from its directory.

The solution is to use absolute imports consistently and always run code via <html><code>python -m package.module</code></html> instead of <html><code>python path/to/module.py</code></html>. The <html><code>-m</code></html> flag treats the module as part of a package, establishing the correct import context.

This is one of the most subtle Python gotchas. Code that works in development (run directly) breaks in production (installed as a package) or vice versa, and it can take hours to debug if you don't know the rule. For library code, prefer absolute imports and <html><code>python -m</code></html>. For scripts that need to be executable directly, avoid relative imports entirely or provide a shebang that runs with <html><code>python -m</code></html>.

----
''Sources''
* <html><code>training/library/topics/python-packaging/footguns.md</code></html>

''Related atoms''
* [[Diagnosing import failures in Python and Docker]]
* [[Inspect sys.path and site-packages to understand module resolution]]
* [[ModuleNotFoundError usually means wrong Python, wrong path, or inactive venv]]
Installing a dependency from a git URL without pinning to a commit (<html><code>pip install git+https://github.com/org/lib.git</code></html>) fetches whatever is on the default branch right now. Builds become non-reproducible: the same <html><code>requirements.txt</code></html> might install different code on different days. If the repo is force-pushed, the build silently gets new code without any indication.

Pinning to a branch (<html><code>@main</code></html>) doesn't solve this; the branch pointer moves. The solution is to pin to a specific commit hash (<html><code>@a1b2c3d</code></html>) or immutable tag (<html><code>@v1.2.3</code></html>). A commit hash guarantees you get the exact code every time.

Even better: publish internal packages to a private PyPI index (devpi, Artifactory, AWS CodeArtifact) instead of installing from git. This decouples the build system from git hosting and lets you control availability, versions, and retention independently.

Git-based installs are fragile in CI and production. They add network failure modes (git server down, ssh key missing), they don't support reproducible builds, and they make auditing versions difficult. Reserve git installs for development-only dependencies.

----
''Sources''
* <html><code>training/library/topics/python-packaging/footguns.md</code></html>

''Related atoms''
* [[Unpinned dependencies make builds non-reproducible and fragile]]
* [[Build and publish internal Python packages to private indexes]]
* [[Version pinning strategy depends on whether you're a library or application]]
Python packages ship in two formats. A wheel (<html><code>.whl</code></html>) is a pre-built binary archive that installs in seconds — no compilation needed on the target machine. Wheels are platform-specific when they contain C extensions; the filename encodes the Python version, ABI, and OS (e.g., <html><code>cp311-cp311-manylinux_2_17_x86_64</code></html> means CPython 3.11 on x86_64 Linux with glibc 2.17+). A source distribution (sdist) is a <html><code>.tar.gz</code></html> of source code; installing it requires build tools like a C compiler on the target machine. Always prefer wheels for deployment: they're faster, more reliable, and don't require the target system to have a build toolchain. Build wheels in CI and push them to your PyPI (private or public).

----
''Sources''
* <html><code>training/library/topics/python-packaging/primer.md</code></html>

''Related atoms''
* [[What is `sdist` in Python packaging?]]
Different version constraints serve different purposes. Exact pinning (<html><code>requests==2.31.0</code></html>) is appropriate for production application deploys and Docker images — you want reproducible, tested versions. Compatible release (<html><code>requests~=2.31.0</code></html>) allows patch updates within a minor version and is useful for libraries, where over-constraining forces users into unnecessary incompatibilities. Minimum version (<html><code>requests&gt;=2.28</code></html>) or ranges (<html><code>&gt;=2.28,&lt;3.0</code></html>) are pragmatic for direct dependency specs when you know what works. For applications: use exact pins in a committed <html><code>requirements.txt</code></html> (generated from a <html><code>.in</code></html> file via <html><code>pip-compile</code></html>), and update periodically with <html><code>pip-compile --upgrade</code></html>. For libraries: use minimum version or compatible release in <html><code>pyproject.toml</code></html> to give downstream projects room to resolve versions. Avoid unpinned <html><code>requests</code></html> in production.

----
''Sources''
* <html><code>training/library/topics/python-packaging/primer.md</code></html>

''Related atoms''
* [[Unpinned dependencies make builds non-reproducible and fragile]]
* [[Lock dependencies with pip-compile for reproducibility]]
When you can't or won't publish to public PyPI, run a private index. ''devpi'' is a lightweight, local-first option: install <html><code>devpi-server</code></html> and <html><code>devpi-client</code></html>, initialize and start the server on <html><code>localhost:3141</code></html>, then upload and install packages as if using public PyPI. ''AWS CodeArtifact'' is AWS's managed option: authenticate with an IAM-generated token and install from a CodeArtifact URL, useful if you're already in AWS. ''pip.conf'' (in <html><code>~/.pip/</code></html> or a virtualenv's root) lets you set a default index URL and extra indexes without per-command arguments — useful when you have both public and private packages. Whichever you choose, packages stay on your network and you keep control over who can push and pull.

----
''Sources''
* <html><code>training/library/topics/python-packaging/primer.md</code></html>

''Related atoms''
* [[Build and publish internal Python packages to private indexes]]
* [[How do you install a package in Python?]]
* [[Editable installs let you edit source and see changes immediately]]
Multi-stage Docker builds separate build-time dependencies from runtime. The first stage installs build tools (gcc, dev headers) and pip-installs dependencies into <html><code>/install</code></html>; the second stage starts from a fresh slim base image, copies the prebuilt packages from stage 1, and discards the build tools. This pattern cuts image size significantly. Key practices: always use <html><code>pip install --no-cache-dir</code></html> to skip pip's internal cache; copy <html><code>requirements.txt</code></html> before source code so code changes don't invalidate the pip-install layer; pin the base image by digest (<html><code>python:3.11-slim@sha256:abc123...</code></html>) for reproducibility; avoid virtualenvs in Docker (you already have process isolation). Install only the runtime library dependencies you need in stage 2 (e.g., <html><code>libpq5</code></html> for PostgreSQL), not development headers.

----
''Sources''
* <html><code>training/library/topics/python-packaging/primer.md</code></html>
<html><code>sys.path</code></html> is the list of directories Python searches when you <html><code>import</code></html> something. You can inspect it with <html><code>import sys; print(sys.path)</code></html> or use <html><code>site.getsitepackages()</code></html> to see all site-packages directories. To find where a specific installed package lives, import it and check <html><code>module.__file__</code></html>. These tools are essential for debugging import errors — they let you verify that a package is actually installed where your Python executable can find it.

----
''Sources''
* <html><code>training/library/topics/python-packaging/primer.md</code></html>

''Related atoms''
* [[What is the `site` module responsible for?]]
* [[What is `sys.path` and how does Python use it?]]
* [[ModuleNotFoundError usually means wrong Python, wrong path, or inactive venv]]
<html><code>PYTHONPATH</code></html> is an environment variable that prepends directories to Python's module search path. Setting <html><code>PYTHONPATH=/opt/mylibs:$PYTHONPATH python script.py</code></html> makes <html><code>/opt/mylibs</code></html> searchable. It's tempting as a quick fix to make a project importable, but it's a footgun: the setting is global and affects //every// Python program in that shell, not just yours. A stray <html><code>PYTHONPATH</code></html> can mask import errors or cause subtle conflicts. Prefer <html><code>pip install -e .</code></html> (editable install) to make a development project importable — it's explicit, scoped to a virtualenv, and doesn't pollute other programs.

----
''Sources''
* <html><code>training/library/topics/python-packaging/primer.md</code></html>

''Related atoms''
* [[What is the `PYTHONPATH` environment variable?]]
* [[What is `sys.path` and how does Python use it?]]
* [[System Python must use virtualenvs to prevent package conflicts]]
<html><code>pip-audit</code></html> scans your installed packages against a known-vulnerabilities database and reports CVEs and fix versions. <html><code>safety</code></html> is a similar alternative. <html><code>pip-licenses</code></html> generates a table of licenses for all your dependencies, useful for compliance audits. These tools are worth running in CI to catch issues before they reach production.

----
''Sources''
* <html><code>training/library/topics/python-packaging/primer.md</code></html>

''Related atoms''
* [[Lock dependencies with pip-compile for reproducibility]]
* [[Diagnose dependency conflicts with pipdeptree]]
<html><code>pip-audit</code></html> is the official PSF tool for vulnerability scanning, checking the public OSV database. Run it on the current environment with <html><code>pip-audit</code></html> or scan a requirements file without installing: <html><code>pip-audit -r requirements.txt</code></html>. Output includes affected package, version, CVE/advisory ID, and available fix versions. For CI pipelines, use <html><code>--format json</code></html> for machine output. <html><code>pip-audit --fix</code></html> attempts automatic upgrades. An alternative is <html><code>safety</code></html>, using the Tidelift database with the same workflow. Both integrate into CI to fail builds if vulnerabilities are found. Beyond version vulnerabilities, audit your dependency list regularly—<html><code>pip list | sort</code></html>—to catch typosquatting (packages impersonating popular libraries). Vulnerability scanning is essential for applications handling sensitive data or exposed to untrusted input. Establish a cadence: run audits weekly or on dependency changes, and prioritize fixing issues based on severity and exploitability, not just CVE presence.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>

''Related atoms''
* [[Lock dependencies with pip-compile for reproducibility]]
* [[Diagnose dependency conflicts with pipdeptree]]
"ModuleNotFoundError" doesn't mean the module isn't installed — it means this Python can't find it. Debug systematically: (1) confirm which Python is running (<html><code>which python3</code></html>, <html><code>python3 -c "import sys; print(sys.executable)"</code></html>). (2) Check where that Python looks for packages (<html><code>python3 -c "import sys; print('\n'.join(sys.path))"</code></html>). (3) Check where the module actually installed (<html><code>python3 -m pip show module_name</code></html>). (4) Verify the virtualenv is activated (<html><code>echo $VIRTUAL_ENV</code></html> — if empty, it isn't). (5) Check for namespace package conflicts (<html><code>python3 -c "import mymodule; print(mymodule.__file__)"</code></html>). (6) If still lost, trace imports with verbose mode (<html><code>python3 -v -c "import mymodule" 2&gt;&amp;1</code></html>). For scripts that need to import from parent directories, use relative paths from <html><code>__file__</code></html> rather than absolute paths, or just install the package in editable mode (<html><code>pip install -e .</code></html>) — it's more reliable and portable.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>

''Related atoms''
* [[Diagnosing import failures in Python and Docker]]
* [[Inspect sys.path and site-packages to understand module resolution]]
* [[System Python must use virtualenvs to prevent package conflicts]]
When a virtualenv breaks—usually after OS upgrades, Python version changes, or corruption—recovery depends on severity and symptoms. Complete recreation is safest: save your requirements, delete the venv, and rebuild with <html><code>python3 -m venv</code></html>. For minor issues or after Python patch updates, <html><code>venv --upgrade</code></html> refreshes the internal structure without deletion. Force-reinstall (<html><code>pip install --force-reinstall -r requirements.txt</code></html>) replaces all packages while keeping the venv intact, useful for fixing corrupted installations. When pip itself is broken, bootstrap directly with <html><code>python3 -m ensurepip --upgrade</code></html>. SSL certificate errors indicate stale CA bundles—update system certificates or temporarily use <html><code>pip --trusted-host</code></html>. The strategy is graduated: start with the least disruptive fix and escalate to full recreation only if needed. Testing each approach in sequence saves time and avoids unnecessary work.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>

''Related atoms''
* [[Quick fixes for common Python installation errors]]
* [[Never mix system and pip packages — use virtualenvs for applications]]
* [[System Python must use virtualenvs to prevent package conflicts]]
Multi-stage builds separate compilation from runtime, removing build-time dependencies from the final image. In the builder stage, install compilers, headers, and build tools (<html><code>build-essential</code></html>, <html><code>libpq-dev</code></html>, etc.), then compile or download wheels for all dependencies. In the runtime stage, start fresh from a minimal image (<html><code>python:3.11-slim</code></html>) and copy only compiled packages, not the toolchain. For compiled packages like numpy or cryptography, generate pre-built wheels in the builder; the runtime installs from those wheels without needing compilers. This shrinks images dramatically—often from 800MB+ down to 150–300MB. A variant: export Poetry or PDM lock files to requirements.txt in the builder, then use standard pip in runtime. Always run applications as non-root (create with <html><code>useradd -r -u 1000</code></html>) and use slim Python image variants. Docker layer caching ensures the builder stage runs infrequently when dependencies change rarely, keeping rebuild times fast.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>
For internal libraries shared across teams, structure the project with a <html><code>src/</code></html> directory containing the package and <html><code>pyproject.toml</code></html> at the root (PEP 621 format). The <html><code>pyproject.toml</code></html> declares build backend (e.g., hatchling), dependencies, and optional dev dependencies. Build with <html><code>python -m build</code></html>, generating both source distributions and wheels in <html><code>dist/</code></html>. For a private package index (AWS CodeArtifact, Artifactory, devpi), use <html><code>twine upload --repository-url &lt;url&gt; dist/*</code></html>. Consumers install from the private index with <html><code>pip install --index-url &lt;url&gt; mylib</code></html>. For early-stage teams, pip installs directly from git: <html><code>pip install git+https://github.com/myorg/mylib.git@v1.2.0</code></html>. Always pin versions in <html><code>pyproject.toml</code></html> using <html><code>&gt;=</code></html> or ranges, never wildcards. Test the built wheel before publishing. The modern standard is PEP 621 <html><code>pyproject.toml</code></html>—setup.py is obsolete and unnecessary.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>

''Related atoms''
* [[Private PyPI solutions: devpi, CodeArtifact, or pip.conf]]
* [[Multiple dependency declaration files create inconsistent builds]]
* [[Git URLs without commit pinning produce non-reproducible builds]]
Vendoring—downloading dependencies as wheels into a local directory—enables offline installations and reduces reliance on external package indexes. Use <html><code>pip download -r requirements.txt -d vendor/</code></html> to populate a <html><code>vendor/</code></html> directory with all transitive dependencies as wheels. Then install without network: <html><code>pip install --no-index --find-links=vendor/ -r requirements.txt</code></html>. In Docker, copy the vendor directory into the builder, then install from it in runtime—the container builds without network access. Vendoring is useful when deployment environments are air-gapped, when you distrust upstream index availability, or when you want to audit all dependencies before reaching production. Keep vendor directories updated by re-running the download command and committing to git, or store in artifact storage (S3, Artifactory) and fetch during builds. The trade-off: vendor directories are large and require maintenance, but they provide determinism and offline capability—essential for critical infrastructure.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>

''Related atoms''
* [[Multi-stage Docker builds eliminate build tools from images]]
<html><code>pipdeptree</code></html> visualizes the entire dependency tree, making conflicts visible. Run without arguments to see the full tree: each package and its immediate dependencies. Use <html><code>pipdeptree --warn fail</code></html> to identify unmet version constraints—it reports packages requiring conflicting versions of dependencies. To find which packages depend on a specific package, use <html><code>pipdeptree --reverse --packages requests</code></html>, showing the inverse dependency graph. This is invaluable when upgrading a widely-used library. For large environments, export as JSON: <html><code>pipdeptree --json</code></html> for scripting. When a conflict is detected, identify the top-level package causing it, then check if a newer version relaxes its constraints. If two top-level packages conflict, determine which to upgrade or downgrade. Conflicts often arise when one dependency hasn't updated to support a new library version—you're stuck waiting for a compatible release or patching the constraint yourself.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>

''Related atoms''
* [[Unpinned dependencies make builds non-reproducible and fragile]]
* [[Scan Python dependencies against known vulnerabilities]]
* [[Lock dependencies with pip-compile for reproducibility]]
Install hangs on "Building wheel"—a package is compiling C extensions. Use <html><code>--only-binary=:all:</code></html> to skip compilation, or install system build dependencies (<html><code>build-essential</code></html>, <html><code>python3-dev</code></html>). Permission denied means you're installing into system Python; always use a virtualenv instead. "Subprocess-exited-with-error" during compilation usually signals missing system libraries: <html><code>libpq-dev</code></html> for psycopg2, <html><code>libffi-dev</code></html> for cryptography, <html><code>libxml2-dev libxslt-dev</code></html> for lxml. When pip is broken, bootstrap it: <html><code>python3 -m ensurepip --upgrade</code></html>. A corrupted cache causes mysterious failures—clear with <html><code>pip cache purge</code></html>. To downgrade after a bad upgrade, specify exact version: <html><code>pip install package==1.2.3</code></html>. When all else fails, recreate the virtualenv and reinstall from a known-good requirements file. Before escalating to major changes, always clear the cache and check system dependencies—most errors are missing build headers or corrupted state, not fundamental incompatibilities.

----
''Sources''
* <html><code>training/library/topics/python-packaging/street_ops.md</code></html>

''Related atoms''
* [[Recover broken virtualenvs through targeted repair methods]]
* [[Diagnosing import failures in Python and Docker]]
* [[System Python must use virtualenvs to prevent package conflicts]]
The Python packaging system has been called the language's biggest weakness by core developers. Between distutils, setuptools, easy_install, pip, pipenv, poetry, flit, hatch, pdm, and conda, Python has had more packaging tools than arguably any other mainstream language, each with different semantics and workflows.

This fragmentation created high barriers to entry for new users and made it hard for tooling to stay compatible. PEP 517 (2017) and PEP 518 (2017) attempted to standardize by defining a universal build backend interface, so tools could work together rather than forking on each other.

The consolidation around pip, <html><code>pyproject.toml</code></html>, and setuptools has improved the situation, but the ecosystem still carries legacy complexity. Understanding when to use which tool, how to migrate, and what approach is "modern" requires implicit knowledge not documented in any single place.

For new projects, the recommendation is clear: use <html><code>pyproject.toml</code></html>, setuptools, pip, and virtualenvs. For existing projects, gradual migration is safer than a sudden rewrite, but the direction is toward standardization.

----
''Sources''
* <html><code>training/library/topics/python-packaging/trivia.md</code></html>

''Related atoms''
* [[What tool is the modern standard for building Python packages?]]
* [[Multiple dependency declaration files create inconsistent builds]]
* [[Python bridges ops scripting and software engineering]]
Q: What is "tuple unpacking"?

A: Assigning elements of a tuple to multiple variables in one line. 
Example: a, b, c = (1, 2, 3). You can also use 
// for catch-all: first, //rest = (1, 2, 3, 
4) gives rest = [2, 3, 4]. Works with any iterable, not just tuples.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is a tuple and how does it differ from a list?]]
* [[Tuple operations]]
* [[Unpacking (* and **)]]
Q: What's the difference between a list and a tuple in Python?

A: A list is mutable (you can change, add, remove elements), while a tuple is immutable (once created, its elements cannot be changed). Tuples are hashable (usable as dict keys), slightly faster, and signal intent that data should not change. Use tuples for fixed collections like coordinates or DB rows.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[Why are tuples slightly faster than lists?]]
* [[Can a tuple be a dictionary key?]]
* [[What is a list data type and how is it used?]]
Q: What is a tuple and how does it differ from a list?

A: An immutable, ordered sequence of items defined with parentheses: t = (1, 2, 3). Because they are immutable, tuples are hashable and can be used as dictionary keys or set elements. A single-element tuple requires a trailing comma: (42,).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[Can a tuple be a dictionary key?]]
* [[Tuple operations]]
* [[Why are tuples slightly faster than lists?]]
Q: How do you write a comment in Python?

A: By starting the line with a #. For multi-line explanations, use consecutive # lines. Triple-quoted strings (docstrings) serve a different purpose — they document modules, classes, and functions and are accessible at runtime via __doc__.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is a Python "magic comment" for encoding?]]
* [[What is the Python REPL's `_` variable?]]
* [[What PEP introduced type hints to Python?]]
Q: What is the "math" module?

A: A standard library module providing mathematical functions like sqrt(), ceil(), floor(), log(), and constants like math.pi and math.e. For example, math.sqrt(16) returns 4.0. For more advanced work (arrays, stats), use numpy instead.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is the `numbers` module?]]
* [[What module provides arbitrary-precision decimal arithmetic?]]
* [[What does the `statistics` module provide?]]
Q: What is the difference between return and print?

A: return sends a value back to the caller and exits the function — it can be captured in a variable or used in expressions. print outputs text to the console for human reading but returns None. A common beginner mistake is using print inside a function and wondering why the result can't be reused.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What value is returned if a function has no return statement?]]
* [[return]]
* [[What is the difference between `__str__` and `__repr__`?]]
Q: What is "nested loop"?

A: A loop placed inside the body of another loop. The inner loop runs completely for each iteration of the outer loop. 
Example: iterating a 2D grid with for row in matrix: for cell in row. Be cautious — deeply nested loops can cause performance issues (O(n^2) or worse).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is iteration in programming and what are common patterns?]]
Q: What are the three logical operators?

A: and, or, and not. They operate on boolean values and use short-circuit evaluation — and stops at the first False, or stops at the first True. This enables patterns like value = x or default_value to set a fallback when x is falsy.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is a Boolean data type and how is it used in programming?]]
* [[What is the result of `True + True`?]]
* [[Why is `True + True == 2`?]]
Q: What does the yield keyword do?

A: It turns a function into a generator, allowing it to produce a sequence of values lazily over multiple invocations. Each yield outputs a value and pauses the function; calling next() resumes it. This enables memory-efficient iteration over large datasets since values are generated on demand rather than stored in a list.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[yield (generators)]]
* [[What is a Python generator?]]
* [[What does `itertools.groupby()` yield?]]
Q: What is an "integer division" operator?

A: // (floor division) divides and returns only the whole number part, discarding the remainder. 
Example: 7 // 2 gives 
# It always rounds toward negative infinity, so -7 // 2 gives -4 (not -3). Pair with % (modulus) to get both quotient and remainder.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[Which operator gives the remainder of division?]]
* [[What does `divmod(a, b)` return?]]
* [[What is `int.as_integer_ratio()` added in Python 3.8?]]
Q: What does the input() function always return?

A: A string value, regardless of what the user types. If you need a number, you must explicitly cast: int(input("Enter a number: ")). Forgetting this cast is one of the most common beginner bugs — comparing input() == 5 will always be False.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is a "Value Error"?]]
* [[What is the difference between == and is in Python?]]
* [[try / except]]
Q: What does the open() mode 'a' do?

A: Opens a file for appending — new writes go to the end without overwriting existing content. If the file does not exist, it is created. Contrast with 'w' which truncates the file. Use 'a' for log files or any case where you want to accumulate data across multiple writes.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[with (context manager)]]
Q: What does the open() mode 'w' do?

A: Opens a file for writing and truncates (empties) it immediately — all existing content is lost. If the file does not exist, it is created. This is destructive: accidentally opening a log file with 'w' erases it. Use 'a' to append instead. Always use with open(...) as f: to ensure the file is properly closed.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[with (context manager)]]
Q: What is a decorator in Python?

A: A decorator is a function that takes another function and extends its behavior without modifying it. The @decorator syntax above a function definition wraps it in additional functionality. Common uses: @staticmethod, @property, logging, access control, memoization. Decorators can be stacked and can accept arguments via a decorator factory pattern.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is a parameterized decorator?]]
* [[Decorator]]
* [[What does `functools.wraps` do?]]
Q: What is a list data type and how is it used?

A: A mutable, ordered sequence of items defined with square brackets: my_list = [1, 2, 3]. Lists support indexing, slicing, appending, and iteration. They can hold mixed types but in practice usually hold one type. Under the hood, Python lists are dynamic arrays, not linked lists.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is the `type` statement in Python 3.12?]]
* [[What's the difference between a list and a tuple in Python?]]
* [[What is a list comprehension and when was it introduced?]]
Q: How do you install a package in Python?

A: Using pip: pip install package_name (downloads from PyPI by default). 
Best practice: always install into a virtual environment, not system Python. Use pip install -r requirements.txt for project dependencies, and pin versions for reproducibility (e.g., requests==2.31.0).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What does PyPI stand for?]]
* [[Editable installs let you edit source and see changes immediately]]
* [[Unpinned dependencies make builds non-reproducible and fragile]]
Q: What is the purpose of garbage collection in Python?

A: Python manages memory using reference counting (freeing objects when their refcount hits zero) plus a cyclic garbage collector that detects reference cycles (e.g., two objects pointing at each other). The gc module lets you inspect or force collection. Memory leaks can still happen if objects are unintentionally held in global lists, caches, or closures.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What does the `gc` module do?]]
* [[Memory profiling is non-deterministic due to reference counting]]
Q: What does if __name__ == "__main__": do?

A: It checks if the file is being run directly (as a script) vs being imported as a module. Code inside this block only executes on direct run. This idiom lets you put tests, demos, or CLI logic in a module file without it running on import. Every well-structured Python script should use this pattern.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[What is `__name__` set to when a module is imported?]]
* [[What is the `__main__.py` file for?]]
* [[What does the `import` statement do in Python?]]
Q: What is Python and what makes it popular for DevOps and scripting?

A: Python is a high-level, interpreted programming language known for its readable syntax and broad usage in web development, automation, data analysis, AI, and DevOps scripting. Its "batteries included" standard library and large ecosystem (PyPI) make it a go-to language for rapid prototyping and production systems alike.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[Python bridges ops scripting and software engineering]]
* [[Name five alternative Python implementations.]]
* [[What is PyPy and why is it significant?]]
Q: What is a "Value Error"?

A: Raised when a function receives the right type but an inappropriate value. 
Example: int("abc") raises ValueError because "abc" is a string (correct type for int()) but not a valid integer. Handle with try/except ValueError. Common in input parsing, type conversion, and data validation.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[try / except]]
* [[What is an "exception"?]]
Q: What is the "os" module primarily used for?

A: Interacting with the operating system: file/directory operations (os.listdir, os.remove, os.makedirs), environment variables ([[os.environ]]), path manipulation (os.path.join), and process management (os.getpid). For modern path handling, prefer pathlib. For running shell commands, prefer subprocess over os.system.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is `os.walk()` used for?]]
* [[What is `os.environ`?]]
* [[What is the `pathlib` module and when was it introduced?]]
Q: What is "decrementing"?

A: Subtracting a value (usually one) from a variable, typically in a loop. Python has no -- operator like C/Java; use x -= 1 instead. Incrementing is the opposite: x += 1. These [[augmented assignment|Augmented assignment]] operators also work with other operations: *=, /=, %=.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[Which operator gives the remainder of division?]]
* [[What is the difference between == and is in Python?]]
* [[What does `collections.Counter.subtract()` do differently from `-`?]]
Q: What is PEP 8 and why does it matter for Python code?

A: The official Python style guide promoting consistent, readable code: 4-space indents, snake_case for functions/variables, CamelCase for classes, max 79-char lines. Enforced by linters like ruff, flake8, or pylint. Following PEP 8 is expected in professional Python codebases and code reviews.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What PEP defines the Python style guide?]]
* [[How does Python define code blocks?]]
* [[What is a PEP?]]
Q: What is the difference between a parameter and an argument?

A: A parameter is the variable name in a function definition; an argument is the actual value passed when calling the function. 
Example: in def greet(name), name is the parameter; in greet("Alice"), "Alice" is the argument. Python supports positional, keyword, default, and variadic (*args, **kwargs) parameters.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What are *args and **kwargs in Python functions?]]
* [[What is `ParamSpec` used for?]]
* [[What does the `*` separator in function parameters do?]]
Q: What is "slicing" in Python?

A: Accessing a range of items using [start:stop:step] syntax. Works on lists, strings, and tuples. Examples: lst[1:4] gets indices 1-3, lst[::-1] reverses, lst[::2] gets every other element. Slicing returns a new object and never raises IndexError even if indices are out of range — it just returns what is available.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What does `[1, 2, 3][::-1]` return?]]
* [[String slicing]]
* [[What is the difference between `list.copy()` and `list[:]`?]]
Q: What is iteration in programming and what are common patterns?

A: The repeated execution of a set of statements, typically using a [[for loop]] (iterating over a sequence) or a [[while loop]] (iterating until a condition is false). Python's for loop works on any iterable: lists, strings, dicts, files, generators. The iter()/next() protocol underlies all iteration.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What does `itertools.cycle(iterable)` do?]]
* [[What is `__iter__` vs `__getitem__` for iteration?]]
* [[What is `itertools.repeat()` commonly used with?]]
Q: Which operator gives the remainder of division?

A: % (modulus). 
Example: 10 % 3 returns 1. Commonly used to check if a number is even (n % 2 == 0), cycle through indices, or implement wrap-around behavior. In Python, the result always has the same sign as the divisor, unlike some other languages.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is an "integer division" operator?]]
* [[What does `divmod(a, b)` return?]]
* [[What is the `decimal` module's `ROUND_HALF_EVEN` rounding mode?]]
Q: What is a Boolean data type and how is it used in programming?

A: A data type representing True or False (capitalized in Python). Booleans are a subclass of int: True == 1, False == 0. Falsy values include 0, None, empty strings, empty collections. Used in conditionals, loops, and logical expressions.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is the result of `True + True`?]]
* [[What is the `__bool__` method?]]
* [[What is the truthiness rule in Python?]]
Q: What are *args and **kwargs in Python functions?

A: *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary. This enables flexible APIs. 
Example: def log(msg, *args, **kwargs) can accept log("error", code, timestamp=now). Order matters in the signature: regular params, *args, keyword-only params, **kwargs. Overusing them hurts readability — prefer explicit parameters when the interface is known.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[*args and **kwargs]]
* [[What is the difference between a parameter and an argument?]]
* [[What does the `*` separator in function parameters do?]]
Q: What is the difference between read() and readlines()?

A: read() returns the entire file as one string; readlines() returns a list where each element is one line. For large files, neither is ideal — iterate line by line with for line in file: instead, which is memory-efficient. readline() reads a single line. Always use context managers (with open(...) as f:) to ensure the file is closed.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[with (context manager)]]
* [[What does the open() mode 'a' do?]]
Q: Is Python statically or dynamically typed?

A: Dynamically typed — variable types are determined at runtime and you do not declare types explicitly. You can reassign x = 5 then x = "hello". This adds flexibility but can hide bugs. [[Type hints]] (PEP 484) add optional static checking via tools like mypy without changing runtime behavior.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is mypy?]]
* [[Name three Python static type checkers besides mypy.]]
* [[What are variables in Python and how are they defined?]]
Q: What value is returned if a function has no return statement?

A: None. Python implicitly returns None when a function exits without a return statement or with a bare return. This is important when chaining function calls — if you accidentally forget return, downstream code receives None, often causing subtle AttributeError bugs.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[return]]
* [[What is the difference between return and print?]]
* [[How do you check for `None` in Python?]]
Q: What is a "Syntax Error"?

A: An error raised when Python's parser encounters code that violates the language's structural rules — such as missing colons, unmatched brackets, or incorrect indentation. SyntaxErrors are caught before runtime so the program never starts. Read the error message carefully: it points to the line and position of the problem.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[How does Python define code blocks?]]
* [[What improvement did Python 3.11 make to error messages?]]
* [[What is an "exception"?]]
Q: What is a "dictionary"?

A: A mutable, unordered (insertion-ordered since Python 3.7) collection of key-value pairs: d = {"name": "Alice", "age": 30}. Keys must be hashable (strings, numbers, tuples). Lookup, insert, and delete are O(1) average. Use .get(key, default) to avoid KeyError. Dicts are the backbone of Python internals — namespaces, kwargs, and JSON all map to dicts.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is `collections.UserDict` for?]]
* [[How does CPython implement dicts internally?]]
* [[What is `dict.setdefault(key, default)`?]]
Q: How does Python define code blocks?

A: By using indentation (whitespace at the start of a line), not braces like C/Java. The standard is 4 spaces per level (PEP 8). Mixing tabs and spaces causes IndentationError. Consistent indentation is enforced by the parser, making Python code visually structured by default.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is a code object in Python?]]
* [[What is PEP 8 and why does it matter for Python code?]]
* [[What is a "Syntax Error"?]]
Q: How do you add an item to the end of a list?

A: Using .append(item) to add a single element, or .extend(iterable) to add multiple elements. 
Note: append([1,2]) adds the list as one nested element; extend([1,2]) adds each element individually. For inserting at a specific position, use .insert(index, item).

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What does `list.extend()` do vs `list.append()`?]]
* [[List operations]]
* [[What is the time complexity of `list.append()`?]]
Q: What is a Python generator?

A: A generator is a function that uses yield to produce a sequence of values lazily. Each call to next() returns the next value and the function state is preserved between yields. Generators are memory-efficient for large datasets (e.g., reading million-line files). Generator expressions: (x''2 for x in range(10''6)) create generators inline. They are single-use — once exhausted, they cannot be restarted.

----
''Sources''
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

//Merged from 2 source atoms.//

''Related atoms''
* [[yield (generators)]]
* [[What does the yield keyword do?]]
* [[What is `yield from` used for?]]
Q: What is a "local variable"?

A: A variable defined inside a function, accessible only within that function's scope. It is created when the function runs and destroyed when it returns. Attempting to access it outside raises NameError. Use the global keyword (sparingly) to modify a module-level variable from within a function.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is the `global` keyword used for?]]
* [[What is the `nonlocal` keyword used for?]]
* [[global / nonlocal]]
Q: What are variables in Python and how are they defined?

A: Named references to data stored in memory. In Python, variables do not have fixed types — they are labels pointing to objects. Assignment (x = 42) binds the name x to an integer object. Multiple names can reference the same object. Use descriptive names (user_count, not uc) for readable code.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[Is Python statically or dynamically typed?]]
* [[What is a Python namespace?]]
Q: What is a "high-level" language?

A: A language abstracted from hardware details, closer to human language than machine code. High-level languages (Python, JavaScript, Ruby) handle memory management and provide rich built-in data structures. 
Trade-off: easier to write and read, but generally slower than low-level languages like C. Python bridges the gap with C extensions and libraries like numpy.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is Python and what makes it popular for DevOps and scripting?]]
* [[Name five alternative Python implementations.]]
Q: How do you check if two values are equal?

A: Using the == operator, which compares values. 
Example: 5 == 5.0 is True (cross-type equality). For identity comparison (same object in memory), use is. For inequality, use !=. For ordered comparisons: <, >, <=, >=. You can chain comparisons: 1 < x < 10 checks both bounds.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is the difference between == and is in Python?]]
* [[What is the difference between `is` and `==` in Python?]]
* [[What are `__lt__`, `__le__`, `__gt__`, `__ge__`?]]
Q: What is the "range()" function used for?

A: Generating a sequence of numbers, typically for loops. range(5) gives 0-4; range(2, 
8) gives 2-7; range(0, 10, 
2) gives even numbers 0-8. It returns a lazy range object (not a list), so range(10**9) uses almost no memory. Convert to a list with list(range(5)) if needed.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is `itertools.repeat()` commonly used with?]]
* [[What is a list comprehension and when was it introduced?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
Q: What does case-sensitivity mean in Python?

A: Uppercase and lowercase letters are treated as distinct — myVar, myvar, and MYVAR are three different names. This applies to variable names, function names, keywords (True not true), and module names. Convention: constants use ALL_CAPS, classes use CamelCase, everything else uses snake_case.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is the wildcard pattern in Python's match statement?]]
* [[What does `str.casefold()` do differently from `str.lower()`?]]
* [[What are variables in Python and how are they defined?]]
Q: What is an "infinite loop"?

A: A loop that never terminates because its exit condition is never met. 
Example: while True: without a break. Common causes: forgetting to increment a counter, wrong comparison operator, or modifying the wrong variable. Ctrl+C sends KeyboardInterrupt to stop it. Sometimes intentional — e.g., event loops and server main loops use while True with break conditions.

----
''Sources''
* <html><code>training/interactive/knowledge/data/cards/python.tsv</code></html>

''Related atoms''
* [[What is iteration in programming and what are common patterns?]]
Q: What is the Ansiballz framework?

A: The mechanism Ansible uses to package Python modules for remote execution. It creates a zipfile containing the module file, imported <html><code>module_utils</code></html> files, and boilerplate code. This is Base64-encoded, wrapped in a small Python script, transferred to the remote host, and executed.

----
''Sources''
* <html><code>training/library/topics/ansible/trivia-compendium.md</code></html>
* <html><code>training/library/topics/python-infra/trivia-compendium.md</code></html>

//Merged from 3 source atoms.//

''Related atoms''
* [[What is `zipimport`?]]
!! MOC — compendium q&a

Every atom extracted from a ''compendium-qa'' source (779 total).

* [[Approximately how many packages are on PyPI as of 2025?]]
* [[Can a tuple be a dictionary key?]]
* [[Can f-strings contain the backslash character?]]
* [[Can the walrus operator be used in all expression contexts?]]
* [[Can you match against object attributes in Python's pattern matching?]]
* [[Can you use built-in types as generics since Python 3.9?]]
* [[Does Python have native support for complex numbers?]]
* [[Does Python intern strings?]]
* [[Does `finally` always execute?]]
* [[Give a common use case for the walrus operator.]]
* [[How can you restrict what classes can be unpickled for security?]]
* [[How do you check for `None` in Python?]]
* [[How do you create a context manager from a generator function using `contextlib`?]]
* [[How do you create a custom exception?]]
* [[How do you create a named tuple with `collections.namedtuple`?]]
* [[How do you format a number with thousands separators in an f-string?]]
* [[How do you implement a max-heap using Python's `heapq` module?]]
* [[How do you set the precision for `decimal.Decimal` operations?]]
* [[How do you stack multiple decorators?]]
* [[How do you suppress exception chaining?]]
* [[How do you use `itertools.product` to get the equivalent of a triple nested loop?]]
* [[How does CPython implement dicts internally?]]
* [[How does CPython's garbage collector handle circular references?]]
* [[How does someone become a Python core developer?]]
* [[How many items does `itertools.permutations('ABC', 2)` yield?]]
* [[How many keywords does Python 3.12 have?]]
* [[In `dataclasses`, what does the `field()` function's `default_factory` parameter do?]]
* [[Is `OrderedDict` still useful now that regular dicts maintain insertion order (since Py…]]
* [[Is there a limit to integer size in Python 3?]]
* [[Name five alternative Python implementations.]]
* [[Name three Python static type checkers besides mypy.]]
* [[What API convention does scikit-learn follow?]]
* [[What ASGI server is commonly used with FastAPI?]]
* [[What Monty Python references exist in the Python stdlib?]]
* [[What NumPy function creates an array of zeros?]]
* [[What PEP defines the Python style guide?]]
* [[What PEP established the Steering Council governance model?]]
* [[What PEP introduced type hints to Python?]]
* [[What PEP number is "The Zen of Python"?]]
* [[What PEPs define structural pattern matching?]]
* [[What Python library has become the standard for data validation and settings management?]]
* [[What WSGI toolkit does Flask use under the hood?]]
* [[What `Enum` subclass was introduced in Python 3.11 to ensure members are valid strings?]]
* [[What are "sprints" at Python conferences?]]
* [[What are Python "lightning talks"?]]
* [[What are `.pth` files?]]
* [[What are `__lt__`, `__le__`, `__gt__`, `__ge__`?]]
* [[What are all 19 aphorisms of The Zen of Python?]]
* [[What are context variables (`contextvars`)?]]
* [[What are exception groups, introduced in Python 3.11?]]
* [[What are first-class functions?]]
* [[What are historically the most downloaded packages on PyPI?]]
* [[What are named groups in regex and how do you use them?]]
* [[What are namespace packages?]]
* [[What are pytest marks?]]
* [[What are the advantages of `collections.deque` over a list?]]
* [[What are the different comprehension types in Python?]]
* [[What are the standard logging levels in Python, from lowest to highest?]]
* [[What are the three generations in CPython's garbage collector?]]
* [[What are the three string formatting approaches in Python?]]
* [[What arguments does `__exit__` receive?]]
* [[What built-in functions are considered functional-style?]]
* [[What caused Guido to resign as BDFL?]]
* [[What critical requirement does `itertools.groupby()` have?]]
* [[What design pattern does Django follow?]]
* [[What did Guido work on at Dropbox?]]
* [[What did Guido work on at Google?]]
* [[What did Python 2.2 introduce?]]
* [[What did Python 2.5 introduce?]]
* [[What did Python 2.6 introduce?]]
* [[What did Python 2.7 introduce?]]
* [[What did Python 3.12 do with the GIL?]]
* [[What did Python 3.7 add?]]
* [[What did `breakpoint()` (Python 3.7) replace?]]
* [[What do parentheses `()` do in a regex pattern?]]
* [[What does BDFL stand for, and who held that title?]]
* [[What does Flask call itself?]]
* [[What does NumPy stand for?]]
* [[What does PSF stand for?]]
* [[What does PyPI stand for?]]
* [[What does SciPy provide that NumPy does not?]]
* [[What does `@dataclass(frozen=True)` do?]]
* [[What does `@dataclass(kw_only=True)` do, introduced in Python 3.10?]]
* [[What does `@dataclass(order=True)` do?]]
* [[What does `@dataclass` generate automatically?]]
* [[What does `@property` do under the hood?]]
* [[What does `Counter.elements()` return?]]
* [[What does `Counter.most_common(n)` return?]]
* [[What does `OrderedDict.move_to_end(key, last=True)` do?]]
* [[What does `[1, 2, 3][::-1]` return?]]
* [[What does `__all__` in `__init__.py` control?]]
* [[What does `__hash__` need to be consistent with?]]
* [[What does `__init__` vs `__new__` do?]]
* [[What does `__subclasshook__` do?]]
* [[What does `any([])` return?]]
* [[What does `any(generator_expression)` short-circuit?]]
* [[What does `argparse.ArgumentParser.add_subparsers()` do?]]
* [[What does `calendar.isleap(year)` check?]]
* [[What does `chr()` and `ord()` do?]]
* [[What does `collections.Counter.subtract()` do differently from `-`?]]
* [[What does `collections.Counter` return when you access a key that doesn't exist?]]
* [[What does `collections.deque(maxlen=n)` do when you append beyond capacity?]]
* [[What does `contextlib.redirect_stdout()` do?]]
* [[What does `contextlib.suppress()` do?]]
* [[What does `copy.deepcopy()` do differently from `copy.copy()`?]]
* [[What does `datetime.datetime.fromisoformat()` parse?]]
* [[What does `deque.rotate(n)` do?]]
* [[What does `dict | other_dict` do in Python 3.9+?]]
* [[What does `dis.dis()` do?]]
* [[What does `divmod(a, b)` return?]]
* [[What does `enumerate()` return?]]
* [[What does `f'{value=}'` do, introduced in Python 3.8?]]
* [[What does `float('inf')` represent?]]
* [[What does `functools.cached_property` do?]]
* [[What does `functools.cmp_to_key` do?]]
* [[What does `functools.lru_cache` do?]]
* [[What does `functools.partial` do?]]
* [[What does `functools.partialmethod` do?]]
* [[What does `functools.reduce` do?]]
* [[What does `functools.singledispatch` do?]]
* [[What does `functools.total_ordering` require you to define?]]
* [[What does `functools.wraps` do?]]
* [[What does `hash(-1)` return in CPython?]]
* [[What does `hash(float('inf'))` return?]]
* [[What does `hashlib` provide?]]
* [[What does `heapq.nlargest(n, iterable)` do, and when is it more efficient than sorting?]]
* [[What does `id()` return?]]
* [[What does `import __hello__` do?]]
* [[What does `import __phello__` do in Python 3.12+?]]
* [[What does `int.bit_length()` return?]]
* [[What does `int.to_bytes()` do?]]
* [[What does `isinstance()` check that `type()` does not?]]
* [[What does `isinstance(True, int)` return?]]
* [[What does `itertools.accumulate()` do?]]
* [[What does `itertools.batched()` do, and when was it added?]]
* [[What does `itertools.chain(*iterables)` do?]]
* [[What does `itertools.combinations('ABCD', 2)` return?]]
* [[What does `itertools.compress(data, selectors)` do?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
* [[What does `itertools.cycle(iterable)` do?]]
* [[What does `itertools.dropwhile(predicate, iterable)` do?]]
* [[What does `itertools.filterfalse(predicate, iterable)` do?]]
* [[What does `itertools.groupby()` yield?]]
* [[What does `itertools.islice()` do?]]
* [[What does `itertools.pairwise()` return for an empty or single-element iterable?]]
* [[What does `itertools.product('AB', '12')` yield?]]
* [[What does `itertools.repeat(elem, times=None)` do?]]
* [[What does `itertools.starmap(func, iterable)` do?]]
* [[What does `itertools.tee(iterable, n=2)` return?]]
* [[What does `itertools.zip_longest()` do differently from `zip()`?]]
* [[What does `json.dumps(obj, default=str)` do?]]
* [[What does `list.extend()` do vs `list.append()`?]]
* [[What does `list.sort()` vs `sorted()` return?]]
* [[What does `math.gcd()` compute?]]
* [[What does `math.lcm()` compute, and when was it added?]]
* [[What does `math.prod()` do, and when was it added?]]
* [[What does `object.__repr__` return by default?]]
* [[What does `object.__subclasses__()` return?]]
* [[What does `os.path.expanduser('~')` return?]]
* [[What does `os.scandir()` return and why is it preferred over `os.listdir()`?]]
* [[What does `pandas.DataFrame.merge()` do?]]
* [[What does `pandas.read_csv()` do?]]
* [[What does `pass` do in Python?]]
* [[What does `pytest.fixture` do?]]
* [[What does `python -O` do?]]
* [[What does `python -c "expr"` do?]]
* [[What does `python -m calendar` do?]]
* [[What does `python -m ensurepip` do?]]
* [[What does `python -m json.tool` do?]]
* [[What does `python -m py_compile script.py` do?]]
* [[What does `python -m site` do?]]
* [[What does `python -m venv myenv` do?]]
* [[What does `python -v` do?]]
* [[What does `raise` without an argument do?]]
* [[What does `re.compile()` return and why use it?]]
* [[What does `re.escape(string)` do?]]
* [[What does `re.findall()` return when the pattern contains groups?]]
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
* [[What does `re.sub(pattern, repl, string)` do?]]
* [[What does `re.subn()` return differently from `re.sub()`?]]
* [[What does `reversed()` require?]]
* [[What does `sorted()` guarantee about equal elements?]]
* [[What does `str.casefold()` do differently from `str.lower()`?]]
* [[What does `str.format_map()` do?]]
* [[What does `str.removeprefix()` do, and when was it added?]]
* [[What does `str.translate()` do?]]
* [[What does `str.zfill(width)` do?]]
* [[What does `string.ascii_letters` contain?]]
* [[What does `struct.pack('>I', 1024)` return?]]
* [[What does `sys.argv` contain?]]
* [[What does `sys.exit()` actually raise?]]
* [[What does `sys.getdefaultencoding()` return in Python 3?]]
* [[What does `sys.getrecursionlimit()` return?]]
* [[What does `sys.getsizeof(())` vs `sys.getsizeof([])` show?]]
* [[What does `sys.getsizeof()` return?]]
* [[What does `sys.getsizeof(1)` return approximately?]]
* [[What does `sys.getswitchinterval()` return?]]
* [[What does `sys.intern(string)` do?]]
* [[What does `sys.platform` return on Linux, macOS, and Windows?]]
* [[What does `sys.settrace()` do?]]
* [[What does `sys.version_info` return?]]
* [[What does `textwrap.dedent()` do?]]
* [[What does `textwrap.fill()` do?]]
* [[What does `timedelta` represent?]]
* [[What does `type(...)` return?]]
* [[What does `typing.Protocol` do?]]
* [[What does `typing.Unpack` do?]]
* [[What does the `%` operator do with strings in Python?]]
* [[What does the `*` separator in function parameters do?]]
* [[What does the `/` separator in function parameters do?]]
* [[What does the `__future__` module do?]]
* [[What does the `__iter__` method return?]]
* [[What does the `abc.abstractmethod` decorator do?]]
* [[What does the `dataclasses.asdict()` function do?]]
* [[What does the `enum.Flag` class allow?]]
* [[What does the `gc` module do?]]
* [[What does the `re.DOTALL` (or `re.S`) flag do?]]
* [[What does the `re.IGNORECASE` (or `re.I`) flag do?]]
* [[What does the `re.MULTILINE` (or `re.M`) flag do?]]
* [[What does the `re.VERBOSE` (or `re.X`) flag do?]]
* [[What does the `secrets` module provide that `random` does not?]]
* [[What does the `statistics` module provide?]]
* [[What does the `str.partition(sep)` method return?]]
* [[What does the `traceback` module provide?]]
* [[What encoding does Python 3 use for source files by default?]]
* [[What features did Python 0.9.0 already include?]]
* [[What file replaced `setup.py` and `setup.cfg` as the modern Python project configuratio…]]
* [[What format spec would you use in an f-string to display a float with exactly 2 decimal…]]
* [[What framework is FastAPI built on top of?]]
* [[What function in `heapq` merges multiple sorted inputs into a single sorted output?]]
* [[What governance model replaced the BDFL?]]
* [[What happened to `long` in Python 3?]]
* [[What happens if you create a `defaultdict` with no argument (i.e., `defaultdict()`)?]]
* [[What happens if you type `from __future__ import braces` in Python?]]
* [[What happens when you add two `Counter` objects together?]]
* [[What happens when you multiply a list: `[[]] * 3`?]]
* [[What happens when you run `import this` in Python?]]
* [[What improvement did Python 3.11 make to error messages?]]
* [[What integers does CPython cache (intern)?]]
* [[What is "EAFP" in Python?]]
* [[What is "duck typing"?]]
* [[What is AIOHTTP?]]
* [[What is Black?]]
* [[What is Bottle's claim to fame?]]
* [[What is C3 linearization?]]
* [[What is CPython bytecode?]]
* [[What is CPython's memory allocator?]]
* [[What is CPython?]]
* [[What is CWI?]]
* [[What is Click?]]
* [[What is Cython?]]
* [[What is Django's ORM?]]
* [[What is Django's `manage.py`?]]
* [[What is Django's migration system?]]
* [[What is Django's primary design philosophy?]]
* [[What is EuroPython?]]
* [[What is Fabric?]]
* [[What is FastAPI's key distinguishing feature?]]
* [[What is Flask's `g` object?]]
* [[What is Gunicorn?]]
* [[What is Hypothesis?]]
* [[What is Invoke?]]
* [[What is Jinja2?]]
* [[What is Jupyter's name derived from?]]
* [[What is Litestar (formerly Starlite)?]]
* [[What is Matplotlib's `pyplot` interface?]]
* [[What is MicroPython?]]
* [[What is NumPy's `dtype`?]]
* [[What is PEP 649 about?]]
* [[What is PEP 703 (free-threading)?]]
* [[What is Pandas `groupby()` used for?]]
* [[What is Polars?]]
* [[What is PyCon US?]]
* [[What is PyData?]]
* [[What is PyInstaller?]]
* [[What is PyPy and why is it significant?]]
* [[What is Pydantic v2's key change from v1?]]
* [[What is Python Fire?]]
* [[What is Python's `match` statement OR pattern?]]
* [[What is Python's `match` statement mapping pattern?]]
* [[What is Python's `match` statement sequence pattern?]]
* [[What is Rich?]]
* [[What is Sanic?]]
* [[What is Starlette?]]
* [[What is Timsort?]]
* [[What is Tornado known for?]]
* [[What is Typer?]]
* [[What is YAML handling in Python?]]
* [[What is `@dataclass` an example of in terms of Python internals?]]
* [[What is `DeprecationWarning` vs `PendingDeprecationWarning`?]]
* [[What is `NotImplemented` vs `NotImplementedError`?]]
* [[What is `PYTHONSTARTUP`?]]
* [[What is `ParamSpec` used for?]]
* [[What is `TypeAlias` used for?]]
* [[What is `TypeVar` used for?]]
* [[What is `__add__` vs `__radd__`?]]
* [[What is `__aiter__` and `__anext__`?]]
* [[What is `__all__` used for in a module?]]
* [[What is `__cached__` on a module?]]
* [[What is `__class_getitem__` used for?]]
* [[What is `__class_getitem__` vs `__getitem__`?]]
* [[What is `__del__` used for?]]
* [[What is `__dict__` on a class vs an instance?]]
* [[What is `__doc__`?]]
* [[What is `__eq__` and `__ne__`?]]
* [[What is `__file__` in a module?]]
* [[What is `__format__` used for?]]
* [[What is `__getattr__` vs `__getattribute__`?]]
* [[What is `__getitem__` used for?]]
* [[What is `__iadd__`?]]
* [[What is `__import__` hook?]]
* [[What is `__init_subclass__` used for?]]
* [[What is `__init_subclass__` vs a metaclass?]]
* [[What is `__iter__` vs `__getitem__` for iteration?]]
* [[What is `__len__` used for?]]
* [[What is `__missing__` used for?]]
* [[What is `__name__` set to when a module is imported?]]
* [[What is `__set_name__` used for?]]
* [[What is `__setitem__` and `__delitem__`?]]
* [[What is `__slots__` and why use it?]]
* [[What is `__slots__` inheritance behavior?]]
* [[What is `__spec__` in a module?]]
* [[What is `aiofiles`?]]
* [[What is `ansible-runner`?]]
* [[What is `argparse.FileType`?]]
* [[What is `async`/`await` in Python?]]
* [[What is `asyncio.Queue`?]]
* [[What is `asyncio.Semaphore` used for?]]
* [[What is `asyncio.create_task()` vs `await`?]]
* [[What is `asyncio.run()` used for?]]
* [[What is `asyncio.sleep()` vs `time.sleep()`?]]
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
* [[What is `asyncio.wait_for()` used for?]]
* [[What is `atexit` used for?]]
* [[What is `base64` encoding used for in Python?]]
* [[What is `cffi` (C Foreign Function Interface)?]]
* [[What is `classmethod` vs `staticmethod` when used with inheritance?]]
* [[What is `collections.ChainMap` used for?]]
* [[What is `collections.UserDict` for?]]
* [[What is `collections.abc.Coroutine`?]]
* [[What is `collections.abc.Hashable`?]]
* [[What is `collections.abc.Iterator` vs `collections.abc.Iterable`?]]
* [[What is `collections.abc.MutableMapping`?]]
* [[What is `collections.abc` and how does it differ from `collections`?]]
* [[What is `compileall` used for?]]
* [[What is `concurrent.futures` and when was it introduced?]]
* [[What is `conda` and how does it differ from `pip`?]]
* [[What is `configparser` used for?]]
* [[What is `conftest.py` in pytest?]]
* [[What is `contextlib.ExitStack` used for?]]
* [[What is `contextlib.closing()` used for?]]
* [[What is `coverage.py` used for?]]
* [[What is `ctypes` used for?]]
* [[What is `decimal.Decimal` vs `float` for financial calculations?]]
* [[What is `dict.setdefault(key, default)`?]]
* [[What is `difflib.get_close_matches()` used for?]]
* [[What is `dir()` used for?]]
* [[What is `enum.unique` used for?]]
* [[What is `exec()` dangerous for?]]
* [[What is `fnmatch` used for?]]
* [[What is `functools.reduce` with an initial value?]]
* [[What is `getattr(obj, name, default)` used for?]]
* [[What is `hasattr(obj, name)` equivalent to?]]
* [[What is `hatch`?]]
* [[What is `hmac` module used for?]]
* [[What is `importlib` used for?]]
* [[What is `inspect.signature()` used for?]]
* [[What is `int.as_integer_ratio()` added in Python 3.8?]]
* [[What is `io.BytesIO` used for?]]
* [[What is `io.StringIO` used for?]]
* [[What is `isort`?]]
* [[What is `itertools.pairwise()` and when was it added?]]
* [[What is `itertools.product` with the `repeat` parameter?]]
* [[What is `itertools.repeat()` commonly used with?]]
* [[What is `json.JSONDecodeError`?]]
* [[What is `manylinux`?]]
* [[What is `marshal` and how does it differ from `pickle`?]]
* [[What is `math.factorial()` used for?]]
* [[What is `math.inf` equal to?]]
* [[What is `math.inf` vs `sys.float_info.max`?]]
* [[What is `math.isclose(a, b)` used for?]]
* [[What is `maturin`?]]
* [[What is `memoryview` used for?]]
* [[What is `multiprocessing.Pool` used for?]]
* [[What is `multiprocessing.Queue` vs `queue.Queue`?]]
* [[What is `mypyc`?]]
* [[What is `object.__new__`?]]
* [[What is `operator.attrgetter()` used for?]]
* [[What is `operator.itemgetter()` used for?]]
* [[What is `operator.methodcaller()` used for?]]
* [[What is `os._exit()` and when is it used?]]
* [[What is `os.environ`?]]
* [[What is `os.walk()` used for?]]
* [[What is `pathlib.Path.glob()` used for?]]
* [[What is `pathlib.Path.resolve()` used for?]]
* [[What is `pdb` and how do you invoke it?]]
* [[What is `pip freeze` used for?]]
* [[What is `pip install -e .` (editable install)?]]
* [[What is `pipx`?]]
* [[What is `poetry`?]]
* [[What is `pre-commit`?]]
* [[What is `py3-none-any` in a wheel filename?]]
* [[What is `pyenv`?]]
* [[What is `pytest.approx()` used for?]]
* [[What is `pytest.mark.parametrize` used for?]]
* [[What is `pytest.monkeypatch`?]]
* [[What is `pytest.raises`?]]
* [[What is `python -m this`?]]
* [[What is `python -m zipapp` used for?]]
* [[What is `ruff`?]]
* [[What is `scipy.optimize.minimize()`?]]
* [[What is `sdist` in Python packaging?]]
* [[What is `selectors` module?]]
* [[What is `shlex.split()` used for?]]
* [[What is `shutil.copytree()` used for?]]
* [[What is `smtplib` used for?]]
* [[What is `sqlite3` in the standard library?]]
* [[What is `ssl.create_default_context()` for?]]
* [[What is `statistics.NormalDist` used for?]]
* [[What is `str.encode()` and `bytes.decode()`?]]
* [[What is `str.isidentifier()`?]]
* [[What is `string.Template` and when would you use it?]]
* [[What is `subprocess.Popen` vs `subprocess.run`?]]
* [[What is `super()` and how does it work?]]
* [[What is `sys.exc_info()` used for?]]
* [[What is `sys.executable`?]]
* [[What is `sys.flags`?]]
* [[What is `sys.float_info`?]]
* [[What is `sys.getrefcount(obj)`?]]
* [[What is `sys.maxsize`?]]
* [[What is `sys.modules`?]]
* [[What is `sys.monitoring` in Python 3.12?]]
* [[What is `sys.path` and how does Python use it?]]
* [[What is `sys.setprofile()` used for?]]
* [[What is `sys.stdin`, `sys.stdout`, `sys.stderr`?]]
* [[What is `sysconfig` used for?]]
* [[What is `threading.Condition`?]]
* [[What is `threading.Event`?]]
* [[What is `threading.Lock` used for?]]
* [[What is `time.monotonic()`?]]
* [[What is `type()` with one argument vs three arguments?]]
* [[What is `types.SimpleNamespace`?]]
* [[What is `typing.Annotated` used for?]]
* [[What is `typing.Any`?]]
* [[What is `typing.AsyncIterator`?]]
* [[What is `typing.Awaitable`?]]
* [[What is `typing.Callable` used for?]]
* [[What is `typing.ClassVar` used for?]]
* [[What is `typing.Final` used for?]]
* [[What is `typing.Literal` used for?]]
* [[What is `typing.NamedTuple` and how does it compare to `collections.namedtuple`?]]
* [[What is `typing.Never` (Python 3.11) or `typing.NoReturn` used for?]]
* [[What is `typing.Optional[X]` equivalent to?]]
* [[What is `typing.Required` and `typing.NotRequired` for TypedDict?]]
* [[What is `typing.TypeGuard` used for?]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.TypedDict` used for?]]
* [[What is `typing.Union` used for?]]
* [[What is `typing.cast()` used for?]]
* [[What is `typing.get_type_hints()` used for?]]
* [[What is `typing.overload` used for?]]
* [[What is `typing.runtime_checkable` used for?]]
* [[What is `unittest.TestCase.setUp()` vs `setUpClass()`?]]
* [[What is `unittest.mock.MagicMock`?]]
* [[What is `unittest.mock.patch` used for?]]
* [[What is `unittest.mock.sentinel`?]]
* [[What is `urllib.parse.urlencode()` used for?]]
* [[What is `urllib.parse.urlparse()` used for?]]
* [[What is `uv` in the Python ecosystem?]]
* [[What is `uvloop`?]]
* [[What is `vars(obj)` equivalent to?]]
* [[What is `virtualenv` and why is it important?]]
* [[What is `yield from` used for?]]
* [[What is `zipimport`?]]
* [[What is a "free list" in CPython?]]
* [[What is a Jupyter kernel?]]
* [[What is a PEP 517 build backend?]]
* [[What is a PEP?]]
* [[What is a Pandas DataFrame?]]
* [[What is a Pandas Series?]]
* [[What is a Python "magic comment" for encoding?]]
* [[What is a Python namespace?]]
* [[What is a Python wheel's tag format?]]
* [[What is a `TYPE_CHECKING` guard?]]
* [[What is a `__fspath__` method?]]
* [[What is a `bytearray` and how does it differ from `bytes`?]]
* [[What is a `mappingproxy`?]]
* [[What is a `requirements.txt` file?]]
* [[What is a closure in Python?]]
* [[What is a code object in Python?]]
* [[What is a context manager protocol?]]
* [[What is a daemon thread?]]
* [[What is a data descriptor vs a non-data descriptor?]]
* [[What is a frozenset?]]
* [[What is a higher-order function?]]
* [[What is a lambda function?]]
* [[What is a list comprehension and when was it introduced?]]
* [[What is a metaclass?]]
* [[What is a named group backreference in regex?]]
* [[What is a negative lookahead?]]
* [[What is a negative lookbehind?]]
* [[What is a non-capturing group in regex?]]
* [[What is a parameterized decorator?]]
* [[What is a positive lookahead in regex?]]
* [[What is a positive lookbehind?]]
* [[What is a virtual subclass in Python's ABC framework?]]
* [[What is boto3?]]
* [[What is broadcasting in NumPy?]]
* [[What is doctest?]]
* [[What is exception chaining in Python?]]
* [[What is httpx?]]
* [[What is monkey patching?]]
* [[What is mypy?]]
* [[What is name mangling in Python?]]
* [[What is nox?]]
* [[What is paramiko?]]
* [[What is pytest's `tmp_path` fixture?]]
* [[What is pytest's key advantage over unittest?]]
* [[What is reference counting in CPython?]]
* [[What is scikit-learn?]]
* [[What is seaborn?]]
* [[What is string interning?]]
* [[What is the "six" library?]]
* [[What is the Ansiballz framework?]]
* [[What is the Django admin?]]
* [[What is the Easter egg hidden in the source code of the `this` module?]]
* [[What is the GIL's full name?]]
* [[What is the GIL's impact on I/O-bound vs CPU-bound threading?]]
* [[What is the LBYL coding style?]]
* [[What is the LEGB rule?]]
* [[What is the MRO in Python?]]
* [[What is the PEP process for proposing language changes?]]
* [[What is the Python REPL's `_` variable?]]
* [[What is the WAT moment with `[] == False`?]]
* [[What is the WAT moment with `hash(-1)` and `hash(-2)` in CPython?]]
* [[What is the WAT moment with tuple addition?]]
* [[What is the `@functools.lru_cache` memory leak risk?]]
* [[What is the `@property` deleter?]]
* [[What is the `@typing.dataclass_transform` decorator?]]
* [[What is the `Ellipsis` object (`...`) used for in Python?]]
* [[What is the `NotImplemented` singleton used for?]]
* [[What is the `PYTHONDONTWRITEBYTECODE` environment variable?]]
* [[What is the `PYTHONPATH` environment variable?]]
* [[What is the `TaskGroup` in Python 3.11's asyncio?]]
* [[What is the `__aenter__` and `__aexit__` protocol?]]
* [[What is the `__annotations__` attribute?]]
* [[What is the `__bool__` method?]]
* [[What is the `__contains__` method?]]
* [[What is the `__debug__` built-in constant?]]
* [[What is the `__init__.py` file for?]]
* [[What is the `__main__.py` file for?]]
* [[What is the `__prepare__` method in metaclasses?]]
* [[What is the `__pycache__` directory?]]
* [[What is the `__qualname__` attribute?]]
* [[What is the `__weakref__` attribute?]]
* [[What is the `abc.ABCMeta` metaclass?]]
* [[What is the `antigravity` module's geohash feature?]]
* [[What is the `apply()` method in Pandas?]]
* [[What is the `array` module used for?]]
* [[What is the `ast` module used for?]]
* [[What is the `cProfile` module?]]
* [[What is the `calendar` module?]]
* [[What is the `collections.OrderedDict` `popitem(last=True)` method?]]
* [[What is the `compile()` built-in?]]
* [[What is the `concurrent.futures.as_completed()` function?]]
* [[What is the `contextlib.aclosing()` context manager?]]
* [[What is the `contextlib.asynccontextmanager` decorator for?]]
* [[What is the `contextlib.nullcontext()` used for?]]
* [[What is the `csv` module?]]
* [[What is the `dataclasses.field()` metadata parameter for?]]
* [[What is the `dataclasses.make_dataclass()` function?]]
* [[What is the `decimal` module's `ROUND_HALF_EVEN` rounding mode?]]
* [[What is the `del` statement?]]
* [[What is the `difflib` module?]]
* [[What is the `dis` module?]]
* [[What is the `email` module?]]
* [[What is the `enum.auto()` function used for?]]
* [[What is the `enum.nonmember()` function added in Python 3.11?]]
* [[What is the `enum.verify` decorator added in Python 3.11?]]
* [[What is the `except*` syntax?]]
* [[What is the `fractions.Fraction.limit_denominator()` method?]]
* [[What is the `global` keyword used for?]]
* [[What is the `graphlib` module?]]
* [[What is the `help()` built-in?]]
* [[What is the `http.server` module used for?]]
* [[What is the `io` module?]]
* [[What is the `json` module's `cls` parameter?]]
* [[What is the `linecache` module?]]
* [[What is the `locale` module?]]
* [[What is the `logging` module's hierarchy?]]
* [[What is the `lru_cache` maximum size by default?]]
* [[What is the `match` statement guard clause?]]
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[What is the `nonlocal` keyword used for?]]
* [[What is the `numbers` module?]]
* [[What is the `operator` module?]]
* [[What is the `pathlib` module and when was it introduced?]]
* [[What is the `perf` profiler support added in Python 3.12?]]
* [[What is the `pickle` protocol version?]]
* [[What is the `platform` module?]]
* [[What is the `profile` module vs `cProfile`?]]
* [[What is the `property` built-in?]]
* [[What is the `pydoc` module?]]
* [[What is the `reprlib` module used for?]]
* [[What is the `requests` library?]]
* [[What is the `secrets.token_urlsafe(nbytes)` function?]]
* [[What is the `select` module?]]
* [[What is the `shelve` module used for?]]
* [[What is the `signal` module used for?]]
* [[What is the `site` module responsible for?]]
* [[What is the `socket` module?]]
* [[What is the `struct` module's byte order prefixes?]]
* [[What is the `subprocess.PIPE` constant?]]
* [[What is the `subprocess.run()` function?]]
* [[What is the `textwrap` module useful for?]]
* [[What is the `type` statement in Python 3.12?]]
* [[What is the `types` module?]]
* [[What is the `typing.Self` type, and when was it introduced?]]
* [[What is the `unicodedata` module?]]
* [[What is the `walrus operator` officially called?]]
* [[What is the `warnings` module?]]
* [[What is the `weakref` module used for?]]
* [[What is the `wheel` filename convention?]]
* [[What is the `wheel` format?]]
* [[What is the `with` statement's full syntax since Python 3.1?]]
* [[What is the `zip()` function's strict mode?]]
* [[What is the `zoneinfo` module?]]
* [[What is the core data structure in NumPy?]]
* [[What is the default recursion limit?]]
* [[What is the default value returned by a `defaultdict(list)` for a missing key?]]
* [[What is the difference between NumPy's `np.array()` and `np.asarray()`?]]
* [[What is the difference between Pandas and Polars?]]
* [[What is the difference between WSGI and ASGI?]]
* [[What is the difference between `@staticmethod` and `@classmethod`?]]
* [[What is the difference between `None` and `False`?]]
* [[What is the difference between `__cause__` and `__context__` on exceptions?]]
* [[What is the difference between `__import__()` and `importlib.import_module()`?]]
* [[What is the difference between `__str__` and `__repr__`?]]
* [[What is the difference between `a += b` and `a = a + b` for lists?]]
* [[What is the difference between `asyncio.gather()` and `TaskGroup`?]]
* [[What is the difference between `bisect.bisect_left()` and `bisect.bisect_right()`?]]
* [[What is the difference between `bytes` and `str` in Python 3?]]
* [[What is the difference between `combinations` and `combinations_with_replacement`?]]
* [[What is the difference between `enum.Enum` and `enum.IntEnum`?]]
* [[What is the difference between `exec()` and `eval()`?]]
* [[What is the difference between `functools.lru_cache` and `functools.cache`?]]
* [[What is the difference between `is` and `==` for `None`?]]
* [[What is the difference between `is` and `==` in Python?]]
* [[What is the difference between `itertools.chain()` and `itertools.chain.from_iterable()`?]]
* [[What is the difference between `list.copy()` and `list[:]`?]]
* [[What is the difference between `re.search()` and `re.fullmatch()`?]]
* [[What is the difference between `str.join()` and concatenation with `+`?]]
* [[What is the difference between `str.strip()` and `str.removeprefix()`/`str.removesuffix…]]
* [[What is the difference between `venv` and `virtualenv`?]]
* [[What is the difference between a "naive" and "aware" datetime in Python?]]
* [[What is the difference between a list comprehension and a generator expression?]]
* [[What is the difference between boto3 client and resource interfaces?]]
* [[What is the difference between concurrency and parallelism in Python?]]
* [[What is the epoch in Python's `time` module?]]
* [[What is the exception hierarchy's root in Python?]]
* [[What is the experimental JIT compiler in Python 3.13?]]
* [[What is the iterator protocol?]]
* [[What is the late binding closures gotcha?]]
* [[What is the maximum date Python's `datetime` can represent?]]
* [[What is the maximum recursion depth in Python by default?]]
* [[What is the mutable default argument gotcha?]]
* [[What is the order of clauses in a try statement?]]
* [[What is the output of `print(0.1 + 0.2)`?]]
* [[What is the output of `round(0.5)` and `round(1.5)` in Python 3?]]
* [[What is the peephole optimizer in CPython?]]
* [[What is the per-interpreter GIL in Python 3.12?]]
* [[What is the precedence of the walrus operator?]]
* [[What is the relationship between `type` and `object`?]]
* [[What is the result of `"hello" * 3`?]]
* [[What is the result of `() is ()`?]]
* [[What is the result of `True + True`?]]
* [[What is the result of `[] is []`?]]
* [[What is the result of `bool([])`?]]
* [[What is the result of `{} == set()`?]]
* [[What is the safer way to use `subprocess`?]]
* [[What is the significance of Python 3.6?]]
* [[What is the significance of `antigravity` in Python?]]
* [[What is the small integer cache in CPython?]]
* [[What is the standard library module for parsing command-line arguments?]]
* [[What is the surprising behavior of `is` with short strings?]]
* [[What is the surprising result of `float('nan') == float('nan')`?]]
* [[What is the time complexity of Python's `dict` lookup?]]
* [[What is the time complexity of `bisect.insort()` for inserting into a sorted list?]]
* [[What is the time complexity of `in` for lists vs sets?]]
* [[What is the time complexity of `list.append()`?]]
* [[What is the time complexity of `list.insert(0, x)`?]]
* [[What is the time module's `perf_counter()` vs `time()`?]]
* [[What is the truthiness rule in Python?]]
* [[What is the type of `{}`?]]
* [[What is the walrus operator in Python?]]
* [[What is the walrus operator's PEP number?]]
* [[What is the wildcard pattern in Python's match statement?]]
* [[What is tox?]]
* [[What language was Python's direct predecessor at CWI Amsterdam?]]
* [[What limitation do lookbehinds have in Python's `re` module?]]
* [[What major feature did Python 3.12 change regarding f-strings?]]
* [[What major features were added in Python 3.10?]]
* [[What major features were added in Python 3.11?]]
* [[What major features were added in Python 3.12?]]
* [[What major features were added in Python 3.13?]]
* [[What major features were added in Python 3.8?]]
* [[What major features were added in Python 3.9?]]
* [[What method can you define on a dataclass to customize how it is initialized after `__i…]]
* [[What method does `defaultdict` call to produce a default value?]]
* [[What method makes an object callable?]]
* [[What method on a namedtuple creates a new instance with some fields replaced?]]
* [[What method on a namedtuple returns a regular dictionary?]]
* [[What method on an `lru_cache`-decorated function shows cache performance?]]
* [[What module allows exact arithmetic with fractions?]]
* [[What module lets you pack and unpack binary data in C struct format?]]
* [[What module provides abstract base classes?]]
* [[What module provides arbitrary-precision decimal arithmetic?]]
* [[What module provides functions for working with temporary files and directories?]]
* [[What module provides functions to maintain a list in sorted order without having to sor…]]
* [[What module provides memory-mapped file access?]]
* [[What module was added in Python 3.11 for parsing TOML files?]]
* [[What new REPL was introduced in Python 3.13?]]
* [[What new generic syntax was introduced in Python 3.12?]]
* [[What parameter to `@dataclass` was added in Python 3.10 to allow slot-based instances?]]
* [[What performance improvement was made in Python 3.11?]]
* [[What safer alternatives to pickle exist for data serialization?]]
* [[What standard library module can you use to measure execution time of small code snippets?]]
* [[What standard library module provides an interface to the operating system's random num…]]
* [[What standard library module provides support for generating universally unique identif…]]
* [[What template engine does Django use by default?]]
* [[What tool is the modern standard for building Python packages?]]
* [[What was Python 1.5 notable for?]]
* [[What was the "Python 3000" or "Py3k" initiative?]]
* [[What was the original name of `pip`?]]
* [[What were the main breaking changes in Python 3.0?]]
* [[What year did Guido van Rossum receive the Award for the Advancement of Free Software f…]]
* [[What year did Python first appear on the TIOBE index top 3?]]
* [[When did Guido van Rossum start working on Python?]]
* [[When did Python 2 reach end of life?]]
* [[When did dict ordering become a language guarantee?]]
* [[When does the `else` clause of a `try` block execute?]]
* [[When was Django first released?]]
* [[When was Python 0.9.0 first released publicly?]]
* [[When was Python 1.0 released?]]
* [[When was Python 2.0 released and what did it add?]]
* [[When was Python 3.0 released?]]
* [[When was `functools.cached_property` introduced?]]
* [[When was `pip` first released?]]
* [[When you set a value on a `ChainMap`, which underlying dict is modified?]]
* [[Where do "spam" and "eggs" come from as Python variable names?]]
* [[Where has Guido van Rossum worked?]]
* [[Where was PyCon US first held?]]
* [[Which Zen aphorism is often cited to argue against Java-style getter/setter methods in …]]
* [[Which Zen aphorism is the "Dutch" one a reference to?]]
* [[Which standard library module provides a min-heap implementation?]]
* [[Who created Django?]]
* [[Who created Flask?]]
* [[Who created Matplotlib and why?]]
* [[Who is the current fastest growing Python web framework (as of 2025)?]]
* [[Who wrote The Zen of Python?]]
* [[Why are NumPy operations faster than Python loops?]]
* [[Why are tuples slightly faster than lists?]]
* [[Why did Guido join Microsoft in 2020?]]
* [[Why do we use raw strings (r'...') for regex patterns in Python?]]
* [[Why does `0.1 + 0.2 != 0.3` in Python?]]
* [[Why does `all([])` return `True`?]]
* [[Why does `import this` have 19 aphorisms when The Zen of Python was supposed to have 20?]]
* [[Why does the GIL exist?]]
* [[Why is `True + True == 2`?]]
* [[Why is the language called "Python"?]]
* [[Why is unpickling data from untrusted sources a security risk?]]
* [[Why must arguments to an `lru_cache`-decorated function be hashable?]]
* [[Why should you avoid using `datetime.utcnow()`?]]
* [[Why should you never use `shell=True` with `subprocess` when handling user input?]]
* [[Why should you not catch `BaseException`?]]
* [[Why was PEP 572 (walrus operator) controversial?]]
* [[Why was `pytz` problematic?]]
* [[Why was `reduce` moved from builtins to `functools` in Python 3?]]
* [[Why was the Python 2 to 3 migration so painful?]]
!! MOC — flashcards

Every atom extracted from a ''flashcard'' source (182 total).

* [[*args and **kwargs]]
* [[@property]]
* [[@staticmethod / @classmethod]]
* [[Abstract base class (ABC)]]
* [[Augmented assignment]]
* [[Calculate the stock span problem]]
* [[Check anagram removal count for two strings]]
* [[Class variable vs instance variable]]
* [[Closure]]
* [[Common string methods]]
* [[Conditional expression (ternary)]]
* [[Custom context manager]]
* [[Custom exceptions]]
* [[Dataclasses vs namedtuples — when to use which?]]
* [[Decorator]]
* [[Detect a cycle in a linked list]]
* [[Detect palindrome]]
* [[Determine if a zero-sum subarray exists]]
* [[Dict comprehension]]
* [[Dict operations]]
* [[Exception hierarchy]]
* [[Explain Python's Method Resolution Order (MRO)]]
* [[Explain Python's property decorator]]
* [[Explain name mangling with double underscores]]
* [[Find all pairs in an array that sum to k]]
* [[Find the first non-repeating character in a string]]
* [[Find the middle element of a linked list in one pass]]
* [[Generate all permutations of a string]]
* [[Generate the largest number from a list of integers]]
* [[Generator expression]]
* [[How do you add an item to the end of a list?]]
* [[How do you check if two values are equal?]]
* [[How do you install a package in Python?]]
* [[How do you write a comment in Python?]]
* [[How does Python define code blocks?]]
* [[How does super() work in Python 3?]]
* [[Implement DFS and BFS for a graph]]
* [[Implement QuickSort]]
* [[Implement a Trie (prefix tree)]]
* [[Implement a linked list with insert, find, delete]]
* [[Implement binary search]]
* [[Implement the Singleton pattern in Python (three ways)]]
* [[Inheritance]]
* [[Is Python statically or dynamically typed?]]
* [[JSON and YAML]]
* [[LEGB scope rule]]
* [[List comprehension]]
* [[List operations]]
* [[Merge two sorted arrays]]
* [[Multi-line strings and docstrings]]
* [[NamedTuple]]
* [[Nested comprehension]]
* [[None]]
* [[Product array — compute products of all elements except self]]
* [[Protocol (structural typing)]]
* [[Reverse words in a sentence]]
* [[Set comprehension]]
* [[Set operations]]
* [[Sliding window maximum]]
* [[String slicing]]
* [[The Global Interpreter Lock constrains Python threading to I/O concurrency]]
* [[Truthy and falsy values]]
* [[Tuple operations]]
* [[Two-pointer technique for sorted array problems]]
* [[Type hints]]
* [[Unpacking (* and **)]]
* [[Walrus operator (:=)]]
* [[What are *args and **kwargs in Python functions?]]
* [[What are class methods and static methods?]]
* [[What are descriptors in Python?]]
* [[What are metaclasses and when would you use them?]]
* [[What are the three logical operators?]]
* [[What are variables in Python and how are they defined?]]
* [[What does case-sensitivity mean in Python?]]
* [[What does if __name__ == "__main__": do?]]
* [[What does the `import` statement do in Python?]]
* [[What does the input() function always return?]]
* [[What does the len() function do?]]
* [[What does the open() mode 'a' do?]]
* [[What does the open() mode 'w' do?]]
* [[What does the yield keyword do?]]
* [[What function returns the data type of an object?]]
* [[What is "decrementing"?]]
* [[What is "nested loop"?]]
* [[What is "slicing" in Python?]]
* [[What is "tuple unpacking"?]]
* [[What is "type casting"?]]
* [[What is PEP 8 and why does it matter for Python code?]]
* [[What is Python and what makes it popular for DevOps and scripting?]]
* [[What is __init_subclass__ and how does it replace metaclasses?]]
* [[What is __repr__ vs __str__?]]
* [[What is __slots__ and when should you use it?]]
* [[What is a "Syntax Error"?]]
* [[What is a "Value Error"?]]
* [[What is a "dictionary"?]]
* [[What is a "high-level" language?]]
* [[What is a "local variable"?]]
* [[What is a Boolean data type and how is it used in programming?]]
* [[What is a Python generator?]]
* [[What is a decorator in Python?]]
* [[What is a list comprehension in Python?]]
* [[What is a list data type and how is it used?]]
* [[What is a tuple and how does it differ from a list?]]
* [[What is a virtual environment in Python and why use it?]]
* [[What is an "exception"?]]
* [[What is an "infinite loop"?]]
* [[What is an "integer division" operator?]]
* [[What is currying in Python?]]
* [[What is duck typing and how does Python use it?]]
* [[What is iteration in programming and what are common patterns?]]
* [[What is the "math" module?]]
* [[What is the "os" module primarily used for?]]
* [[What is the "range()" function used for?]]
* [[What is the ABC module and how do you use abstract classes?]]
* [[What is the difference between == and is in Python?]]
* [[What is the difference between a parameter and an argument?]]
* [[What is the difference between read() and readlines()?]]
* [[What is the difference between return and print?]]
* [[What is the purpose of garbage collection in Python?]]
* [[What value is returned if a function has no return statement?]]
* [[What's the difference between a list and a tuple in Python?]]
* [[Which operator gives the remainder of division?]]
* [[__add__, __eq__, __lt__ (operator overloading)]]
* [[__enter__ and __exit__]]
* [[__init__ and __repr__]]
* [[__len__ and __getitem__]]
* [[__slots__]]
* [[any() and all()]]
* [[argparse]]
* [[as (aliasing)]]
* [[assert]]
* [[async / await]]
* [[break]]
* [[class]]
* [[collections.Counter]]
* [[collections.defaultdict]]
* [[collections.deque]]
* [[continue]]
* [[dataclass]]
* [[datetime]]
* [[def (function definition)]]
* [[del (delete)]]
* [[enumerate()]]
* [[f-string (formatted string literal)]]
* [[for loop]]
* [[for/else and while/else]]
* [[frozenset]]
* [[functools essentials]]
* [[global / nonlocal]]
* [[hashlib]]
* [[if / elif / else]]
* [[in / not in (membership)]]
* [[is / is not (identity)]]
* [[isinstance() and type()]]
* [[itertools essentials]]
* [[lambda (anonymous function)]]
* [[logging]]
* [[map() and filter()]]
* [[match / case (structural pattern matching)]]
* [[multiprocessing]]
* [[os.environ]]
* [[pass]]
* [[pathlib basics]]
* [[raise]]
* [[re (regular expressions)]]
* [[return]]
* [[secrets (secure random)]]
* [[self]]
* [[shutil]]
* [[sorted() and .sort()]]
* [[str vs bytes]]
* [[subprocess basics]]
* [[super()]]
* [[tempfile]]
* [[threading]]
* [[try / except]]
* [[try / except / else / finally]]
* [[while loop]]
* [[with (context manager)]]
* [[yield (generators)]]
* [[zip tricks]]
* [[zip()]]
!! MOC — footguns

Every atom extracted from a ''footgun'' source (13 total).

* [[AWS API pagination limits cause silent data loss]]
* [[Git URLs without commit pinning produce non-reproducible builds]]
* [[Hardcoded credentials in code are readily compromised]]
* [[Mixing system packages and pip creates version conflicts]]
* [[Multiple dependency declaration files create inconsistent builds]]
* [[Non-atomic file writes corrupt state on process termination]]
* [[Overly broad exception handlers hide bugs and failures]]
* [[Passing interpolated strings to shell=True allows command injection]]
* [[Relative imports fail when modules are run directly instead of via python -m]]
* [[System Python must use virtualenvs to prevent package conflicts]]
* [[Unmanaged HTTP request timeouts cause cascading hangs]]
* [[Unpinned dependencies make builds non-reproducible and fragile]]
* [[__init__.py is required for directories to be importable as packages]]
!! MOC — other

Every atom extracted from a ''other'' source (109 total).

* [[All Python debuggers use sys.settrace() with measurable overhead]]
* [[Alpine musl libc breaks glibc wheels and DNS in Python containers]]
* [[Assertions are development aids, removed in production with -O]]
* [[Atomic file updates prevent corruption and data loss]]
* [[Audit dependencies for security vulnerabilities and license compliance]]
* [[Bare except clauses hide all errors, including bugs in your code]]
* [[Blocking I/O calls freeze the asyncio event loop and all other coroutines]]
* [[Blocking in async handlers starves the entire event loop]]
* [[Bootstrap Python on fresh OS installs with raw module]]
* [[Build and publish internal Python packages to private indexes]]
* [[CPU profiling reveals which functions consume the most time]]
* [[Circular imports produce partially-initialized modules]]
* [[Click structures CLI tools with validation and subcommands]]
* [[Code-first load testing is more accessible than UI-based tools]]
* [[Concurrency model choice drives deployment speed orders of magnitude]]
* [[Debugger breakpoints in threads deadlock waiting for stdin]]
* [[Debugging Python encoding errors in production]]
* [[Debugging hung async code via debug mode and task inspection]]
* [[Debugging memory leaks with tracemalloc and objgraph]]
* [[Debugging segfaults in Python C extensions]]
* [[Debugging tool selection by symptom and environment]]
* [[Diagnose dependency conflicts with pipdeptree]]
* [[Diagnosing import failures in Python and Docker]]
* [[Diagnostic commands for Python infrastructure debugging]]
* [[Docker multi-stage builds minimize image size for Python apps]]
* [[Editable installs let you edit source and see changes immediately]]
* [[Event loop blocking in async Python services]]
* [[Event loops are thread-local; use run_coroutine_threadsafe to call async from threads]]
* [[Exception chaining preserves the original cause in the traceback]]
* [[Exceptions in threads disappear silently without propagating]]
* [[Exponential backoff in retries prevents service overload]]
* [[Forgetting async with for sessions leaks file descriptors and connections]]
* [[Forking after threading creates deadlocked child processes with copied lock state]]
* [[GIL prevents CPU parallelism but releases during I/O]]
* [[Generators enable streaming processing without loading entire files into memory]]
* [[Graceful async shutdown tracks tasks and respects cancellation]]
* [[Import-time side effects create fragile, order-dependent loading]]
* [[Inconsistent lock acquisition order causes deadlock between threads]]
* [[Inspect sys.path and site-packages to understand module resolution]]
* [[Introspection of Python in Docker containers]]
* [[JVM and interpreted languages require runtime perf maps for readable function names]]
* [[Jinja2 templates generate infrastructure code and configs]]
* [[Lock dependencies with pip-compile for reproducibility]]
* [[Locust enables stateful user workflows with distributed execution]]
* [[Logging levels organize severity and information categories]]
* [[Manage multiple Python versions for different projects]]
* [[Memory profiling is non-deterministic due to reference counting]]
* [[ModuleNotFoundError usually means wrong Python, wrong path, or inactive venv]]
* [[Multi-stage Docker builds eliminate build tools from images]]
* [[Multiple APIs exist for capturing and formatting exception information]]
* [[Multiprocessing achieves true CPU parallelism with separate interpreters]]
* [[Multiprocessing in Docker requires init process and fork-safe startup]]
* [[Mutable default arguments are shared across all function calls]]
* [[Never mix system and pip packages — use virtualenvs for applications]]
* [[Operational failures compound when you skip documentation and caution]]
* [[PYTHONFAULTHANDLER captures segfaults in C extensions]]
* [[PYTHONPATH prepends to sys.path globally — prefer pip install -e instead]]
* [[Print debugging remains the most common debugging technique]]
* [[Private PyPI solutions: devpi, CodeArtifact, or pip.conf]]
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
* [[ProcessPoolExecutor requires serializable functions and data; lambdas cannot be pickled]]
* [[Profiling strategies for slow FastAPI endpoints]]
* [[Python 3.11 shows exact expression locations in tracebacks]]
* [[Python bridges ops scripting and software engineering]]
* [[Python buffers stdout; output vanishes in Docker without flags]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
* [[Python's traceback format influenced error reporting across languages]]
* [[Quick HTTP server from any directory with Python]]
* [[Quick fixes for common Python installation errors]]
* [[Rate-limited async API client with retry and backoff handles bulk scanning safely]]
* [[Recover broken virtualenvs through targeted repair methods]]
* [[SSL certificate verification requires pointing to the correct CA bundle]]
* [[Scan Python dependencies against known vulnerabilities]]
* [[Semaphore limits concurrent operations without blocking new submissions]]
* [[Seven common pitfalls in Python infrastructure scripts]]
* [[Shared mutable state in threads requires explicit synchronization]]
* [[Signal handlers require event-loop registration in asyncio, main-thread setup in threading]]
* [[Structured logging for production troubleshooting]]
* [[Systematic procedure to diagnose hung Python processes using live profiling and system introspection]]
* [[The GIL does not make individual operations atomic; protect shared state with locks]]
* [[The trace module counts execution to identify hot paths and bottlenecks]]
* [[The warnings module signals deprecations and issues separately from exceptions]]
* [[ThreadPoolExecutor defaults to too many workers for resource-limited services]]
* [[ThreadPoolExecutor enables controlled parallel fleet operations]]
* [[Threading pools coordinate I/O-bound work with shared memory and locks]]
* [[Threads do not parallelize CPU-bound work; the GIL serializes operations]]
* [[Unjoined processes remain in the process table as zombies until parent exits]]
* [[Vendor dependencies for offline and supply-chain secure installs]]
* [[Version pinning strategy depends on whether you're a library or application]]
* [[Wheels are pre-built, sdists are source distributions]]
* [[Workload type determines the optimal concurrency model]]
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[boto3 accesses AWS APIs with proper error handling and pagination]]
* [[cgitb module provides formatted tracebacks with context]]
* [[concurrent.futures parallelizes I/O-bound infrastructure tasks]]
* [[concurrent.futures unifies thread and process pool APIs]]
* [[debugpy enables remote debugging of containerized code]]
* [[dis module reveals Python bytecode and optimization patterns]]
* [[faulthandler captures Python stack traces when the process crashes]]
* [[ipdb and pdb++ extend pdb with completion and visualization]]
* [[is checks identity; == checks value; small ints are interned]]
* [[paramiko enables SSH automation with connection lifecycle management]]
* [[pathlib replaces os.path for modern file operations]]
* [[pdb shipped with Python 1.0 in 1994]]
* [[python -i flag creates post-mortem debugging environment]]
* [[requests with retries and timeout handles flaky APIs safely]]
* [[strace reveals system-level bottlenecks by showing process syscalls]]
* [[subprocess runs shell commands safely with argument lists]]
* [[subprocess.run blocks; use asyncio.create_subprocess_exec for concurrency]]
!! MOC — confidence high

Atoms with confidence in the ''high'' band (1072 total).

* [[*args and **kwargs]]
* [[@property]]
* [[@staticmethod / @classmethod]]
* [[AWS API pagination limits cause silent data loss]]
* [[Abstract base class (ABC)]]
* [[All Python debuggers use sys.settrace() with measurable overhead]]
* [[Approximately how many packages are on PyPI as of 2025?]]
* [[Assertions are development aids, removed in production with -O]]
* [[Atomic file updates prevent corruption and data loss]]
* [[Augmented assignment]]
* [[Bare except clauses hide all errors, including bugs in your code]]
* [[Blocking I/O calls freeze the asyncio event loop and all other coroutines]]
* [[Blocking in async handlers starves the entire event loop]]
* [[Bootstrap Python on fresh OS installs with raw module]]
* [[Build and publish internal Python packages to private indexes]]
* [[CPU profiling reveals which functions consume the most time]]
* [[Calculate the stock span problem]]
* [[Can a tuple be a dictionary key?]]
* [[Can f-strings contain the backslash character?]]
* [[Can the walrus operator be used in all expression contexts?]]
* [[Can you match against object attributes in Python's pattern matching?]]
* [[Can you use built-in types as generics since Python 3.9?]]
* [[Check anagram removal count for two strings]]
* [[Circular imports produce partially-initialized modules]]
* [[Class variable vs instance variable]]
* [[Click structures CLI tools with validation and subcommands]]
* [[Closure]]
* [[Common string methods]]
* [[Concurrency model choice drives deployment speed orders of magnitude]]
* [[Conditional expression (ternary)]]
* [[Custom context manager]]
* [[Custom exceptions]]
* [[Dataclasses vs namedtuples — when to use which?]]
* [[Debugger breakpoints in threads deadlock waiting for stdin]]
* [[Debugging Python encoding errors in production]]
* [[Debugging hung async code via debug mode and task inspection]]
* [[Debugging memory leaks with tracemalloc and objgraph]]
* [[Debugging segfaults in Python C extensions]]
* [[Debugging tool selection by symptom and environment]]
* [[Decorator]]
* [[Detect a cycle in a linked list]]
* [[Detect palindrome]]
* [[Determine if a zero-sum subarray exists]]
* [[Diagnose dependency conflicts with pipdeptree]]
* [[Diagnosing import failures in Python and Docker]]
* [[Diagnostic commands for Python infrastructure debugging]]
* [[Dict comprehension]]
* [[Dict operations]]
* [[Docker multi-stage builds minimize image size for Python apps]]
* [[Does Python have native support for complex numbers?]]
* [[Does Python intern strings?]]
* [[Does `finally` always execute?]]
* [[Editable installs let you edit source and see changes immediately]]
* [[Event loop blocking in async Python services]]
* [[Event loops are thread-local; use run_coroutine_threadsafe to call async from threads]]
* [[Exception chaining preserves the original cause in the traceback]]
* [[Exception hierarchy]]
* [[Exceptions in threads disappear silently without propagating]]
* [[Explain Python's Method Resolution Order (MRO)]]
* [[Explain Python's property decorator]]
* [[Explain name mangling with double underscores]]
* [[Exponential backoff in retries prevents service overload]]
* [[Find all pairs in an array that sum to k]]
* [[Find the first non-repeating character in a string]]
* [[Find the middle element of a linked list in one pass]]
* [[Forgetting async with for sessions leaks file descriptors and connections]]
* [[Forking after threading creates deadlocked child processes with copied lock state]]
* [[GIL prevents CPU parallelism but releases during I/O]]
* [[Generate all permutations of a string]]
* [[Generate the largest number from a list of integers]]
* [[Generator expression]]
* [[Generators enable streaming processing without loading entire files into memory]]
* [[Git URLs without commit pinning produce non-reproducible builds]]
* [[Give a common use case for the walrus operator.]]
* [[Graceful async shutdown tracks tasks and respects cancellation]]
* [[Hardcoded credentials in code are readily compromised]]
* [[How can you restrict what classes can be unpickled for security?]]
* [[How do you add an item to the end of a list?]]
* [[How do you check for `None` in Python?]]
* [[How do you check if two values are equal?]]
* [[How do you create a context manager from a generator function using `contextlib`?]]
* [[How do you create a custom exception?]]
* [[How do you create a named tuple with `collections.namedtuple`?]]
* [[How do you format a number with thousands separators in an f-string?]]
* [[How do you implement a max-heap using Python's `heapq` module?]]
* [[How do you install a package in Python?]]
* [[How do you set the precision for `decimal.Decimal` operations?]]
* [[How do you stack multiple decorators?]]
* [[How do you suppress exception chaining?]]
* [[How do you use `itertools.product` to get the equivalent of a triple nested loop?]]
* [[How do you write a comment in Python?]]
* [[How does CPython implement dicts internally?]]
* [[How does CPython's garbage collector handle circular references?]]
* [[How does Python define code blocks?]]
* [[How does someone become a Python core developer?]]
* [[How does super() work in Python 3?]]
* [[How many items does `itertools.permutations('ABC', 2)` yield?]]
* [[How many keywords does Python 3.12 have?]]
* [[Implement DFS and BFS for a graph]]
* [[Implement QuickSort]]
* [[Implement a Trie (prefix tree)]]
* [[Implement a linked list with insert, find, delete]]
* [[Implement binary search]]
* [[Implement the Singleton pattern in Python (three ways)]]
* [[Import-time side effects create fragile, order-dependent loading]]
* [[In `dataclasses`, what does the `field()` function's `default_factory` parameter do?]]
* [[Inconsistent lock acquisition order causes deadlock between threads]]
* [[Inheritance]]
* [[Introspection of Python in Docker containers]]
* [[Is Python statically or dynamically typed?]]
* [[Is `OrderedDict` still useful now that regular dicts maintain insertion order (since Py…]]
* [[Is there a limit to integer size in Python 3?]]
* [[JSON and YAML]]
* [[JVM and interpreted languages require runtime perf maps for readable function names]]
* [[Jinja2 templates generate infrastructure code and configs]]
* [[LEGB scope rule]]
* [[List comprehension]]
* [[List operations]]
* [[Lock dependencies with pip-compile for reproducibility]]
* [[Logging levels organize severity and information categories]]
* [[Manage multiple Python versions for different projects]]
* [[Memory profiling is non-deterministic due to reference counting]]
* [[Merge two sorted arrays]]
* [[Mixing system packages and pip creates version conflicts]]
* [[ModuleNotFoundError usually means wrong Python, wrong path, or inactive venv]]
* [[Multi-line strings and docstrings]]
* [[Multi-stage Docker builds eliminate build tools from images]]
* [[Multiple APIs exist for capturing and formatting exception information]]
* [[Multiple dependency declaration files create inconsistent builds]]
* [[Multiprocessing achieves true CPU parallelism with separate interpreters]]
* [[Multiprocessing in Docker requires init process and fork-safe startup]]
* [[Mutable default arguments are shared across all function calls]]
* [[Name five alternative Python implementations.]]
* [[Name three Python static type checkers besides mypy.]]
* [[NamedTuple]]
* [[Nested comprehension]]
* [[Never mix system and pip packages — use virtualenvs for applications]]
* [[Non-atomic file writes corrupt state on process termination]]
* [[None]]
* [[Overly broad exception handlers hide bugs and failures]]
* [[PYTHONFAULTHANDLER captures segfaults in C extensions]]
* [[PYTHONPATH prepends to sys.path globally — prefer pip install -e instead]]
* [[Passing interpolated strings to shell=True allows command injection]]
* [[ProcessPoolExecutor for CPU-bound parallel file work]]
* [[ProcessPoolExecutor requires serializable functions and data; lambdas cannot be pickled]]
* [[Product array — compute products of all elements except self]]
* [[Profiling strategies for slow FastAPI endpoints]]
* [[Protocol (structural typing)]]
* [[Python 3.11 shows exact expression locations in tracebacks]]
* [[Python bridges ops scripting and software engineering]]
* [[Python buffers stdout; output vanishes in Docker without flags]]
* [[Python's packaging ecosystem was recognized as fragmented and confusing]]
* [[Quick HTTP server from any directory with Python]]
* [[Quick fixes for common Python installation errors]]
* [[Rate-limited async API client with retry and backoff handles bulk scanning safely]]
* [[Recover broken virtualenvs through targeted repair methods]]
* [[Relative imports fail when modules are run directly instead of via python -m]]
* [[Reverse words in a sentence]]
* [[SSL certificate verification requires pointing to the correct CA bundle]]
* [[Scan Python dependencies against known vulnerabilities]]
* [[Semaphore limits concurrent operations without blocking new submissions]]
* [[Set comprehension]]
* [[Set operations]]
* [[Seven common pitfalls in Python infrastructure scripts]]
* [[Shared mutable state in threads requires explicit synchronization]]
* [[Sliding window maximum]]
* [[String slicing]]
* [[Structured logging for production troubleshooting]]
* [[System Python must use virtualenvs to prevent package conflicts]]
* [[Systematic procedure to diagnose hung Python processes using live profiling and system introspection]]
* [[The GIL does not make individual operations atomic; protect shared state with locks]]
* [[The Global Interpreter Lock constrains Python threading to I/O concurrency]]
* [[The trace module counts execution to identify hot paths and bottlenecks]]
* [[The warnings module signals deprecations and issues separately from exceptions]]
* [[ThreadPoolExecutor defaults to too many workers for resource-limited services]]
* [[ThreadPoolExecutor enables controlled parallel fleet operations]]
* [[Threading pools coordinate I/O-bound work with shared memory and locks]]
* [[Threads do not parallelize CPU-bound work; the GIL serializes operations]]
* [[Truthy and falsy values]]
* [[Tuple operations]]
* [[Two-pointer technique for sorted array problems]]
* [[Type hints]]
* [[Unjoined processes remain in the process table as zombies until parent exits]]
* [[Unmanaged HTTP request timeouts cause cascading hangs]]
* [[Unpacking (* and **)]]
* [[Unpinned dependencies make builds non-reproducible and fragile]]
* [[Vendor dependencies for offline and supply-chain secure installs]]
* [[Version pinning strategy depends on whether you're a library or application]]
* [[Walrus operator (:=)]]
* [[What API convention does scikit-learn follow?]]
* [[What ASGI server is commonly used with FastAPI?]]
* [[What Monty Python references exist in the Python stdlib?]]
* [[What NumPy function creates an array of zeros?]]
* [[What PEP defines the Python style guide?]]
* [[What PEP established the Steering Council governance model?]]
* [[What PEP introduced type hints to Python?]]
* [[What PEP number is "The Zen of Python"?]]
* [[What PEPs define structural pattern matching?]]
* [[What Python library has become the standard for data validation and settings management?]]
* [[What WSGI toolkit does Flask use under the hood?]]
* [[What `Enum` subclass was introduced in Python 3.11 to ensure members are valid strings?]]
* [[What are "sprints" at Python conferences?]]
* [[What are *args and **kwargs in Python functions?]]
* [[What are Python "lightning talks"?]]
* [[What are `.pth` files?]]
* [[What are `__lt__`, `__le__`, `__gt__`, `__ge__`?]]
* [[What are all 19 aphorisms of The Zen of Python?]]
* [[What are class methods and static methods?]]
* [[What are context variables (`contextvars`)?]]
* [[What are descriptors in Python?]]
* [[What are exception groups, introduced in Python 3.11?]]
* [[What are first-class functions?]]
* [[What are historically the most downloaded packages on PyPI?]]
* [[What are metaclasses and when would you use them?]]
* [[What are named groups in regex and how do you use them?]]
* [[What are namespace packages?]]
* [[What are pytest marks?]]
* [[What are the advantages of `collections.deque` over a list?]]
* [[What are the different comprehension types in Python?]]
* [[What are the standard logging levels in Python, from lowest to highest?]]
* [[What are the three generations in CPython's garbage collector?]]
* [[What are the three logical operators?]]
* [[What are the three string formatting approaches in Python?]]
* [[What are variables in Python and how are they defined?]]
* [[What arguments does `__exit__` receive?]]
* [[What built-in functions are considered functional-style?]]
* [[What caused Guido to resign as BDFL?]]
* [[What critical requirement does `itertools.groupby()` have?]]
* [[What design pattern does Django follow?]]
* [[What did Guido work on at Dropbox?]]
* [[What did Guido work on at Google?]]
* [[What did Python 2.2 introduce?]]
* [[What did Python 2.5 introduce?]]
* [[What did Python 2.6 introduce?]]
* [[What did Python 2.7 introduce?]]
* [[What did Python 3.12 do with the GIL?]]
* [[What did Python 3.7 add?]]
* [[What did `breakpoint()` (Python 3.7) replace?]]
* [[What do parentheses `()` do in a regex pattern?]]
* [[What does BDFL stand for, and who held that title?]]
* [[What does Flask call itself?]]
* [[What does NumPy stand for?]]
* [[What does PSF stand for?]]
* [[What does PyPI stand for?]]
* [[What does SciPy provide that NumPy does not?]]
* [[What does `@dataclass(frozen=True)` do?]]
* [[What does `@dataclass(kw_only=True)` do, introduced in Python 3.10?]]
* [[What does `@dataclass(order=True)` do?]]
* [[What does `@dataclass` generate automatically?]]
* [[What does `@property` do under the hood?]]
* [[What does `Counter.elements()` return?]]
* [[What does `Counter.most_common(n)` return?]]
* [[What does `OrderedDict.move_to_end(key, last=True)` do?]]
* [[What does `[1, 2, 3][::-1]` return?]]
* [[What does `__all__` in `__init__.py` control?]]
* [[What does `__hash__` need to be consistent with?]]
* [[What does `__init__` vs `__new__` do?]]
* [[What does `__subclasshook__` do?]]
* [[What does `any([])` return?]]
* [[What does `any(generator_expression)` short-circuit?]]
* [[What does `argparse.ArgumentParser.add_subparsers()` do?]]
* [[What does `calendar.isleap(year)` check?]]
* [[What does `chr()` and `ord()` do?]]
* [[What does `collections.Counter.subtract()` do differently from `-`?]]
* [[What does `collections.Counter` return when you access a key that doesn't exist?]]
* [[What does `collections.deque(maxlen=n)` do when you append beyond capacity?]]
* [[What does `contextlib.redirect_stdout()` do?]]
* [[What does `contextlib.suppress()` do?]]
* [[What does `copy.deepcopy()` do differently from `copy.copy()`?]]
* [[What does `datetime.datetime.fromisoformat()` parse?]]
* [[What does `deque.rotate(n)` do?]]
* [[What does `dict | other_dict` do in Python 3.9+?]]
* [[What does `dis.dis()` do?]]
* [[What does `divmod(a, b)` return?]]
* [[What does `enumerate()` return?]]
* [[What does `f'{value=}'` do, introduced in Python 3.8?]]
* [[What does `float('inf')` represent?]]
* [[What does `functools.cached_property` do?]]
* [[What does `functools.cmp_to_key` do?]]
* [[What does `functools.lru_cache` do?]]
* [[What does `functools.partial` do?]]
* [[What does `functools.partialmethod` do?]]
* [[What does `functools.reduce` do?]]
* [[What does `functools.singledispatch` do?]]
* [[What does `functools.total_ordering` require you to define?]]
* [[What does `functools.wraps` do?]]
* [[What does `hash(-1)` return in CPython?]]
* [[What does `hash(float('inf'))` return?]]
* [[What does `hashlib` provide?]]
* [[What does `heapq.nlargest(n, iterable)` do, and when is it more efficient than sorting?]]
* [[What does `id()` return?]]
* [[What does `import __hello__` do?]]
* [[What does `import __phello__` do in Python 3.12+?]]
* [[What does `int.bit_length()` return?]]
* [[What does `int.to_bytes()` do?]]
* [[What does `isinstance()` check that `type()` does not?]]
* [[What does `isinstance(True, int)` return?]]
* [[What does `itertools.accumulate()` do?]]
* [[What does `itertools.batched()` do, and when was it added?]]
* [[What does `itertools.chain(*iterables)` do?]]
* [[What does `itertools.combinations('ABCD', 2)` return?]]
* [[What does `itertools.compress(data, selectors)` do?]]
* [[What does `itertools.count(start=0, step=1)` do?]]
* [[What does `itertools.cycle(iterable)` do?]]
* [[What does `itertools.dropwhile(predicate, iterable)` do?]]
* [[What does `itertools.filterfalse(predicate, iterable)` do?]]
* [[What does `itertools.groupby()` yield?]]
* [[What does `itertools.islice()` do?]]
* [[What does `itertools.pairwise()` return for an empty or single-element iterable?]]
* [[What does `itertools.product('AB', '12')` yield?]]
* [[What does `itertools.repeat(elem, times=None)` do?]]
* [[What does `itertools.starmap(func, iterable)` do?]]
* [[What does `itertools.tee(iterable, n=2)` return?]]
* [[What does `itertools.zip_longest()` do differently from `zip()`?]]
* [[What does `json.dumps(obj, default=str)` do?]]
* [[What does `list.extend()` do vs `list.append()`?]]
* [[What does `list.sort()` vs `sorted()` return?]]
* [[What does `math.gcd()` compute?]]
* [[What does `math.lcm()` compute, and when was it added?]]
* [[What does `math.prod()` do, and when was it added?]]
* [[What does `object.__repr__` return by default?]]
* [[What does `object.__subclasses__()` return?]]
* [[What does `os.path.expanduser('~')` return?]]
* [[What does `os.scandir()` return and why is it preferred over `os.listdir()`?]]
* [[What does `pandas.DataFrame.merge()` do?]]
* [[What does `pandas.read_csv()` do?]]
* [[What does `pass` do in Python?]]
* [[What does `pytest.fixture` do?]]
* [[What does `python -O` do?]]
* [[What does `python -c "expr"` do?]]
* [[What does `python -m calendar` do?]]
* [[What does `python -m ensurepip` do?]]
* [[What does `python -m json.tool` do?]]
* [[What does `python -m py_compile script.py` do?]]
* [[What does `python -m site` do?]]
* [[What does `python -m venv myenv` do?]]
* [[What does `python -v` do?]]
* [[What does `raise` without an argument do?]]
* [[What does `re.compile()` return and why use it?]]
* [[What does `re.escape(string)` do?]]
* [[What does `re.findall()` return when the pattern contains groups?]]
* [[What does `re.split(pattern, string)` do differently from `str.split()`?]]
* [[What does `re.sub(pattern, repl, string)` do?]]
* [[What does `re.subn()` return differently from `re.sub()`?]]
* [[What does `reversed()` require?]]
* [[What does `sorted()` guarantee about equal elements?]]
* [[What does `str.casefold()` do differently from `str.lower()`?]]
* [[What does `str.format_map()` do?]]
* [[What does `str.removeprefix()` do, and when was it added?]]
* [[What does `str.translate()` do?]]
* [[What does `str.zfill(width)` do?]]
* [[What does `string.ascii_letters` contain?]]
* [[What does `struct.pack('>I', 1024)` return?]]
* [[What does `sys.argv` contain?]]
* [[What does `sys.exit()` actually raise?]]
* [[What does `sys.getdefaultencoding()` return in Python 3?]]
* [[What does `sys.getrecursionlimit()` return?]]
* [[What does `sys.getsizeof(())` vs `sys.getsizeof([])` show?]]
* [[What does `sys.getsizeof()` return?]]
* [[What does `sys.getsizeof(1)` return approximately?]]
* [[What does `sys.getswitchinterval()` return?]]
* [[What does `sys.intern(string)` do?]]
* [[What does `sys.platform` return on Linux, macOS, and Windows?]]
* [[What does `sys.settrace()` do?]]
* [[What does `sys.version_info` return?]]
* [[What does `textwrap.dedent()` do?]]
* [[What does `textwrap.fill()` do?]]
* [[What does `timedelta` represent?]]
* [[What does `type(...)` return?]]
* [[What does `typing.Protocol` do?]]
* [[What does `typing.Unpack` do?]]
* [[What does case-sensitivity mean in Python?]]
* [[What does if __name__ == "__main__": do?]]
* [[What does the `%` operator do with strings in Python?]]
* [[What does the `*` separator in function parameters do?]]
* [[What does the `/` separator in function parameters do?]]
* [[What does the `__future__` module do?]]
* [[What does the `__iter__` method return?]]
* [[What does the `abc.abstractmethod` decorator do?]]
* [[What does the `dataclasses.asdict()` function do?]]
* [[What does the `enum.Flag` class allow?]]
* [[What does the `gc` module do?]]
* [[What does the `import` statement do in Python?]]
* [[What does the `re.DOTALL` (or `re.S`) flag do?]]
* [[What does the `re.IGNORECASE` (or `re.I`) flag do?]]
* [[What does the `re.MULTILINE` (or `re.M`) flag do?]]
* [[What does the `re.VERBOSE` (or `re.X`) flag do?]]
* [[What does the `secrets` module provide that `random` does not?]]
* [[What does the `statistics` module provide?]]
* [[What does the `str.partition(sep)` method return?]]
* [[What does the `traceback` module provide?]]
* [[What does the input() function always return?]]
* [[What does the len() function do?]]
* [[What does the open() mode 'a' do?]]
* [[What does the open() mode 'w' do?]]
* [[What does the yield keyword do?]]
* [[What encoding does Python 3 use for source files by default?]]
* [[What features did Python 0.9.0 already include?]]
* [[What file replaced `setup.py` and `setup.cfg` as the modern Python project configuratio…]]
* [[What format spec would you use in an f-string to display a float with exactly 2 decimal…]]
* [[What framework is FastAPI built on top of?]]
* [[What function in `heapq` merges multiple sorted inputs into a single sorted output?]]
* [[What function returns the data type of an object?]]
* [[What governance model replaced the BDFL?]]
* [[What happened to `long` in Python 3?]]
* [[What happens if you create a `defaultdict` with no argument (i.e., `defaultdict()`)?]]
* [[What happens if you type `from __future__ import braces` in Python?]]
* [[What happens when you add two `Counter` objects together?]]
* [[What happens when you multiply a list: `[[]] * 3`?]]
* [[What happens when you run `import this` in Python?]]
* [[What improvement did Python 3.11 make to error messages?]]
* [[What integers does CPython cache (intern)?]]
* [[What is "EAFP" in Python?]]
* [[What is "decrementing"?]]
* [[What is "duck typing"?]]
* [[What is "nested loop"?]]
* [[What is "slicing" in Python?]]
* [[What is "tuple unpacking"?]]
* [[What is "type casting"?]]
* [[What is AIOHTTP?]]
* [[What is Black?]]
* [[What is Bottle's claim to fame?]]
* [[What is C3 linearization?]]
* [[What is CPython bytecode?]]
* [[What is CPython's memory allocator?]]
* [[What is CPython?]]
* [[What is CWI?]]
* [[What is Click?]]
* [[What is Cython?]]
* [[What is Django's ORM?]]
* [[What is Django's `manage.py`?]]
* [[What is Django's migration system?]]
* [[What is Django's primary design philosophy?]]
* [[What is EuroPython?]]
* [[What is Fabric?]]
* [[What is FastAPI's key distinguishing feature?]]
* [[What is Flask's `g` object?]]
* [[What is Gunicorn?]]
* [[What is Hypothesis?]]
* [[What is Invoke?]]
* [[What is Jinja2?]]
* [[What is Jupyter's name derived from?]]
* [[What is Litestar (formerly Starlite)?]]
* [[What is Matplotlib's `pyplot` interface?]]
* [[What is MicroPython?]]
* [[What is NumPy's `dtype`?]]
* [[What is PEP 649 about?]]
* [[What is PEP 703 (free-threading)?]]
* [[What is PEP 8 and why does it matter for Python code?]]
* [[What is Pandas `groupby()` used for?]]
* [[What is Polars?]]
* [[What is PyCon US?]]
* [[What is PyData?]]
* [[What is PyInstaller?]]
* [[What is PyPy and why is it significant?]]
* [[What is Pydantic v2's key change from v1?]]
* [[What is Python Fire?]]
* [[What is Python and what makes it popular for DevOps and scripting?]]
* [[What is Python's `match` statement OR pattern?]]
* [[What is Python's `match` statement mapping pattern?]]
* [[What is Python's `match` statement sequence pattern?]]
* [[What is Rich?]]
* [[What is Sanic?]]
* [[What is Starlette?]]
* [[What is Timsort?]]
* [[What is Tornado known for?]]
* [[What is Typer?]]
* [[What is YAML handling in Python?]]
* [[What is __init_subclass__ and how does it replace metaclasses?]]
* [[What is __repr__ vs __str__?]]
* [[What is __slots__ and when should you use it?]]
* [[What is `@dataclass` an example of in terms of Python internals?]]
* [[What is `DeprecationWarning` vs `PendingDeprecationWarning`?]]
* [[What is `NotImplemented` vs `NotImplementedError`?]]
* [[What is `PYTHONSTARTUP`?]]
* [[What is `ParamSpec` used for?]]
* [[What is `TypeAlias` used for?]]
* [[What is `TypeVar` used for?]]
* [[What is `__add__` vs `__radd__`?]]
* [[What is `__aiter__` and `__anext__`?]]
* [[What is `__all__` used for in a module?]]
* [[What is `__cached__` on a module?]]
* [[What is `__class_getitem__` used for?]]
* [[What is `__class_getitem__` vs `__getitem__`?]]
* [[What is `__del__` used for?]]
* [[What is `__dict__` on a class vs an instance?]]
* [[What is `__doc__`?]]
* [[What is `__eq__` and `__ne__`?]]
* [[What is `__file__` in a module?]]
* [[What is `__format__` used for?]]
* [[What is `__getattr__` vs `__getattribute__`?]]
* [[What is `__getitem__` used for?]]
* [[What is `__iadd__`?]]
* [[What is `__import__` hook?]]
* [[What is `__init_subclass__` used for?]]
* [[What is `__init_subclass__` vs a metaclass?]]
* [[What is `__iter__` vs `__getitem__` for iteration?]]
* [[What is `__len__` used for?]]
* [[What is `__missing__` used for?]]
* [[What is `__name__` set to when a module is imported?]]
* [[What is `__set_name__` used for?]]
* [[What is `__setitem__` and `__delitem__`?]]
* [[What is `__slots__` and why use it?]]
* [[What is `__slots__` inheritance behavior?]]
* [[What is `__spec__` in a module?]]
* [[What is `aiofiles`?]]
* [[What is `ansible-runner`?]]
* [[What is `argparse.FileType`?]]
* [[What is `async`/`await` in Python?]]
* [[What is `asyncio.Queue`?]]
* [[What is `asyncio.Semaphore` used for?]]
* [[What is `asyncio.create_task()` vs `await`?]]
* [[What is `asyncio.run()` used for?]]
* [[What is `asyncio.sleep()` vs `time.sleep()`?]]
* [[What is `asyncio.to_thread()` added in Python 3.9?]]
* [[What is `asyncio.wait_for()` used for?]]
* [[What is `atexit` used for?]]
* [[What is `base64` encoding used for in Python?]]
* [[What is `cffi` (C Foreign Function Interface)?]]
* [[What is `classmethod` vs `staticmethod` when used with inheritance?]]
* [[What is `collections.ChainMap` used for?]]
* [[What is `collections.UserDict` for?]]
* [[What is `collections.abc.Coroutine`?]]
* [[What is `collections.abc.Hashable`?]]
* [[What is `collections.abc.Iterator` vs `collections.abc.Iterable`?]]
* [[What is `collections.abc.MutableMapping`?]]
* [[What is `collections.abc` and how does it differ from `collections`?]]
* [[What is `compileall` used for?]]
* [[What is `concurrent.futures` and when was it introduced?]]
* [[What is `conda` and how does it differ from `pip`?]]
* [[What is `configparser` used for?]]
* [[What is `conftest.py` in pytest?]]
* [[What is `contextlib.ExitStack` used for?]]
* [[What is `contextlib.closing()` used for?]]
* [[What is `coverage.py` used for?]]
* [[What is `ctypes` used for?]]
* [[What is `decimal.Decimal` vs `float` for financial calculations?]]
* [[What is `dict.setdefault(key, default)`?]]
* [[What is `difflib.get_close_matches()` used for?]]
* [[What is `dir()` used for?]]
* [[What is `enum.unique` used for?]]
* [[What is `exec()` dangerous for?]]
* [[What is `fnmatch` used for?]]
* [[What is `functools.reduce` with an initial value?]]
* [[What is `getattr(obj, name, default)` used for?]]
* [[What is `hasattr(obj, name)` equivalent to?]]
* [[What is `hatch`?]]
* [[What is `hmac` module used for?]]
* [[What is `importlib` used for?]]
* [[What is `inspect.signature()` used for?]]
* [[What is `int.as_integer_ratio()` added in Python 3.8?]]
* [[What is `io.BytesIO` used for?]]
* [[What is `io.StringIO` used for?]]
* [[What is `isort`?]]
* [[What is `itertools.pairwise()` and when was it added?]]
* [[What is `itertools.product` with the `repeat` parameter?]]
* [[What is `itertools.repeat()` commonly used with?]]
* [[What is `json.JSONDecodeError`?]]
* [[What is `manylinux`?]]
* [[What is `marshal` and how does it differ from `pickle`?]]
* [[What is `math.factorial()` used for?]]
* [[What is `math.inf` equal to?]]
* [[What is `math.inf` vs `sys.float_info.max`?]]
* [[What is `math.isclose(a, b)` used for?]]
* [[What is `maturin`?]]
* [[What is `memoryview` used for?]]
* [[What is `multiprocessing.Pool` used for?]]
* [[What is `multiprocessing.Queue` vs `queue.Queue`?]]
* [[What is `mypyc`?]]
* [[What is `object.__new__`?]]
* [[What is `operator.attrgetter()` used for?]]
* [[What is `operator.itemgetter()` used for?]]
* [[What is `operator.methodcaller()` used for?]]
* [[What is `os._exit()` and when is it used?]]
* [[What is `os.environ`?]]
* [[What is `os.walk()` used for?]]
* [[What is `pathlib.Path.glob()` used for?]]
* [[What is `pathlib.Path.resolve()` used for?]]
* [[What is `pdb` and how do you invoke it?]]
* [[What is `pip freeze` used for?]]
* [[What is `pip install -e .` (editable install)?]]
* [[What is `pipx`?]]
* [[What is `poetry`?]]
* [[What is `pre-commit`?]]
* [[What is `py3-none-any` in a wheel filename?]]
* [[What is `pyenv`?]]
* [[What is `pytest.approx()` used for?]]
* [[What is `pytest.mark.parametrize` used for?]]
* [[What is `pytest.monkeypatch`?]]
* [[What is `pytest.raises`?]]
* [[What is `python -m this`?]]
* [[What is `python -m zipapp` used for?]]
* [[What is `ruff`?]]
* [[What is `scipy.optimize.minimize()`?]]
* [[What is `sdist` in Python packaging?]]
* [[What is `selectors` module?]]
* [[What is `shlex.split()` used for?]]
* [[What is `shutil.copytree()` used for?]]
* [[What is `smtplib` used for?]]
* [[What is `sqlite3` in the standard library?]]
* [[What is `ssl.create_default_context()` for?]]
* [[What is `statistics.NormalDist` used for?]]
* [[What is `str.encode()` and `bytes.decode()`?]]
* [[What is `str.isidentifier()`?]]
* [[What is `string.Template` and when would you use it?]]
* [[What is `subprocess.Popen` vs `subprocess.run`?]]
* [[What is `super()` and how does it work?]]
* [[What is `sys.exc_info()` used for?]]
* [[What is `sys.executable`?]]
* [[What is `sys.flags`?]]
* [[What is `sys.float_info`?]]
* [[What is `sys.getrefcount(obj)`?]]
* [[What is `sys.maxsize`?]]
* [[What is `sys.modules`?]]
* [[What is `sys.monitoring` in Python 3.12?]]
* [[What is `sys.path` and how does Python use it?]]
* [[What is `sys.setprofile()` used for?]]
* [[What is `sys.stdin`, `sys.stdout`, `sys.stderr`?]]
* [[What is `sysconfig` used for?]]
* [[What is `threading.Condition`?]]
* [[What is `threading.Event`?]]
* [[What is `threading.Lock` used for?]]
* [[What is `time.monotonic()`?]]
* [[What is `type()` with one argument vs three arguments?]]
* [[What is `types.SimpleNamespace`?]]
* [[What is `typing.Annotated` used for?]]
* [[What is `typing.Any`?]]
* [[What is `typing.AsyncIterator`?]]
* [[What is `typing.Awaitable`?]]
* [[What is `typing.Callable` used for?]]
* [[What is `typing.ClassVar` used for?]]
* [[What is `typing.Final` used for?]]
* [[What is `typing.Literal` used for?]]
* [[What is `typing.NamedTuple` and how does it compare to `collections.namedtuple`?]]
* [[What is `typing.Never` (Python 3.11) or `typing.NoReturn` used for?]]
* [[What is `typing.Optional[X]` equivalent to?]]
* [[What is `typing.Required` and `typing.NotRequired` for TypedDict?]]
* [[What is `typing.TypeGuard` used for?]]
* [[What is `typing.TypeVarTuple` used for?]]
* [[What is `typing.TypedDict` used for?]]
* [[What is `typing.Union` used for?]]
* [[What is `typing.cast()` used for?]]
* [[What is `typing.get_type_hints()` used for?]]
* [[What is `typing.overload` used for?]]
* [[What is `typing.runtime_checkable` used for?]]
* [[What is `unittest.TestCase.setUp()` vs `setUpClass()`?]]
* [[What is `unittest.mock.MagicMock`?]]
* [[What is `unittest.mock.patch` used for?]]
* [[What is `unittest.mock.sentinel`?]]
* [[What is `urllib.parse.urlencode()` used for?]]
* [[What is `urllib.parse.urlparse()` used for?]]
* [[What is `uv` in the Python ecosystem?]]
* [[What is `uvloop`?]]
* [[What is `vars(obj)` equivalent to?]]
* [[What is `virtualenv` and why is it important?]]
* [[What is `yield from` used for?]]
* [[What is `zipimport`?]]
* [[What is a "Syntax Error"?]]
* [[What is a "Value Error"?]]
* [[What is a "dictionary"?]]
* [[What is a "free list" in CPython?]]
* [[What is a "high-level" language?]]
* [[What is a "local variable"?]]
* [[What is a Boolean data type and how is it used in programming?]]
* [[What is a Jupyter kernel?]]
* [[What is a PEP 517 build backend?]]
* [[What is a PEP?]]
* [[What is a Pandas DataFrame?]]
* [[What is a Pandas Series?]]
* [[What is a Python "magic comment" for encoding?]]
* [[What is a Python generator?]]
* [[What is a Python namespace?]]
* [[What is a Python wheel's tag format?]]
* [[What is a `TYPE_CHECKING` guard?]]
* [[What is a `__fspath__` method?]]
* [[What is a `bytearray` and how does it differ from `bytes`?]]
* [[What is a `mappingproxy`?]]
* [[What is a `requirements.txt` file?]]
* [[What is a closure in Python?]]
* [[What is a code object in Python?]]
* [[What is a context manager protocol?]]
* [[What is a daemon thread?]]
* [[What is a data descriptor vs a non-data descriptor?]]
* [[What is a decorator in Python?]]
* [[What is a frozenset?]]
* [[What is a higher-order function?]]
* [[What is a lambda function?]]
* [[What is a list comprehension and when was it introduced?]]
* [[What is a list comprehension in Python?]]
* [[What is a list data type and how is it used?]]
* [[What is a metaclass?]]
* [[What is a named group backreference in regex?]]
* [[What is a negative lookahead?]]
* [[What is a negative lookbehind?]]
* [[What is a non-capturing group in regex?]]
* [[What is a parameterized decorator?]]
* [[What is a positive lookahead in regex?]]
* [[What is a positive lookbehind?]]
* [[What is a tuple and how does it differ from a list?]]
* [[What is a virtual environment in Python and why use it?]]
* [[What is a virtual subclass in Python's ABC framework?]]
* [[What is an "exception"?]]
* [[What is an "infinite loop"?]]
* [[What is an "integer division" operator?]]
* [[What is boto3?]]
* [[What is broadcasting in NumPy?]]
* [[What is currying in Python?]]
* [[What is doctest?]]
* [[What is duck typing and how does Python use it?]]
* [[What is exception chaining in Python?]]
* [[What is httpx?]]
* [[What is iteration in programming and what are common patterns?]]
* [[What is monkey patching?]]
* [[What is mypy?]]
* [[What is name mangling in Python?]]
* [[What is nox?]]
* [[What is paramiko?]]
* [[What is pytest's `tmp_path` fixture?]]
* [[What is pytest's key advantage over unittest?]]
* [[What is reference counting in CPython?]]
* [[What is scikit-learn?]]
* [[What is seaborn?]]
* [[What is string interning?]]
* [[What is the "math" module?]]
* [[What is the "os" module primarily used for?]]
* [[What is the "range()" function used for?]]
* [[What is the "six" library?]]
* [[What is the ABC module and how do you use abstract classes?]]
* [[What is the Ansiballz framework?]]
* [[What is the Django admin?]]
* [[What is the Easter egg hidden in the source code of the `this` module?]]
* [[What is the GIL's full name?]]
* [[What is the GIL's impact on I/O-bound vs CPU-bound threading?]]
* [[What is the LBYL coding style?]]
* [[What is the LEGB rule?]]
* [[What is the MRO in Python?]]
* [[What is the PEP process for proposing language changes?]]
* [[What is the Python REPL's `_` variable?]]
* [[What is the WAT moment with `[] == False`?]]
* [[What is the WAT moment with `hash(-1)` and `hash(-2)` in CPython?]]
* [[What is the WAT moment with tuple addition?]]
* [[What is the `@functools.lru_cache` memory leak risk?]]
* [[What is the `@property` deleter?]]
* [[What is the `@typing.dataclass_transform` decorator?]]
* [[What is the `Ellipsis` object (`...`) used for in Python?]]
* [[What is the `NotImplemented` singleton used for?]]
* [[What is the `PYTHONDONTWRITEBYTECODE` environment variable?]]
* [[What is the `PYTHONPATH` environment variable?]]
* [[What is the `TaskGroup` in Python 3.11's asyncio?]]
* [[What is the `__aenter__` and `__aexit__` protocol?]]
* [[What is the `__annotations__` attribute?]]
* [[What is the `__bool__` method?]]
* [[What is the `__contains__` method?]]
* [[What is the `__debug__` built-in constant?]]
* [[What is the `__init__.py` file for?]]
* [[What is the `__main__.py` file for?]]
* [[What is the `__prepare__` method in metaclasses?]]
* [[What is the `__pycache__` directory?]]
* [[What is the `__qualname__` attribute?]]
* [[What is the `__weakref__` attribute?]]
* [[What is the `abc.ABCMeta` metaclass?]]
* [[What is the `antigravity` module's geohash feature?]]
* [[What is the `apply()` method in Pandas?]]
* [[What is the `array` module used for?]]
* [[What is the `ast` module used for?]]
* [[What is the `cProfile` module?]]
* [[What is the `calendar` module?]]
* [[What is the `collections.OrderedDict` `popitem(last=True)` method?]]
* [[What is the `compile()` built-in?]]
* [[What is the `concurrent.futures.as_completed()` function?]]
* [[What is the `contextlib.aclosing()` context manager?]]
* [[What is the `contextlib.asynccontextmanager` decorator for?]]
* [[What is the `contextlib.nullcontext()` used for?]]
* [[What is the `csv` module?]]
* [[What is the `dataclasses.field()` metadata parameter for?]]
* [[What is the `dataclasses.make_dataclass()` function?]]
* [[What is the `decimal` module's `ROUND_HALF_EVEN` rounding mode?]]
* [[What is the `del` statement?]]
* [[What is the `difflib` module?]]
* [[What is the `dis` module?]]
* [[What is the `email` module?]]
* [[What is the `enum.auto()` function used for?]]
* [[What is the `enum.nonmember()` function added in Python 3.11?]]
* [[What is the `enum.verify` decorator added in Python 3.11?]]
* [[What is the `except*` syntax?]]
* [[What is the `fractions.Fraction.limit_denominator()` method?]]
* [[What is the `global` keyword used for?]]
* [[What is the `graphlib` module?]]
* [[What is the `help()` built-in?]]
* [[What is the `http.server` module used for?]]
* [[What is the `io` module?]]
* [[What is the `json` module's `cls` parameter?]]
* [[What is the `linecache` module?]]
* [[What is the `locale` module?]]
* [[What is the `logging` module's hierarchy?]]
* [[What is the `lru_cache` maximum size by default?]]
* [[What is the `match` statement guard clause?]]
* [[What is the `match` statement's `__match_args__` attribute used for?]]
* [[What is the `nonlocal` keyword used for?]]
* [[What is the `numbers` module?]]
* [[What is the `operator` module?]]
* [[What is the `pathlib` module and when was it introduced?]]
* [[What is the `perf` profiler support added in Python 3.12?]]
* [[What is the `pickle` protocol version?]]
* [[What is the `platform` module?]]
* [[What is the `profile` module vs `cProfile`?]]
* [[What is the `property` built-in?]]
* [[What is the `pydoc` module?]]
* [[What is the `reprlib` module used for?]]
* [[What is the `requests` library?]]
* [[What is the `secrets.token_urlsafe(nbytes)` function?]]
* [[What is the `select` module?]]
* [[What is the `shelve` module used for?]]
* [[What is the `signal` module used for?]]
* [[What is the `site` module responsible for?]]
* [[What is the `socket` module?]]
* [[What is the `struct` module's byte order prefixes?]]
* [[What is the `subprocess.PIPE` constant?]]
* [[What is the `subprocess.run()` function?]]
* [[What is the `textwrap` module useful for?]]
* [[What is the `type` statement in Python 3.12?]]
* [[What is the `types` module?]]
* [[What is the `typing.Self` type, and when was it introduced?]]
* [[What is the `unicodedata` module?]]
* [[What is the `walrus operator` officially called?]]
* [[What is the `warnings` module?]]
* [[What is the `weakref` module used for?]]
* [[What is the `wheel` filename convention?]]
* [[What is the `wheel` format?]]
* [[What is the `with` statement's full syntax since Python 3.1?]]
* [[What is the `zip()` function's strict mode?]]
* [[What is the `zoneinfo` module?]]
* [[What is the core data structure in NumPy?]]
* [[What is the default recursion limit?]]
* [[What is the default value returned by a `defaultdict(list)` for a missing key?]]
* [[What is the difference between == and is in Python?]]
* [[What is the difference between NumPy's `np.array()` and `np.asarray()`?]]
* [[What is the difference between Pandas and Polars?]]
* [[What is the difference between WSGI and ASGI?]]
* [[What is the difference between `@staticmethod` and `@classmethod`?]]
* [[What is the difference between `None` and `False`?]]
* [[What is the difference between `__cause__` and `__context__` on exceptions?]]
* [[What is the difference between `__import__()` and `importlib.import_module()`?]]
* [[What is the difference between `__str__` and `__repr__`?]]
* [[What is the difference between `a += b` and `a = a + b` for lists?]]
* [[What is the difference between `asyncio.gather()` and `TaskGroup`?]]
* [[What is the difference between `bisect.bisect_left()` and `bisect.bisect_right()`?]]
* [[What is the difference between `bytes` and `str` in Python 3?]]
* [[What is the difference between `combinations` and `combinations_with_replacement`?]]
* [[What is the difference between `enum.Enum` and `enum.IntEnum`?]]
* [[What is the difference between `exec()` and `eval()`?]]
* [[What is the difference between `functools.lru_cache` and `functools.cache`?]]
* [[What is the difference between `is` and `==` for `None`?]]
* [[What is the difference between `is` and `==` in Python?]]
* [[What is the difference between `itertools.chain()` and `itertools.chain.from_iterable()`?]]
* [[What is the difference between `list.copy()` and `list[:]`?]]
* [[What is the difference between `re.search()` and `re.fullmatch()`?]]
* [[What is the difference between `str.join()` and concatenation with `+`?]]
* [[What is the difference between `str.strip()` and `str.removeprefix()`/`str.removesuffix…]]
* [[What is the difference between `venv` and `virtualenv`?]]
* [[What is the difference between a "naive" and "aware" datetime in Python?]]
* [[What is the difference between a list comprehension and a generator expression?]]
* [[What is the difference between a parameter and an argument?]]
* [[What is the difference between boto3 client and resource interfaces?]]
* [[What is the difference between concurrency and parallelism in Python?]]
* [[What is the difference between read() and readlines()?]]
* [[What is the difference between return and print?]]
* [[What is the epoch in Python's `time` module?]]
* [[What is the exception hierarchy's root in Python?]]
* [[What is the experimental JIT compiler in Python 3.13?]]
* [[What is the iterator protocol?]]
* [[What is the late binding closures gotcha?]]
* [[What is the maximum date Python's `datetime` can represent?]]
* [[What is the maximum recursion depth in Python by default?]]
* [[What is the mutable default argument gotcha?]]
* [[What is the order of clauses in a try statement?]]
* [[What is the output of `print(0.1 + 0.2)`?]]
* [[What is the output of `round(0.5)` and `round(1.5)` in Python 3?]]
* [[What is the peephole optimizer in CPython?]]
* [[What is the per-interpreter GIL in Python 3.12?]]
* [[What is the precedence of the walrus operator?]]
* [[What is the purpose of garbage collection in Python?]]
* [[What is the relationship between `type` and `object`?]]
* [[What is the result of `"hello" * 3`?]]
* [[What is the result of `() is ()`?]]
* [[What is the result of `True + True`?]]
* [[What is the result of `[] is []`?]]
* [[What is the result of `bool([])`?]]
* [[What is the result of `{} == set()`?]]
* [[What is the safer way to use `subprocess`?]]
* [[What is the significance of Python 3.6?]]
* [[What is the significance of `antigravity` in Python?]]
* [[What is the small integer cache in CPython?]]
* [[What is the standard library module for parsing command-line arguments?]]
* [[What is the surprising behavior of `is` with short strings?]]
* [[What is the surprising result of `float('nan') == float('nan')`?]]
* [[What is the time complexity of Python's `dict` lookup?]]
* [[What is the time complexity of `bisect.insort()` for inserting into a sorted list?]]
* [[What is the time complexity of `in` for lists vs sets?]]
* [[What is the time complexity of `list.append()`?]]
* [[What is the time complexity of `list.insert(0, x)`?]]
* [[What is the time module's `perf_counter()` vs `time()`?]]
* [[What is the truthiness rule in Python?]]
* [[What is the type of `{}`?]]
* [[What is the walrus operator in Python?]]
* [[What is the walrus operator's PEP number?]]
* [[What is the wildcard pattern in Python's match statement?]]
* [[What is tox?]]
* [[What language was Python's direct predecessor at CWI Amsterdam?]]
* [[What limitation do lookbehinds have in Python's `re` module?]]
* [[What major feature did Python 3.12 change regarding f-strings?]]
* [[What major features were added in Python 3.10?]]
* [[What major features were added in Python 3.11?]]
* [[What major features were added in Python 3.12?]]
* [[What major features were added in Python 3.13?]]
* [[What major features were added in Python 3.8?]]
* [[What major features were added in Python 3.9?]]
* [[What method can you define on a dataclass to customize how it is initialized after `__i…]]
* [[What method does `defaultdict` call to produce a default value?]]
* [[What method makes an object callable?]]
* [[What method on a namedtuple creates a new instance with some fields replaced?]]
* [[What method on a namedtuple returns a regular dictionary?]]
* [[What method on an `lru_cache`-decorated function shows cache performance?]]
* [[What module allows exact arithmetic with fractions?]]
* [[What module lets you pack and unpack binary data in C struct format?]]
* [[What module provides abstract base classes?]]
* [[What module provides arbitrary-precision decimal arithmetic?]]
* [[What module provides functions for working with temporary files and directories?]]
* [[What module provides functions to maintain a list in sorted order without having to sor…]]
* [[What module provides memory-mapped file access?]]
* [[What module was added in Python 3.11 for parsing TOML files?]]
* [[What new REPL was introduced in Python 3.13?]]
* [[What new generic syntax was introduced in Python 3.12?]]
* [[What parameter to `@dataclass` was added in Python 3.10 to allow slot-based instances?]]
* [[What performance improvement was made in Python 3.11?]]
* [[What safer alternatives to pickle exist for data serialization?]]
* [[What standard library module can you use to measure execution time of small code snippets?]]
* [[What standard library module provides an interface to the operating system's random num…]]
* [[What standard library module provides support for generating universally unique identif…]]
* [[What template engine does Django use by default?]]
* [[What tool is the modern standard for building Python packages?]]
* [[What value is returned if a function has no return statement?]]
* [[What was Python 1.5 notable for?]]
* [[What was the "Python 3000" or "Py3k" initiative?]]
* [[What was the original name of `pip`?]]
* [[What were the main breaking changes in Python 3.0?]]
* [[What year did Guido van Rossum receive the Award for the Advancement of Free Software f…]]
* [[What year did Python first appear on the TIOBE index top 3?]]
* [[What's the difference between a list and a tuple in Python?]]
* [[Wheels are pre-built, sdists are source distributions]]
* [[When did Guido van Rossum start working on Python?]]
* [[When did Python 2 reach end of life?]]
* [[When did dict ordering become a language guarantee?]]
* [[When does the `else` clause of a `try` block execute?]]
* [[When was Django first released?]]
* [[When was Python 0.9.0 first released publicly?]]
* [[When was Python 1.0 released?]]
* [[When was Python 2.0 released and what did it add?]]
* [[When was Python 3.0 released?]]
* [[When was `functools.cached_property` introduced?]]
* [[When was `pip` first released?]]
* [[When you set a value on a `ChainMap`, which underlying dict is modified?]]
* [[Where do "spam" and "eggs" come from as Python variable names?]]
* [[Where has Guido van Rossum worked?]]
* [[Where was PyCon US first held?]]
* [[Which Zen aphorism is often cited to argue against Java-style getter/setter methods in …]]
* [[Which Zen aphorism is the "Dutch" one a reference to?]]
* [[Which operator gives the remainder of division?]]
* [[Which standard library module provides a min-heap implementation?]]
* [[Who created Django?]]
* [[Who created Flask?]]
* [[Who created Matplotlib and why?]]
* [[Who is the current fastest growing Python web framework (as of 2025)?]]
* [[Who wrote The Zen of Python?]]
* [[Why are NumPy operations faster than Python loops?]]
* [[Why are tuples slightly faster than lists?]]
* [[Why did Guido join Microsoft in 2020?]]
* [[Why do we use raw strings (r'...') for regex patterns in Python?]]
* [[Why does `0.1 + 0.2 != 0.3` in Python?]]
* [[Why does `all([])` return `True`?]]
* [[Why does `import this` have 19 aphorisms when The Zen of Python was supposed to have 20?]]
* [[Why does the GIL exist?]]
* [[Why is `True + True == 2`?]]
* [[Why is the language called "Python"?]]
* [[Why is unpickling data from untrusted sources a security risk?]]
* [[Why must arguments to an `lru_cache`-decorated function be hashable?]]
* [[Why should you avoid using `datetime.utcnow()`?]]
* [[Why should you never use `shell=True` with `subprocess` when handling user input?]]
* [[Why should you not catch `BaseException`?]]
* [[Why was PEP 572 (walrus operator) controversial?]]
* [[Why was `pytz` problematic?]]
* [[Why was `reduce` moved from builtins to `functools` in Python 3?]]
* [[Why was the Python 2 to 3 migration so painful?]]
* [[Workload type determines the optimal concurrency model]]
* [[__add__, __eq__, __lt__ (operator overloading)]]
* [[__enter__ and __exit__]]
* [[__init__ and __repr__]]
* [[__init__.py is required for directories to be importable as packages]]
* [[__len__ and __getitem__]]
* [[__slots__]]
* [[any() and all()]]
* [[argparse]]
* [[as (aliasing)]]
* [[assert]]
* [[async / await]]
* [[asyncio runs coroutines on a single-threaded event loop without locks]]
* [[boto3 accesses AWS APIs with proper error handling and pagination]]
* [[break]]
* [[cgitb module provides formatted tracebacks with context]]
* [[class]]
* [[collections.Counter]]
* [[collections.defaultdict]]
* [[collections.deque]]
* [[concurrent.futures parallelizes I/O-bound infrastructure tasks]]
* [[concurrent.futures unifies thread and process pool APIs]]
* [[continue]]
* [[dataclass]]
* [[datetime]]
* [[debugpy enables remote debugging of containerized code]]
* [[def (function definition)]]
* [[del (delete)]]
* [[dis module reveals Python bytecode and optimization patterns]]
* [[enumerate()]]
* [[f-string (formatted string literal)]]
* [[faulthandler captures Python stack traces when the process crashes]]
* [[for loop]]
* [[for/else and while/else]]
* [[frozenset]]
* [[functools essentials]]
* [[global / nonlocal]]
* [[hashlib]]
* [[if / elif / else]]
* [[in / not in (membership)]]
* [[is / is not (identity)]]
* [[is checks identity; == checks value; small ints are interned]]
* [[isinstance() and type()]]
* [[itertools essentials]]
* [[lambda (anonymous function)]]
* [[logging]]
* [[map() and filter()]]
* [[match / case (structural pattern matching)]]
* [[multiprocessing]]
* [[os.environ]]
* [[paramiko enables SSH automation with connection lifecycle management]]
* [[pass]]
* [[pathlib basics]]
* [[pathlib replaces os.path for modern file operations]]
* [[pdb shipped with Python 1.0 in 1994]]
* [[python -i flag creates post-mortem debugging environment]]
* [[raise]]
* [[re (regular expressions)]]
* [[requests with retries and timeout handles flaky APIs safely]]
* [[return]]
* [[secrets (secure random)]]
* [[self]]
* [[shutil]]
* [[sorted() and .sort()]]
* [[str vs bytes]]
* [[strace reveals system-level bottlenecks by showing process syscalls]]
* [[subprocess basics]]
* [[subprocess runs shell commands safely with argument lists]]
* [[subprocess.run blocks; use asyncio.create_subprocess_exec for concurrency]]
* [[super()]]
* [[tempfile]]
* [[threading]]
* [[try / except]]
* [[try / except / else / finally]]
* [[while loop]]
* [[with (context manager)]]
* [[yield (generators)]]
* [[zip tricks]]
* [[zip()]]
!! MOC — confidence mid

Atoms with confidence in the ''mid'' band (11 total).

* [[Alpine musl libc breaks glibc wheels and DNS in Python containers]]
* [[Audit dependencies for security vulnerabilities and license compliance]]
* [[Code-first load testing is more accessible than UI-based tools]]
* [[Inspect sys.path and site-packages to understand module resolution]]
* [[Locust enables stateful user workflows with distributed execution]]
* [[Operational failures compound when you skip documentation and caution]]
* [[Print debugging remains the most common debugging technique]]
* [[Private PyPI solutions: devpi, CodeArtifact, or pip.conf]]
* [[Python's traceback format influenced error reporting across languages]]
* [[Signal handlers require event-loop registration in asyncio, main-thread setup in threading]]
* [[ipdb and pdb++ extend pdb with completion and visualization]]
!! MOC — merged atoms

Atoms that were consolidated from 2+ source concepts during cross-dedup (24 total). Reading these is a cheap way to see where the pipeline found duplication worth collapsing.

* [[Alpine musl libc breaks glibc wheels and DNS in Python containers]]
* [[Hardcoded credentials in code are readily compromised]]
* [[The Global Interpreter Lock constrains Python threading to I/O concurrency]]
* [[What are *args and **kwargs in Python functions?]]
* [[What are descriptors in Python?]]
* [[What does `functools.singledispatch` do?]]
* [[What does `functools.total_ordering` require you to define?]]
* [[What does `functools.wraps` do?]]
* [[What does `int.to_bytes()` do?]]
* [[What does `itertools.dropwhile(predicate, iterable)` do?]]
* [[What does `pytest.fixture` do?]]
* [[What does `sys.getsizeof()` return?]]
* [[What does `sys.platform` return on Linux, macOS, and Windows?]]
* [[What does if __name__ == "__main__": do?]]
* [[What does the `__future__` module do?]]
* [[What is `__slots__` and why use it?]]
* [[What is `itertools.product` with the `repeat` parameter?]]
* [[What is `pathlib.Path.glob()` used for?]]
* [[What is `sys.maxsize`?]]
* [[What is a Python generator?]]
* [[What is a decorator in Python?]]
* [[What is the Ansiballz framework?]]
* [[What is the difference between `re.search()` and `re.fullmatch()`?]]
* [[pdb shipped with Python 1.0 in 1994]]
!! Maps of Content

! By kind
* [[MOC: compendium q&a]]
* [[MOC: flashcards]]
* [[MOC: footguns]]
* [[MOC: other]]

! By confidence
* [[MOC: confidence high]]
* [[MOC: confidence mid]]

! Quality
* [[MOC: merged atoms]]
Python infra — atoms deck
canonical atomic concepts from python-infra and related sources
GettingStarted
[[MOC: index]]
[[GettingStarted]]
[[MOC: index]]
----
''By kind''
* [[MOC: footguns]]
* [[MOC: trivia]]
* [[MOC: flashcards]]
* [[MOC: compendium q&a]]
* [[MOC: primer]]
* [[MOC: anti-primer]]
* [[MOC: street ops]]
* [[MOC: cheatsheet]]
----
''By confidence''
* [[MOC: confidence high]]
* [[MOC: confidence mid]]
----
''Quality''
* [[MOC: merged atoms]]
!! Python infra — atoms deck

''1083 atoms'' — canonical atomic concepts from python-infra and related sources

//Each tiddler is one atomic concept. Sources and related atoms are listed in the footer. Cross-dedup has already merged duplicates, so every concept should appear exactly once.//

! Start here

* [[MOC: index]] — master index of MOCs
* [[MOC: merged atoms]] — concepts consolidated from multiple sources

! Breakdown — by kind

|!Kind|!Count|!Jump|h
|Compendium Q&A|779|[[MOC: compendium q&a]]|
|Flashcards|182|[[MOC: flashcards]]|
|Other|109|[[MOC: other]]|
|Footguns|13|[[MOC: footguns]]|

! Breakdown — by confidence

|!Band|!Count|!Jump|h
|high|1072|[[MOC: confidence high]]|
|mid|11|[[MOC: confidence mid]]|

! Pipeline provenance

* Raw extracted atoms (whole corpus): 17641
* After intra-source dedup (whole corpus): 7753
* In this deck (domain = python, post cross-dedup): 1083
* Atoms in this deck merged from multiple sources: 24

See ''FULL-CORPUS-REPORT.md'' in the grokzett repo for full metrics.
/* grokzett TWC deck theme overrides */
body, #contentWrapper { font-family: -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; }
.tiddler { margin-bottom: 1.5em; }
.tiddler .title { font-size: 1.4em; letter-spacing: -0.01em; }
.viewer { line-height: 1.55; }
.viewer h1, .viewer h2, .viewer h3 { border-bottom: none; margin-top: 1.2em; }
.viewer h1 { font-size: 1.35em; }
.viewer h2 { font-size: 1.20em; }
.viewer h3 { font-size: 1.05em; color: #444; }
.viewer blockquote { border-left: 3px solid #c9d6df; margin: 1em 0; padding: 0.2em 1em; background: #f6f9fb; color: #333; }
.viewer code { background: #f2f2f2; padding: 1px 5px; border-radius: 3px; font-size: 0.92em; }
.viewer pre { background: #282c34; color: #abb2bf; padding: 0.8em 1em; border-radius: 6px; overflow-x: auto; font-size: 0.88em; line-height: 1.4; }
.viewer pre code { background: transparent; padding: 0; color: inherit; border-radius: 0; }
.viewer pre.literal { background: #282c34; color: #abb2bf; }
.viewer table { border-collapse: collapse; margin: 1em 0; font-size: 0.92em; width: auto; }
.viewer th, .viewer td { border: 1px solid #d8dee4; padding: 6px 10px; }
.viewer th { background: #eef2f6; text-align: left; }
.viewer tr:nth-child(even) td { background: #fbfcfd; }
.viewer hr { border: none; border-top: 1px solid #dde3e9; margin: 1.5em 0; }
.tagged { background: #eef5fb; padding: 4px 8px; border-radius: 4px; margin-right: 4px; }

/* grokzett status controls (injected by features.js per tiddler) */
.grokzett-status {
  font-size: 0.85em; margin: 0.3em 0 1em; color: #555;
  display: flex; align-items: center; gap: 6px;
}
.grokzett-status .gz-label { color: #888; letter-spacing: 0.02em; }
.grokzett-status button {
  border: 1px solid #c9d6df; background: #f7f9fb; padding: 2px 10px;
  font-size: 0.92em; cursor: pointer; border-radius: 12px; color: #333;
}
.grokzett-status button:hover { background: #e6edf3; }
.grokzett-status button.active { background: #2b6cb0; color: white; border-color: #2b6cb0; }

/* Fixed filter bar (top-right) */
.grokzett-filter-bar {
  position: fixed; top: 10px; right: 10px; z-index: 10000;
  background: #2d3748; color: #e2e8f0;
  padding: 8px 14px; border-radius: 8px;
  font-size: 0.85em; font-family: -apple-system, "Segoe UI", Roboto, sans-serif;
  display: flex; align-items: center; gap: 12px;
  box-shadow: 0 3px 12px rgba(0,0,0,0.25);
}
.grokzett-filter-bar .gz-title { font-weight: 600; letter-spacing: 0.02em; }
.grokzett-filter-bar select, .grokzett-filter-bar button {
  background: #4a5568; color: #e2e8f0; border: 1px solid #718096;
  border-radius: 4px; padding: 2px 8px; font: inherit;
}
.grokzett-filter-bar button { cursor: pointer; }
.grokzett-filter-bar button:hover { background: #5a6678; }
.grokzett-filter-bar label { display: flex; align-items: center; gap: 4px; }
.grokzett-filter-bar #gz-counts { opacity: 0.75; font-size: 0.95em; }

/* Subtle status badge on each tiddler (color bar at left) */
.tiddler[data-gz-status="learning"] { border-left: 3px solid #ed8936; padding-left: 8px; }
.tiddler[data-gz-status="known"] { border-left: 3px solid #48bb78; padding-left: 8px; opacity: 0.7; }

/* Cloze spans — trivia mode */
.gz-cloze {
  background: #f6e05e; color: #f6e05e; border-radius: 3px; padding: 0 4px;
  cursor: pointer; user-select: none; transition: color 0.15s;
}
.gz-cloze.revealed { color: #533f03; background: #fef6ad; }

/* Flashcard Q/A layout */
.gz-flash-a {
  margin-top: 1em; padding: 0.8em 1em; background: #f7fafc;
  border-radius: 6px; border: 1px solid #e2e8f0; position: relative;
}
.gz-flash-a.hidden > * { filter: blur(5px); user-select: none; }
.gz-flash-a.hidden { cursor: pointer; }
.gz-flash-a.hidden::after {
  content: "click to reveal answer";
  position: absolute; left: 0; right: 0; top: 50%; transform: translateY(-50%);
  text-align: center; color: #718096; font-size: 0.9em; letter-spacing: 0.05em;
  pointer-events: none;
}
.gz-flash-a:not(.hidden) { border-left: 4px solid #48bb78; }