{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "An interesting collection of surprising snippets and lesser-known Python features.
\n", "\n", "Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].)\n", "\n", "Python, being a beautifully designed high-level and interpreter-based programming language, provides us with many features for the programmer's comfort. But sometimes, the outcomes of a Python snippet may not seem obvious at first sight.\n", "\n", "Here is a fun project attempting to explain what exactly is happening under the hood for some counter-intuitive snippets and lesser-known features in Python.\n", "\n", "While some of the examples you see below may not be WTFs in the truest sense, but they'll reveal some of the interesting parts of Python that you might be unaware of. I find it a nice way to learn the internals of a programming language, and I believe that you'll find it interesting too!\n", "\n", "If you're an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt. You may have already experienced some of them before, and I might be able to revive sweet old memories of yours! :sweat_smile:\n", "\n", "PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/).\n", "\n", "So, here we go...\n", "\n", "# Table of Contents\n", "\n", "\n", "\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", " + [▶ Splitsies](#-splitsies)\n", " + [▶ Hash brownies](#-hash-brownies)\n", " + [▶ Disorder within order](#-disorder-within-order)\n", " + [▶ Keep trying...](#-keep-trying)\n", " + [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same)\n", " + [▶ For what?](#-for-what)\n", " + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy)\n", " + [▶ How not to use `is` operator](#-how-not-to-use-is-operator)\n", " + [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt)\n", " + [▶ The sticky output function](#-the-sticky-output-function)\n", " + [▶ The chicken-egg problem](#-the-chicken-egg-problem)\n", " + [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-)\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", " + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist)\n", " + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans)\n", " + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes)\n", " + [▶ Non-reflexive class method](#-non-reflexive-class-method)\n", " + [▶ yielding None](#-yielding-none)\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", " + [▶ Yielding from... return!](#-yielding-from-return)\n", " + [▶ Lossy zip of iterators](#-lossy-zip-of-iterators)\n", " + [▶ Subclass relationships](#-subclass-relationships)\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", " * [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: 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", " + [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating)\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", " + [▶ The out of scope variable](#-the-out-of-scope-variable)\n", " + [▶ Be careful with chained operations](#-be-careful-with-chained-operations)\n", " + [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope)\n", " + [▶ Needles in a Haystack](#-needles-in-a-haystack)\n", " + [▶ Wild imports](#-wild-imports)\n", " * [Section: Read the docs](#section-read-the-docs)\n", " + [▶ All sorted?](#-all-sorted)\n", " + [▶ All-true-ation](#-all-true-ation)\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: Miscellaneous](#section-miscellaneous)\n", " + [▶ `+=` is faster](#--is-faster)\n", " + [▶ Let's make a giant string!](#-lets-make-a-giant-string)\n", " + [▶ Minor Ones](#-minor-ones)\n", "- [Contributing](#contributing)\n", "- [Acknowledgements](#acknowledgements)\n", "- [🎓 License](#%F0%9F%8E%93-license)\n", " * [Surprise your friends too?](#surprise-your-friends-too)\n", " * [Need a pdf version?](#need-a-pdf-version)\n", "\n", "\n", "\n", "# Structure of the Examples\n", "\n", "All the examples are structured like below:\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", "> (Optional): One line describing the unexpected output.\n", ">\n", ">\n", "> #### 💡 Explanation:\n", ">\n", "> * Brief explanation of what's happening and why is it happening.\n", "> ```py\n", "> # Set up code\n", "> # More examples for further clarification (if necessary)\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, and they should work for all the Python versions unless explicitly specified before the output.\n", "\n", "# Usage\n", "\n", "A nice way to get the most out of these examples, in my opinion, is to read them chronologically, and for every example:\n", "- Carefully read the initial code for setting up the example. 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 (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfPython)).\n", " - If yes, give a gentle pat on your back, and you may skip to the next example.\n", "\n", "PS: You can also read WTFPython at the command line using the [pypi package](https://pypi.python.org/pypi/wtfpython),\n", "```sh\n", "$ pip install wtfpython -U\n", "$ wtfpython\n", "```\n", "---\n", "\n", "# 👀 Examples\n", "\n", "\n", "\n", "# Hosted notebook instructions\n", "\n", "This is just an experimental attempt of browsing wtfpython through jupyter notebooks. Some examples are read-only because, \n", "- they either require a version of Python that's not supported in the hosted runtime.\n", "- or they can't be reproduced in the notebook envrinonment.\n", "\n", "The expected outputs are already present in collapsed cells following the code cells. The Google colab provides Python2 (2.7) and Python3 (3.6, default) runtimes. You can switch among these for Python2 specific examples. For examples specific to other minor versions, you can simply refer to collapsed outputs (it's not possible to control the minor version in hosted notebooks as of now). You can check the active version using\n", "\n", "```py\n", ">>> import sys\n", ">>> sys.version\n", "# Prints out Python version here.\n", "```\n", "\n", "That being said, most of tbe examples do work as expected. If you face any trouble, feel free to consult the original content on wtfpython and create an issue in the repo. Have fun!\n", "\n", "---\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ▶ First things first! *\n", "For some reason, the Python 3.8's \"Walrus\" operator (`:=`) has become quite popular. Let's check it out,\n", "\n", "1\\.\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```py\n", "# Python version 3.8+\n", "\n", ">>> a = \"wtf_walrus\"\n", ">>> a\n", "```\n", "```py\n", "'wtf_walrus'\n", "\n", "```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```py\n", ">>> a := \"wtf_walrus\"\n", "```\n", "```py\n", "File \"