[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-1460":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":20,"compositeScore":21,"rankGlobal":10,"rankLanguage":10,"license":22,"archived":23,"fork":23,"defaultBranch":24,"hasWiki":25,"hasPages":23,"topics":26,"createdAt":10,"pushedAt":10,"updatedAt":36,"readmeContent":37,"aiSummary":38,"trendingCount":16,"starSnapshotCount":16,"syncStatus":39,"lastSyncTime":40,"discoverSource":41},1460,"wtfpython","satwikkansal\u002Fwtfpython","satwikkansal","What the f*ck Python? 😱","",null,"Python",36981,2668,703,67,0,3,19,56,13,81.1,"Do What The F*ck You Want To Public License",false,"master",true,[27,28,29,30,31,32,33,34,35],"documentation","gotchas","interview-questions","pitfalls","python","python-interview-questions","snippets","wats","wtf","2026-06-11 04:00:47","\u003C!-- markdownlint-disable MD013 -->\n\u003Cp align=\"center\">\n    \u003Cpicture>\n      \u003Csource media=\"(prefers-color-scheme: dark)\" srcset=\"\u002Fimages\u002Flogo_dark_theme.svg\">\n      \u003Csource media=\"(prefers-color-scheme: light)\" srcset=\"\u002Fimages\u002Flogo.svg\">\n      \u003Cimg alt=\"Shows a wtfpython logo.\" src=\"\u002Fimages\u002Flogo.svg\">\n    \u003C\u002Fpicture>\n\u003C\u002Fp>\n\u003Ch1 align=\"center\">What the f*ck Python! 😱\u003C\u002Fh1>\n\u003Cp align=\"center\">Exploring and understanding Python through surprising snippets.\u003C\u002Fp>\n\nTranslations: [Chinese 中文](https:\u002F\u002Fgithub.com\u002Fleisurelicht\u002Fwtfpython-cn) |\n[Vietnamese Tiếng Việt](https:\u002F\u002Fgithub.com\u002Fvuduclyunitn\u002Fwtfptyhon-vi) |\n[Spanish Español](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20220511161045\u002Fhttps:\u002F\u002Fgithub.com\u002FJoseDeFreitas\u002Fwtfpython-es) |\n[Korean 한국어](https:\u002F\u002Fgithub.com\u002Fbuttercrab\u002Fwtfpython-ko) |\n[Russian Русский](https:\u002F\u002Fgithub.com\u002Fsatwikkansal\u002Fwtfpython\u002Ftree\u002Fmaster\u002Ftranslations\u002Fru-russian) |\n[German Deutsch](https:\u002F\u002Fgithub.com\u002FBenSt099\u002Fwtfpython) |\n[Persian فارسی](https:\u002F\u002Fgithub.com\u002Fsatwikkansal\u002Fwtfpython\u002Ftree\u002Fmaster\u002Ftranslations\u002Ffa-farsi) |\n[Add translation](https:\u002F\u002Fgithub.com\u002Fsatwikkansal\u002Fwtfpython\u002Fissues\u002Fnew?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].)\n\nOther modes: [Interactive Website](https:\u002F\u002Fwtfpython-interactive.vercel.app) | [Interactive Notebook](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002Fsatwikkansal\u002Fwtfpython\u002Fblob\u002Fmaster\u002Firrelevant\u002Fwtf.ipynb)\n\nPython, being a beautifully designed high-level and interpreter-based programming language,\nprovides us with many features for the programmer's comfort.\nBut sometimes, the outcomes of a Python snippet may not seem obvious at first sight.\n\nHere's a fun project attempting to explain what exactly is happening under the hood for some counter-intuitive snippets\nand lesser-known features in Python.\n\nWhile some of the examples you see below may not be WTFs in the truest sense,\nbut they'll reveal some of the interesting parts of Python that you might be unaware of.\nI find it a nice way to learn the internals of a programming language, and I believe that you'll find it interesting too!\n\nIf you're an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt\nYou may have already experienced some of them before, and I might be able to revive sweet old memories of yours! :sweat_smile:\n\nPS: If you're a returning reader, you can learn about the new modifications [here](https:\u002F\u002Fgithub.com\u002Fsatwikkansal\u002Fwtfpython\u002Freleases\u002F)\n(the examples marked with asterisk are the ones added in the latest major revision).\n\nSo, here we go...\n\n# Table of Contents\n\n\u003C!-- Generated using \"markdown-toc -i README.md --maxdepth 3\"-->\n\n\u003C!-- toc -->\n\n- [Structure of the Examples](#structure-of-the-examples)\n  - [▶ Some fancy Title](#-some-fancy-title)\n- [Usage](#usage)\n- [👀 Examples](#-examples)\n  - [Section: Strain your brain!](#section-strain-your-brain)\n    - [▶ First things first! \\*](#-first-things-first-)\n    - [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes)\n    - [▶ Be careful with chained operations](#-be-careful-with-chained-operations)\n    - [▶ How not to use `is` operator](#-how-not-to-use-is-operator)\n    - [▶ Hash brownies](#-hash-brownies)\n    - [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same)\n    - [▶ Disorder within order \\*](#-disorder-within-order-)\n    - [▶ Keep trying... \\*](#-keep-trying-)\n    - [▶ For what?](#-for-what)\n    - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy)\n    - [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-)\n    - [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt)\n    - [▶ Schrödinger's variable](#-schrödingers-variable-)\n    - [▶ The chicken-egg problem \\*](#-the-chicken-egg-problem-)\n    - [▶ Subclass relationships](#-subclass-relationships)\n    - [▶ Methods equality and identity](#-methods-equality-and-identity)\n    - [▶ All-true-ation \\*](#-all-true-ation-)\n    - [▶ The surprising comma](#-the-surprising-comma)\n    - [▶ Strings and the backslashes](#-strings-and-the-backslashes)\n    - [▶ not knot!](#-not-knot)\n    - [▶ Half triple-quoted strings](#-half-triple-quoted-strings)\n    - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans)\n    - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes)\n    - [▶ yielding None](#-yielding-none)\n    - [▶ Yielding from... return! \\*](#-yielding-from-return-)\n    - [▶ Nan-reflexivity \\*](#-nan-reflexivity-)\n    - [▶ Mutating the immutable!](#-mutating-the-immutable)\n    - [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope)\n    - [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion)\n    - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this)\n    - [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion)\n  - [Section: Slippery Slopes](#section-slippery-slopes)\n    - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it)\n    - [▶ Stubborn `del` operation](#-stubborn-del-operation)\n    - [▶ The out of scope variable](#-the-out-of-scope-variable)\n    - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating)\n    - [▶ Lossy zip of iterators \\*](#-lossy-zip-of-iterators-)\n    - [▶ Loop variables leaking out!](#-loop-variables-leaking-out)\n    - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments)\n    - [▶ Catching the Exceptions](#-catching-the-exceptions)\n    - [▶ Same operands, different story!](#-same-operands-different-story)\n    - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope)\n    - [▶ Rounding like a banker \\*](#-rounding-like-a-banker-)\n    - [▶ Needles in a Haystack \\*](#-needles-in-a-haystack-)\n    - [▶ Splitsies \\*](#-splitsies-)\n    - [▶ Wild imports \\*](#-wild-imports-)\n    - [▶ All sorted? \\*](#-all-sorted-)\n    - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist)\n  - [Section: The Hidden treasures!](#section-the-hidden-treasures)\n    - [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly)\n    - [▶ `goto`, but why?](#-goto-but-why)\n    - [▶ Brace yourself!](#-brace-yourself)\n    - [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life)\n    - [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated)\n    - [▶ Yes, it exists!](#-yes-it-exists)\n    - [▶ Ellipsis \\*](#-ellipsis-)\n    - [▶ Inpinity](#-inpinity)\n    - [▶ Let's mangle](#-lets-mangle)\n  - [Section: Appearances are deceptive!](#section-appearances-are-deceptive)\n    - [▶ Skipping lines?](#-skipping-lines)\n    - [▶ Teleportation](#-teleportation)\n    - [▶ Well, something is fishy...](#-well-something-is-fishy)\n  - [Section: Miscellaneous](#section-miscellaneous)\n    - [▶ `+=` is faster](#--is-faster)\n    - [▶ Let's make a giant string!](#-lets-make-a-giant-string)\n    - [▶ Slowing down `dict` lookups \\*](#-slowing-down-dict-lookups-)\n    - [▶ Bloating instance `dict`s \\*](#-bloating-instance-dicts-)\n    - [▶ Minor Ones \\*](#-minor-ones-)\n- [Contributing](#contributing)\n- [Acknowledgements](#acknowledgements)\n- [🎓 License](#-license)\n  - [Surprise your friends as well!](#surprise-your-friends-as-well)\n  - [More content like this?](#more-content-like-this)\n\n\u003C!-- tocstop -->\n\n# Structure of the Examples\n\nAll the examples are structured like below:\n\n> ## Section: (if necessary)\n>\n> ### ▶ Some fancy Title\n>\n> ```py\n> # Set up the code.\n> # Preparation for the magic...\n> ```\n>\n> **Output (Python version(s)):**\n>\n> ```py\n> >>> triggering_statement\n> Some unexpected output\n> ```\n>\n> (Optional): One line describing the unexpected output.\n>\n> #### 💡 Explanation:\n>\n> - Brief explanation of what's happening and why is it happening.\n>\n> ```py\n> # Set up code\n> # More examples for further clarification (if necessary)\n> ```\n>\n> **Output (Python version(s)):**\n>\n> ```py\n> >>> trigger # some example that makes it easy to unveil the magic\n> # some justified output\n> ```\n\n**Note:** All the examples are tested on Python 3.5.2 interactive interpreter,\nand they should work for all the Python versions unless explicitly specified before the output.\n\n# Usage\n\nA nice way to get the most out of these examples, in my opinion, is to read them in sequential order, and for every example:\n\n- Carefully read the initial code for setting up the example.\n  If you're an experienced Python programmer, you'll successfully anticipate what's going to happen next most of the time.\n- Read the output snippets and,\n  - Check if the outputs are the same as you'd expect.\n  - Make sure if you know the exact reason behind the output being the way it is.\n    - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation\n  (and if you still don't understand, shout out! and create an issue [here](https:\u002F\u002Fgithub.com\u002Fsatwikkansal\u002Fwtfpython\u002Fissues\u002Fnew)).\n    - If yes, give a gentle pat on your back, and you may skip to the next example.\n\n---\n\n# 👀 Examples\n\n## Section: Strain your brain!\n\n### ▶ First things first! \\*\n\n\u003C!-- Example ID: d3d73936-3cf1-4632-b5ab-817981338863 -->\n\nFor some reason, the Python 3.8's \"Walrus\" operator (`:=`) has become quite popular. Let's check it out,\n\n1\\.\n\n```py\n# Python version 3.8+\n\n>>> a = \"wtf_walrus\"\n>>> a\n'wtf_walrus'\n\n>>> a := \"wtf_walrus\"\nFile \"\u003Cstdin>\", line 1\n    a := \"wtf_walrus\"\n      ^\nSyntaxError: invalid syntax\n\n>>> (a := \"wtf_walrus\") # This works though\n'wtf_walrus'\n>>> a\n'wtf_walrus'\n```\n\n2 \\.\n\n```py\n# Python version 3.8+\n\n>>> a = 6, 9\n>>> a\n(6, 9)\n\n>>> (a := 6, 9)\n(6, 9)\n>>> a\n6\n\n>>> a, b = 6, 9 # Typical unpacking\n>>> a, b\n(6, 9)\n>>> (a, b = 16, 19) # Oops\n  File \"\u003Cstdin>\", line 1\n    (a, b = 16, 19)\n          ^\nSyntaxError: invalid syntax\n\n>>> (a, b := 16, 19) # This prints out a weird 3-tuple\n(6, 16, 19)\n\n>>> a # a is still unchanged?\n6\n\n>>> b\n16\n```\n\n#### 💡 Explanation\n\nThe Walrus operator (`:=`) was introduced in Python 3.8,\nit can be useful in situations where you'd want to assign values to variables within an expression.\n\n```py\ndef some_func():\n        # Assume some expensive computation here\n        # time.sleep(1000)\n        return 5\n\n# So instead of,\nif some_func():\n        print(some_func()) # Which is bad practice since computation is happening twice\n\n# or\na = some_func()\nif a:\n    print(a)\n\n# Now you can concisely write\nif a := some_func():\n        print(a)\n```\n\n**Output (> 3.8):**\n\n```py\n5\n5\n5\n```\n\nThis saved one line of code, and implicitly prevented invoking `some_func` twice.\n\n- Unparenthesized \"assignment expression\" (use of walrus operator), is restricted at the top level,\n  hence the `SyntaxError` in the `a := \"wtf_walrus\"` statement of the first snippet.\n  Parenthesizing it worked as expected and assigned `a`.\n- As usual, parenthesizing of an expression containing `=` operator is not allowed.\n  Hence the syntax error in `(a, b = 6, 9)`.\n- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier,\n  and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means,\n  - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9)` (where `a`'s value is 6')\n\n    ```py\n    >>> (a := 6, 9) == ((a := 6), 9)\n    True\n    >>> x = (a := 696, 9)\n    >>> x\n    (696, 9)\n    >>> x[0] is a # Both reference same memory location\n    True\n    ```\n\n  - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple.\n\n---\n\n### ▶ Strings can be tricky sometimes\n\n\u003C!-- Example ID: 30f1d3fc-e267-4b30-84ef-4d9e7091ac1a --->\n\n1\\. Notice that both the ids are same.\n\n```python:snippets\u002F2_tricky_strings.py -s 2 -e 3\nassert id(\"some_string\") == id(\"some\" + \"_\" + \"string\")\nassert id(\"some_string\") == id(\"some_string\")\n```\n\n2\\. `True` because it is invoked in script. Might be `False` in `python shell` or `ipython`\n\n```python:snippets\u002F2_tricky_strings.py -s 6 -e 12\na = \"wtf\"\nb = \"wtf\"\nassert a is b\n\na = \"wtf!\"\nb = \"wtf!\"\nassert a is b\n```\n\n3\\. `True` because it is invoked in script. Might be `False` in `python shell` or `ipython`\n\n```python:snippets\u002F2_tricky_strings.py -s 15 -e 19\na, b = \"wtf!\", \"wtf!\"\nassert a is b\n\na = \"wtf!\"; b = \"wtf!\"\nassert a is b\n```\n\n4\\. **Disclaimer - snippet is not relevant in modern Python versions**\n\n**Output (\u003C Python3.7 )**\n\n```py\n>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'\nTrue\n>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'\nFalse\n```\n\nMakes sense, right?\n\n#### 💡 Explanation:\n\n- The behavior in first and second snippets is due to a CPython optimization (called string interning)\n  that tries to use existing immutable objects in some cases rather than creating a new object every time.\n- After being \"interned,\" many variables may reference the same string object in memory (saving memory thereby).\n- In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is\n  implementation-dependent. There are some rules that can be used to guess if a string will be interned or not:\n  - All length 0 and length 1 strings are interned.\n  - Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned)\n  - Strings that are not composed of ASCII letters, digits or underscores, are not interned.\n  This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https:\u002F\u002Fgithub.com\u002Fpython\u002Fcpython\u002Fblob\u002F3.6\u002FObjects\u002Fcodeobject.c#L19)\n\n\u003Cp align=\"center\">\n    \u003Cpicture>\n      \u003Csource media=\"(prefers-color-scheme: dark)\" srcset=\"\u002Fimages\u002Fstring-intern\u002Fstring_interning_dark_theme.svg\">\n      \u003Csource media=\"(prefers-color-scheme: light)\" srcset=\"\u002Fimages\u002Fstring-intern\u002Fstring_interning.svg\">\n      \u003Cimg alt=\"Shows a string interning process.\" src=\"\u002Fimages\u002Fstring-intern\u002Fstring_interning.svg\">\n    \u003C\u002Fpicture>\n\u003C\u002Fp>\n\n- When `a` and `b` are set to `\"wtf!\"` in the same line, the Python interpreter creates a new object,\n  then references the second variable at the same time. If you do it on separate lines, it doesn't \"know\" that\n  there's already `\"wtf!\"` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above).\n  It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython\n  (check this [issue](https:\u002F\u002Fgithub.com\u002Fsatwikkansal\u002Fwtfpython\u002Fissues\u002F100) for more discussion).\n- A compile unit in an interactive environment like IPython consists of a single statement,\n  whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement,\n  whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line.\n  This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`,\n  and also explain why they are same when invoked in `some_file.py`\n- The abrupt change in the output of the fourth snippet is due to a\n  [peephole optimization](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FPeephole_optimization) technique known as Constant folding.\n  This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save\n  a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 21.\n  (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`).\n  [Here's](https:\u002F\u002Fgithub.com\u002Fpython\u002Fcpython\u002Fblob\u002F3.6\u002FPython\u002Fpeephole.c#L288) the implementation source for the same.\n- Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer\n  with some change in logic as well, so the fourth snippet doesn't work for Python 3.7.\n  You can read more about the change [here](https:\u002F\u002Fbugs.python.org\u002Fissue11549).\n\n---\n\n### ▶ Be careful with chained operations\n\n\u003C!-- Example ID: 07974979-9c86-4720-80bd-467aa19470d9 --->\n\n```py\n>>> (False == False) in [False] # makes sense\nFalse\n>>> False == (False in [False]) # makes sense\nFalse\n>>> False == False in [False] # now what?\nTrue\n\n>>> True is False == False\nFalse\n>>> False is False is False\nTrue\n\n>>> 1 > 0 \u003C 1\nTrue\n>>> (1 > 0) \u003C 1\nFalse\n>>> 1 > (0 \u003C 1)\nFalse\n```\n\n#### 💡 Explanation:\n\nAs per https:\u002F\u002Fdocs.python.org\u002F3\u002Freference\u002Fexpressions.html#comparisons\n\n> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators,\n  then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z,\n  except that each expression is evaluated at most once.\n\nWhile such behavior might seem silly to you in the above examples,\nit's fantastic with stuff like `a == b == c` and `0 \u003C= x \u003C= 100`.\n\n- `False is False is False` is equivalent to `(False is False) and (False is False)`\n- `True is False == False` is equivalent to `(True is False) and (False == False)`\n  and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n- `1 > 0 \u003C 1` is equivalent to `(1 > 0) and (0 \u003C 1)` which evaluates to `True`.\n- The expression `(1 > 0) \u003C 1` is equivalent to `True \u003C 1` and\n\n  ```py\n  >>> int(True)\n  1\n  >>> True + 1 # not relevant for this example, but just for fun\n  2\n  ```\n\n  So, `1 \u003C 1` evaluates to `False`\n\n---\n\n### ▶ How not to use `is` operator\n\n\u003C!-- Example ID: 230fa2ac-ab36-4ad1-b675-5f5a1c1a6217 --->\n\nThe following is a very famous example present all over the internet.\n\n1\\.\n\n```py\n>>> a = 256\n>>> b = 256\n>>> a is b\nTrue\n\n>>> a = 257\n>>> b = 257\n>>> a is b\nFalse\n```\n\n2\\.\n\n```py\n>>> a = []\n>>> b = []\n>>> a is b\nFalse\n\n>>> a = tuple()\n>>> b = tuple()\n>>> a is b\nTrue\n```\n\n3\\.\n**Output**\n\n```py\n>>> a, b = 257, 257\n>>> a is b\nTrue\n```\n\n**Output (Python 3.7.x specifically)**\n\n```py\n>>> a, b = 257, 257\n>>> a is b\nFalse\n```\n\n#### 💡 Explanation:\n\n**The difference between `is` and `==`**\n\n- `is` operator checks if both the operands refer to the same object (i.e., it checks if the identity of the operands matches or not).\n- `==` operator compares the values of both the operands and checks if they are the same.\n- So `is` is for reference equality and `==` is for value equality. An example to clear things up,\n\n  ```py\n  >>> class A: pass\n  >>> A() is A() # These are two empty objects at two different memory locations.\n  False\n  ```\n\n**`256` is an existing object but `257` isn't**\n\nWhen you start up python the numbers from `-5` to `256` will be allocated. These numbers are used a lot, so it makes sense just to have them ready.\n\nQuoting from https:\u002F\u002Fdocs.python.org\u002F3\u002Fc-api\u002Flong.html\n\n> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behavior of Python, in this case, is undefined. :-)\n\n```py\n>>> id(256)\n10922528\n>>> a = 256\n>>> b = 256\n>>> id(a)\n10922528\n>>> id(b)\n10922528\n>>> id(257)\n140084850247312\n>>> x = 257\n>>> y = 257\n>>> id(x)\n140084850247440\n>>> id(y)\n140084850247344\n```\n\nHere the interpreter isn't smart enough while executing `y = 257` to recognize that we've already created an integer of the value `257,` and so it goes on to create another object in the memory.\n\nSimilar optimization applies to other **immutable** objects like empty tuples as well. Since lists are mutable, that's why `[] is []` will return `False` and `() is ()` will return `True`. This explains our second snippet. Let's move on to the third one,\n\n**Both `a` and `b` refer to the same object when initialized with same value in the same line.**\n\n**Output**\n\n```py\n>>> a, b = 257, 257\n>>> id(a)\n140640774013296\n>>> id(b)\n140640774013296\n>>> a = 257\n>>> b = 257\n>>> id(a)\n140640774013392\n>>> id(b)\n140640774013488\n```\n\n- When a and b are set to `257` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't \"know\" that there's already `257` as an object.\n\n- It's a compiler optimization and specifically applies to the interactive environment. When you enter two lines in a live interpreter, they're compiled separately, therefore optimized separately. If you were to try this example in a `.py` file, you would not see the same behavior, because the file is compiled all at once. This optimization is not limited to integers, it works for other immutable data types like strings (check the \"Strings are tricky example\") and floats as well,\n\n  ```py\n  >>> a, b = 257.0, 257.0\n  >>> a is b\n  True\n  ```\n\n- Why didn't this work for Python 3.7? The abstract reason is because such compiler optimizations are implementation specific (i.e. may change with version, OS, etc). I'm still figuring out what exact implementation change cause the issue, you can check out this [issue](https:\u002F\u002Fgithub.com\u002Fsatwikkansal\u002Fwtfpython\u002Fissues\u002F100) for updates.\n\n---\n\n### ▶ Hash brownies\n\n\u003C!-- Example ID: eb17db53-49fd-4b61-85d6-345c5ca213ff --->\n\n1\\.\n\n```py\nsome_dict = {}\nsome_dict[5.5] = \"JavaScript\"\nsome_dict[5.0] = \"Ruby\"\nsome_dict[5] = \"Python\"\n```\n\n**Output:**\n\n```py\n>>> some_dict[5.5]\n\"JavaScript\"\n>>> some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n\"Python\"\n>>> some_dict[5]\n\"Python\"\n\n>>> complex_five = 5 + 0j\n>>> type(complex_five)\ncomplex\n>>> some_dict[complex_five]\n\"Python\"\n```\n\nSo, why is Python all over the place?\n\n#### 💡 Explanation\n\n- Uniqueness of keys in a Python dictionary is by _equivalence_, not identity. So even though `5`, `5.0`, and `5 + 0j` are distinct objects of different types, since they're equal, they can't both be in the same `dict` (or `set`). As soon as you insert any one of them, attempting to look up any distinct but equivalent key will succeed with the original mapped value (rather than failing with a `KeyError`):\n\n  ```py\n  >>> 5 == 5.0 == 5 + 0j\n  True\n  >>> 5 is not 5.0 is not 5 + 0j\n  True\n  >>> some_dict = {}\n  >>> some_dict[5.0] = \"Ruby\"\n  >>> 5.0 in some_dict\n  True\n  >>> (5 in some_dict) and (5 + 0j in some_dict)\n  True\n  ```\n\n- This applies when setting an item as well. So when you do `some_dict[5] = \"Python\"`, Python finds the existing item with equivalent key `5.0 -> \"Ruby\"`, overwrites its value in place, and leaves the original key alone.\n\n  ```py\n  >>> some_dict\n  {5.0: 'Ruby'}\n  >>> some_dict[5] = \"Python\"\n  >>> some_dict\n  {5.0: 'Python'}\n  ```\n\n- So how can we update the key to `5` (instead of `5.0`)? We can't actually do this update in place, but what we can do is first delete the key (`del some_dict[5.0]`), and then set it (`some_dict[5]`) to get the integer `5` as the key instead of floating `5.0`, though this should be needed in rare cases.\n\n- How did Python find `5` in a dictionary containing `5.0`? Python does this in constant time without having to scan through every item by using hash functions. When Python looks up a key `foo` in a dict, it first computes `hash(foo)` (which runs in constant-time). Since in Python it is required that objects that compare equal also have the same hash value ([docs](https:\u002F\u002Fdocs.python.org\u002F3\u002Freference\u002Fdatamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value.\n\n  ```py\n  >>> 5 == 5.0 == 5 + 0j\n  True\n  >>> hash(5) == hash(5.0) == hash(5 + 0j)\n  True\n  ```\n\n  **Note:** The inverse is not necessarily true: Objects with equal hash values may themselves be unequal. (This causes what's known as a [hash collision](\u003Chttps:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FCollision_(computer_science)>), and degrades the constant-time performance that hashing usually provides.)\n\n---\n\n### ▶ Deep down, we're all the same.\n\n\u003C!-- Example ID: 8f99a35f-1736-43e2-920d-3b78ec35da9b --->\n\n```py\nclass WTF:\n  pass\n```\n\n**Output:**\n\n```py\n>>> WTF() == WTF() # two different instances can't be equal\nFalse\n>>> WTF() is WTF() # identities are also different\nFalse\n>>> hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\nTrue\n>>> id(WTF()) == id(WTF())\nTrue\n```\n\n#### 💡 Explanation:\n\n- When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed.\n- When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same.\n- So, the object's id is unique only for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id.\n- But why did the `is` operator evaluate to `False`? Let's see with this snippet.\n\n  ```py\n  class WTF(object):\n    def __init__(self): print(\"I\")\n    def __del__(self): print(\"D\")\n  ```\n\n  **Output:**\n\n  ```py\n  >>> WTF() is WTF()\n  I\n  I\n  D\n  D\n  False\n  >>> id(WTF()) == id(WTF())\n  I\n  D\n  I\n  D\n  True\n  ```\n\n  As you may observe, the order in which the objects are destroyed is what made all the difference here.\n\n---\n\n### ▶ Disorder within order \\*\n\n\u003C!-- Example ID: 91bff1f8-541d-455a-9de4-6cd8ff00ea66 --->\n\n```py\nfrom collections import OrderedDict\n\ndictionary = dict()\ndictionary[1] = 'a'; dictionary[2] = 'b';\n\nordered_dict = OrderedDict()\nordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n\nanother_ordered_dict = OrderedDict()\nanother_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n\nclass DictWithHash(dict):\n    \"\"\"\n    A dict that also implements __hash__ magic.\n    \"\"\"\n    __hash__ = lambda self: 0\n\nclass OrderedDictWithHash(OrderedDict):\n    \"\"\"\n    An OrderedDict that also implements __hash__ magic.\n    \"\"\"\n    __hash__ = lambda self: 0\n```\n\n**Output**\n\n```py\n>>> dictionary == ordered_dict # If a == b\nTrue\n>>> dictionary == another_ordered_dict # and b == c\nTrue\n>>> ordered_dict == another_ordered_dict # then why isn't c == a ??\nFalse\n\n# We all know that a set consists of only unique elements,\n# let's try making a set of these dictionaries and see what happens...\n\n>>> len({dictionary, ordered_dict, another_ordered_dict})\nTraceback (most recent call last):\n  File \"\u003Cstdin>\", line 1, in \u003Cmodule>\nTypeError: unhashable type: 'dict'\n\n# Makes sense since dict don't have __hash__ implemented, let's use\n# our wrapper classes.\n>>> dictionary = DictWithHash()\n>>> dictionary[1] = 'a'; dictionary[2] = 'b';\n>>> ordered_dict = OrderedDictWithHash()\n>>> ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n>>> another_ordered_dict = OrderedDictWithHash()\n>>> another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n>>> len({dictionary, ordered_dict, another_ordered_dict})\n1\n>>> len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n2\n```\n\nWhat is going on here?\n\n#### 💡 Explanation:\n\n- The reason why intransitive equality didn't hold among `dictionary`, `ordered_dict` and `another_ordered_dict` is because of the way `__eq__` method is implemented in `OrderedDict` class. From the [docs](https:\u002F\u002Fdocs.python.org\u002F3\u002Flibrary\u002Fcollections.html#ordereddict-objects)\n\n  > Equality tests between OrderedDict objects are order-sensitive and are implemented as `list(od1.items())==list(od2.items())`. Equality tests between `OrderedDict` objects and other Mapping objects are order-insensitive like regular dictionaries.\n\n- The reason for this equality in behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used.\n- Okay, so why did changing the order affect the length of the generated `set` object? The answer is the lack of intransitive equality only. Since sets are \"unordered\" collections of unique elements, the order in which elements are inserted shouldn't matter. But in this case, it does matter. Let's break it down a bit,\n\n  ```py\n  >>> some_set = set()\n  >>> some_set.add(dictionary) # these are the mapping objects from the snippets above\n  >>> ordered_dict in some_set\n  True\n  >>> some_set.add(ordered_dict)\n  >>> len(some_set)\n  1\n  >>> another_ordered_dict in some_set\n  True\n  >>> some_set.add(another_ordered_dict)\n  >>> len(some_set)\n  1\n\n  >>> another_set = set()\n  >>> another_set.add(ordered_dict)\n  >>> another_ordered_dict in another_set\n  False\n  >>> another_set.add(another_ordered_dict)\n  >>> len(another_set)\n  2\n  >>> dictionary in another_set\n  True\n  >>> another_set.add(another_ordered_dict)\n  >>> len(another_set)\n  2\n  ```\n\n  So the inconsistency is due to `another_ordered_dict in another_set` being `False` because `ordered_dict` was already present in `another_set` and as observed before, `ordered_dict == another_ordered_dict` is `False`.\n\n---\n\n### ▶ Keep trying... \\*\n\n\u003C!-- Example ID: b4349443-e89f-4d25-a109-82616be9d41a --->\n\n```py\ndef some_func():\n    try:\n        return 'from_try'\n    finally:\n        return 'from_finally'\n\ndef another_func():\n    for _ in range(3):\n        try:\n            continue\n        finally:\n            print(\"Finally!\")\n\ndef one_more_func(): # A gotcha!\n    try:\n        for i in range(3):\n            try:\n                1 \u002F i\n            except ZeroDivisionError:\n                # Let's throw it here and handle it outside for loop\n                raise ZeroDivisionError(\"A trivial divide by zero error\")\n            finally:\n                print(\"Iteration\", i)\n                break\n    except ZeroDivisionError as e:\n        print(\"Zero division error occurred\", e)\n```\n\n**Output:**\n\n```py\n>>> some_func()\n'from_finally'\n\n>>> another_func()\nFinally!\nFinally!\nFinally!\n\n>>> 1 \u002F 0\nTraceback (most recent call last):\n  File \"\u003Cstdin>\", line 1, in \u003Cmodule>\nZeroDivisionError: division by zero\n\n>>> one_more_func()\nIteration 0\n\n```\n\n#### 💡 Explanation:\n\n- When a `return`, `break` or `continue` statement is executed in the `try` suite of a \"try…finally\" statement, the `finally` clause is also executed on the way out.\n- The return value of a function is determined by the last `return` statement executed. Since the `finally` clause always executes, a `return` statement executed in the `finally` clause will always be the last one executed.\n- The caveat here is, if the finally clause executes a `return` or `break` statement, the temporarily saved exception is discarded.\n\n---\n\n### ▶ For what?\n\n\u003C!-- Example ID: 64a9dccf-5083-4bc9-98aa-8aeecde4f210 --->\n\n```py\nsome_string = \"wtf\"\nsome_dict = {}\nfor i, some_dict[i] in enumerate(some_string):\n    i = 10\n```\n\n**Output:**\n\n```py\n>>> some_dict # An indexed dict appears.\n{0: 'w', 1: 't', 2: 'f'}\n```\n\n#### 💡 Explanation:\n\n- A `for` statement is defined in the [Python grammar](https:\u002F\u002Fdocs.python.org\u002F3\u002Freference\u002Fgrammar.html) as:\n\n  ```\n  for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\n  ```\n\n  Where `exprlist` is the assignment target. This means that the equivalent of `{exprlist} = {next_value}` is **executed for each item** in the iterable.\n  An interesting example that illustrates this:\n\n  ```py\n  for i in range(4):\n      print(i)\n      i = 10\n  ```\n\n  **Output:**\n\n  ```\n  0\n  1\n  2\n  3\n  ```\n\n  Did you expect the loop to run just once?\n\n  **💡 Explanation:**\n\n  - The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(4)` in this case) is unpacked and assigned the target list variables (`i` in this case).\n\n- The `enumerate(some_string)` function yields a new value `i` (a counter going up) and a character from the `some_string` in each iteration. It then sets the (just assigned) `i` key of the dictionary `some_dict` to that character. The unrolling of the loop can be simplified as:\n\n  ```py\n  >>> i, some_dict[i] = (0, 'w')\n  >>> i, some_dict[i] = (1, 't')\n  >>> i, some_dict[i] = (2, 'f')\n  >>> some_dict\n  ```\n\n---\n\n### ▶ Evaluation time discrepancy\n\n\u003C!-- Example ID: 6aa11a4b-4cf1-467a-b43a-810731517e98 --->\n\n1\\.\n\n```py\narray = [1, 8, 15]\n# A typical generator expression\ngen = (x for x in array if array.count(x) > 0)\narray = [2, 8, 22]\n```\n\n**Output:**\n\n```py\n>>> print(list(gen)) # Where did the other values go?\n[8]\n```\n\n2\\.\n\n```py\narray_1 = [1,2,3,4]\ngen_1 = (x for x in array_1)\narray_1 = [1,2,3,4,5]\n\narray_2 = [1,2,3,4]\ngen_2 = (x for x in array_2)\narray_2[:] = [1,2,3,4,5]\n```\n\n**Output:**\n\n```py\n>>> print(list(gen_1))\n[1, 2, 3, 4]\n\n>>> print(list(gen_2))\n[1, 2, 3, 4, 5]\n```\n\n3\\.\n\n```py\narray_3 = [1, 2, 3]\narray_4 = [10, 20, 30]\ngen = (i + j for i in array_3 for j in array_4)\n\narray_3 = [4, 5, 6]\narray_4 = [400, 500, 600]\n```\n\n**Output:**\n\n```py\n>>> print(list(gen))\n[401, 501, 601, 402, 502, 602, 403, 503, 603]\n```\n\n#### 💡 Explanation\n\n- In a [generator](https:\u002F\u002Fwiki.python.org\u002Fmoin\u002FGenerators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at runtime.\n- So before runtime, `array` is re-assigned to the list `[2, 8, 22]`, and since out of `1`, `8` and `15`, only the count of `8` is greater than `0`, the generator only yields `8`.\n- The differences in the output of `g1` and `g2` in the second part is due the way variables `array_1` and `array_2` are re-assigned values.\n- In the first case, `array_1` is bound to the new object `[1,2,3,4,5]` and since the `in` clause is evaluated at the declaration time it still refers to the old object `[1,2,3,4]` (which is not destroyed).\n- In the second case, the slice assignment to `array_2` updates the same old object `[1,2,3,4]` to `[1,2,3,4,5]`. Hence both the `g2` and `array_2` still have reference to the same object (which has now been updated to `[1,2,3,4,5]`).\n- Okay, going by the logic discussed so far, shouldn't be the value of `list(gen)` in the third snippet be `[11, 21, 31, 12, 22, 32, 13, 23, 33]`? (because `array_3` and `array_4` are going to behave just like `array_1`). The reason why (only) `array_4` values got updated is explained in [PEP-289](https:\u002F\u002Fwww.python.org\u002Fdev\u002Fpeps\u002Fpep-0289\u002F#the-details)\n\n  > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n\n---\n\n### ▶ `is not ...` is not `is (not ...)`\n\n\u003C!-- Example ID: b26fb1ed-0c7d-4b9c-8c6d-94a58a055c0d --->\n\n```py\n>>> 'something' is not None\nTrue\n>>> 'something' is (not None)\nFalse\n```\n\n#### 💡 Explanation\n\n- `is not` is a single binary operator, and has behavior different than using `is` and `not` separated.\n- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise.\n- In the example, `(not None)` evaluates to `True` since the value `None` is `False` in a boolean context, so the expression becomes `'something' is True`.\n\n---\n\n### ▶ A tic-tac-toe where X wins in the first attempt!\n\n\u003C!-- Example ID: 69329249-bdcb-424f-bd09-cca2e6705a7a --->\n\n```py\n# Let's initialize a row\nrow = [\"\"] * 3 #row i['', '', '']\n# Let's make a board\nboard = [row] * 3\n```\n\n**Output:**\n\n```py\n>>> board\n[['', '', ''], ['', '', ''], ['', '', '']]\n>>> board[0]\n['', '', '']\n>>> board[0][0]\n''\n>>> board[0][0] = \"X\"\n>>> board\n[['X', '', ''], ['X', '', ''], ['X', '', '']]\n```\n\nWe didn't assign three `\"X\"`s, did we?\n\n#### 💡 Explanation:\n\nWhen we initialize `row` variable, this visualization explains what happens in the memory\n\n\u003Cp align=\"center\">\n    \u003Cpicture>\n      \u003Csource media=\"(prefers-color-scheme: dark)\" srcset=\"\u002Fimages\u002Ftic-tac-toe\u002Fafter_row_initialized_dark_theme.svg\">\n      \u003Csource media=\"(prefers-color-scheme: light)\" srcset=\"\u002Fimages\u002Ftic-tac-toe\u002Fafter_row_initialized.svg\">\n      \u003Cimg alt=\"Shows a memory segment after row is initialized.\" src=\"\u002Fimages\u002Ftic-tac-toe\u002Fafter_row_initialized.svg\">\n    \u003C\u002Fpicture>\n\u003C\u002Fp>\n\nAnd when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`)\n\n\u003Cp align=\"center\">\n    \u003Cpicture>\n      \u003Csource media=\"(prefers-color-scheme: dark)\" srcset=\"\u002Fimages\u002Ftic-tac-toe\u002Fafter_board_initialized_dark_theme.svg\">\n      \u003Csource media=\"(prefers-color-scheme: light)\" srcset=\"\u002Fimages\u002Ftic-tac-toe\u002Fafter_board_initialized.svg\">\n      \u003Cimg alt=\"Shows a memory segment after board is initialized.\" src=\"\u002Fimages\u002Ftic-tac-toe\u002Fafter_board_initialized.svg\">\n    \u003C\u002Fpicture>\n\u003C\u002Fp>\n\nWe can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https:\u002F\u002Fgithub.com\u002Fsatwikkansal\u002Fwtfpython\u002Fissues\u002F68) issue).\n\n```py\n>>> board = [['']*3 for _ in range(3)]\n>>> board[0][0] = \"X\"\n>>> board\n[['X', '', ''], ['', '', ''], ['', '', '']]\n```\n\n---\n\n### ▶ Schrödinger's variable \\*\n\n\u003C!-- Example ID: 4dc42f77-94cb-4eb5-a120-8203d3ed7604 --->\n\n```py\nfuncs = []\nresults = []\nfor x in range(7):\n    def some_func():\n        return x\n    funcs.append(some_func)\n    results.append(some_func())  # note the function call here\n\nfuncs_results = [func() for func in funcs]\n```\n\n**Output (Python version):**\n\n```py\n>>> results\n[0, 1, 2, 3, 4, 5, 6]\n>>> funcs_results\n[6, 6, 6, 6, 6, 6, 6]\n```\n\nThe values of `x` were different in every iteration prior to appending `some_func` to `funcs`, but all the functions return 6 when they're evaluated after the loop completes.\n\n2.\n\n```py\n>>> powers_of_x = [lambda x: x**i for i in range(10)]\n>>> [f(2) for f in powers_of_x]\n[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n```\n\n#### 💡 Explanation:\n\n- When defining a function inside a loop that uses the loop variable in its body,\n  the loop function's closure is bound to the _variable_, not its _value_.\n  The function looks up `x` in the surrounding context, rather than using the value of `x` at the time\n  the function is created. So all of the functions use the latest value assigned to the variable for computation.\n  We can see that it's using the `x` from the surrounding context (i.e. _not_ a local variable) with:\n\n```py\n>>> import inspect\n>>> inspect.getclosurevars(funcs[0])\nClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set())\n```\n\nSince `x` is a global value, we can change the value that the `funcs` will lookup and return by updating `x`:\n\n```py\n>>> x = 42\n>>> [func() for func in funcs]\n[42, 42, 42, 42, 42, 42, 42]\n```\n\n- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why does this work?** Because this will define the variable _inside_ the function's scope. It will no longer go to the surrounding (global) scope to look up the variables value but will create a local variable that stores the value of `x` at that point in time.\n\n```py\nfuncs = []\nfor x in range(7):\n    def some_func(x=x):\n        return x\n    funcs.append(some_func)\n```\n\n**Output:**\n\n```py\n>>> funcs_results = [func() for func in funcs]\n>>> funcs_results\n[0, 1, 2, 3, 4, 5, 6]\n```\n\nIt is not longer using the `x` in the global scope:\n\n```py\n>>> inspect.getclosurevars(funcs[0])\nClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set())\n```\n\n---\n\n### ▶ The chicken-egg problem \\*\n\n\u003C!-- Example ID: 60730dc2-0d79-4416-8568-2a63323b3ce8 --->\n\n1\\.\n\n```py\n>>> isinstance(3, int)\nTrue\n>>> isinstance(type, object)\nTrue\n>>> isinstance(object, type)\nTrue\n```\n\nSo which is the \"ultimate\" base class? There's more to the confusion by the way,\n\n2\\.\n\n```py\n>>> class A: pass\n>>> isinstance(A, A)\nFalse\n>>> isinstance(type, type)\nTrue\n>>> isinstance(object, object)\nTrue\n```\n\n3\\.\n\n```py\n>>> issubclass(int, object)\nTrue\n>>> issubclass(type, object)\nTrue\n>>> issubclass(object, type)\nFalse\n```\n\n#### 💡 Explanation\n\n- `type` is a [metaclass](https:\u002F\u002Frealpython.com\u002Fpython-metaclasses\u002F) in Python.\n- **Everything** is an `object` in Python, which includes classes as well as their objects (instances).\n- class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`.\n- There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking about these relationships (`issubclass` and `isinstance`) in terms of Python classes. The relationship between `object` and `type` can't be reproduced in pure python. To be more precise the following relationships can't be reproduced in pure Python,\n  - class A is an instance of class B, and class B is an instance of class A.\n  - class A is an instance of itself.\n- These relationships between `object` and `type` (both being instances of each other as well as themselves) exist in Python because of \"cheating\" at the implementation level.\n\n---\n\n### ▶ Subclass relationships\n\n\u003C!-- Example ID: 9f6d8cf0-e1b5-42d0-84a0-4cfab25a0bc0 --->\n\n**Output:**\n\n```py\n>>> from collections.abc import Hashable\n>>> issubclass(list, object)\nTrue\n>>> issubclass(object, Hashable)\nTrue\n>>> issubclass(list, Hashable)\nFalse\n```\n\nThe Subclass relationships were expected to be transitive, right? (i.e., if `A` is a subclass of `B`, and `B` is a subclass of `C`, the `A` _should_ a subclass of `C`)\n\n#### 💡 Explanation:\n\n- Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass.\n- When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey \"`__hash__`\" method in `cls` or anything it inherits from.\n- Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation.\n- More detailed explanation can be found [here](https:\u002F\u002Fwww.naftaliharris.com\u002Fblog\u002Fpython-subclass-intransitivity\u002F).\n\n---\n\n### ▶ Methods equality and identity\n\n\u003C!-- Example ID: 94802911-48fe-4242-defa-728ae893fa32 --->\n\n1.\n\n```py\nclass SomeClass:\n    def method(self):\n        pass\n\n    @classmethod\n    def classm(cls):\n        pass\n\n    @staticmethod\n    def staticm():\n        pass\n```\n\n**Output:**\n\n```py\n>>> print(SomeClass.method is SomeClass.method)\nTrue\n>>> print(SomeClass.classm is SomeClass.classm)\nFalse\n>>> print(SomeClass.classm == SomeClass.classm)\nTrue\n>>> print(SomeClass.staticm is SomeClass.staticm)\nTrue\n```\n\nAccessing `classm` twice, we get an equal object, but not the _same_ one? Let's see what happens\nwith instances of `SomeClass`:\n\n2.\n\n```py\no1 = SomeClass()\no2 = SomeClass()\n```\n\n**Output:**\n\n```py\n>>> print(o1.method == o2.method)\nFalse\n>>> print(o1.method == o1.method)\nTrue\n>>> print(o1.method is o1.method)\nFalse\n>>> print(o1.classm is o1.classm)\nFalse\n>>> print(o1.classm == o1.classm == o2.classm == SomeClass.classm)\nTrue\n>>> print(o1.staticm is o1.staticm is o2.staticm is SomeClass.staticm)\nTrue\n```\n\nAccessing `classm` or `method` twice, creates equal but not _same_ objects for the same instance of `SomeClass`.\n\n#### 💡 Explanation\n\n- Functions are [descriptors](https:\u002F\u002Fdocs.python.org\u002F3\u002Fhowto\u002Fdescriptor.html). Whenever a function is accessed as an\n  attribute, the descriptor is invoked, creating a method object which \"binds\" the function with the object owning the\n  attribute. If called, the method calls the function, implicitly passing the bound object as the first argument\n  (this is how we get `self` as the first argument, despite not passing it explicitly).\n\n```py\n>>> o1.method\n\u003Cbound method SomeClass.method of \u003C__main__.SomeClass object at ...>>\n```\n\n- Accessing the attribute multiple times creates a method object every time! Therefore `o1.method is o1.method` is\n  never truthy. Accessing functions as class attributes (as opposed to instance) does not create methods, however; so\n  `SomeClass.method is SomeClass.method` is truthy.\n\n```py\n>>> SomeClass.method\n\u003Cfunction SomeClass.method at ...>\n```\n\n- `classmethod` transforms functions into class methods. Class methods are descriptors that, when accessed, create\n  a method object which binds the _class_ (type) of the object, instead of the object itself.\n\n```py\n>>> o1.classm\n\u003Cbound method SomeClass.classm of \u003Cclass '__main__.SomeClass'>>\n```\n\n- Unlike functions, `classmethod`s will create a method also when accessed as class attributes (in which case they\n  bind the class, not to the type of it). So `SomeClass.classm is SomeClass.classm` is falsy.\n\n```py\n>>> SomeClass.classm\n\u003Cbound method SomeClass.classm of \u003Cclass '__main__.SomeClass'>>\n```\n\n- A method object compares equal when both the functions are equal, and the bound objects are the same. So\n  `o1.method == o1.method` is truthy, although not the same object in memory.\n- `staticmethod` transforms functions into a \"no-op\" descriptor, which returns the function as-is. No method\n  objects are ever created, so comparison with `is` is truthy.\n\n```py\n>>> o1.staticm\n\u003Cfunction SomeClass.staticm at ...>\n>>> SomeClass.staticm\n\u003Cfunction SomeClass.staticm at ...>\n```\n\n- Having to create new \"method\" objects every time Python calls instance methods and having to modify the arguments\nevery time in order to insert `self` affected performance badly.\nCPython 3.7 [solved it](https:\u002F\u002Fbugs.python.org\u002Fissue26110) by introducing new opcodes that deal with calling methods\nwithout creating the temporary method objects. This is used only when the accessed function is actually called, so the\nsnippets here are not affected, and still generate methods :)\n\n### ▶ All-true-ation \\*\n\n\u003C!-- Example ID: dfe6d845-e452-48fe-a2da-0ed3869a8042 -->\n\n```py\n>>> all([True, True, True])\nTrue\n>>> all([True, True, False])\nFalse\n\n>>> all([])\nTrue\n>>> all([[]])\nFalse\n>>> all([[[]]])\nTrue\n```\n\nWhy's this True-False alteration?\n\n#### 💡 Explanation:\n\n- The implementation of `all` function is equivalent to\n\n- ```py\n  def all(iterable):\n      for element in iterable:\n          if not element:\n              return False\n      return True\n  ```\n\n- `all([])` returns `True` since the iterable is empty.\n- `all([[]])` returns `False` because the passed array has one element, `[]`, and in python, an empty list is falsy.\n- `all([[[]]])` and higher recursive variants are always `True`. This is because the passed array's single element (`[[...]]`) is no longer empty, and lists with values are truthy.\n\n---\n\n### ▶ The surprising comma\n\n\u003C!-- Example ID: 31a819c8-ed73-4dcc-84eb-91bedbb51e58 --->\n\n**Output (\u003C 3.6):**\n\n```py\n>>> def f(x, y,):\n...     print(x, y)\n...\n>>> def g(x=4, y=5,):\n...     print(x, y)\n...\n>>> def h(x, **kwargs,):\n  File \"\u003Cstdin>\", line 1\n    def h(x, **kwargs,):\n                     ^\nSyntaxError: invalid syntax\n\n>>> def h(*args,):\n  File \"\u003Cstdin>\", line 1\n    def h(*args,):\n                ^\nSyntaxError: invalid syntax\n```\n\n#### 💡 Explanation:\n\n- Trailing comma is not always legal in formal parameters list of a Python function.\n- In Python, the argument list is defined partially with leading commas and partially with trailing commas. This conflict causes situations where a comma is trapped in the middle, and no rule accepts it.\n- **Note:** The trailing comma problem is [fixed in Python 3.6](https:\u002F\u002Fbugs.python.org\u002Fissue9232). The remarks in [this](https:\u002F\u002Fbugs.python.org\u002Fissue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n\n---\n\n### ▶ Strings and the backslashes\n\n\u003C!-- Example ID: 6ae622c3-6d99-4041-9b33-507bd1a4407b --->\n\n**Output:**\n\n```py\n>>> print(\"\\\"\")\n\"\n\n>>> print(r\"\\\"\")\n\\\"\n\n>>> print(r\"\\\")\nFile \"\u003Cstdin>\", line 1\n    print(r\"\\\")\n              ^\nSyntaxError: EOL while scanning string literal\n\n>>> r'\\'' == \"\\\\'\"\nTrue\n```\n\n#### 💡 Explanation\n\n- In a usual python string, the backslash is used to escape characters that may have a special meaning (like single-quote, double-quote, and the backslash itself).\n\n  ```py\n  >>> \"wt\\\"f\"\n  'wt\"f'\n  ```\n\n- In a raw string literal (as indicated by the prefix `r`), the backslashes pass themselves as is along with the behavior of escaping the following character.\n\n  ```py\n  >>> r'wt\\\"f' == 'wt\\\\\"f'\n  True\n  >>> print(repr(r'wt\\\"f'))\n  'wt\\\\\"f'\n\n  >>> print(\"\\n\")\n\n  >>> print(r\"\\\\n\")\n  '\\\\n'\n  ```\n\n- This means when a parser encounters a backslash in a raw string, it expects another character following it. And in our case (`print(r\"\\\")`), the backslash escaped the trailing quote, leaving the parser without a terminating quote (hence the `SyntaxError`). That's why backslashes don't work at the end of a raw string.\n\n---\n\n### ▶ not knot!\n\n\u003C!-- Example ID: 7034deb1-7443-417d-94ee-29a800524de8 --->\n\n```py\nx = True\ny = False\n```\n\n**Output:**\n\n```py\n>>> not x == y\nTrue\n>>> x == not y\n  File \"\u003Cinput>\", line 1\n    x == not y\n           ^\nSyntaxError: invalid syntax\n```\n\n#### 💡 Explanation:\n\n- Operator precedence affects how an expression is evaluated, and `==` operator has higher precedence than `not` operator in Python.\n- So `not x == y` is equivalent to `not (x == y)` which is equivalent to `not (True == False)` finally evaluating to `True`.\n- But `x == not y` raises a `SyntaxError` because it can be thought of being equivalent to `(x == not) y` and not `x == (not y)` which you might have expected at first sight.\n- The parser expected the `not` token to be a part of the `not in` operator (because both `==` and `not in` operators have the same precedence), but after not being able to find an `in` token following the `not` token, it raises a `SyntaxError`.\n\n---\n\n### ▶ Half triple-quoted strings\n\n\u003C!-- Example ID: c55da3e2-1034-43b9-abeb-a7a970a2ad9e --->\n\n**Output:**\n\n```py\n>>> print('wtfpython''')\nwtfpython\n>>> print(\"wtfpython\"\"\")\nwtfpython\n>>> # The following statements raise `SyntaxError`\n>>> # print('''wtfpython')\n>>> # print(\"\"\"wtfpython\")\n  File \"\u003Cinput>\", line 3\n    print(\"\"\"wtfpython\")\n                        ^\nSyntaxError: EOF while scanning triple-quoted string literal\n```\n\n#### 💡 Explanation:\n\n- Python supports implicit [string literal concatenation](https:\u002F\u002Fdocs.python.org\u002F3\u002Freference\u002Flexical_analysis.html#string-literal-concatenation), Example,\n\n  ```\n  >>> print(\"wtf\" \"python\")\n  wtfpython\n  >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n  wtf\n  ```\n\n- `'''` and `\"\"\"` are also string delimiters in Python which causes a SyntaxError because the Python interpreter was expecting a terminating triple quote as delimiter while scanning the currently encountered triple quoted string literal.\n\n---\n\n### ▶ What's wrong with booleans?\n\n\u003C!-- Example ID: 0bba5fa7-9e6d-4cd2-8b94-952d061af5dd --->\n\n1\\.\n\n```py\n# A simple example to count the number of booleans and\n# integers in an iterable of mixed data types.\nmixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\nintegers_found_so_far = 0\nbooleans_found_so_far = 0\n\nfor item in mixed_list:\n    if isinstance(item, int):\n        integers_found_so_far += 1\n    elif isinstance(item, bool):\n        booleans_found_so_far += 1\n```\n\n**Output:**\n\n```py\n>>> integers_found_so_far\n4\n>>> booleans_found_so_far\n0\n```\n\n2\\.\n\n```py\n>>> some_bool = True\n>>> \"wtf\" * some_bool\n'wtf'\n>>> some_bool = False\n>>> \"wtf\" * some_bool\n''\n```\n\n3\\.\n\n```py\ndef tell_truth():\n    True = False\n    if True == False:\n        print(\"I have lost faith in truth!\")\n```\n\n**Output (\u003C 3.x):**\n\n```py\n>>> tell_truth()\nI have lost faith in truth!\n```\n\n#### 💡 Explanation:\n\n- `bool` is a subclass of `int` in Python\n\n  ```py\n  >>> issubclass(bool, int)\n  True\n  >>> issubclass(int, bool)\n  False\n  ```\n\n- And thus, `True` and `False` are instances of `int`\n\n  ```py\n  >>> isinstance(True, int)\n  True\n  >>> isinstance(False, int)\n  True\n  ```\n\n- The integer value of `True` is `1` and that of `False` is `0`.\n\n  ```py\n  >>> int(True)\n  1\n  >>> int(False)\n  0\n  ```\n\n- See this StackOverflow [answer](https:\u002F\u002Fstackoverflow.com\u002Fa\u002F8169049\u002F4354153) for the rationale behind it.\n\n- Initially, Python used to have no `bool` type (people used 0 for false and non-zero value like 1 for true). `True`, `False`, and a `bool` type was added in 2.x versions, but, for backward compatibility, `True` and `False` couldn't be made constants. They just were built-in variables, and it was possible to reassign them\n\n- Python 3 was backward-incompatible, the issue was finally fixed, and thus the last snippet won't work with Python 3.x!\n\n---\n\n### ▶ Class attributes and instance attributes\n\n\u003C!-- Example ID: 6f332208-33bd-482d-8106-42863b739ed9 --->\n\n1\\.\n\n```py\nclass A:\n    x = 1\n\nclass B(A):\n    pass\n\nclass C(A):\n    pass\n```\n\n**Output:**\n\n```py\n>>> A.x, B.x, C.x\n(1, 1, 1)\n>>> B.x = 2\n>>> A.x, B.x, C.x\n(1, 2, 1)\n>>> A.x = 3\n>>> A.x, B.x, C.x # C.x changed, but B.x didn't\n(3, 2, 3)\n>>> a = A()\n>>> a.x, A.x\n(3, 3)\n>>> a.x += 1\n>>> a.x, A.x\n(4, 3)\n```\n\n2\\.\n\n```py\nclass SomeClass:\n    some_var = 15\n    some_list = [5]\n    another_list = [5]\n    def __init__(self, x):\n        self.some_var = x + 1\n        self.some_list = self.some_list + [x]\n        self.another_list += [x]\n```\n\n**Output:**\n\n```py\n>>> some_obj = SomeClass(420)\n>>> some_obj.some_list\n[5, 420]\n>>> some_obj.another_list\n[5, 420]\n>>> another_obj = SomeClass(111)\n>>> another_obj.some_list\n[5, 111]\n>>> another_obj.another_list\n[5, 420, 111]\n>>> another_obj.another_list is SomeClass.another_list\nTrue\n>>> another_obj.another_list is some_obj.another_list\nTrue\n```\n\n#### 💡 Explanation:\n\n- Class variables and variables in class instances are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of the current class, the parent classes are searched for it.\n- The `+=` operator modifies the mutable object in-place without creating a new object. So changing the attribute of one instance affects the other instances and the class attribute as well.\n\n---\n\n### ▶ yielding None\n\n\u003C!-- Example ID: 5a40c241-2c30-40d0-8ba9-cf7e097b3b53 --->\n\n```py\nsome_iterable = ('a', 'b')\n\ndef some_func(val):\n    return \"something\"\n```\n\n**Output (\u003C= 3.7.x):**\n\n```py\n>>> [x for x in some_iterable]\n['a', 'b']\n>>> [(yield x) for x in some_iterable]\n\u003Cgenerator object \u003Clistcomp> at 0x7f70b0a4ad58>\n>>> list([(yield x) for x in some_iterable])\n['a', 'b']\n>>> list((yield x) for x in some_iterable)\n['a', None, 'b', None]\n>>> list(some_func((yield x)) for x in some_iterable)\n['a', 'something', 'b', 'something']\n```\n\n#### 💡 Explanation:\n\n- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n- Source and explanation can be found here: https:\u002F\u002Fstackoverflow.com\u002Fquestions\u002F32139885\u002Fyield-in-list-comprehensions-and-generator-expressions\n- Related bug report: https:\u002F\u002Fbugs.python.org\u002Fissue10544\n- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n\n---\n\n### ▶ Yielding from... return! \\*\n\n\u003C!-- Example ID: 5626d8ef-8802-49c2-adbc-7cda5c550816 --->\n\n1\\.\n\n```py\ndef some_func(x):\n    if x == 3:\n        return [\"wtf\"]\n    else:\n        yield from range(x)\n```\n\n**Output (> 3.3):**\n\n```py\n>>> list(some_func(3))\n[]\n```\n\nWhere did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n\n2\\.\n\n```py\ndef some_func(x):\n    if x == 3:\n        return [\"wtf\"]\n    else:\n        for i in range(x):\n          yield i\n```\n\n**Output:**\n\n```py\n>>> list(some_func(3))\n[]\n```\n\nThe same result, this didn't work either.\n\n#### 💡 Explanation:\n\n- From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https:\u002F\u002Fwww.python.org\u002Fdev\u002Fpeps\u002Fpep-0380\u002F)). The [official docs](https:\u002F\u002Fwww.python.org\u002Fdev\u002Fpeps\u002Fpep-0380\u002F#enhancements-to-stopiteration) say that,\n\n> \"... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator.\"\n\n- In the case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically caught inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list.\n\n- To get `[\"wtf\"]` from the generator `some_func` we need to catch the `StopIteration` exception,\n\n  ```py\n  try:\n      next(some_func(3))\n  except StopIteration as e:\n      some_string = e.value\n  ```\n\n  ```py\n  >>> some_string\n  [\"wtf\"]\n  ```\n\n---\n\n### ▶ Nan-reflexivity \\*\n\n\u003C!-- Example ID: 59bee91a-36e0-47a4-8c7d-aa89bf1d3976 --->\n\n1\\.\n\n```py\na = float('inf')\nb = float('nan')\nc = float('-iNf')  # These strings are case-insensitive\nd = float('nan')\n```\n\n**Output:**\n\n```py\n>>> a\ninf\n>>> b\nnan\n>>> c\n-inf\n>>> float('some_other_string')\nValueError: could not convert string to float: some_other_string\n>>> a == -c # inf==inf\nTrue\n>>> None == None # None == None\nTrue\n>>> b == d # but nan!=nan\nFalse\n>>> 50 \u002F a\n0.0\n>>> a \u002F a\nnan\n>>> 23 + b\nnan\n```\n\n2\\.\n\n```py\n>>> x = float('nan')\n>>> y = x \u002F x\n>>> y is y # identity holds\nTrue\n>>> y == y # equality fails of y\nFalse\n>>> [y] == [y] # but the equality succeeds for the list containing y\nTrue\n```\n\n#### 💡 Explanation:\n\n- `'inf'` and `'nan'` are special strings (case-insensitive), which, when explicitly typecast-ed to `float` type, are used to represent mathematical \"infinity\" and \"not a number\" respectively.\n\n- Since according to IEEE standards `NaN != NaN`, obeying this rule breaks the reflexivity assumption of a collection element in Python i.e. if `x` is a part of a collection like `list`, the implementations like comparison are based on the assumption that `x == x`. Because of this assumption, the identity is compared first (since it's faster) while comparing two elements, and the values are compared only when the identities mismatch. The following snippet will make things clearer,\n\n  ```py\n  >>> x = float('nan')\n  >>> x == x, [x] == [x]\n  (False, True)\n  >>> y = float('nan')\n  >>> y == y, [y] == [y]\n  (False, True)\n  >>> x == y, [x] == [y]\n  (False, False)\n  ```\n\n  Since the identities of `x` and `y` are different, the values are considered, which are also different; hence the comparison returns `False` this time.\n\n- Interesting read: [Reflexivity, and other pillars of civilization](https:\u002F\u002Fbertrandmeyer.com\u002F2010\u002F02\u002F06\u002Freflexivity-and-other-pillars-of-civilization\u002F)\n\n---\n\n### ▶ Mutating the immutable!\n\n\u003C!-- Example ID: 15a9e782-1695-43ea-817a-a9208f6bb33d --->\n\nThis might seem trivial if you know how references work in Python.\n\n```py\nsome_tuple = (\"A\", \"tuple\", \"with\", \"values\")\nanother_tuple = ([1, 2], [3, 4], [5, 6])\n```\n\n**Output:**\n\n```py\n>>> some_tuple[2] = \"change this\"\nTypeError: 'tuple' object does not support item assignment\n>>> another_tuple[2].append(1000) #This throws no error\n>>> another_tuple\n([1, 2], [3, 4], [5, 6, 1000])\n>>> another_tuple[2] += [99, 999]\nTypeError: 'tuple' object does not support item assignment\n>>> another_tuple\n([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n```\n\nBut I thought tuples were immutable...\n\n#### 💡 Explanation:\n\n- Quoting from https:\u002F\u002Fdocs.python.org\u002F3\u002Freference\u002Fdatamodel.html\n\n  > Immutable sequences\n\n        An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.)\n\n- `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place.\n- There's also an explanation in [official Python FAQ](https:\u002F\u002Fdocs.python.org\u002F3\u002Ffaq\u002Fprogramming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works).\n\n---\n\n### ▶ The disappearing variable from outer scope\n\n\u003C!-- Example ID: 7f1e71b6-cb3e-44fb-aa47-87ef1b7decc8 --->\n\n```py\ne = 7\ntry:\n    raise Exception()\nexcept Exception as e:\n    pass\n```\n\n**Output (Python 2.x):**\n\n```py\n>>> print(e)\n# prints nothing\n```\n\n**Output (Python 3.x):**\n\n```py\n>>> print(e)\nNameError: name 'e' is not defined\n```\n\n#### 💡 Explanation:\n\n- Source: https:\u002F\u002Fdocs.python.org\u002F3\u002Freference\u002Fcompound_stmts.html#except\n\n  When an exception has been assigned using `as` target, it is cleared at the end of the `except` clause. This is as if\n\n  ```py\n  except E as N:\n      foo\n  ```\n\n  was translated into\n\n  ```py\n  except E as N:\n      try:\n          foo\n      finally:\n          del N\n  ```\n\n  This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because, with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.\n\n- The clauses are not scoped in Python. Everything in the example is present in the same scope, and the variable `e` got removed due to the execution of the `except` clause. The same is not the case with functions that have their separate inner-scopes. The example below illustrates this:\n\n  ```py\n  def f(x):\n      del(x)\n      print(x)\n\n  x = 5\n  y = [5, 4, 3]\n  ```\n\n  **Output:**\n\n  ```py\n  >>> f(x)\n  UnboundLocalError: local variable 'x' referenced before assignment\n  >>> f(y)\n  UnboundLocalError: local variable 'x' referenced before assignment\n  >>> x\n  5\n  >>> y\n  [5, 4, 3]\n  ```\n\n- In Python 2.x, the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing.\n\n  **Output (Python 2.x):**\n\n  ```py\n  >>> e\n  Exception()\n  >>> print e\n  # Nothing is printed!\n  ```\n\n---\n\n### ▶ The mysterious key type conversion\n\n\u003C!-- Example ID: 00f42dd0-b9ef-408d-9e39-1bc209ce3f36 --->\n\n```py\nclass SomeClass(str):\n    pass\n\nsome_dict = {'s': 42}\n```\n\n**Output:**\n\n```py\n>>> type(list(some_dict.keys())[0])\nstr\n>>> s = SomeClass('s')\n>>> some_dict[s] = 40\n>>> some_dict # expected: Two different keys-value pairs\n{'s': 40}\n>>> type(list(some_dict.keys())[0])\nstr\n```\n\n#### 💡 Explanation:\n\n- Both the object `s` and the string `\"s\"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class.\n- `SomeClass(\"s\") == \"s\"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class.\n- Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary.\n- For the desired behavior, we can redefine the `__eq__` method in `SomeClass`\n\n  ```py\n  class SomeClass(str):\n    def __eq__(self, other):\n        return (\n            type(self) is SomeClass\n            and type(other) is SomeClass\n            and super().__eq__(other)\n        )\n\n    # When we define a custom __eq__, Python stops automatically inheriting the\n    # __hash__ method, so we need to define it as well\n    __hash__ = str.__hash__\n\n  some_dict = {'s':42}\n  ```\n\n  **Output:**\n\n  ```py\n  >>> s = SomeClass('s')\n  >>> some_dict[s] = 40\n  >>> some_dict\n  {'s': 40, 's': 42}\n  >>> keys = list(some_dict.keys())\n  >>> type(keys[0]), type(keys[1])\n  (__main__.SomeClass, str)\n  ```\n\n---\n\n### ▶ Let's see if you can guess this?\n\n\u003C!-- Example ID: 81aa9fbe-bd63-4283-b56d-6fdd14c9105e --->\n\n```py\na, b = a[b] = {}, 5\n```\n\n**Output:**\n\n```py\n>>> a\n{5: ({...}, 5)}\n```\n\n#### 💡 Explanation:\n\n- According to [Python language reference](https:\u002F\u002Fdocs.python.org\u002F3\u002Freference\u002Fsimple_stmts.html#assignment-statements), assignment statements have the form\n\n  ```\n  (target_list \"=\")+ (expression_list | yield_expression)\n  ```\n\n  and\n\n> An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.\n\n- The `+` in `(target_list \"=\")+` means there can be **one or more** target lists. In this case, target lists are `a, b` and `a[b]` (note the expression list is exactly one, which in our case is `{}, 5`).\n\n- After the expression list is evaluated, its value is unpacked to the target lists from **left to right**. So, in our case, first the `{}, 5` tuple is unpacked to `a, b` and we now have `a = {}` and `b = 5`.\n\n- `a` is now assigned to `{}`, which is a mutable object.\n\n- The second target list is `a[b]` (you may expect this to throw an error because both `a` and `b` have not been defined in the statements before. But remember, we just assigned `a` to `{}` and `b` to `5`).\n\n- Now, we are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference (the `{...}` in the output refers to the same object that `a` is already referencing). Another simpler example of circular reference could be\n\n  ```py\n  >>> some_list = some_list[0] = [0]\n  >>> some_list\n  [[...]]\n  >>> some_list[0]\n  [[...]]\n  >>> some_list is some_list[0]\n  True\n  >>> some_list[0][0][0][0][0][0] == some_list\n  True\n  ```\n\n  Similar is the case in our example (`a[b][0]` is the same object as `a`)\n\n- So to sum it up, you can break the example down to\n\n  ```py\n  a, b = {}, 5\n  a[b] = a, b\n  ```\n\n  And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n\n  ```py\n  >>> a[b][0] is a\n  True\n  ```\n\n---\n\n### ▶ Exceeds the limit for integer string conversion\n\n```py\n>>> # Python 3.10.6\n>>> int(\"2\" * 5432)\n\n>>> # Python 3.10.8\n>>> int(\"2\" * 5432)\n```\n\n**Output:**\n\n```py\n>>> # Python 3.10.6\n222222222222222222222222222222222222222222222222222222222222222...\n\n>>> # Python 3.10.8\nTraceback (most recent call last):\n   ...\nValueError: Exceeds the limit (4300) for integer string conversion:\n   value has 5432 digits; use sys.set_int_max_str_digits()\n   to increase the limit.\n```\n\n#### 💡 Explanation:\n\nThis call to `int()` works fine in Python 3.10.6 and raises a ValueError in Python 3.10.8. Note that Python can still work with large integers. The error is only raised when converting between integers and strings.\n\nFortunately, you can increase the limit for the allowed number of digits when you expect an operation to exceed it. To do this, you can use one of the following:\n\n- The -X int_max_str_digits command-line flag\n- The set_int_max_str_digits() function from the sys module\n- The PYTHONINTMAXSTRDIGITS environment variable\n\n[Check the documentation](https:\u002F\u002Fdocs.python.org\u002F3\u002Flibrary\u002Fstdtypes.html#int-max-str-digits) for more details on changing the default limit if y","wtfpython 是一个旨在通过令人惊讶的代码片段来探索和理解 Python 的项目。它汇集了一系列不直观或鲜为人知的 Python 特性，帮助开发者深入了解这门语言的工作原理。项目中的每个示例都经过精心挑选，以揭示 Python 中一些有趣但可能让人困惑的行为。适合于所有级别的 Python 开发者使用，无论是初学者还是经验丰富的程序员都能从中受益。对于那些希望提升自己对 Python 内部机制理解的人来说，wtfpython 提供了一个既具挑战性又富有趣味的学习资源。此外，该项目还支持多种语言版本，并且有交互式网站和笔记本等多种学习模式可供选择。",2,"2026-06-11 02:43:53","top_all"]