From d7477885b863dc8194ac65eefed49a7c22dfd43d Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Wed, 5 Dec 2018 04:16:32 +0530 Subject: [PATCH 001/221] Update broken link --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d9b9563e..855e2acb 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ While some of the examples you see below may not be WTFs in the truest sense, bu If you're an experienced Python programmer, you can take it as a challenge to get most of them right in first attempt. You may be already familiar with some of these examples, and I might be able to revive sweet old memories of yours being bitten by these gotchas :sweat_smile: -If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). +PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). So, here we go... @@ -2358,7 +2358,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' * https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines * https://stackoverflow.com/questions/1011431/common-pitfalls-in-python * https://www.python.org/doc/humor/ -* https://www.satwikkansal.xyz/archives/posts/python/My-Python-archives/ +* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 # 🎓 License @@ -2373,9 +2373,9 @@ The idea and design for this collection were initially inspired by Denys Dovhan' If you have any wtfs, ideas or suggestions, please share. -## Want to surprise your geeky pythonist friends? +## Surprise your geeky pythonist friends? -You can recommend wtfpython to your friends on Twitter and Linkedin by using these quick links, +You can use these quick links to recommend wtfpython to your friends, [Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) From b0e7a816ec356197699d8c4d799d7c86457dbbaf Mon Sep 17 00:00:00 2001 From: Hannes Date: Wed, 5 Dec 2018 20:45:59 +0100 Subject: [PATCH 002/221] make the function *call* more visible (#104) It is easy to overlook the () in that appending operation, I propose adding a short comment. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 855e2acb..9049fdb8 100644 --- a/README.md +++ b/README.md @@ -555,7 +555,7 @@ for x in range(7): def some_func(): return x funcs.append(some_func) - results.append(some_func()) + results.append(some_func()) # note the function call here funcs_results = [func() for func in funcs] ``` From 9c5f26e7588e561a716a93165a5696356c179715 Mon Sep 17 00:00:00 2001 From: Hannes Date: Wed, 5 Dec 2018 20:50:17 +0100 Subject: [PATCH 003/221] match order of display to if/else order (#105) I was WTFing for way too long until I realised that the results were displayed in opposite order of the if/else statement. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9049fdb8..79820a0f 100644 --- a/README.md +++ b/README.md @@ -774,10 +774,10 @@ for item in mixed_list: **Output:** ```py ->>> booleans_found_so_far -0 >>> integers_found_so_far 4 +>>> booleans_found_so_far +0 ``` 2\. From 64b310953a58ddcb3dc65173d1d4fafdc18c8d49 Mon Sep 17 00:00:00 2001 From: 1f604 <1f604@users.noreply.github.com> Date: Thu, 6 Dec 2018 18:54:45 +0000 Subject: [PATCH 004/221] fix typo (#107) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 79820a0f..d59943d8 100644 --- a/README.md +++ b/README.md @@ -838,7 +838,7 @@ class C(A): pass ``` -**Ouptut:** +**Output:** ```py >>> A.x, B.x, C.x (1, 1, 1) From 30e05a5973930c38cdb59f1c02b85b19b22ac531 Mon Sep 17 00:00:00 2001 From: kyblockstacking <40349734+kyblockstacking@users.noreply.github.com> Date: Sun, 9 Dec 2018 06:53:28 -0800 Subject: [PATCH 005/221] Rephrase sentence to make more sense (#109) --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 142de187..7f672aca 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -11,4 +11,4 @@ I'm really grateful to all the contributors. Following are the wonderful people | chris-rands | [chris-rands](https://github.com/chris-rands) | [#32](https:/github.com/satwikkansal/wtfpython/issues/32) | | sohaibfarooqi | [sohaibfarooqi](https://github.com/sohaibfarooqi) | [#63](https:/github.com/satwikkansal/wtfpython/issues/63) | -Thank you all for taking out time, and helping to make this project awesome! :smile: +Thank you all for taking out the time to make this project more awesome! :smile: From b262f2975641da1493853a390a171a051f561914 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 16 Dec 2018 16:23:39 +0530 Subject: [PATCH 006/221] Add reference to chinese translation --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d59943d8..9827fc46 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![WTFPL 2.0][license-image]][license-url] +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) 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 to a regular user at first sight. From 54883f5134896870436f716b849e935a23e23340 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 31 Mar 2019 19:08:19 +0530 Subject: [PATCH 007/221] Use http instead of https This will avoid CERTIFICATE_VERIFY_FAILED errors due to SSL. --- wtfpython-pypi/wtf_python/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wtfpython-pypi/wtf_python/main.py b/wtfpython-pypi/wtf_python/main.py index 73de9b82..621995af 100644 --- a/wtfpython-pypi/wtf_python/main.py +++ b/wtfpython-pypi/wtf_python/main.py @@ -4,7 +4,7 @@ except ImportError: from urllib import urlretrieve -url = ("https://raw.githubusercontent.com/satwikkansal/" +url = ("http://raw.githubusercontent.com/satwikkansal/" "wtfpython/master/README.md") file_name = "content.md" From 596186d81c82cfef0290d28cd2ddb227e916a306 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Wed, 1 May 2019 19:12:17 +0530 Subject: [PATCH 008/221] Add json generator --- irrelevant/json_generator.py | 156 +++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 irrelevant/json_generator.py diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py new file mode 100644 index 00000000..86820f19 --- /dev/null +++ b/irrelevant/json_generator.py @@ -0,0 +1,156 @@ +import pprint +fname = "/Users/300041709/code/self/wtfpython/README.md" +examples = [] + +# The globals +current_example = 1 +current_section_name = "" + + +def parse_example_parts(lines): + parts = { + "build_up": [], + "explanation": [] + } + next_line = next(lines) + sequence_num = 1 + content = [] + # store build_up till an H4 (explanation) is encountered + while not next_line.startswith("#### "): + # Watching out for the snippets + if next_line.startswith("```"): + # It's a snippet, whatever found until now is text + if content: + parts["build_up"].append( + { + "type": "text", + "sequence_num": sequence_num, + "value": content + } + ) + sequence_num += 1 + content = [] + + next_line = next(lines) + while not next_line.startswith("```"): + content.append(next_line) + next_line = next(lines) + # Snippet is over + parts["build_up"].append( + { + "type": "code", + "sequence_num": sequence_num, + "value": content + } + ) + sequence_num += 1 + content = [] + next_line = next(lines) + continue + else: + # It's a text, go on. + content.append(next_line) + next_line = next(lines) + + # Explanation encountered, save any content till now (if any) + if content: + parts["build_up"].append( + { + "type": "text", + "sequence_num": sequence_num, + "value": content + } + ) + + # Reset stuff + sequence_num = 1 + content = [] + + # store lines again until --- or another H3 is encountered + while not (next_line.startswith("---") or + next_line.startswith("### ")): + + if next_line.startswith("```"): + # It's a snippet, whatever found until now is text + if content: + parts["explanation"].append( + { + "type": "text", + "sequence_num": sequence_num, + "value": content + } + ) + sequence_num += 1 + content = [] + + next_line = next(lines) + while not next_line.startswith("```"): + content.append(next_line) + next_line = next(lines) + # Snippet is over + parts["explanation"].append( + { + "type": "code", + "sequence_num": sequence_num, + "value": content + } + ) + sequence_num += 1 + content = [] + next_line = next(lines) + continue + else: + # It's a text, go on. + content.append(next_line) + next_line = next(lines) + + # All done + if content: + parts["explanation"].append( + { + "type": "text", + "sequence_num": sequence_num, + "value": content + } + ) + + return next_line, parts + + +with open(fname, 'r+', encoding="utf-8") as f: + lines = iter(f.readlines()) + line = next(lines) + result = [] + try: + while True: + if line.startswith("## "): + # A section is encountered + current_section_name = line.replace("## ", "").strip() + line = next(lines) + # Until a new section is encountered + while not (line.startswith("## " )): + # check if it's a H3 + if line.startswith("### "): + # An example is encountered + title = line.replace("### ", "") + example_details = { + "id": current_example, + "title": line.replace("### ", ""), + "section": current_section_name + } + line, example_details["parts"] = parse_example_parts(lines) + result.append(example_details) + current_example += 1 + else: + # todo catch section text + line = next(lines) + else: + line = next(lines) + + except StopIteration: + pprint.pprint(result, indent=2) + print(len(result)) + + + + From c475cbfe826f2b65d3674f3acf724f14f97c50dc Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Wed, 1 May 2019 19:55:46 +0530 Subject: [PATCH 009/221] Use absolute path for the pager. Fixes https://github.com/satwikkansal/wtfpython/issues/119 --- wtfpython-pypi/wtf_python/main.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/wtfpython-pypi/wtf_python/main.py b/wtfpython-pypi/wtf_python/main.py index 73de9b82..b8bfdced 100644 --- a/wtfpython-pypi/wtf_python/main.py +++ b/wtfpython-pypi/wtf_python/main.py @@ -1,3 +1,5 @@ +from os.path import dirname, join, realpath + import pydoc try: from urllib.request import urlretrieve @@ -6,13 +8,14 @@ url = ("https://raw.githubusercontent.com/satwikkansal/" "wtfpython/master/README.md") -file_name = "content.md" + +file_path = join(dirname(dirname(realpath(__file__))), "content.md") def fetch_updated_doc(): try: print("Fetching the latest version...") - urlretrieve(url, file_name) + urlretrieve(url, file_path) print("Done!") except Exception as e: print(e) @@ -21,7 +24,7 @@ def fetch_updated_doc(): def render_doc(): - with open(file_name, 'r') as f: + with open(file_path, 'r', encoding="utf-8") as f: content = f.read() pydoc.pager(content) From 5c8c4c58439dd2ce020c536343b2b4460ce3cd02 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 6 May 2019 23:47:24 +0530 Subject: [PATCH 010/221] Get the generator in a working state --- irrelevant/json_generator.py | 239 +++++++++++++++++++++++++---------- 1 file changed, 175 insertions(+), 64 deletions(-) diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py index 86820f19..ea75cb5c 100644 --- a/irrelevant/json_generator.py +++ b/irrelevant/json_generator.py @@ -1,52 +1,85 @@ +import json import pprint fname = "/Users/300041709/code/self/wtfpython/README.md" examples = [] # The globals current_example = 1 +sequence_num = 1 current_section_name = "" -def parse_example_parts(lines): +STATEMENT_PREFIXES = ["...", ">>> ", "$ "] + + +def generate_code_block(statements, output): + global sequence_num + result = { + "type": "code", + "sequence_num": sequence_num, + "statements": statements, + "output": output + } + sequence_num += 1 + return result + + +def generate_markdown_block(lines): + global sequence_num + result = { + "type": "markdown", + "sequence_num": sequence_num, + "value": lines + } + sequence_num += 1 + return result + +def is_interactive_statement(line): + for prefix in STATEMENT_PREFIXES: + if line.startswith(prefix): + return True + return False + +def parse_example_parts(lines, example_title_line): parts = { "build_up": [], "explanation": [] } - next_line = next(lines) - sequence_num = 1 content = [] + statements_so_far = [] + output_so_far = [] + next_line = example_title_line # store build_up till an H4 (explanation) is encountered while not next_line.startswith("#### "): # Watching out for the snippets if next_line.startswith("```"): # It's a snippet, whatever found until now is text + is_interactive = False if content: - parts["build_up"].append( - { - "type": "text", - "sequence_num": sequence_num, - "value": content - } - ) - sequence_num += 1 + parts["build_up"].append(generate_markdown_block(content)) content = [] next_line = next(lines) + while not next_line.startswith("```"): - content.append(next_line) + if is_interactive_statement(next_line): + is_interactive = True + if (output_so_far): + parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + statements_so_far, output_so_far = [], [] + statements_so_far.append(next_line) + else: + # can be either output or normal code + if is_interactive: + output_so_far.append(next_line) + else: + statements_so_far.append(next_line) next_line = next(lines) + # Snippet is over - parts["build_up"].append( - { - "type": "code", - "sequence_num": sequence_num, - "value": content - } - ) - sequence_num += 1 - content = [] + parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + statements_so_far, output_so_far = [], [] next_line = next(lines) - continue else: # It's a text, go on. content.append(next_line) @@ -54,51 +87,43 @@ def parse_example_parts(lines): # Explanation encountered, save any content till now (if any) if content: - parts["build_up"].append( - { - "type": "text", - "sequence_num": sequence_num, - "value": content - } - ) + parts["build_up"].append(generate_markdown_block(content)) # Reset stuff - sequence_num = 1 content = [] + statements_so_far, output_so_far = [], [] # store lines again until --- or another H3 is encountered while not (next_line.startswith("---") or next_line.startswith("### ")): - if next_line.startswith("```"): # It's a snippet, whatever found until now is text + is_interactive = False if content: - parts["explanation"].append( - { - "type": "text", - "sequence_num": sequence_num, - "value": content - } - ) - sequence_num += 1 + parts["build_up"].append(generate_markdown_block(content)) content = [] next_line = next(lines) + while not next_line.startswith("```"): - content.append(next_line) + if is_interactive_statement(next_line): + is_interactive = True + if (output_so_far): + parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + statements_so_far, output_so_far = [], [] + statements_so_far.append(next_line) + else: + # can be either output or normal code + if is_interactive: + output_so_far.append(next_line) + else: + statements_so_far.append(next_line) next_line = next(lines) + # Snippet is over - parts["explanation"].append( - { - "type": "code", - "sequence_num": sequence_num, - "value": content - } - ) - sequence_num += 1 - content = [] + parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + statements_so_far, output_so_far = [], [] next_line = next(lines) - continue else: # It's a text, go on. content.append(next_line) @@ -106,16 +131,105 @@ def parse_example_parts(lines): # All done if content: - parts["explanation"].append( - { - "type": "text", - "sequence_num": sequence_num, - "value": content - } - ) + parts["explanation"].append(generate_markdown_block(content)) return next_line, parts +def remove_from_beginning(tokens, line): + for token in tokens: + if line.startswith(token): + line = line.replace(token, "") + return line + + +def inspect_and_sanitize_code_lines(lines): + tokens_to_remove = STATEMENT_PREFIXES + result = [] + is_print_present = False + for line in lines: + line = remove_from_beginning(tokens_to_remove, line) + if line.startswith("print ") or line.startswith("print("): + is_print_present = True + result.append(line) + return is_print_present, result + +def convert_to_cells(cell_contents): + cells = [] + for stuff in cell_contents: + if stuff["type"] == "markdown": + # todo add metadata later + cells.append( + { + "cell_type": "markdown", + "metadata": {}, + "source": stuff["value"] + } + ) + elif stuff["type"] == "code": + is_print_present, sanitized_code = inspect_and_sanitize_code_lines(stuff["statements"]) + if is_print_present: + cells.append( + { + "cell_type": "code", + "metadata": { + "collapsed": True + }, + "execution_count": None, + "outputs": [{ + "name": "stdout", + "output_type": "stream", + "text": stuff["output"] + }], + "source": sanitized_code + } + ) + else: + cells.append( + { + "cell_type": "code", + "execution_count": None, + "metadata": { + "collapsed": True + }, + "outputs": [{ + "data": { + "text/plain": stuff["output"] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": None + }], + "source": sanitized_code + } + ) + + return cells + + +def convert_to_notebook(parsed_json): + result = { + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 + } + for example in parsed_json: + parts = example["parts"] + build_up = parts.get("build_up") + explanation = parts.get("explanation") + notebook_path = "test.ipynb" + + if(build_up): + result["cells"] += convert_to_cells(build_up) + + if(explanation): + result["cells"] += convert_to_cells(explanation) + + pprint.pprint(result, indent=2) + with open(notebook_path, "w") as f: + json.dump(result, f) + + with open(fname, 'r+', encoding="utf-8") as f: lines = iter(f.readlines()) @@ -126,6 +240,7 @@ def parse_example_parts(lines): if line.startswith("## "): # A section is encountered current_section_name = line.replace("## ", "").strip() + section_text = [] line = next(lines) # Until a new section is encountered while not (line.startswith("## " )): @@ -138,19 +253,15 @@ def parse_example_parts(lines): "title": line.replace("### ", ""), "section": current_section_name } - line, example_details["parts"] = parse_example_parts(lines) + line, example_details["parts"] = parse_example_parts(lines, line) result.append(example_details) current_example += 1 else: - # todo catch section text + section_text.append(line) line = next(lines) else: line = next(lines) except StopIteration: pprint.pprint(result, indent=2) - print(len(result)) - - - - + convert_to_notebook(result) From 45bec627d1511690fa7f1b5623860da94bb74822 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 6 May 2019 23:49:57 +0530 Subject: [PATCH 011/221] Add todos --- irrelevant/json_generator.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py index ea75cb5c..cfebf4f5 100644 --- a/irrelevant/json_generator.py +++ b/irrelevant/json_generator.py @@ -1,3 +1,15 @@ +""" +An inefficient monolithic piece of code that'll generate jupyter notebook +from the projects main README. + +TODO + +- CLI arguments for running this thing. +- Add it to prepush hook +- Use templates? + +""" + import json import pprint fname = "/Users/300041709/code/self/wtfpython/README.md" From 31dcd9b0629f61e6f577c76c31addaf55609109c Mon Sep 17 00:00:00 2001 From: hippie Date: Fri, 7 Jun 2019 02:15:34 +0800 Subject: [PATCH 012/221] add encoding (#122) if not set encoding attr,there maybe have some exceptions when open reading. --- wtfpython-pypi/wtf_python/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wtfpython-pypi/wtf_python/main.py b/wtfpython-pypi/wtf_python/main.py index 621995af..5799178c 100644 --- a/wtfpython-pypi/wtf_python/main.py +++ b/wtfpython-pypi/wtf_python/main.py @@ -21,7 +21,7 @@ def fetch_updated_doc(): def render_doc(): - with open(file_name, 'r') as f: + with open(file_name, 'r', encoding='utf-8') as f: content = f.read() pydoc.pager(content) From f03f7dcad956c941e9f9d9247f50e8ffde98e013 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Fri, 7 Jun 2019 23:48:07 +0530 Subject: [PATCH 013/221] Some hideous typora corrections and a new snippets added Also closes https://github.com/satwikkansal/wtfpython/issues/73 --- README.md | 55 +++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 8f116bdb..d4de4d7f 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

+

What the f*ck Python! 🐍

An interesting collection of surprising snippets and lesser-known Python features.

@@ -201,11 +201,10 @@ Makes sense, right? * All length 0 and length 1 strings are interned. * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) - + + When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. + Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. - --- ### ▶ Time for some hash brownies! @@ -246,7 +245,7 @@ some_dict[5] = "Python" --- -### ▶ Return return everywhere! +### ▶ Keep trying? * ```py def some_func(): @@ -254,18 +253,55 @@ def some_func(): return 'from_try' finally: return 'from_finally' + +def another_func(): + for _ in range(3): + try: + continue + finally: + print("Finally!") + +def one_more_func(): # A gotcha! + try: + for i in range(3): + try: + 1 / i + except ZeroDivisionError: + # Let's throw it here and handle it outside for loop + raise ZeroDivisionError("A trivial divide by zero error") + finally: + print("Iteration", i) + break + except ZeroDivisionError as e: + print("Zero division error ocurred", e) ``` **Output:** + ```py >>> some_func() 'from_finally' + +>>> another_func() +Finally! +Finally! +Finally! + +>>> 1 / 0 +Traceback (most recent call last): + File "", line 1, in +ZeroDivisionError: division by zero + +>>> one_more_func() +Iteration 0 + ``` #### 💡 Explanation: - 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. - 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. +- The caveat here is, if the finally clause executes a `return` or `break` statement, the temporarily saved exception is discarded. --- @@ -529,11 +565,11 @@ We didn't assign 3 "X"s or did we? When we initialize `row` variable, this visualization explains what happens in the memory -![image](/images/tic-tac-toe/after_row_initialized.png) +![image](images/tic-tac-toe/after_row_initialized.png) And 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`) -![image](/images/tic-tac-toe/after_board_initialized.png) +![image](images/tic-tac-toe/after_board_initialized.png) We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue). @@ -1183,8 +1219,9 @@ a, b = a[b] = {}, 5 (target_list "=")+ (expression_list | yield_expression) ``` and - > 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. - + +> 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. + * 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`). * After the expression list is evaluated, it's 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`. @@ -1318,6 +1355,7 @@ Shouldn't that be 100? * **Don't mix tabs and spaces!** The character just preceding return is a "tab", and the code is indented by multiple of "4 spaces" elsewhere in the example. * This is how Python handles tabs: + > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...> * So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. * Python 3 is kind enough to throw an error for such cases automatically. @@ -1978,6 +2016,7 @@ There we go. #### 💡 Explanation: - This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means). - Quoting from the PEP-401 + > Recognized that the != inequality operator in Python 3.0 was a horrible, finger pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. - There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/). From 3806284f78b1631fb693bd828c55b9ed4885c5cc Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Fri, 7 Jun 2019 23:48:51 +0530 Subject: [PATCH 014/221] Update content.md --- wtfpython-pypi/content.md | 79 ++++++++++++++++++++++----------------- 1 file changed, 44 insertions(+), 35 deletions(-) diff --git a/wtfpython-pypi/content.md b/wtfpython-pypi/content.md index 486a98e7..9827fc46 100644 --- a/wtfpython-pypi/content.md +++ b/wtfpython-pypi/content.md @@ -1,9 +1,10 @@

-

What the f*ck Python! 🐍

-

An interesting collection of surprising snippets and lesser-known Python features.

+

What the f*ck Python! 🐍

+

An interesting collection of surprising snippets and lesser-known Python features.

[![WTFPL 2.0][license-image]][license-url] +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) 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 to a regular user at first sight. @@ -13,7 +14,7 @@ While some of the examples you see below may not be WTFs in the truest sense, bu If you're an experienced Python programmer, you can take it as a challenge to get most of them right in first attempt. You may be already familiar with some of these examples, and I might be able to revive sweet old memories of yours being bitten by these gotchas :sweat_smile: -If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). +PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). So, here we go... @@ -77,7 +78,7 @@ So, here we go... - [▶ Yes, it exists!](#-yes-it-exists) - [▶ Inpinity *](#-inpinity-) - [▶ Mangling time! *](#-mangling-time-) - - [Section: Miscallaneous](#section-miscallaneous) + - [Section: Miscellaneous](#section-miscellaneous) - [▶ `+=` is faster](#--is-faster) - [▶ Let's make a giant string!](#-lets-make-a-giant-string) - [▶ Explicit typecast of strings](#-explicit-typecast-of-strings) @@ -97,22 +98,22 @@ All the examples are structured like below: > ### ▶ Some fancy Title * > The asterisk at the end of the title indicates the example was not present in the first release and has been recently added. -> +> > ```py > # Setting up the code. > # Preparation for the magic... > ``` -> +> > **Output (Python version):** > ```py > >>> triggering_statement > Probably unexpected output > ``` > (Optional): One line describing the unexpected output. -> -> +> +> > #### 💡 Explanation: -> +> > * Brief explanation of what's happening and why is it happening. > ```py > Setting up examples for clarification (if necessary) @@ -200,10 +201,10 @@ Makes sense, right? + In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation dependent. There are some facts that can be used to guess if a string will be interned or not: * All length 0 and length 1 strings are interned. * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) - * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. + * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) + When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. -+ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. But since the python bytecode generated after compilation is stored in `.pyc` files, the strings greater than length of 20 are discarded for peephole optimization (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`) ++ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. --- @@ -241,7 +242,7 @@ some_dict[5] = "Python" True ``` **Note:** Objects with different values may also have same hash (known as hash collision). -* When the statement `some_dict[5] = "Python"` is executed, the existing value "JavaScript" is overwritten with "Python" because Python recongnizes `5` and `5.0` as the same keys of the dictionary `some_dict`. +* When the statement `some_dict[5] = "Python"` is executed, the existing value "JavaScript" is overwritten with "Python" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`. * This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains beautifully the rationale behind it. --- @@ -296,16 +297,24 @@ True * But why did the `is` operator evaluated to `False`? Let's see with this snippet. ```py class WTF(object): - def __init__(self): print("I ") - def __del__(self): print("D ") + def __init__(self): print("I") + def __del__(self): print("D") ``` **Output:** ```py >>> WTF() is WTF() - I I D D + I + I + D + D + False >>> id(WTF()) == id(WTF()) - I D I D + I + D + I + D + True ``` As you may observe, the order in which the objects are destroyed is what made all the difference here. @@ -530,7 +539,7 @@ And when the `board` is initialized by multiplying the `row`, this is what happe We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue). ```py ->>> board = [(['']*3)*3] # board = = [['']*3 for _ in range(3)] +>>> board = [['']*3 for _ in range(3)] >>> board[0][0] = "X" >>> board [['X', '', ''], ['', '', ''], ['', '', '']] @@ -547,7 +556,7 @@ for x in range(7): def some_func(): return x funcs.append(some_func) - results.append(some_func()) + results.append(some_func()) # note the function call here funcs_results = [func() for func in funcs] ``` @@ -766,10 +775,10 @@ for item in mixed_list: **Output:** ```py ->>> booleans_found_so_far -0 >>> integers_found_so_far 4 +>>> booleans_found_so_far +0 ``` 2\. @@ -830,7 +839,7 @@ class C(A): pass ``` -**Ouptut:** +**Output:** ```py >>> A.x, B.x, C.x (1, 1, 1) @@ -1135,7 +1144,7 @@ str and type(other) is SomeClass and super().__eq__(other) ) - + # When we define a custom __eq__, Python stops automatically inheriting the # __hash__ method, so we need to define it as well __hash__ = str.__hash__ @@ -1148,7 +1157,7 @@ str >>> s = SomeClass('s') >>> some_dict[s] = 40 >>> some_dict - {'s': 40} + {'s': 40, 's': 42} >>> keys = list(some_dict.keys()) >>> type(keys[0]), type(keys[1]) (__main__.SomeClass, str) @@ -1313,7 +1322,7 @@ Shouldn't that be 100? > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...> * So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. * Python 3 is kind enough to throw an error for such cases automatically. - + **Output (Python 3.x):** ```py TabError: inconsistent use of tabs and spaces in indentation @@ -1697,7 +1706,7 @@ a += [5, 6, 7, 8] * The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged. -* The expression `a + =[5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. +* The expression `a += [5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. --- @@ -1731,7 +1740,7 @@ UnboundLocalError: local variable 'a' referenced before assignment a += 1 return a ``` - + **Output:** ```py >>> another_func() @@ -1895,7 +1904,7 @@ Sshh.. It's a super secret. #### 💡 Explanation: + `antigravity` module is one of the few easter eggs released by Python developers. + `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python. -+ Well, there's more to it. There's **another easter egg inside the easter egg**. If look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/). ++ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/). --- @@ -2115,7 +2124,7 @@ AttributeError: 'Yo' object has no attribute '__honey' True ``` -Why did `Yo()._Yo__honey` worked? Only Indian readers would understand. +Why did `Yo()._Yo__honey` work? Only Indian readers would understand. #### 💡 Explanation: @@ -2127,7 +2136,7 @@ Why did `Yo()._Yo__honey` worked? Only Indian readers would understand. --- -## Section: Miscallaneous +## Section: Miscellaneous ### ▶ `+=` is faster @@ -2272,7 +2281,7 @@ nan ### ▶ Minor Ones * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) - + **💡 Explanation:** If `join()` is a method on a string then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API. @@ -2350,7 +2359,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' * https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines * https://stackoverflow.com/questions/1011431/common-pitfalls-in-python * https://www.python.org/doc/humor/ -* https://www.satwikkansal.xyz/archives/posts/python/My-Python-archives/ +* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 # 🎓 License @@ -2365,12 +2374,12 @@ The idea and design for this collection were initially inspired by Denys Dovhan' If you have any wtfs, ideas or suggestions, please share. -## Want to share wtfpython with friends? +## Surprise your geeky pythonist friends? -You can use these quick links for Twitter and Linkedin. +You can use these quick links to recommend wtfpython to your friends, -[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) | -[Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) +[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) + | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) ## Need a pdf version? From bc68ae0ff32480c715f08800ece3bd0d709be912 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 00:23:33 +0530 Subject: [PATCH 015/221] Update evaluation time discrepency example: Add another snippet Resolves https://github.com/satwikkansal/wtfpython/issues/41 --- README.md | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d4de4d7f..116032de 100644 --- a/README.md +++ b/README.md @@ -408,7 +408,7 @@ for i, some_dict[i] in enumerate(some_string): --- -### ▶ Evaluation time discrepancy +### ▶ Evaluation time discrepancy ^ 1\. ```py @@ -444,6 +444,23 @@ array_2[:] = [1,2,3,4,5] [1,2,3,4,5] ``` +3\. + +```py +array_3 = [1, 2, 3] +array_4 = [10, 20, 30] +g = (i + j for i in array_3 for j in array_4) + +array_3 = [4, 5, 6] +array_4 = [400, 500, 600] +``` + +**Output:** +```py +>>> print(list(g)) +[401, 501, 601, 402, 502, 602, 403, 503, 603] +``` + #### 💡 Explanation - In a [generator](https://wiki.python.org/moin/Generators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at runtime. @@ -451,6 +468,9 @@ array_2[:] = [1,2,3,4,5] - 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. - In the first case, `array_1` is binded 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). - 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]`). +- Okay, going by the logic discussed so far, shouldn't be the value of `list(g)` 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://www.python.org/dev/peps/pep-0289/#the-details) + > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run. + --- @@ -1221,7 +1241,7 @@ a, b = a[b] = {}, 5 and > 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. - + * 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`). * After the expression list is evaluated, it's 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`. From e0cb30bf3be6cd0e9988a0530536f239dfc9d6a7 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 00:41:58 +0530 Subject: [PATCH 016/221] Modifying a dictionary while iterating over it: Add note Resolves https://github.com/satwikkansal/wtfpython/issues/53 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 116032de..8378981c 100644 --- a/README.md +++ b/README.md @@ -469,8 +469,8 @@ array_4 = [400, 500, 600] - In the first case, `array_1` is binded 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). - 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]`). - Okay, going by the logic discussed so far, shouldn't be the value of `list(g)` 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://www.python.org/dev/peps/pep-0289/#the-details) + > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run. - --- @@ -1423,7 +1423,7 @@ Yes, it runs for exactly **eight** times and stops. * Iteration over a dictionary that you edit at the same time is not supported. * It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. * How deleted keys are handled and when the resize occurs might be different for different Python implementations. -* For more information, you may refer to this StackOverflow [thread](https://stackoverflow.com/questions/44763802/bug-in-python-dict) explaining a similar example in detail. +* So for Python versions other than Python 2.7 - Python 3.5 the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. --- From 092dd096bfc8cf9ceebef444597958ee5f4c0b98 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 02:53:53 +0530 Subject: [PATCH 017/221] Expand strings and backslashes Resolves https://github.com/satwikkansal/wtfpython/issues/69 --- README.md | 51 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 8378981c..05bbe158 100644 --- a/README.md +++ b/README.md @@ -469,7 +469,7 @@ array_4 = [400, 500, 600] - In the first case, `array_1` is binded 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). - 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]`). - Okay, going by the logic discussed so far, shouldn't be the value of `list(g)` 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://www.python.org/dev/peps/pep-0289/#the-details) - + > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run. --- @@ -702,30 +702,47 @@ SyntaxError: invalid syntax --- -### ▶ Backslashes at the end of string +### ▶ Strings and the backslashes\ **Output:** -``` ->>> print("\\ C:\\") -\ C:\ ->>> print(r"\ C:") -\ C: ->>> print(r"\ C:\") +```py +>>> print("\"") +" - File "", line 1 - print(r"\ C:\") - ^ +>>> print(r"\"") +\" + +>>> print(r"\") +File "", line 1 + print(r"\") + ^ SyntaxError: EOL while scanning string literal + +>>> r'\'' == "\\'" +True ``` #### 💡 Explanation -- In a raw string literal, as indicated by the prefix `r`, the backslash doesn't have the special meaning. - ```py - >>> print(repr(r"wt\"f")) - 'wt\\"f' - ``` -- What the interpreter actually does, though, is simply change the behavior of backslashes, so they pass themselves and the following character through. That's why backslashes don't work at the end of a raw string. +- In a normal python string, the backslash is used to escape characters that may have special meaning (like single-quote, double-quote and the backslash itself). + ```py + >>> 'wt\"f' + 'wt"f' + ``` +- 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. + ```py + >>> r'wt\"f' == 'wt\\"f' + True + >>> print(repr(r'wt\"f') + 'wt\\"f' + + >>> print("\n") + + + >>> print(r"\\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. --- From c52919b9ec6b3c945b30730a786af15ad9507ca3 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 14:21:19 +0530 Subject: [PATCH 018/221] Add new snippet: Splitsies Resolves https://github.com/satwikkansal/wtfpython/issues/80 --- README.md | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 05bbe158..2947bb7b 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,44 @@ Makes sense, right? --- +### ▶ Splitsies ^ + +```py +>>> 'a'.split() +['a'] + +# is same as +>>> 'a'.split(' ') +['a'] + +# but +>>> len(''.split()) +0 + +# isn't the same as +>>> len(''.split(' ')) +1 +``` + +#### 💡 Explanation: + +- It might appear at first that the default seperator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split), + > If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`. + > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`. +- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear, + ```py + >>> ' a '.split(' ') + ['', 'a', ''] + >>> ' a '.split() + ['a'] + >>> ''.split(' ') + [''] + ``` + +--- + + + ### ▶ Time for some hash brownies! 1\. @@ -702,7 +740,7 @@ SyntaxError: invalid syntax --- -### ▶ Strings and the backslashes\ +### ▶ Strings and the backslashes\ ^ **Output:** ```py From a33f715b2620e60d1ae2a15c998e907e8d5e4d17 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 14:49:59 +0530 Subject: [PATCH 019/221] Let's meet Friendly Language Uncle For Life: Add notes for non-interactive evn Resolves https://github.com/satwikkansal/wtfpython/issues/94 --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2947bb7b..dc6fd7fa 100644 --- a/README.md +++ b/README.md @@ -2071,7 +2071,7 @@ Braces? No way! If you think that's disappointing, use Java. --- -### ▶ Let's meet Friendly Language Uncle For Life * +### ▶ Let's meet Friendly Language Uncle For Life ^ **Output (Python 3.x)** ```py @@ -2094,6 +2094,11 @@ There we go. > Recognized that the != inequality operator in Python 3.0 was a horrible, finger pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. - There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/). +- It works well on interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working, + ```py + from __future__ import barry_as_FLUFL + print(eval('"Ruby" <> "Python"')) + ``` --- From 85352fc45d80f20d46fc4d6cb5a0cea483408089 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 16:30:53 +0530 Subject: [PATCH 020/221] Add example: Ellipsis Resolves https://github.com/satwikkansal/wtfpython/issues/96 --- README.md | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/README.md b/README.md index dc6fd7fa..e32e1cec 100644 --- a/README.md +++ b/README.md @@ -2203,6 +2203,66 @@ Try block executed successfully... - `else` clause after try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. --- +### ▶ Ellipsis ^ + +```py +def some_func(): + Ellipsis +``` + +**Output** +```py +>>> some_func() +# No output, No Error + +>>> SomeRandomString +Traceback (most recent call last): + File "", line 1, in +NameError: name 'SomeRandomString' is not defined + +>>> Ellipsis +Ellipsis +``` + +#### 💡 Explanation +- In Python, `Ellipsis` is a globally available builtin object which is equivalent to `...`. + ```py + >>> ... + Ellipsis + ``` +- Eliipsis can be used for several purposes, + + As a placeholder for code that hasn't been written yet (just like `pass` statement) + + In slicing syntax to represent the full slices in remaining direction + ```py + >>> import numpy as np + >>> three_dimensional_array = np.arange(8).reshape(2, 2, 2) + array([ + [ + [0, 1], + [2, 3] + ], + + [ + [4, 5], + [6, 7] + ] + ]) + ``` + So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions + ```py + >>> three_dimensional_array[:,:,1] + array([[1, 3], + [5, 7]]) + >>> three_dimensional_array[..., 1] # using Ellipsis. + array([[1, 3], + [5, 7]]) + ``` + Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`) + + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`)) + + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the "no argument passed" and "None value passed" scenarios). + + +--- ### ▶ Inpinity * From 72e39d3248facb57b11f01f30dee8f99cda6548d Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 23:25:37 +0530 Subject: [PATCH 021/221] Update example "is is not what it is" Related to https://github.com/satwikkansal/wtfpython/issues/100 --- README.md | 49 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index cbe9c683..72e1ebda 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ True >>> a is b False ->>> a, b = "wtf!", "wtf!" +>>> a = "wtf!"; b = "wtf!"; >>> a is b True ``` @@ -513,10 +513,11 @@ array_4 = [400, 500, 600] --- -### ▶ `is` is not what it is! +### ▶ Messing around with `is` operator^ The following is a very famous example present all over the internet. +1\. ```py >>> a = 256 >>> b = 256 @@ -527,6 +528,37 @@ True >>> b = 257 >>> a is b False +``` + +2\. + +```py +>>> a = [] +>>> b = [] +>>> a is b +False + +>>> a = tuple() +>>> b = tuple() +>>> a is b +True +``` + +3\. +**Output (< Python 3.7)** +``` +>>> a, b = 257, 257 +True + +>>> a = 257; b = 257 +>>> a is b +True +``` + +**Output (Python 3.7)** +``` +>>> a, b = 257, 257 +False >>> a = 257; b = 257 >>> a is b @@ -541,9 +573,8 @@ True * `==` operator compares the values of both the operands and checks if they are the same. * So `is` is for reference equality and `==` is for value equality. An example to clear things up, ```py - >>> [] == [] - True - >>> [] is [] # These are two empty lists at two different memory locations. + >>> class A: pass + >>> A() is A() # These are two empty objects at two different memory locations. False ``` @@ -575,8 +606,11 @@ Quoting from https://docs.python.org/3/c-api/long.html Here 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. +Similar 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, + **Both `a` and `b` refer to the same object when initialized with same value in the same line.** +**Output (< Python 3.7)** ```py >>> a, b = 257, 257 >>> id(a) @@ -593,6 +627,7 @@ Here the interpreter isn't smart enough while executing `y = 257` to recognize t * 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. * 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. +* 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://github.com/satwikkansal/wtfpython/issues/100) for updates. --- @@ -776,6 +811,7 @@ True 'wt\\"f' >>> print("\n") + ``` >>> print(r"\\n") @@ -2262,8 +2298,7 @@ Ellipsis + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`)) + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the "no argument passed" and "None value passed" scenarios). - ---- +--- ### ▶ Inpinity * From 9ea7ab0c5a05cbafc41c4432293202a7836d908f Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 00:07:02 +0530 Subject: [PATCH 022/221] New example: The chicken-egg problem Closes https://github.com/satwikkansal/wtfpython/issues/101 --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/README.md b/README.md index 72e1ebda..c9b68ee1 100644 --- a/README.md +++ b/README.md @@ -730,6 +730,54 @@ Even when the values of `x` were different in every iteration prior to appending --- +### ▶ The chicken-egg problem ^ + +1\. +```py +>>> isinstance(3, int) +True +>>> isinstance(type, object) +True +>>> isinstance(object, type) +True +``` + +2\. So which is the ultimate, base class? And wait, there's more to the confusion + +```py +>>> class A: pass +>>> isinstance(A, A) +False +>>> isinstance(type, type) +True +>>> isinstance(object, object) +True +``` + +3\. + +```py +>>> issubclass(int, object) +True +>>> issubclass(type, object) +True +>>> issubclass(object, type) +False +``` + + +#### 💡 Explanation + +- `type` is a [metaclass](https://realpython.com/python-metaclasses/) in Python. +- **Everything** is an `object` in Python, which includes classes as well as their objects (instances). +- class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`. +- There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking 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, + + class A is instance of class B, and class B is an instance of class A. + + class A is an instance of itself. +- These relationships between `object` and `type` (both being instances of eachother as well as themselves) exist in Python because of "cheating" at implementation level. + +--- + ### ▶ `is not ...` is not `is (not ...)` ```py From 2bfa6d2e5bb123a177d6c4c4c20a20ac3f822fca Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 03:59:09 +0530 Subject: [PATCH 023/221] Let's make a giant string: Use %timeit for measuring time Fixes https://github.com/satwikkansal/wtfpython/issues/106 --- README.md | 63 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index c9b68ee1..f9a22ab4 100644 --- a/README.md +++ b/README.md @@ -2450,40 +2450,47 @@ def convert_list_to_string(l, iters): ``` **Output:** + ```py ->>> timeit(add_string_with_plus(10000)) -1000 loops, best of 3: 972 µs per loop ->>> timeit(add_bytes_with_plus(10000)) -1000 loops, best of 3: 815 µs per loop ->>> timeit(add_string_with_format(10000)) -1000 loops, best of 3: 508 µs per loop ->>> timeit(add_string_with_join(10000)) -1000 loops, best of 3: 878 µs per loop ->>> l = ["xyz"]*10000 ->>> timeit(convert_list_to_string(l, 10000)) -10000 loops, best of 3: 80 µs per loop +# Executed in ipython shell using %timeit for better readablity of results. +# You can also use the timeit module in normal python shell/scriptm=, example usage below +# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) + +>>> NUM_ITERS = 1000 +>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) +124 µs ± 4.73 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) +>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) +211 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_format(NUM_ITERS) +61 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_join(NUM_ITERS) +117 µs ± 3.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> l = ["xyz"]*NUM_ITERS +>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) +10.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` Let's increase the number of iterations by a factor of 10. ```py ->>> timeit(add_string_with_plus(100000)) # Linear increase in execution time -100 loops, best of 3: 9.75 ms per loop ->>> timeit(add_bytes_with_plus(100000)) # Quadratic increase -1000 loops, best of 3: 974 ms per loop ->>> timeit(add_string_with_format(100000)) # Linear increase -100 loops, best of 3: 5.25 ms per loop ->>> timeit(add_string_with_join(100000)) # Linear increase -100 loops, best of 3: 9.85 ms per loop ->>> l = ["xyz"]*100000 ->>> timeit(convert_list_to_string(l, 100000)) # Linear increase -1000 loops, best of 3: 723 µs per loop +>>> NUM_ITERS = 10000 +>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time +1.26 ms ± 76.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase +6.82 ms ± 134 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase +645 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase +1.17 ms ± 7.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> l = ["xyz"]*NUM_ITERS +>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase +86.3 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` #### 💡 Explanation -- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) from here. It is generally used to measure the execution time of snippets. +- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces. - Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function) -- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for short strings). +- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings). - Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster. - `add_string_with_plus` didn't show a quadratic increase in execution time unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example. Had the statement been `s = s + "x" + "y" + "z"` instead of `s += "xyz"`, the increase would have been quadratic. ```py @@ -2493,10 +2500,10 @@ Let's increase the number of iterations by a factor of 10. s = s + "x" + "y" + "z" assert len(s) == 3*iters - >>> timeit(add_string_with_plus(10000)) - 100 loops, best of 3: 9.87 ms per loop - >>> timeit(add_string_with_plus(100000)) # Quadratic increase in execution time - 1 loops, best of 3: 1.09 s per loop + >>> %timeit -n100 add_string_with_plus(1000) + 388 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) + >>> %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time + 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` --- From 80a969a556f2a018941e537031367b1cca30a37a Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 17:34:50 +0530 Subject: [PATCH 024/221] Brace yourself: Add to explanation Resolves https://github.com/satwikkansal/wtfpython/issues/114 --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f9a22ab4..fbba80a7 100644 --- a/README.md +++ b/README.md @@ -2148,11 +2148,13 @@ from __future__ import braces SyntaxError: not a chance ``` -Braces? No way! If you think that's disappointing, use Java. +Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)? #### 💡 Explanation: -+ The `__future__` module is normally used to provide features from future versions of Python. The "future" here is however ironic. ++ The `__future__` module is normally used to provide features from future versions of Python. The "future" in this specific context is however ironic. + This is an easter egg concerned with the community's feelings on this issue. ++ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file. ++ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement. --- From bf967b0332ff2c5d645ab4f420f1c24a9b0702db Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 17:56:36 +0530 Subject: [PATCH 025/221] String can be tricky: Remove outdated snippet Related to https://github.com/satwikkansal/wtfpython/issues/120 --- README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index fbba80a7..71088cd5 100644 --- a/README.md +++ b/README.md @@ -179,13 +179,12 @@ True >>> b = "wtf!" >>> a is b False - ->>> a = "wtf!"; b = "wtf!"; ->>> a is b -True ``` 3\. + +**Output (< Python3.7 )** + ```py >>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' True @@ -203,8 +202,8 @@ Makes sense, right? * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) -+ When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. + Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. ++ Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). --- From 4d5a2f0d97d4dc348ad5f0754855268c6daa99dd Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 19:45:13 +0530 Subject: [PATCH 026/221] New example: Lossy zip of iterators Resolves https://github.com/satwikkansal/wtfpython/issues/121 --- README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/README.md b/README.md index 71088cd5..c8de2423 100644 --- a/README.md +++ b/README.md @@ -1251,6 +1251,55 @@ I've lost faith in truth! --- +### ▶ Lossy zip of iterators + +```py +>>> numbers = list(range(7)) +>>> numbers +[0, 1, 2, 3, 4, 5, 6] +>>> first_three, remaining = numbers[:3], numbers[3:] +>>> first_three, remaining +([0, 1, 2], [3, 4, 5, 6]) +>>> numbers_iter = iter(numbers) +>>> list(zip(numbers_iter, first_three)) +[(0, 0), (1, 1), (2, 2)] +# so far so good, let's zip the remaining +>>> list(zip(numbers_iter, remaining)) +[(4, 3), (5, 4), (6, 5)] +``` +Where did element `3` go from the `numbers` list? + +#### 💡 Explanation: + +- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function, + ```py + def zip(*iterables): + sentinel = object() + iterators = [iter(it) for it in iterables] + while iterators: + result = [] + for it in iterators: + elem = next(it, sentinel) + if elem is sentinel: + return + result.append(elem) + yield tuple(result) + ``` +- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. +- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`. +- The correct way to do the above using `zip` would be, + ```py + >>> numbers = list(range(7)) + >>> numbers_iter = iter(numbers) + >>> list(zip(first_three, numbers_iter)) + [(0, 0), (1, 1), (2, 2)] + >>> list(zip(remaining, numbers_iter)) + [(3, 3), (4, 4), (5, 5), (6, 6)] + ``` + The first argument of zip should be the one with fewest elements. + +--- + ### ▶ From filled to None in one instruction... ```py From 362447a5d252c3be58d76d68285bde9d077c87de Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 10 Jun 2019 00:14:01 +0530 Subject: [PATCH 027/221] Add new example: Disorder within order Resolves https://github.com/satwikkansal/wtfpython/issues/77 --- README.md | 115 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 109 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c8de2423..27995d39 100644 --- a/README.md +++ b/README.md @@ -261,26 +261,131 @@ some_dict[5] = "Python" "Ruby" >>> some_dict[5.0] "Python" ->>> some_dict[5] +>>> some_dict[5] # "Python" destroyed the existence of "JavaScript"? +"Python" + +>>> complex_five = 5 + 0j +>>> type(complex_five) +complex +>>> some_dict[complex_five] "Python" ``` -"Python" destroyed the existence of "JavaScript"? +So, why is Python all over the place? + #### 💡 Explanation * Python dictionaries check for equality and compare the hash value to determine if two keys are the same. * Immutable objects with same value always have the same hash in Python. ```py - >>> 5 == 5.0 + >>> 5 == 5.0 == 5 + 0j True - >>> hash(5) == hash(5.0) + >>> hash(5) == hash(5.0) == hash(5 + 0j) True ``` **Note:** Objects with different values may also have same hash (known as hash collision). * When the statement `some_dict[5] = "Python"` is executed, the existing value "JavaScript" is overwritten with "Python" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`. * This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains beautifully the rationale behind it. +--- + +### ▶ The disorder within order ^ + +```py +from collections import OrderedDict + +dictionary = dict() +dictionary[1] = 'a'; dictionary[2] = 'b'; + +ordered_dict = OrderedDict() +ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; + +another_ordered_dict = OrderedDict() +another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; + +class DictWithHash(dict): + """ + A dict that also implements __hash__ magic. + """ + __hash__ = lambda self: 0 + +class OrderedDictWithHash(OrderedDict): + """ + A dict that also implements __hash__ magic. + """ + __hash__ = lambda self: 0 +``` + +**Output** +```py +>>> dictionary == ordered_dict # If a == b +True +>>> dictionary == another_ordered_dict # and b == c +True +>>> ordered_dict == another_ordered_dict # the why isn't c == a ?? +False + +# We all know that a set consists of only unique elements, +# let's try making a set of these dictionaries and see what happens... + +>>> len({dictionary, ordered_dict, another_ordered_dict}) +Traceback (most recent call last): + File "", line 1, in +TypeError: unhashable type: 'dict' + +# Makes sense since dict don't have __hash__ implemented, let's use +# our wrapper classes. +>>> dictionary = DictWithHash() +>>> dictionary[1] = 'a'; dictionary[2] = 'b'; +>>> ordered_dict = OrderedDictWithHash() +>>> ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; +>>> another_ordered_dict = OrderedDictWithHash() +>>> another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; +>>> len({dictionary, ordered_dict, another_ordered_dict}) +1 +>>> len({ordered_dict, another_ordered_dict, dictionary}) # changing the order +2 +``` + +What is going on here? + +#### 💡 Explanation: + +- 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://docs.python.org/3/library/collections.html#ordereddict-objects) + > 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. +- The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. +- Okay, so why did changing the order affect the lenght 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, + ```py + >>> some_set = set() + >>> some_set.add(dictionary) # these are the mapping objects from the snippets above + >>> ordered_dict in some_set + True + >>> some_set.add(ordered_dict) + >>> len(some_set) + 1 + >>> another_ordered_dict in some_set + True + >>> some_set.add(another_ordered_dict) + >>> len(some_set) + 1 + + >>> another_set = set() + >>> another_set.add(ordered_dict) + >>> another_ordered_dict in another_set + False + >>> another_set.add(another_ordered_dict) + >>> len(another_set) + 2 + >>> dictionary in another_set + True + >>> another_set.add(another_ordered_dict) + >>> len(another_set) + 2 + ``` + 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`. + + --- ### ▶ Keep trying? * @@ -858,8 +963,6 @@ True 'wt\\"f' >>> print("\n") - ``` - >>> print(r"\\n") '\\\\n' From c6e0d795ff712032144c4d795d6eaa8a5b0df7d0 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 10 Jun 2019 23:22:08 +0530 Subject: [PATCH 028/221] Some minor changes, and add assertion example --- README.md | 53 +++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 27995d39..6283d3e8 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Python, being a beautifully designed high-level and interpreter-based programmin Here is a fun project to collect such tricky & counter-intuitive examples and lesser-known features in Python, attempting to discuss what exactly is happening under the hood! -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 think you'll find them interesting as well! +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! If you're an experienced Python programmer, you can take it as a challenge to get most of them right in first attempt. You may be already familiar with some of these examples, and I might be able to revive sweet old memories of yours being bitten by these gotchas :sweat_smile: @@ -104,10 +104,10 @@ All the examples are structured like below: > # Preparation for the magic... > ``` > -> **Output (Python version):** +> **Output (Python version(s)):** > ```py > >>> triggering_statement -> Probably unexpected output +> Some unexpected output > ``` > (Optional): One line describing the unexpected output. > @@ -118,7 +118,7 @@ All the examples are structured like below: > ```py > Setting up examples for clarification (if necessary) > ``` -> **Output:** +> **Output Output (Python version(s)):** > ```py > >>> trigger # some example that makes it easy to unveil the magic > # some justified output @@ -128,15 +128,15 @@ All the examples are structured like below: # Usage -A nice way to get the most out of these examples, in my opinion, will be just to read the examples chronologically, and for every example: +A nice way to get the most out of these examples, in my opinion, will be to just read them chronologically, and for every example: - Carefully read the initial code for setting up the example. If you're an experienced Python programmer, most of the times you will successfully anticipate what's going to happen next. - Read the output snippets and, + Check if the outputs are the same as you'd expect. + Make sure if you know the exact reason behind the output being the way it is. - - If no, 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)). + - 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)). - If yes, give a gentle pat on your back, and you may skip to the next example. -PS: You can also read WTFpython at the command line. There's a pypi package and an npm package (supports colored formatting) for the same. +PS: You can also read WTFPython at the command line. There's a pypi package and an npm package (which supports colored formatting) for the same. To install the npm package [`wtfpython`](https://www.npmjs.com/package/wtfpython) ```sh @@ -2185,7 +2185,10 @@ class SomeClass: --- -### ▶ Needle in a Haystack + +--- + +### ▶ Needles in a Haystack 1\. ```py @@ -2224,13 +2227,45 @@ e tuple() ``` +3\. Not asserting strongly enough + +```py +a = "python" +b = "javascript" +``` +**Output:** +```py +# An assert statement with an assertion failure message. +>>> assert(a == b, "Both languages are different") +# No AssertionError is raised +``` + #### 💡 Explanation: * For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. * For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. * `()` is a special token and denotes empty `tuple`. +* For 3, no `AssertionError` was raised because we're asserting entire tuple, instead of asserting the individual expression `a == b`. The following snippet will clear things up, + ```py + >>> a = "python" + >>> b = "javascript" + >>> assert a == b + Traceback (most recent call last): + File "", line 1, in + AssertionError + + >>> assert (a == b, "Values are not equal") + :1: SyntaxWarning: assertion is always true, perhaps remove parentheses? + + >>> assert a == b, "Values are not equal" + Traceback (most recent call last): + File "", line 1, in + AssertionError: Values aren not equal + ``` --- + + --- @@ -2658,6 +2693,8 @@ Let's increase the number of iterations by a factor of 10. >>> %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` +- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which, + > There should be one-- and preferably only one --obvious way to do it. --- From 8b4bbb219658477480474198a6b462b49aa73c8f Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Tue, 11 Jun 2019 00:43:32 +0530 Subject: [PATCH 029/221] Add new example: Wild imports --- README.md | 115 +++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 100 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 6283d3e8..841d40a7 100644 --- a/README.md +++ b/README.md @@ -1856,21 +1856,22 @@ print(x, ': x in global') ``` 3\. -``` -x = 1 -print([x for x in range(5)]) -print(x, ': x in global') -``` -**Output (on Python 2.x):** +**Output (Python 2.x):** ``` +>>> x = 1 +>>> print([x for x in range(5)]) [0, 1, 2, 3, 4] +>>> print(x, ': x in global') (4, ': x in global') ``` -**Output (on Python 3.x):** +**Output (Python 3.x):** ``` +>>> x = 1 +>>> print([x for x in range(5)]) [0, 1, 2, 3, 4] +>>> print(x, ': x in global') 1 : x in global ``` @@ -2183,12 +2184,10 @@ class SomeClass: - A generator expression has its own scope. - Starting from Python 3.X, list comprehensions also have their own scope. ---- - --- -### ▶ Needles in a Haystack +### ▶ Needles in a Haystack ^ 1\. ```py @@ -2227,7 +2226,31 @@ e tuple() ``` -3\. Not asserting strongly enough +3\. + +``` +ten_words_list = [ + "some", + "very", + "big", + "list", + "that" + "consists", + "of", + "exactly", + "ten", + "words" +] +``` + +**Output** + +```py +>>> len(ten_words_list) +9 +``` + +4\. Not asserting strongly enough ```py a = "python" @@ -2244,7 +2267,12 @@ b = "javascript" * For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. * For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. * `()` is a special token and denotes empty `tuple`. -* For 3, no `AssertionError` was raised because we're asserting entire tuple, instead of asserting the individual expression `a == b`. The following snippet will clear things up, +* In 3, as you might have already figured out, there's a missing comma after 5th element (`"that"`) in the list. So by implicit string literal concatenation, + ```py + >>> ten_words_list + ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] + ``` +* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up, ```py >>> a = "python" >>> b = "javascript" @@ -2264,7 +2292,60 @@ b = "javascript" --- +### ▶ Wild imports + +```py +# File: module.py + +def some_weird_name_func_(): + print("works!") + +def _another_weird_name_func(): + print("works!") + +``` + +**Output** + +```py +>>> from module import * +>>> some_weird_name_func_() +"works!" +>>> _another_weird_name_func() +Traceback (most recent call last): + File "", line 1, in +NameError: name '_another_weird_name_func' is not defined +``` + +#### 💡 Explanation: + +- It if often adivsable to not use wildcard imports. In wildcard imports, the names with leading underscore are be imported. This may lead to errors in runtime. +- Had we used `from ... import a, b, c` syntax, the above `NameError` won't have occurred. + ```py + >>> from module import some_weird_name_func_, _another_weird_name_func + >>> _another_weird_name_func() + works! + ``` +- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports. +```py +__all__ = ['_another_weird_name_func'] +def some_weird_name_func_(): + print("works!") + +def _another_weird_name_func(): + print("works!") +``` +**Output** + +```py +>>> _another_weird_name_func() +"works!" +>>> some_weird_name_func_() +Traceback (most recent call last): + File "", line 1, in +NameError: name 'some_weird_name_func_' is not defined +``` --- @@ -2561,12 +2642,12 @@ The spelling is intended. Please, don't submit a patch for this. class Yo(object): def __init__(self): self.__honey = True - self.bitch = True + self.bro = True ``` **Output:** ```py ->>> Yo().bitch +>>> Yo().bro True >>> Yo().__honey AttributeError: 'Yo' object has no attribute '__honey' @@ -2574,7 +2655,7 @@ AttributeError: 'Yo' object has no attribute '__honey' True ``` -Why did `Yo()._Yo__honey` work? Only Indian readers would understand. +Why did `Yo()._Yo__honey` work? #### 💡 Explanation: @@ -2584,6 +2665,10 @@ Why did `Yo()._Yo__honey` work? Only Indian readers would understand. --- + + + + --- ## Section: Miscellaneous From 14e03a37662f52e5a06d5af1b3d5ef1e2d7cba93 Mon Sep 17 00:00:00 2001 From: cclauss Date: Fri, 28 Jun 2019 07:03:12 +0200 Subject: [PATCH 030/221] Add automated testing using Travis CI The repo switch would need to be turned on at https://travis-ci.com/satwikkansal/wtfpython to enable free automated testing of all code changes. --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..8d2ea6bb --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: python +install: pip install flake8 +script: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics From a4776a6b672d4fd0f1c4b91e8ca07ddb4537faae Mon Sep 17 00:00:00 2001 From: cclauss Date: Tue, 2 Jul 2019 15:36:23 +0200 Subject: [PATCH 031/221] Use ==/!= to compare str, bytes, and int literals Identity is not the same thing as equality in Python. $ __[flake8](http://flake8.pycqa.org) . --count --select=E9,F63,F7,F82 --show-source --statistics__ ``` if resp.status_code is 200: ^ 1 F632 use ==/!= to compare str, bytes, and int literals 1 ``` --- irrelevant/generate_contributions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/irrelevant/generate_contributions.py b/irrelevant/generate_contributions.py index 136f6538..f396f32b 100644 --- a/irrelevant/generate_contributions.py +++ b/irrelevant/generate_contributions.py @@ -39,7 +39,7 @@ issue_string = ', '.join([issue_format.format(i, i) for i in issues]) resp = requests.get(github_rest_api.format(handle)) name = handle - if resp.status_code is 200: + if resp.status_code == 200: pprint.pprint(resp.json()['name']) else: print(handle, resp.content) @@ -48,4 +48,4 @@ handle, issue_string)) -print(table_header + "\n".join(rows_so_far)) \ No newline at end of file +print(table_header + "\n".join(rows_so_far)) From e611f24e7f1b43ec1ec019f49e891504693286e9 Mon Sep 17 00:00:00 2001 From: zachkirsch Date: Wed, 3 Jul 2019 11:39:57 -0400 Subject: [PATCH 032/221] Change constant-folding max from <20 to <=20 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9827fc46..0e6fd1c7 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,7 @@ Makes sense, right? * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) + When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. -+ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. ++ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than or equal to 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. --- From 12a1ac10cbc83c46eab4aed3b8f2f37593d656da Mon Sep 17 00:00:00 2001 From: Zach Kirsch Date: Wed, 3 Jul 2019 11:46:31 -0400 Subject: [PATCH 033/221] Fix github URL typos in CONTRIBUTORS.md --- CONTRIBUTORS.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7f672aca..a5e440ed 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -2,13 +2,13 @@ I'm really grateful to all the contributors. Following are the wonderful people | Contributor | Github | Issues | |-------------|--------|--------| -| Lucas-C | [Lucas-C](https://github.com/Lucas-C) | [#36](https:/github.com/satwikkansal/wtfpython/issues/36) | -| MittalAshok | [MittalAshok](https://github.com/MittalAshok) | [#23](https:/github.com/satwikkansal/wtfpython/issues/23) | -| asottile | [asottile](https://github.com/asottile) | [#40](https:/github.com/satwikkansal/wtfpython/issues/40) | -| MostAwesomeDude | [MostAwesomeDude](https://github.com/MostAwesomeDude) | [#1](https:/github.com/satwikkansal/wtfpython/issues/1) | -| tukkek | [tukkek](https://github.com/tukkek) | [#11](https:/github.com/satwikkansal/wtfpython/issues/11), [#26](https:/github.com/satwikkansal/wtfpython/issues/26) | -| PiaFraus | [PiaFraus](https://github.com/PiaFraus) | [#9](https:/github.com/satwikkansal/wtfpython/issues/9) | -| chris-rands | [chris-rands](https://github.com/chris-rands) | [#32](https:/github.com/satwikkansal/wtfpython/issues/32) | -| sohaibfarooqi | [sohaibfarooqi](https://github.com/sohaibfarooqi) | [#63](https:/github.com/satwikkansal/wtfpython/issues/63) | +| Lucas-C | [Lucas-C](https://github.com/Lucas-C) | [#36](https://github.com/satwikkansal/wtfpython/issues/36) | +| MittalAshok | [MittalAshok](https://github.com/MittalAshok) | [#23](https://github.com/satwikkansal/wtfpython/issues/23) | +| asottile | [asottile](https://github.com/asottile) | [#40](https://github.com/satwikkansal/wtfpython/issues/40) | +| MostAwesomeDude | [MostAwesomeDude](https://github.com/MostAwesomeDude) | [#1](https://github.com/satwikkansal/wtfpython/issues/1) | +| tukkek | [tukkek](https://github.com/tukkek) | [#11](https://github.com/satwikkansal/wtfpython/issues/11), [#26](https://github.com/satwikkansal/wtfpython/issues/26) | +| PiaFraus | [PiaFraus](https://github.com/PiaFraus) | [#9](https://github.com/satwikkansal/wtfpython/issues/9) | +| chris-rands | [chris-rands](https://github.com/chris-rands) | [#32](https://github.com/satwikkansal/wtfpython/issues/32) | +| sohaibfarooqi | [sohaibfarooqi](https://github.com/sohaibfarooqi) | [#63](https://github.com/satwikkansal/wtfpython/issues/63) | Thank you all for taking out the time to make this project more awesome! :smile: From 96455422efc903d14c4c35818d231d7a5cfc5c86 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 7 Jul 2019 22:17:33 +0530 Subject: [PATCH 034/221] Update the booleans example Fix some technically incorrect terminologies and snippets. --- README.md | 96 ++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 71 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 841d40a7..f29fd25e 100644 --- a/README.md +++ b/README.md @@ -1057,7 +1057,7 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t 1\. ```py -# A simple example to count the number of boolean and +# A simple example to count the number of booleans and # integers in an iterable of mixed data types. mixed_list = [False, 1.0, "some_string", 3, True, [], False] integers_found_so_far = 0 @@ -1078,33 +1078,27 @@ for item in mixed_list: 0 ``` -2\. -```py -another_dict = {} -another_dict[True] = "JavaScript" -another_dict[1] = "Ruby" -another_dict[1.0] = "Python" -``` - -**Output:** -```py ->>> another_dict[True] -"Python" -``` -3\. +2\. ```py >>> some_bool = True ->>> "wtf"*some_bool +>>> "wtf" * some_bool 'wtf' >>> some_bool = False ->>> "wtf"*some_bool +>>> "wtf" * some_bool '' ``` #### 💡 Explanation: -* Booleans are a subclass of `int` +* `bool` is a subclass of `int` in Python + ```py + >>> issubclass(bool, int) + True + >>> issubclass(int, bool) + False + ``` +* And thus, `True` and `False` are instances of `int` ```py >>> isinstance(True, int) True @@ -1114,8 +1108,10 @@ another_dict[1.0] = "Python" * The integer value of `True` is `1` and that of `False` is `0`. ```py - >>> True == 1 == 1.0 and False == 0 == 0.0 - True + >>> int(True) + 1 + >>> int(False) + 0 ``` * See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for the rationale behind it. @@ -1718,7 +1714,7 @@ Yes, it runs for exactly **eight** times and stops. --- -### ▶ Stubborn `del` operator * +### ▶ Stubborn `del` operation * ```py class SomeClass: @@ -2319,7 +2315,7 @@ NameError: name '_another_weird_name_func' is not defined #### 💡 Explanation: -- It if often adivsable to not use wildcard imports. In wildcard imports, the names with leading underscore are be imported. This may lead to errors in runtime. +- It if often adivsable to not use wildcard imports. The first obvious reason for this is In wildcard imports, the names with leading underscore are be imported. This may lead to errors in runtime. - Had we used `from ... import a, b, c` syntax, the above `NameError` won't have occurred. ```py >>> from module import some_weird_name_func_, _another_weird_name_func @@ -2636,8 +2632,9 @@ The spelling is intended. Please, don't submit a patch for this. --- -### ▶ Mangling time! * +### ▶ Let's mangle ^ +1\. ```py class Yo(object): def __init__(self): @@ -2655,13 +2652,62 @@ AttributeError: 'Yo' object has no attribute '__honey' True ``` +2\. +```py +class Yo(object): + def __init__(self): + # Let's try something symmetrical this time + self.__honey__ = True + self.bro = True +``` + +**Output:** +```py +>>> Yo().bro +True + +>>> Yo()._Yo__honey__ +Traceback (most recent call last): + File "", line 1, in +AttributeError: 'Yo' object has no attribute '_Yo__honey__' +``` + Why did `Yo()._Yo__honey` work? +2\. + +```py +_A__variable = "Some value" + +class A(object): + def some_func(self): + return __variable # not initiatlized anywhere yet +``` + +**Output:** +```py +Traceback (most recent call last): + File "", line 1, in +AttributeError: 'A' object has no attribute '__variable' + +>>> >>> A().some_func() +'Some value' +``` + +3\. + +```py + +``` + + #### 💡 Explanation: * [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces. -* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore) and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. -* So, to access `__honey` attribute, we are required to append `_Yo` to the front which would prevent conflicts with the same name attribute defined in any other class. +* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a "dunder") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. +* So, to access `__honey` attribute in first snippet, we had to append `_Yo` to the front which would prevent conflicts with the same name attribute defined in any other class. +* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores. +* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable` which also happens to be the name of the variable we declared in outer scope. --- From 4d8e5795a324c10dfd9f78e017c4e2a1550ddb3d Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 7 Jul 2019 22:18:35 +0530 Subject: [PATCH 035/221] Update TOC --- README.md | 167 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 115 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index f29fd25e..0152d13f 100644 --- a/README.md +++ b/README.md @@ -28,66 +28,129 @@ So, here we go... - [Usage](#usage) - [👀 Examples](#-examples) - [Section: Strain your brain!](#section-strain-your-brain) - - [▶ Strings can be tricky sometimes *](#-strings-can-be-tricky-sometimes-) - - [▶ Time for some hash brownies!](#-time-for-some-hash-brownies) - - [▶ Return return everywhere!](#-return-return-everywhere) - - [▶ Deep down, we're all the same. *](#-deep-down-were-all-the-same-) - - [▶ For what?](#-for-what) - - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - - [▶ `is` is not what it is!](#-is-is-not-what-it-is) - - [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - - [▶ The sticky output function](#-the-sticky-output-function) - - [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) - - [▶ The surprising comma](#-the-surprising-comma) - - [▶ Backslashes at the end of string](#-backslashes-at-the-end-of-string) - - [▶ not knot!](#-not-knot) - - [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - - [▶ yielding None](#-yielding-none) - - [▶ Mutating the immutable!](#-mutating-the-immutable) - - [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) - - [▶ When True is actually False](#-when-true-is-actually-false) - - [▶ From filled to None in one instruction...](#-from-filled-to-none-in-one-instruction) - - [▶ Subclass relationships *](#-subclass-relationships-) - - [▶ The mysterious key type conversion *](#-the-mysterious-key-type-conversion-) - - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + - [▶ Strings can be tricky sometimes *](#%E2%96%B6-strings-can-be-tricky-sometimes-) + - [💡 Explanation:](#-explanation) + - [▶ Splitsies ^](#%E2%96%B6-splitsies-%5E) + - [💡 Explanation:](#-explanation-1) + - [▶ Time for some hash brownies!](#%E2%96%B6-time-for-some-hash-brownies) + - [💡 Explanation](#-explanation) + - [▶ The disorder within order ^](#%E2%96%B6-the-disorder-within-order-%5E) + - [💡 Explanation:](#-explanation-2) + - [▶ Keep trying? *](#%E2%96%B6-keep-trying-) + - [💡 Explanation:](#-explanation-3) + - [▶ Deep down, we're all the same. *](#%E2%96%B6-deep-down-were-all-the-same-) + - [💡 Explanation:](#-explanation-4) + - [▶ For what?](#%E2%96%B6-for-what) + - [💡 Explanation:](#-explanation-5) + - [▶ Evaluation time discrepancy ^](#%E2%96%B6-evaluation-time-discrepancy-%5E) + - [💡 Explanation](#-explanation-1) + - [▶ Messing around with `is` operator^](#%E2%96%B6-messing-around-with-is-operator%5E) + - [💡 Explanation:](#-explanation-6) + - [▶ A tic-tac-toe where X wins in the first attempt!](#%E2%96%B6-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + - [💡 Explanation:](#-explanation-7) + - [▶ The sticky output function](#%E2%96%B6-the-sticky-output-function) + - [💡 Explanation](#-explanation-2) + - [▶ The chicken-egg problem ^](#%E2%96%B6-the-chicken-egg-problem-%5E) + - [💡 Explanation](#-explanation-3) + - [▶ `is not ...` is not `is (not ...)`](#%E2%96%B6-is-not--is-not-is-not-) + - [💡 Explanation](#-explanation-4) + - [▶ The surprising comma](#%E2%96%B6-the-surprising-comma) + - [💡 Explanation:](#-explanation-8) + - [▶ Strings and the backslashes\ ^](#%E2%96%B6-strings-and-the-backslashes%5C-%5E) + - [💡 Explanation](#-explanation-5) + - [▶ not knot!](#%E2%96%B6-not-knot) + - [💡 Explanation:](#-explanation-9) + - [▶ Half triple-quoted strings](#%E2%96%B6-half-triple-quoted-strings) + - [💡 Explanation:](#-explanation-10) + - [▶ Midnight time doesn't exist?](#%E2%96%B6-midnight-time-doesnt-exist) + - [💡 Explanation:](#-explanation-11) + - [▶ What's wrong with booleans?](#%E2%96%B6-whats-wrong-with-booleans) + - [💡 Explanation:](#-explanation-12) + - [▶ Class attributes and instance attributes](#%E2%96%B6-class-attributes-and-instance-attributes) + - [💡 Explanation:](#-explanation-13) + - [▶ yielding None](#%E2%96%B6-yielding-none) + - [💡 Explanation:](#-explanation-14) + - [▶ Mutating the immutable!](#%E2%96%B6-mutating-the-immutable) + - [💡 Explanation:](#-explanation-15) + - [▶ The disappearing variable from outer scope](#%E2%96%B6-the-disappearing-variable-from-outer-scope) + - [💡 Explanation:](#-explanation-16) + - [▶ When True is actually False](#%E2%96%B6-when-true-is-actually-false) + - [💡 Explanation:](#-explanation-17) + - [▶ Lossy zip of iterators](#%E2%96%B6-lossy-zip-of-iterators) + - [💡 Explanation:](#-explanation-18) + - [▶ From filled to None in one instruction...](#%E2%96%B6-from-filled-to-none-in-one-instruction) + - [💡 Explanation](#-explanation-6) + - [▶ Subclass relationships *](#%E2%96%B6-subclass-relationships-) + - [💡 Explanation:](#-explanation-19) + - [▶ The mysterious key type conversion *](#%E2%96%B6-the-mysterious-key-type-conversion-) + - [💡 Explanation:](#-explanation-20) + - [▶ Let's see if you can guess this?](#%E2%96%B6-lets-see-if-you-can-guess-this) + - [💡 Explanation:](#-explanation-21) - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - - [▶ Skipping lines?](#-skipping-lines) - - [▶ Teleportation *](#-teleportation-) - - [▶ Well, something is fishy...](#-well-something-is-fishy) + - [▶ Skipping lines?](#%E2%96%B6-skipping-lines) + - [💡 Explanation](#-explanation-7) + - [▶ Teleportation *](#%E2%96%B6-teleportation-) + - [💡 Explanation:](#-explanation-22) + - [▶ Well, something is fishy...](#%E2%96%B6-well-something-is-fishy) + - [💡 Explanation](#-explanation-8) - [Section: Watch out for the landmines!](#section-watch-out-for-the-landmines) - - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) - - [▶ Stubborn `del` operator *](#-stubborn-del-operator-) - - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - - [▶ Loop variables leaking out!](#-loop-variables-leaking-out) - - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - - [▶ Catching the Exceptions](#-catching-the-exceptions) - - [▶ Same operands, different story!](#-same-operands-different-story) - - [▶ The out of scope variable](#-the-out-of-scope-variable) - - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - - [▶ Needle in a Haystack](#-needle-in-a-haystack) + - [▶ Modifying a dictionary while iterating over it](#%E2%96%B6-modifying-a-dictionary-while-iterating-over-it) + - [💡 Explanation:](#-explanation-23) + - [▶ Stubborn `del` operation *](#%E2%96%B6-stubborn-del-operation-) + - [💡 Explanation:](#-explanation-24) + - [▶ Deleting a list item while iterating](#%E2%96%B6-deleting-a-list-item-while-iterating) + - [💡 Explanation:](#-explanation-25) + - [▶ Loop variables leaking out!](#%E2%96%B6-loop-variables-leaking-out) + - [💡 Explanation:](#-explanation-26) + - [▶ Beware of default mutable arguments!](#%E2%96%B6-beware-of-default-mutable-arguments) + - [💡 Explanation:](#-explanation-27) + - [▶ Catching the Exceptions](#%E2%96%B6-catching-the-exceptions) + - [💡 Explanation](#-explanation-9) + - [▶ Same operands, different story!](#%E2%96%B6-same-operands-different-story) + - [💡 Explanation:](#-explanation-28) + - [▶ The out of scope variable](#%E2%96%B6-the-out-of-scope-variable) + - [💡 Explanation:](#-explanation-29) + - [▶ Be careful with chained operations](#%E2%96%B6-be-careful-with-chained-operations) + - [💡 Explanation:](#-explanation-30) + - [▶ Name resolution ignoring class scope](#%E2%96%B6-name-resolution-ignoring-class-scope) + - [💡 Explanation](#-explanation-10) + - [▶ Needles in a Haystack ^](#%E2%96%B6-needles-in-a-haystack-%5E) + - [💡 Explanation:](#-explanation-31) + - [▶ Wild imports](#%E2%96%B6-wild-imports) + - [💡 Explanation:](#-explanation-32) - [Section: The Hidden treasures!](#section-the-hidden-treasures) - - [▶ Okay Python, Can you make me fly? *](#-okay-python-can-you-make-me-fly-) - - [▶ `goto`, but why? *](#-goto-but-why-) - - [▶ Brace yourself! *](#-brace-yourself-) - - [▶ Let's meet Friendly Language Uncle For Life *](#-lets-meet-friendly-language-uncle-for-life-) - - [▶ Even Python understands that love is complicated *](#-even-python-understands-that-love-is-complicated-) - - [▶ Yes, it exists!](#-yes-it-exists) - - [▶ Inpinity *](#-inpinity-) - - [▶ Mangling time! *](#-mangling-time-) + - [▶ Okay Python, Can you make me fly? *](#%E2%96%B6-okay-python-can-you-make-me-fly-) + - [💡 Explanation:](#-explanation-33) + - [▶ `goto`, but why? *](#%E2%96%B6-goto-but-why-) + - [💡 Explanation:](#-explanation-34) + - [▶ Brace yourself! *](#%E2%96%B6-brace-yourself-) + - [💡 Explanation:](#-explanation-35) + - [▶ Let's meet Friendly Language Uncle For Life ^](#%E2%96%B6-lets-meet-friendly-language-uncle-for-life-%5E) + - [💡 Explanation:](#-explanation-36) + - [▶ Even Python understands that love is complicated *](#%E2%96%B6-even-python-understands-that-love-is-complicated-) + - [💡 Explanation:](#-explanation-37) + - [▶ Yes, it exists!](#%E2%96%B6-yes-it-exists) + - [💡 Explanation:](#-explanation-38) + - [▶ Ellipsis ^](#%E2%96%B6-ellipsis-%5E) + - [💡 Explanation](#-explanation-11) + - [▶ Inpinity *](#%E2%96%B6-inpinity-) + - [💡 Explanation:](#-explanation-39) + - [▶ Let's mangle ^](#%E2%96%B6-lets-mangle-%5E) + - [💡 Explanation:](#-explanation-40) - [Section: Miscellaneous](#section-miscellaneous) - - [▶ `+=` is faster](#--is-faster) - - [▶ Let's make a giant string!](#-lets-make-a-giant-string) - - [▶ Explicit typecast of strings](#-explicit-typecast-of-strings) - - [▶ Minor Ones](#-minor-ones) + - [▶ `+=` is faster](#%E2%96%B6--is-faster) + - [💡 Explanation:](#-explanation-41) + - [▶ Let's make a giant string!](#%E2%96%B6-lets-make-a-giant-string) + - [💡 Explanation](#-explanation-12) + - [▶ Explicit typecast of strings](#%E2%96%B6-explicit-typecast-of-strings) + - [💡 Explanation:](#-explanation-42) + - [▶ Minor Ones](#%E2%96%B6-minor-ones) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) + - [Some nice Links!](#some-nice-links) - [🎓 License](#-license) - [Help](#help) - - [Want to share wtfpython with friends?](#want-to-share-wtfpython-with-friends) + - [Surprise your geeky pythonist friends?](#surprise-your-geeky-pythonist-friends) - [Need a pdf version?](#need-a-pdf-version) From 98701351c617aff53c2ad24c109867ff7ab80550 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 8 Jul 2019 02:54:49 +0530 Subject: [PATCH 036/221] Add uuids to examples --- README.md | 114 +++++++++++++++++++++++++++--------------------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 0326d051..c6833f3c 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ Now, just run `wtfpython` at the command line which will open this collection in ## Section: Strain your brain! ### ▶ Strings can be tricky sometimes * - + 1\. ```py >>> a = "some_string" @@ -271,7 +271,7 @@ Makes sense, right? --- ### ▶ Splitsies ^ - + ```py >>> 'a'.split() ['a'] @@ -308,7 +308,7 @@ Makes sense, right? ### ▶ Time for some hash brownies! - + 1\. ```py some_dict = {} @@ -353,7 +353,7 @@ So, why is Python all over the place? --- ### ▶ The disorder within order ^ - + ```py from collections import OrderedDict @@ -451,7 +451,7 @@ What is going on here? --- ### ▶ Keep trying? * - + ```py def some_func(): try: @@ -511,7 +511,7 @@ Iteration 0 --- ### ▶ Deep down, we're all the same. * - + ```py class WTF: pass @@ -561,7 +561,7 @@ True --- ### ▶ For what? - + ```py some_string = "wtf" some_dict = {} @@ -614,7 +614,7 @@ for i, some_dict[i] in enumerate(some_string): --- ### ▶ Evaluation time discrepancy ^ - + 1\. ```py array = [1, 8, 15] @@ -680,7 +680,7 @@ array_4 = [400, 500, 600] --- ### ▶ Messing around with `is` operator^ - + The following is a very famous example present all over the internet. 1\. @@ -798,7 +798,7 @@ Similar optimization applies to other **immutable** objects like empty tuples as --- ### ▶ A tic-tac-toe where X wins in the first attempt! - + ```py # Let's initialize a row row = [""]*3 #row i['', '', ''] @@ -843,7 +843,7 @@ We can avoid this scenario here by not using `row` variable to generate `board`. --- ### ▶ The sticky output function - + ```py funcs = [] results = [] @@ -897,7 +897,7 @@ Even when the values of `x` were different in every iteration prior to appending --- ### ▶ The chicken-egg problem ^ - + 1\. ```py >>> isinstance(3, int) @@ -945,7 +945,7 @@ False --- ### ▶ `is not ...` is not `is (not ...)` - + ```py >>> 'something' is not None True @@ -961,7 +961,7 @@ False --- ### ▶ The surprising comma - + **Output:** ```py >>> def f(x, y,): @@ -991,7 +991,7 @@ SyntaxError: invalid syntax --- ### ▶ Strings and the backslashes\ ^ - + **Output:** ```py >>> print("\"") @@ -1034,7 +1034,7 @@ True --- ### ▶ not knot! - + ```py x = True y = False @@ -1061,7 +1061,7 @@ SyntaxError: invalid syntax --- ### ▶ Half triple-quoted strings - + **Output:** ```py >>> print('wtfpython''') @@ -1086,7 +1086,7 @@ wtfpython --- ### ▶ Midnight time doesn't exist? - + ```py from datetime import datetime @@ -1116,7 +1116,7 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t --- ### ▶ What's wrong with booleans? - + 1\. ```py # A simple example to count the number of booleans and @@ -1181,7 +1181,7 @@ for item in mixed_list: --- ### ▶ Class attributes and instance attributes - + 1\. ```py class A: @@ -1251,7 +1251,7 @@ True --- ### ▶ yielding None - + ```py some_iterable = ('a', 'b') @@ -1280,7 +1280,7 @@ def some_func(val): --- ### ▶ Mutating the immutable! - + ```py some_tuple = ("A", "tuple", "with", "values") another_tuple = ([1, 2], [3, 4], [5, 6]) @@ -1313,7 +1313,7 @@ But I thought tuples were immutable... --- ### ▶ The disappearing variable from outer scope - + ```py e = 7 try: @@ -1393,7 +1393,7 @@ NameError: name 'e' is not defined --- ### ▶ When True is actually False - + ```py True = False if True == False: @@ -1413,7 +1413,7 @@ I've lost faith in truth! --- ### ▶ Lossy zip of iterators - + ```py >>> numbers = list(range(7)) >>> numbers @@ -1462,7 +1462,7 @@ Where did element `3` go from the `numbers` list? --- ### ▶ From filled to None in one instruction... - + ```py some_list = [1, 2, 3] some_dict = { @@ -1490,7 +1490,7 @@ Most methods that modify the items of sequence/mapping objects like `list.append --- ### ▶ Subclass relationships * - + **Output:** ```py >>> from collections import Hashable @@ -1514,7 +1514,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` --- ### ▶ The mysterious key type conversion * - + ```py class SomeClass(str): pass @@ -1570,7 +1570,7 @@ str --- ### ▶ Let's see if you can guess this? - + ```py a, b = a[b] = {}, 5 ``` @@ -1631,7 +1631,7 @@ a, b = a[b] = {}, 5 ## Section: Appearances are deceptive! ### ▶ Skipping lines? - + **Output:** ```py >>> value = 11 @@ -1667,7 +1667,7 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ --- ### ▶ Teleportation * - + ```py import numpy as np @@ -1697,7 +1697,7 @@ Where's the Nobel Prize? --- ### ▶ Well, something is fishy... - + ```py def square(x): """ @@ -1742,7 +1742,7 @@ Shouldn't that be 100? ### ▶ Modifying a dictionary while iterating over it - + ```py x = {0: None} @@ -1777,7 +1777,7 @@ Yes, it runs for exactly **eight** times and stops. --- ### ▶ Stubborn `del` operation * - + ```py class SomeClass: def __del__(self): @@ -1820,7 +1820,7 @@ Okay, now it's deleted :confused: --- ### ▶ Deleting a list item while iterating - + ```py list_1 = [1, 2, 3, 4] list_2 = [1, 2, 3, 4] @@ -1880,7 +1880,7 @@ Can you guess why the output is `[2, 4]`? --- ### ▶ Loop variables leaking out! - + 1\. ```py for x in range(7): @@ -1944,7 +1944,7 @@ print(x, ': x in global') --- ### ▶ Beware of default mutable arguments! - + ```py def some_func(default_arg=[]): default_arg.append("some_string") @@ -2001,7 +2001,7 @@ def some_func(default_arg=[]): --- ### ▶ Catching the Exceptions - + ```py some_list = [1, 2, 3] try: @@ -2076,7 +2076,7 @@ SyntaxError: invalid syntax --- ### ▶ Same operands, different story! - + 1\. ```py a = [1, 2, 3, 4] @@ -2118,7 +2118,7 @@ a += [5, 6, 7, 8] --- ### ▶ The out of scope variable - + ```py a = 1 def some_func(): @@ -2157,7 +2157,7 @@ UnboundLocalError: local variable 'a' referenced before assignment --- ### ▶ Be careful with chained operations - + ```py >>> (False == False) in [False] # makes sense False @@ -2202,7 +2202,7 @@ While such behavior might seem silly to you in the above examples, it's fantasti --- ### ▶ Name resolution ignoring class scope - + 1\. ```py x = 5 @@ -2246,7 +2246,7 @@ class SomeClass: --- ### ▶ Needles in a Haystack ^ - + 1\. ```py x, y = (0, 1) if True else None, None @@ -2351,7 +2351,7 @@ b = "javascript" --- ### ▶ Wild imports - + ```py # File: module.py @@ -2413,7 +2413,7 @@ NameError: name 'some_weird_name_func_' is not defined This section contains few of the lesser-known interesting things about Python that most beginners like me are unaware of (well, not anymore). ### ▶ Okay Python, Can you make me fly? * - + Well, here you go ```py @@ -2431,7 +2431,7 @@ Sshh.. It's a super secret. --- ### ▶ `goto`, but why? * - + ```py from goto import goto, label for i in range(9): @@ -2459,7 +2459,7 @@ Freedom! --- ### ▶ Brace yourself! * - + If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing, ```py @@ -2484,7 +2484,7 @@ Braces? No way! If you think that's disappointing, use Java. Okay, another surpr --- ### ▶ Let's meet Friendly Language Uncle For Life ^ - + **Output (Python 3.x)** ```py >>> from __future__ import barry_as_FLUFL @@ -2515,7 +2515,7 @@ There we go. --- ### ▶ Even Python understands that love is complicated * - + ```py import this ``` @@ -2572,7 +2572,7 @@ True --- ### ▶ Yes, it exists! - + **The `else` clause for loops.** One typical example might be: ```py @@ -2616,7 +2616,7 @@ Try block executed successfully... --- ### ▶ Ellipsis ^ - + ```py def some_func(): Ellipsis @@ -2676,7 +2676,7 @@ Ellipsis --- ### ▶ Inpinity * - + The spelling is intended. Please, don't submit a patch for this. **Output (Python 3.x):** @@ -2695,7 +2695,7 @@ The spelling is intended. Please, don't submit a patch for this. --- ### ▶ Let's mangle ^ - + 1\. ```py class Yo(object): @@ -2783,7 +2783,7 @@ AttributeError: 'A' object has no attribute '__variable' ### ▶ `+=` is faster - + ```py # using "+", three strings: >>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) @@ -2799,7 +2799,7 @@ AttributeError: 'A' object has no attribute '__variable' --- ### ▶ Let's make a giant string! - + ```py def add_string_with_plus(iters): s = "" @@ -2892,7 +2892,7 @@ Let's increase the number of iterations by a factor of 10. --- ### ▶ Explicit typecast of strings - + ```py a = float('inf') b = float('nan') @@ -2931,7 +2931,7 @@ nan --- ### ▶ Minor Ones - + * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) **💡 Explanation:** From 863e1f4512fd91ae0dde79833377c629c21dee77 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 8 Jul 2019 03:00:33 +0530 Subject: [PATCH 037/221] Fix uuid comments --- README.md | 114 +++++++++++++++++++++++++++--------------------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index c6833f3c..81281197 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ Now, just run `wtfpython` at the command line which will open this collection in ## Section: Strain your brain! ### ▶ Strings can be tricky sometimes * - + 1\. ```py >>> a = "some_string" @@ -271,7 +271,7 @@ Makes sense, right? --- ### ▶ Splitsies ^ - + ```py >>> 'a'.split() ['a'] @@ -308,7 +308,7 @@ Makes sense, right? ### ▶ Time for some hash brownies! - + 1\. ```py some_dict = {} @@ -353,7 +353,7 @@ So, why is Python all over the place? --- ### ▶ The disorder within order ^ - + ```py from collections import OrderedDict @@ -451,7 +451,7 @@ What is going on here? --- ### ▶ Keep trying? * - + ```py def some_func(): try: @@ -511,7 +511,7 @@ Iteration 0 --- ### ▶ Deep down, we're all the same. * - + ```py class WTF: pass @@ -561,7 +561,7 @@ True --- ### ▶ For what? - + ```py some_string = "wtf" some_dict = {} @@ -614,7 +614,7 @@ for i, some_dict[i] in enumerate(some_string): --- ### ▶ Evaluation time discrepancy ^ - + 1\. ```py array = [1, 8, 15] @@ -680,7 +680,7 @@ array_4 = [400, 500, 600] --- ### ▶ Messing around with `is` operator^ - + The following is a very famous example present all over the internet. 1\. @@ -798,7 +798,7 @@ Similar optimization applies to other **immutable** objects like empty tuples as --- ### ▶ A tic-tac-toe where X wins in the first attempt! - + ```py # Let's initialize a row row = [""]*3 #row i['', '', ''] @@ -843,7 +843,7 @@ We can avoid this scenario here by not using `row` variable to generate `board`. --- ### ▶ The sticky output function - + ```py funcs = [] results = [] @@ -897,7 +897,7 @@ Even when the values of `x` were different in every iteration prior to appending --- ### ▶ The chicken-egg problem ^ - + 1\. ```py >>> isinstance(3, int) @@ -945,7 +945,7 @@ False --- ### ▶ `is not ...` is not `is (not ...)` - + ```py >>> 'something' is not None True @@ -961,7 +961,7 @@ False --- ### ▶ The surprising comma - + **Output:** ```py >>> def f(x, y,): @@ -991,7 +991,7 @@ SyntaxError: invalid syntax --- ### ▶ Strings and the backslashes\ ^ - + **Output:** ```py >>> print("\"") @@ -1034,7 +1034,7 @@ True --- ### ▶ not knot! - + ```py x = True y = False @@ -1061,7 +1061,7 @@ SyntaxError: invalid syntax --- ### ▶ Half triple-quoted strings - + **Output:** ```py >>> print('wtfpython''') @@ -1086,7 +1086,7 @@ wtfpython --- ### ▶ Midnight time doesn't exist? - + ```py from datetime import datetime @@ -1116,7 +1116,7 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t --- ### ▶ What's wrong with booleans? - + 1\. ```py # A simple example to count the number of booleans and @@ -1181,7 +1181,7 @@ for item in mixed_list: --- ### ▶ Class attributes and instance attributes - + 1\. ```py class A: @@ -1251,7 +1251,7 @@ True --- ### ▶ yielding None - + ```py some_iterable = ('a', 'b') @@ -1280,7 +1280,7 @@ def some_func(val): --- ### ▶ Mutating the immutable! - + ```py some_tuple = ("A", "tuple", "with", "values") another_tuple = ([1, 2], [3, 4], [5, 6]) @@ -1313,7 +1313,7 @@ But I thought tuples were immutable... --- ### ▶ The disappearing variable from outer scope - + ```py e = 7 try: @@ -1393,7 +1393,7 @@ NameError: name 'e' is not defined --- ### ▶ When True is actually False - + ```py True = False if True == False: @@ -1413,7 +1413,7 @@ I've lost faith in truth! --- ### ▶ Lossy zip of iterators - + ```py >>> numbers = list(range(7)) >>> numbers @@ -1462,7 +1462,7 @@ Where did element `3` go from the `numbers` list? --- ### ▶ From filled to None in one instruction... - + ```py some_list = [1, 2, 3] some_dict = { @@ -1490,7 +1490,7 @@ Most methods that modify the items of sequence/mapping objects like `list.append --- ### ▶ Subclass relationships * - + **Output:** ```py >>> from collections import Hashable @@ -1514,7 +1514,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` --- ### ▶ The mysterious key type conversion * - + ```py class SomeClass(str): pass @@ -1570,7 +1570,7 @@ str --- ### ▶ Let's see if you can guess this? - + ```py a, b = a[b] = {}, 5 ``` @@ -1631,7 +1631,7 @@ a, b = a[b] = {}, 5 ## Section: Appearances are deceptive! ### ▶ Skipping lines? - + **Output:** ```py >>> value = 11 @@ -1667,7 +1667,7 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ --- ### ▶ Teleportation * - + ```py import numpy as np @@ -1697,7 +1697,7 @@ Where's the Nobel Prize? --- ### ▶ Well, something is fishy... - + ```py def square(x): """ @@ -1742,7 +1742,7 @@ Shouldn't that be 100? ### ▶ Modifying a dictionary while iterating over it - + ```py x = {0: None} @@ -1777,7 +1777,7 @@ Yes, it runs for exactly **eight** times and stops. --- ### ▶ Stubborn `del` operation * - + ```py class SomeClass: def __del__(self): @@ -1820,7 +1820,7 @@ Okay, now it's deleted :confused: --- ### ▶ Deleting a list item while iterating - + ```py list_1 = [1, 2, 3, 4] list_2 = [1, 2, 3, 4] @@ -1880,7 +1880,7 @@ Can you guess why the output is `[2, 4]`? --- ### ▶ Loop variables leaking out! - + 1\. ```py for x in range(7): @@ -1944,7 +1944,7 @@ print(x, ': x in global') --- ### ▶ Beware of default mutable arguments! - + ```py def some_func(default_arg=[]): default_arg.append("some_string") @@ -2001,7 +2001,7 @@ def some_func(default_arg=[]): --- ### ▶ Catching the Exceptions - + ```py some_list = [1, 2, 3] try: @@ -2076,7 +2076,7 @@ SyntaxError: invalid syntax --- ### ▶ Same operands, different story! - + 1\. ```py a = [1, 2, 3, 4] @@ -2118,7 +2118,7 @@ a += [5, 6, 7, 8] --- ### ▶ The out of scope variable - + ```py a = 1 def some_func(): @@ -2157,7 +2157,7 @@ UnboundLocalError: local variable 'a' referenced before assignment --- ### ▶ Be careful with chained operations - + ```py >>> (False == False) in [False] # makes sense False @@ -2202,7 +2202,7 @@ While such behavior might seem silly to you in the above examples, it's fantasti --- ### ▶ Name resolution ignoring class scope - + 1\. ```py x = 5 @@ -2246,7 +2246,7 @@ class SomeClass: --- ### ▶ Needles in a Haystack ^ - + 1\. ```py x, y = (0, 1) if True else None, None @@ -2351,7 +2351,7 @@ b = "javascript" --- ### ▶ Wild imports - + ```py # File: module.py @@ -2413,7 +2413,7 @@ NameError: name 'some_weird_name_func_' is not defined This section contains few of the lesser-known interesting things about Python that most beginners like me are unaware of (well, not anymore). ### ▶ Okay Python, Can you make me fly? * - + Well, here you go ```py @@ -2431,7 +2431,7 @@ Sshh.. It's a super secret. --- ### ▶ `goto`, but why? * - + ```py from goto import goto, label for i in range(9): @@ -2459,7 +2459,7 @@ Freedom! --- ### ▶ Brace yourself! * - + If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing, ```py @@ -2484,7 +2484,7 @@ Braces? No way! If you think that's disappointing, use Java. Okay, another surpr --- ### ▶ Let's meet Friendly Language Uncle For Life ^ - + **Output (Python 3.x)** ```py >>> from __future__ import barry_as_FLUFL @@ -2515,7 +2515,7 @@ There we go. --- ### ▶ Even Python understands that love is complicated * - + ```py import this ``` @@ -2572,7 +2572,7 @@ True --- ### ▶ Yes, it exists! - + **The `else` clause for loops.** One typical example might be: ```py @@ -2616,7 +2616,7 @@ Try block executed successfully... --- ### ▶ Ellipsis ^ - + ```py def some_func(): Ellipsis @@ -2676,7 +2676,7 @@ Ellipsis --- ### ▶ Inpinity * - + The spelling is intended. Please, don't submit a patch for this. **Output (Python 3.x):** @@ -2695,7 +2695,7 @@ The spelling is intended. Please, don't submit a patch for this. --- ### ▶ Let's mangle ^ - + 1\. ```py class Yo(object): @@ -2783,7 +2783,7 @@ AttributeError: 'A' object has no attribute '__variable' ### ▶ `+=` is faster - + ```py # using "+", three strings: >>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) @@ -2799,7 +2799,7 @@ AttributeError: 'A' object has no attribute '__variable' --- ### ▶ Let's make a giant string! - + ```py def add_string_with_plus(iters): s = "" @@ -2892,7 +2892,7 @@ Let's increase the number of iterations by a factor of 10. --- ### ▶ Explicit typecast of strings - + ```py a = float('inf') b = float('nan') @@ -2931,7 +2931,7 @@ nan --- ### ▶ Minor Ones - + * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) **💡 Explanation:** From 4618bed5f6ef4cf02996ee0198ffc31488349cad Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 8 Jul 2019 22:01:41 +0530 Subject: [PATCH 038/221] Remove asterisks and carets from titles --- README.md | 146 +++++++++++++++++------------------------------------- 1 file changed, 45 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 81281197..4a7157f5 100644 --- a/README.md +++ b/README.md @@ -28,126 +28,71 @@ So, here we go... - [Usage](#usage) - [👀 Examples](#-examples) - [Section: Strain your brain!](#section-strain-your-brain) - - [▶ Strings can be tricky sometimes *](#%E2%96%B6-strings-can-be-tricky-sometimes-) - - [💡 Explanation:](#-explanation) - - [▶ Splitsies ^](#%E2%96%B6-splitsies-%5E) - - [💡 Explanation:](#-explanation-1) + - [▶ Strings can be tricky sometimes](#%E2%96%B6-strings-can-be-tricky-sometimes) + - [▶ Splitsies](#%E2%96%B6-splitsies) +- [is same as](#is-same-as) +- [but](#but) +- [isn't the same as](#isnt-the-same-as) - [▶ Time for some hash brownies!](#%E2%96%B6-time-for-some-hash-brownies) - - [💡 Explanation](#-explanation) - - [▶ The disorder within order ^](#%E2%96%B6-the-disorder-within-order-%5E) - - [💡 Explanation:](#-explanation-2) - - [▶ Keep trying? *](#%E2%96%B6-keep-trying-) - - [💡 Explanation:](#-explanation-3) - - [▶ Deep down, we're all the same. *](#%E2%96%B6-deep-down-were-all-the-same-) - - [💡 Explanation:](#-explanation-4) + - [▶ The disorder within order](#%E2%96%B6-the-disorder-within-order) + - [▶ Keep trying?](#%E2%96%B6-keep-trying) + - [▶ Deep down, we're all the same](#%E2%96%B6-deep-down-were-all-the-same) - [▶ For what?](#%E2%96%B6-for-what) - - [💡 Explanation:](#-explanation-5) - - [▶ Evaluation time discrepancy ^](#%E2%96%B6-evaluation-time-discrepancy-%5E) - - [💡 Explanation](#-explanation-1) + - [▶ Evaluation time discrepancy](#%E2%96%B6-evaluation-time-discrepancy) - [▶ Messing around with `is` operator^](#%E2%96%B6-messing-around-with-is-operator%5E) - - [💡 Explanation:](#-explanation-6) - [▶ A tic-tac-toe where X wins in the first attempt!](#%E2%96%B6-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - - [💡 Explanation:](#-explanation-7) - [▶ The sticky output function](#%E2%96%B6-the-sticky-output-function) - - [💡 Explanation](#-explanation-2) - - [▶ The chicken-egg problem ^](#%E2%96%B6-the-chicken-egg-problem-%5E) - - [💡 Explanation](#-explanation-3) + - [▶ The chicken-egg problem](#%E2%96%B6-the-chicken-egg-problem) - [▶ `is not ...` is not `is (not ...)`](#%E2%96%B6-is-not--is-not-is-not-) - - [💡 Explanation](#-explanation-4) - [▶ The surprising comma](#%E2%96%B6-the-surprising-comma) - - [💡 Explanation:](#-explanation-8) - - [▶ Strings and the backslashes\ ^](#%E2%96%B6-strings-and-the-backslashes%5C-%5E) - - [💡 Explanation](#-explanation-5) + - [▶ Strings and the backslashes](#%E2%96%B6-strings-and-the-backslashes) - [▶ not knot!](#%E2%96%B6-not-knot) - - [💡 Explanation:](#-explanation-9) - [▶ Half triple-quoted strings](#%E2%96%B6-half-triple-quoted-strings) - - [💡 Explanation:](#-explanation-10) - [▶ Midnight time doesn't exist?](#%E2%96%B6-midnight-time-doesnt-exist) - - [💡 Explanation:](#-explanation-11) - [▶ What's wrong with booleans?](#%E2%96%B6-whats-wrong-with-booleans) - - [💡 Explanation:](#-explanation-12) - [▶ Class attributes and instance attributes](#%E2%96%B6-class-attributes-and-instance-attributes) - - [💡 Explanation:](#-explanation-13) - [▶ yielding None](#%E2%96%B6-yielding-none) - - [💡 Explanation:](#-explanation-14) - [▶ Mutating the immutable!](#%E2%96%B6-mutating-the-immutable) - - [💡 Explanation:](#-explanation-15) - [▶ The disappearing variable from outer scope](#%E2%96%B6-the-disappearing-variable-from-outer-scope) - - [💡 Explanation:](#-explanation-16) - [▶ When True is actually False](#%E2%96%B6-when-true-is-actually-false) - - [💡 Explanation:](#-explanation-17) - [▶ Lossy zip of iterators](#%E2%96%B6-lossy-zip-of-iterators) - - [💡 Explanation:](#-explanation-18) - [▶ From filled to None in one instruction...](#%E2%96%B6-from-filled-to-none-in-one-instruction) - - [💡 Explanation](#-explanation-6) - - [▶ Subclass relationships *](#%E2%96%B6-subclass-relationships-) - - [💡 Explanation:](#-explanation-19) - - [▶ The mysterious key type conversion *](#%E2%96%B6-the-mysterious-key-type-conversion-) - - [💡 Explanation:](#-explanation-20) + - [▶ Subclass relationships](#%E2%96%B6-subclass-relationships) + - [▶ The mysterious key type conversion](#%E2%96%B6-the-mysterious-key-type-conversion) - [▶ Let's see if you can guess this?](#%E2%96%B6-lets-see-if-you-can-guess-this) - - [💡 Explanation:](#-explanation-21) - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - [▶ Skipping lines?](#%E2%96%B6-skipping-lines) - - [💡 Explanation](#-explanation-7) - - [▶ Teleportation *](#%E2%96%B6-teleportation-) - - [💡 Explanation:](#-explanation-22) + - [▶ Teleportation](#%E2%96%B6-teleportation) - [▶ Well, something is fishy...](#%E2%96%B6-well-something-is-fishy) - - [💡 Explanation](#-explanation-8) - [Section: Watch out for the landmines!](#section-watch-out-for-the-landmines) - [▶ Modifying a dictionary while iterating over it](#%E2%96%B6-modifying-a-dictionary-while-iterating-over-it) - - [💡 Explanation:](#-explanation-23) - - [▶ Stubborn `del` operation *](#%E2%96%B6-stubborn-del-operation-) - - [💡 Explanation:](#-explanation-24) - [▶ Deleting a list item while iterating](#%E2%96%B6-deleting-a-list-item-while-iterating) - - [💡 Explanation:](#-explanation-25) - [▶ Loop variables leaking out!](#%E2%96%B6-loop-variables-leaking-out) - - [💡 Explanation:](#-explanation-26) - [▶ Beware of default mutable arguments!](#%E2%96%B6-beware-of-default-mutable-arguments) - - [💡 Explanation:](#-explanation-27) - [▶ Catching the Exceptions](#%E2%96%B6-catching-the-exceptions) - - [💡 Explanation](#-explanation-9) - [▶ Same operands, different story!](#%E2%96%B6-same-operands-different-story) - - [💡 Explanation:](#-explanation-28) - [▶ The out of scope variable](#%E2%96%B6-the-out-of-scope-variable) - - [💡 Explanation:](#-explanation-29) - [▶ Be careful with chained operations](#%E2%96%B6-be-careful-with-chained-operations) - - [💡 Explanation:](#-explanation-30) - [▶ Name resolution ignoring class scope](#%E2%96%B6-name-resolution-ignoring-class-scope) - - [💡 Explanation](#-explanation-10) - - [▶ Needles in a Haystack ^](#%E2%96%B6-needles-in-a-haystack-%5E) - - [💡 Explanation:](#-explanation-31) + - [▶ Needles in a Haystack](#%E2%96%B6-needles-in-a-haystack) - [▶ Wild imports](#%E2%96%B6-wild-imports) - - [💡 Explanation:](#-explanation-32) - [Section: The Hidden treasures!](#section-the-hidden-treasures) - - [▶ Okay Python, Can you make me fly? *](#%E2%96%B6-okay-python-can-you-make-me-fly-) - - [💡 Explanation:](#-explanation-33) - - [▶ `goto`, but why? *](#%E2%96%B6-goto-but-why-) - - [💡 Explanation:](#-explanation-34) - - [▶ Brace yourself! *](#%E2%96%B6-brace-yourself-) - - [💡 Explanation:](#-explanation-35) - - [▶ Let's meet Friendly Language Uncle For Life ^](#%E2%96%B6-lets-meet-friendly-language-uncle-for-life-%5E) - - [💡 Explanation:](#-explanation-36) - - [▶ Even Python understands that love is complicated *](#%E2%96%B6-even-python-understands-that-love-is-complicated-) - - [💡 Explanation:](#-explanation-37) + - [▶ Okay Python, Can you make me fly?](#%E2%96%B6-okay-python-can-you-make-me-fly) + - [▶ `goto`, but why?](#%E2%96%B6-goto-but-why) + - [▶ Brace yourself!](#%E2%96%B6-brace-yourself) + - [▶ Let's meet Friendly Language Uncle For Life](#%E2%96%B6-lets-meet-friendly-language-uncle-for-life) + - [▶ Even Python understands that love is complicated](#%E2%96%B6-even-python-understands-that-love-is-complicated) - [▶ Yes, it exists!](#%E2%96%B6-yes-it-exists) - - [💡 Explanation:](#-explanation-38) - - [▶ Ellipsis ^](#%E2%96%B6-ellipsis-%5E) - - [💡 Explanation](#-explanation-11) - - [▶ Inpinity *](#%E2%96%B6-inpinity-) - - [💡 Explanation:](#-explanation-39) - - [▶ Let's mangle ^](#%E2%96%B6-lets-mangle-%5E) - - [💡 Explanation:](#-explanation-40) + - [▶ Ellipsis](#%E2%96%B6-ellipsis) + - [▶ Inpinity](#%E2%96%B6-inpinity) + - [▶ Let's mangle](#%E2%96%B6-lets-mangle) - [Section: Miscellaneous](#section-miscellaneous) - [▶ `+=` is faster](#%E2%96%B6--is-faster) - - [💡 Explanation:](#-explanation-41) - [▶ Let's make a giant string!](#%E2%96%B6-lets-make-a-giant-string) - - [💡 Explanation](#-explanation-12) - [▶ Explicit typecast of strings](#%E2%96%B6-explicit-typecast-of-strings) - - [💡 Explanation:](#-explanation-42) - [▶ Minor Ones](#%E2%96%B6-minor-ones) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) - - [Some nice Links!](#some-nice-links) - [🎓 License](#-license) - [Help](#help) - [Surprise your geeky pythonist friends?](#surprise-your-geeky-pythonist-friends) @@ -159,8 +104,7 @@ So, here we go... All the examples are structured like below: -> ### ▶ Some fancy Title * -> The asterisk at the end of the title indicates the example was not present in the first release and has been recently added. +> ### ▶ Some fancy Title > > ```py > # Setting up the code. @@ -220,7 +164,7 @@ Now, just run `wtfpython` at the command line which will open this collection in ## Section: Strain your brain! -### ▶ Strings can be tricky sometimes * +### ▶ Strings can be tricky sometimes 1\. ```py @@ -270,7 +214,7 @@ Makes sense, right? --- -### ▶ Splitsies ^ +### ▶ Splitsies ```py >>> 'a'.split() @@ -352,7 +296,7 @@ So, why is Python all over the place? --- -### ▶ The disorder within order ^ +### ▶ The disorder within order ```py from collections import OrderedDict @@ -450,7 +394,7 @@ What is going on here? --- -### ▶ Keep trying? * +### ▶ Keep trying? ```py def some_func(): @@ -510,7 +454,7 @@ Iteration 0 --- -### ▶ Deep down, we're all the same. * +### ▶ Deep down, we're all the same ```py class WTF: @@ -613,7 +557,7 @@ for i, some_dict[i] in enumerate(some_string): --- -### ▶ Evaluation time discrepancy ^ +### ▶ Evaluation time discrepancy 1\. ```py @@ -896,7 +840,7 @@ Even when the values of `x` were different in every iteration prior to appending --- -### ▶ The chicken-egg problem ^ +### ▶ The chicken-egg problem 1\. ```py @@ -990,7 +934,7 @@ SyntaxError: invalid syntax --- -### ▶ Strings and the backslashes\ ^ +### ▶ Strings and the backslashes **Output:** ```py @@ -1489,7 +1433,7 @@ Most methods that modify the items of sequence/mapping objects like `list.append --- -### ▶ Subclass relationships * +### ▶ Subclass relationships **Output:** ```py @@ -1513,7 +1457,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` --- -### ▶ The mysterious key type conversion * +### ▶ The mysterious key type conversion ```py class SomeClass(str): @@ -1666,7 +1610,7 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ --- -### ▶ Teleportation * +### ▶ Teleportation ```py import numpy as np @@ -1776,7 +1720,7 @@ Yes, it runs for exactly **eight** times and stops. --- -### ▶ Stubborn `del` operation * +### ▶ Stubborn `del` operation ```py class SomeClass: @@ -2245,7 +2189,7 @@ class SomeClass: --- -### ▶ Needles in a Haystack ^ +### ▶ Needles in a Haystack 1\. ```py @@ -2412,7 +2356,7 @@ NameError: name 'some_weird_name_func_' is not defined This section contains few of the lesser-known interesting things about Python that most beginners like me are unaware of (well, not anymore). -### ▶ Okay Python, Can you make me fly? * +### ▶ Okay Python, Can you make me fly? Well, here you go @@ -2430,7 +2374,7 @@ Sshh.. It's a super secret. --- -### ▶ `goto`, but why? * +### ▶ `goto`, but why? ```py from goto import goto, label @@ -2458,7 +2402,7 @@ Freedom! --- -### ▶ Brace yourself! * +### ▶ Brace yourself! If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing, @@ -2483,7 +2427,7 @@ Braces? No way! If you think that's disappointing, use Java. Okay, another surpr --- -### ▶ Let's meet Friendly Language Uncle For Life ^ +### ▶ Let's meet Friendly Language Uncle For Life **Output (Python 3.x)** ```py @@ -2514,7 +2458,7 @@ There we go. --- -### ▶ Even Python understands that love is complicated * +### ▶ Even Python understands that love is complicated ```py import this @@ -2615,7 +2559,7 @@ Try block executed successfully... - `else` clause after try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. --- -### ▶ Ellipsis ^ +### ▶ Ellipsis ```py def some_func(): @@ -2675,7 +2619,7 @@ Ellipsis --- -### ▶ Inpinity * +### ▶ Inpinity The spelling is intended. Please, don't submit a patch for this. @@ -2694,7 +2638,7 @@ The spelling is intended. Please, don't submit a patch for this. --- -### ▶ Let's mangle ^ +### ▶ Let's mangle 1\. ```py From d3157d61a303e31082ac7a82ebfd5e39e5ae8eb9 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 8 Jul 2019 22:22:04 +0530 Subject: [PATCH 039/221] Fix toc --- README.md | 141 ++++++++++++++++++++++++++---------------------------- 1 file changed, 69 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index 4a7157f5..5787e06f 100644 --- a/README.md +++ b/README.md @@ -20,85 +20,82 @@ So, here we go... # Table of Contents - - - + - [Structure of the Examples](#structure-of-the-examples) + + [▶ Some fancy Title](#-some-fancy-title) - [Usage](#usage) - [👀 Examples](#-examples) - - [Section: Strain your brain!](#section-strain-your-brain) - - [▶ Strings can be tricky sometimes](#%E2%96%B6-strings-can-be-tricky-sometimes) - - [▶ Splitsies](#%E2%96%B6-splitsies) -- [is same as](#is-same-as) -- [but](#but) -- [isn't the same as](#isnt-the-same-as) - - [▶ Time for some hash brownies!](#%E2%96%B6-time-for-some-hash-brownies) - - [▶ The disorder within order](#%E2%96%B6-the-disorder-within-order) - - [▶ Keep trying?](#%E2%96%B6-keep-trying) - - [▶ Deep down, we're all the same](#%E2%96%B6-deep-down-were-all-the-same) - - [▶ For what?](#%E2%96%B6-for-what) - - [▶ Evaluation time discrepancy](#%E2%96%B6-evaluation-time-discrepancy) - - [▶ Messing around with `is` operator^](#%E2%96%B6-messing-around-with-is-operator%5E) - - [▶ A tic-tac-toe where X wins in the first attempt!](#%E2%96%B6-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - - [▶ The sticky output function](#%E2%96%B6-the-sticky-output-function) - - [▶ The chicken-egg problem](#%E2%96%B6-the-chicken-egg-problem) - - [▶ `is not ...` is not `is (not ...)`](#%E2%96%B6-is-not--is-not-is-not-) - - [▶ The surprising comma](#%E2%96%B6-the-surprising-comma) - - [▶ Strings and the backslashes](#%E2%96%B6-strings-and-the-backslashes) - - [▶ not knot!](#%E2%96%B6-not-knot) - - [▶ Half triple-quoted strings](#%E2%96%B6-half-triple-quoted-strings) - - [▶ Midnight time doesn't exist?](#%E2%96%B6-midnight-time-doesnt-exist) - - [▶ What's wrong with booleans?](#%E2%96%B6-whats-wrong-with-booleans) - - [▶ Class attributes and instance attributes](#%E2%96%B6-class-attributes-and-instance-attributes) - - [▶ yielding None](#%E2%96%B6-yielding-none) - - [▶ Mutating the immutable!](#%E2%96%B6-mutating-the-immutable) - - [▶ The disappearing variable from outer scope](#%E2%96%B6-the-disappearing-variable-from-outer-scope) - - [▶ When True is actually False](#%E2%96%B6-when-true-is-actually-false) - - [▶ Lossy zip of iterators](#%E2%96%B6-lossy-zip-of-iterators) - - [▶ From filled to None in one instruction...](#%E2%96%B6-from-filled-to-none-in-one-instruction) - - [▶ Subclass relationships](#%E2%96%B6-subclass-relationships) - - [▶ The mysterious key type conversion](#%E2%96%B6-the-mysterious-key-type-conversion) - - [▶ Let's see if you can guess this?](#%E2%96%B6-lets-see-if-you-can-guess-this) - - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - - [▶ Skipping lines?](#%E2%96%B6-skipping-lines) - - [▶ Teleportation](#%E2%96%B6-teleportation) - - [▶ Well, something is fishy...](#%E2%96%B6-well-something-is-fishy) - - [Section: Watch out for the landmines!](#section-watch-out-for-the-landmines) - - [▶ Modifying a dictionary while iterating over it](#%E2%96%B6-modifying-a-dictionary-while-iterating-over-it) - - [▶ Deleting a list item while iterating](#%E2%96%B6-deleting-a-list-item-while-iterating) - - [▶ Loop variables leaking out!](#%E2%96%B6-loop-variables-leaking-out) - - [▶ Beware of default mutable arguments!](#%E2%96%B6-beware-of-default-mutable-arguments) - - [▶ Catching the Exceptions](#%E2%96%B6-catching-the-exceptions) - - [▶ Same operands, different story!](#%E2%96%B6-same-operands-different-story) - - [▶ The out of scope variable](#%E2%96%B6-the-out-of-scope-variable) - - [▶ Be careful with chained operations](#%E2%96%B6-be-careful-with-chained-operations) - - [▶ Name resolution ignoring class scope](#%E2%96%B6-name-resolution-ignoring-class-scope) - - [▶ Needles in a Haystack](#%E2%96%B6-needles-in-a-haystack) - - [▶ Wild imports](#%E2%96%B6-wild-imports) - - [Section: The Hidden treasures!](#section-the-hidden-treasures) - - [▶ Okay Python, Can you make me fly?](#%E2%96%B6-okay-python-can-you-make-me-fly) - - [▶ `goto`, but why?](#%E2%96%B6-goto-but-why) - - [▶ Brace yourself!](#%E2%96%B6-brace-yourself) - - [▶ Let's meet Friendly Language Uncle For Life](#%E2%96%B6-lets-meet-friendly-language-uncle-for-life) - - [▶ Even Python understands that love is complicated](#%E2%96%B6-even-python-understands-that-love-is-complicated) - - [▶ Yes, it exists!](#%E2%96%B6-yes-it-exists) - - [▶ Ellipsis](#%E2%96%B6-ellipsis) - - [▶ Inpinity](#%E2%96%B6-inpinity) - - [▶ Let's mangle](#%E2%96%B6-lets-mangle) - - [Section: Miscellaneous](#section-miscellaneous) - - [▶ `+=` is faster](#%E2%96%B6--is-faster) - - [▶ Let's make a giant string!](#%E2%96%B6-lets-make-a-giant-string) - - [▶ Explicit typecast of strings](#%E2%96%B6-explicit-typecast-of-strings) - - [▶ Minor Ones](#%E2%96%B6-minor-ones) + * [Section: Strain your brain!](#section-strain-your-brain) + + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) + + [▶ Splitsies](#-splitsies) + + [▶ Time for some hash brownies!](#-time-for-some-hash-brownies) + + [▶ The disorder within order](#-the-disorder-within-order) + + [▶ Keep trying?](#-keep-trying) + + [▶ Deep down, we're all the same](#-deep-down-were-all-the-same) + + [▶ For what?](#-for-what) + + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) + + [▶ Messing around with `is` operator](#-messing-around-with-is-operator) + + [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + + [▶ The sticky output function](#-the-sticky-output-function) + + [▶ The chicken-egg problem](#-the-chicken-egg-problem) + + [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) + + [▶ The surprising comma](#-the-surprising-comma) + + [▶ Strings and the backslashes](#-strings-and-the-backslashes) + + [▶ not knot!](#-not-knot) + + [▶ Half triple-quoted strings](#-half-triple-quoted-strings) + + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) + + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) + + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) + + [▶ yielding None](#-yielding-none) + + [▶ Mutating the immutable!](#-mutating-the-immutable) + + [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) + + [▶ When True is actually False](#-when-true-is-actually-false) + + [▶ Lossy zip of iterators](#-lossy-zip-of-iterators) + + [▶ From filled to None in one instruction...](#-from-filled-to-none-in-one-instruction) + + [▶ Subclass relationships](#-subclass-relationships) + + [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) + + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + * [Section: Appearances are deceptive!](#section-appearances-are-deceptive) + + [▶ Skipping lines?](#-skipping-lines) + + [▶ Teleportation](#-teleportation) + + [▶ Well, something is fishy...](#-well-something-is-fishy) + * [Section: Watch out for the landmines!](#section-watch-out-for-the-landmines) + + [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + + [▶ Stubborn `del` operation](#-stubborn-del-operation) + + [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) + + [▶ Loop variables leaking out!](#-loop-variables-leaking-out) + + [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) + + [▶ Catching the Exceptions](#-catching-the-exceptions) + + [▶ Same operands, different story!](#-same-operands-different-story) + + [▶ The out of scope variable](#-the-out-of-scope-variable) + + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + + [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) + + [▶ Needles in a Haystack](#-needles-in-a-haystack) + + [▶ Wild imports](#-wild-imports) + * [Section: The Hidden treasures!](#section-the-hidden-treasures) + + [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) + + [▶ `goto`, but why?](#-goto-but-why) + + [▶ Brace yourself!](#-brace-yourself) + + [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) + + [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) + + [▶ Yes, it exists!](#-yes-it-exists) + + [▶ Ellipsis](#-ellipsis) + + [▶ Inpinity](#-inpinity) + + [▶ Let's mangle](#-lets-mangle) + * [Section: Miscellaneous](#section-miscellaneous) + + [▶ `+=` is faster](#--is-faster) + + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + + [▶ Explicit typecast of strings](#-explicit-typecast-of-strings) + + [▶ Minor Ones](#-minor-ones) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) - [🎓 License](#-license) - - [Help](#help) - - [Surprise your geeky pythonist friends?](#surprise-your-geeky-pythonist-friends) - - [Need a pdf version?](#need-a-pdf-version) + * [Help](#help) + * [Surprise your geeky pythonist friends?](#surprise-your-geeky-pythonist-friends) + * [Need a pdf version?](#need-a-pdf-version) - + # Structure of the Examples @@ -623,7 +620,7 @@ array_4 = [400, 500, 600] --- -### ▶ Messing around with `is` operator^ +### ▶ Messing around with `is` operator The following is a very famous example present all over the internet. From 772a96c36fbecfa74f314c3b60c3f58315b068a5 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 13 Jul 2019 22:41:27 +0530 Subject: [PATCH 040/221] change order --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5787e06f..f140259c 100644 --- a/README.md +++ b/README.md @@ -262,9 +262,9 @@ some_dict[5] = "Python" ```py >>> some_dict[5.5] "Ruby" ->>> some_dict[5.0] +>>> some_dict[5.0] # "Python" destroyed the existence of "JavaScript"? "Python" ->>> some_dict[5] # "Python" destroyed the existence of "JavaScript"? +>>> some_dict[5] "Python" >>> complex_five = 5 + 0j From ffe64385762b91d9548777b165a4120f3ff2eccd Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 21 Jul 2019 18:57:01 +0530 Subject: [PATCH 041/221] Commit insert_ids script --- irrelevant/insert_ids.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 irrelevant/insert_ids.py diff --git a/irrelevant/insert_ids.py b/irrelevant/insert_ids.py new file mode 100644 index 00000000..a16bf5f5 --- /dev/null +++ b/irrelevant/insert_ids.py @@ -0,0 +1,24 @@ +import uuid + +new_file = [] +original_file = [] + +fname = "../README.md" + + +def generate_random_id_comment(): + random_id = uuid.uuid4() + return f"" + + +with open(fname, "r") as f: + original_file = f.readlines() + + +for line in original_file: + new_file.append(line) + if line.strip().startswith("### "): + new_file.append(generate_random_id_comment()) + +with open(fname, "w") as f: + f.write("".join(new_file)) From b0622a10ad2d1a5b5b339e89e2836002f6e008c6 Mon Sep 17 00:00:00 2001 From: Nikita Sobolev Date: Tue, 30 Jul 2019 00:34:58 +0300 Subject: [PATCH 042/221] Fixes code highlight --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0e6fd1c7..d66d6328 100644 --- a/README.md +++ b/README.md @@ -1845,7 +1845,7 @@ x, y = (0, 1) if True else None, None ``` **Output:** -``` +```py >>> x, y # expected (0, 1) ((0, 1), None) ``` From cedbfba829b894d1d6d45cd5f00e5611ee339a01 Mon Sep 17 00:00:00 2001 From: Kislov Dmitry Date: Fri, 13 Sep 2019 12:03:27 +1000 Subject: [PATCH 043/221] New snippet: yielding from... return! --- README.md | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/README.md b/README.md index d66d6328..47bf681d 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ So, here we go... - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - [▶ Needle in a Haystack](#-needle-in-a-haystack) + - [▶ Yielding from... return!](#-yielding-from-return) - [Section: The Hidden treasures!](#section-the-hidden-treasures) - [▶ Okay Python, Can you make me fly? *](#-okay-python-can-you-make-me-fly-) - [▶ `goto`, but why? *](#-goto-but-why-) @@ -1883,6 +1884,64 @@ tuple() --- +### ▶ Yielding from... return! + +1\. +```py +def func(k): + if k == 3: + return ["A string..."] + else: + yield from range(k) +``` + +**Output:** +```py +>>> list(func(3)) # expected: ["A string..."] +[] +``` + +The same behavior is true if we rewrite `yield from` as a for loop. + +2\. +```py +def func(k): + if k == 3: + return ["A string..."] + else: + for j in range(k): + yield j +``` + +**Output:** +```py +>>> list(func(3)) # expected: ["A string..."] +[] +``` + +#### 💡 Explanation: + +Starting from Python 3.3+ it became possible to use return statement +with values inside generators ([PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official doc](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) says that "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." + +So, to get `["A string..."]` from the generator `func` we need to catch `StopIteration`, e.g.: + +```py +try: + next(func(3)) +except StopIteration as e: + string = e.value +``` + +```py +>>> string +['A string...'] +``` + +Note that `list(...)` automatically catches `StopIteration`. In case of `func(3)` `StopIteration` raises at the beginning because of `return` statement. Therefore, `list(func(3))` results in an empty list. + +--- + --- From c5665da81d583b92868218bc2a1f07436fd0456d Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 13 Sep 2019 15:01:45 +0530 Subject: [PATCH 044/221] Nitpicks in the new example --- README.md | 55 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 47bf681d..be27847b 100644 --- a/README.md +++ b/README.md @@ -1888,57 +1888,60 @@ tuple() 1\. ```py -def func(k): - if k == 3: - return ["A string..."] +def some_func(x): + if x == 3: + return ["wtf"] else: - yield from range(k) + yield from range(x) ``` **Output:** ```py ->>> list(func(3)) # expected: ["A string..."] +>>> list(some_func(3)) [] ``` -The same behavior is true if we rewrite `yield from` as a for loop. +Where did the `"wtf"` go? Is it due to some special effect of `yield from`? Let's validate that, 2\. ```py -def func(k): - if k == 3: - return ["A string..."] +def some_func(x): + if x == 3: + return ["wtf"] else: - for j in range(k): - yield j + for i in range(x): + yield i ``` **Output:** ```py ->>> list(func(3)) # expected: ["A string..."] +>>> list(some_func(3)) [] ``` +Same result, that didn't work either. + #### 💡 Explanation: -Starting from Python 3.3+ it became possible to use return statement -with values inside generators ([PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official doc](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) says that "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." ++ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that, -So, to get `["A string..."]` from the generator `func` we need to catch `StopIteration`, e.g.: +> "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." -```py -try: - next(func(3)) -except StopIteration as e: - string = e.value -``` ++ In case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically catched inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. -```py ->>> string -['A string...'] -``` ++ To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, + ```py + try: + next(some_func(3)) + except StopIteration as e: + some_string = e.value + ``` + + ```py + >>> some_string + ["wtf"] + ``` -Note that `list(...)` automatically catches `StopIteration`. In case of `func(3)` `StopIteration` raises at the beginning because of `return` statement. Therefore, `list(func(3))` results in an empty list. --- From 03719dea4584ac2237b4ed0c9274afb063e3dd70 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 13 Sep 2019 15:15:31 +0530 Subject: [PATCH 045/221] Add few pointers for contributing well --- CONTRIBUTING.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 13a5a0dd..e9c43dbf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,3 +36,10 @@ Probably unexpected output ``` ``` + + +Few things that you can consider while writing an example, + +- Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's strictly enforced scheme in the project, but you can take a glance at other examples to get a gist. +- Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write. +- Also, please don't forget to add your name to the [contributors list](/CONTRIBUTING.md). \ No newline at end of file From 290921fe12091a2364a2ff0a876c557baad19ec1 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Wed, 1 May 2019 19:12:17 +0530 Subject: [PATCH 046/221] Add json generator --- irrelevant/json_generator.py | 156 +++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 irrelevant/json_generator.py diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py new file mode 100644 index 00000000..86820f19 --- /dev/null +++ b/irrelevant/json_generator.py @@ -0,0 +1,156 @@ +import pprint +fname = "/Users/300041709/code/self/wtfpython/README.md" +examples = [] + +# The globals +current_example = 1 +current_section_name = "" + + +def parse_example_parts(lines): + parts = { + "build_up": [], + "explanation": [] + } + next_line = next(lines) + sequence_num = 1 + content = [] + # store build_up till an H4 (explanation) is encountered + while not next_line.startswith("#### "): + # Watching out for the snippets + if next_line.startswith("```"): + # It's a snippet, whatever found until now is text + if content: + parts["build_up"].append( + { + "type": "text", + "sequence_num": sequence_num, + "value": content + } + ) + sequence_num += 1 + content = [] + + next_line = next(lines) + while not next_line.startswith("```"): + content.append(next_line) + next_line = next(lines) + # Snippet is over + parts["build_up"].append( + { + "type": "code", + "sequence_num": sequence_num, + "value": content + } + ) + sequence_num += 1 + content = [] + next_line = next(lines) + continue + else: + # It's a text, go on. + content.append(next_line) + next_line = next(lines) + + # Explanation encountered, save any content till now (if any) + if content: + parts["build_up"].append( + { + "type": "text", + "sequence_num": sequence_num, + "value": content + } + ) + + # Reset stuff + sequence_num = 1 + content = [] + + # store lines again until --- or another H3 is encountered + while not (next_line.startswith("---") or + next_line.startswith("### ")): + + if next_line.startswith("```"): + # It's a snippet, whatever found until now is text + if content: + parts["explanation"].append( + { + "type": "text", + "sequence_num": sequence_num, + "value": content + } + ) + sequence_num += 1 + content = [] + + next_line = next(lines) + while not next_line.startswith("```"): + content.append(next_line) + next_line = next(lines) + # Snippet is over + parts["explanation"].append( + { + "type": "code", + "sequence_num": sequence_num, + "value": content + } + ) + sequence_num += 1 + content = [] + next_line = next(lines) + continue + else: + # It's a text, go on. + content.append(next_line) + next_line = next(lines) + + # All done + if content: + parts["explanation"].append( + { + "type": "text", + "sequence_num": sequence_num, + "value": content + } + ) + + return next_line, parts + + +with open(fname, 'r+', encoding="utf-8") as f: + lines = iter(f.readlines()) + line = next(lines) + result = [] + try: + while True: + if line.startswith("## "): + # A section is encountered + current_section_name = line.replace("## ", "").strip() + line = next(lines) + # Until a new section is encountered + while not (line.startswith("## " )): + # check if it's a H3 + if line.startswith("### "): + # An example is encountered + title = line.replace("### ", "") + example_details = { + "id": current_example, + "title": line.replace("### ", ""), + "section": current_section_name + } + line, example_details["parts"] = parse_example_parts(lines) + result.append(example_details) + current_example += 1 + else: + # todo catch section text + line = next(lines) + else: + line = next(lines) + + except StopIteration: + pprint.pprint(result, indent=2) + print(len(result)) + + + + From 3479b2befb884ce8a14d087f5febe5b445016c5a Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Wed, 1 May 2019 19:55:46 +0530 Subject: [PATCH 047/221] Use absolute path for the pager. Fixes https://github.com/satwikkansal/wtfpython/issues/119 --- wtfpython-pypi/wtf_python/main.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/wtfpython-pypi/wtf_python/main.py b/wtfpython-pypi/wtf_python/main.py index 5799178c..bf768154 100644 --- a/wtfpython-pypi/wtf_python/main.py +++ b/wtfpython-pypi/wtf_python/main.py @@ -1,3 +1,5 @@ +from os.path import dirname, join, realpath + import pydoc try: from urllib.request import urlretrieve @@ -6,13 +8,14 @@ url = ("http://raw.githubusercontent.com/satwikkansal/" "wtfpython/master/README.md") -file_name = "content.md" + +file_path = join(dirname(dirname(realpath(__file__))), "content.md") def fetch_updated_doc(): try: print("Fetching the latest version...") - urlretrieve(url, file_name) + urlretrieve(url, file_path) print("Done!") except Exception as e: print(e) @@ -21,7 +24,7 @@ def fetch_updated_doc(): def render_doc(): - with open(file_name, 'r', encoding='utf-8') as f: + with open(file_path, 'r', encoding="utf-8") as f: content = f.read() pydoc.pager(content) From efdac8f9caf82336d6c13686a7a9c393fa3ccbab Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 6 May 2019 23:47:24 +0530 Subject: [PATCH 048/221] Get the generator in a working state --- irrelevant/json_generator.py | 239 +++++++++++++++++++++++++---------- 1 file changed, 175 insertions(+), 64 deletions(-) diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py index 86820f19..ea75cb5c 100644 --- a/irrelevant/json_generator.py +++ b/irrelevant/json_generator.py @@ -1,52 +1,85 @@ +import json import pprint fname = "/Users/300041709/code/self/wtfpython/README.md" examples = [] # The globals current_example = 1 +sequence_num = 1 current_section_name = "" -def parse_example_parts(lines): +STATEMENT_PREFIXES = ["...", ">>> ", "$ "] + + +def generate_code_block(statements, output): + global sequence_num + result = { + "type": "code", + "sequence_num": sequence_num, + "statements": statements, + "output": output + } + sequence_num += 1 + return result + + +def generate_markdown_block(lines): + global sequence_num + result = { + "type": "markdown", + "sequence_num": sequence_num, + "value": lines + } + sequence_num += 1 + return result + +def is_interactive_statement(line): + for prefix in STATEMENT_PREFIXES: + if line.startswith(prefix): + return True + return False + +def parse_example_parts(lines, example_title_line): parts = { "build_up": [], "explanation": [] } - next_line = next(lines) - sequence_num = 1 content = [] + statements_so_far = [] + output_so_far = [] + next_line = example_title_line # store build_up till an H4 (explanation) is encountered while not next_line.startswith("#### "): # Watching out for the snippets if next_line.startswith("```"): # It's a snippet, whatever found until now is text + is_interactive = False if content: - parts["build_up"].append( - { - "type": "text", - "sequence_num": sequence_num, - "value": content - } - ) - sequence_num += 1 + parts["build_up"].append(generate_markdown_block(content)) content = [] next_line = next(lines) + while not next_line.startswith("```"): - content.append(next_line) + if is_interactive_statement(next_line): + is_interactive = True + if (output_so_far): + parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + statements_so_far, output_so_far = [], [] + statements_so_far.append(next_line) + else: + # can be either output or normal code + if is_interactive: + output_so_far.append(next_line) + else: + statements_so_far.append(next_line) next_line = next(lines) + # Snippet is over - parts["build_up"].append( - { - "type": "code", - "sequence_num": sequence_num, - "value": content - } - ) - sequence_num += 1 - content = [] + parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + statements_so_far, output_so_far = [], [] next_line = next(lines) - continue else: # It's a text, go on. content.append(next_line) @@ -54,51 +87,43 @@ def parse_example_parts(lines): # Explanation encountered, save any content till now (if any) if content: - parts["build_up"].append( - { - "type": "text", - "sequence_num": sequence_num, - "value": content - } - ) + parts["build_up"].append(generate_markdown_block(content)) # Reset stuff - sequence_num = 1 content = [] + statements_so_far, output_so_far = [], [] # store lines again until --- or another H3 is encountered while not (next_line.startswith("---") or next_line.startswith("### ")): - if next_line.startswith("```"): # It's a snippet, whatever found until now is text + is_interactive = False if content: - parts["explanation"].append( - { - "type": "text", - "sequence_num": sequence_num, - "value": content - } - ) - sequence_num += 1 + parts["build_up"].append(generate_markdown_block(content)) content = [] next_line = next(lines) + while not next_line.startswith("```"): - content.append(next_line) + if is_interactive_statement(next_line): + is_interactive = True + if (output_so_far): + parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + statements_so_far, output_so_far = [], [] + statements_so_far.append(next_line) + else: + # can be either output or normal code + if is_interactive: + output_so_far.append(next_line) + else: + statements_so_far.append(next_line) next_line = next(lines) + # Snippet is over - parts["explanation"].append( - { - "type": "code", - "sequence_num": sequence_num, - "value": content - } - ) - sequence_num += 1 - content = [] + parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + statements_so_far, output_so_far = [], [] next_line = next(lines) - continue else: # It's a text, go on. content.append(next_line) @@ -106,16 +131,105 @@ def parse_example_parts(lines): # All done if content: - parts["explanation"].append( - { - "type": "text", - "sequence_num": sequence_num, - "value": content - } - ) + parts["explanation"].append(generate_markdown_block(content)) return next_line, parts +def remove_from_beginning(tokens, line): + for token in tokens: + if line.startswith(token): + line = line.replace(token, "") + return line + + +def inspect_and_sanitize_code_lines(lines): + tokens_to_remove = STATEMENT_PREFIXES + result = [] + is_print_present = False + for line in lines: + line = remove_from_beginning(tokens_to_remove, line) + if line.startswith("print ") or line.startswith("print("): + is_print_present = True + result.append(line) + return is_print_present, result + +def convert_to_cells(cell_contents): + cells = [] + for stuff in cell_contents: + if stuff["type"] == "markdown": + # todo add metadata later + cells.append( + { + "cell_type": "markdown", + "metadata": {}, + "source": stuff["value"] + } + ) + elif stuff["type"] == "code": + is_print_present, sanitized_code = inspect_and_sanitize_code_lines(stuff["statements"]) + if is_print_present: + cells.append( + { + "cell_type": "code", + "metadata": { + "collapsed": True + }, + "execution_count": None, + "outputs": [{ + "name": "stdout", + "output_type": "stream", + "text": stuff["output"] + }], + "source": sanitized_code + } + ) + else: + cells.append( + { + "cell_type": "code", + "execution_count": None, + "metadata": { + "collapsed": True + }, + "outputs": [{ + "data": { + "text/plain": stuff["output"] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": None + }], + "source": sanitized_code + } + ) + + return cells + + +def convert_to_notebook(parsed_json): + result = { + "cells": [], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 + } + for example in parsed_json: + parts = example["parts"] + build_up = parts.get("build_up") + explanation = parts.get("explanation") + notebook_path = "test.ipynb" + + if(build_up): + result["cells"] += convert_to_cells(build_up) + + if(explanation): + result["cells"] += convert_to_cells(explanation) + + pprint.pprint(result, indent=2) + with open(notebook_path, "w") as f: + json.dump(result, f) + + with open(fname, 'r+', encoding="utf-8") as f: lines = iter(f.readlines()) @@ -126,6 +240,7 @@ def parse_example_parts(lines): if line.startswith("## "): # A section is encountered current_section_name = line.replace("## ", "").strip() + section_text = [] line = next(lines) # Until a new section is encountered while not (line.startswith("## " )): @@ -138,19 +253,15 @@ def parse_example_parts(lines): "title": line.replace("### ", ""), "section": current_section_name } - line, example_details["parts"] = parse_example_parts(lines) + line, example_details["parts"] = parse_example_parts(lines, line) result.append(example_details) current_example += 1 else: - # todo catch section text + section_text.append(line) line = next(lines) else: line = next(lines) except StopIteration: pprint.pprint(result, indent=2) - print(len(result)) - - - - + convert_to_notebook(result) From a5e7cd7cf83c3dc8522b9e5889758cf993967c2e Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 6 May 2019 23:49:57 +0530 Subject: [PATCH 049/221] Add todos --- irrelevant/json_generator.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py index ea75cb5c..cfebf4f5 100644 --- a/irrelevant/json_generator.py +++ b/irrelevant/json_generator.py @@ -1,3 +1,15 @@ +""" +An inefficient monolithic piece of code that'll generate jupyter notebook +from the projects main README. + +TODO + +- CLI arguments for running this thing. +- Add it to prepush hook +- Use templates? + +""" + import json import pprint fname = "/Users/300041709/code/self/wtfpython/README.md" From 810dbe15822ff0393dd29746573bb950bc58220f Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Fri, 7 Jun 2019 23:48:07 +0530 Subject: [PATCH 050/221] Some hideous typora corrections and a new snippets added Also closes https://github.com/satwikkansal/wtfpython/issues/73 --- README.md | 55 +++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index be27847b..7fffe0cd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

+

What the f*ck Python! 🐍

An interesting collection of surprising snippets and lesser-known Python features.

@@ -203,11 +203,10 @@ Makes sense, right? * All length 0 and length 1 strings are interned. * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) - + + When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. + Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than or equal to 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. - --- ### ▶ Time for some hash brownies! @@ -248,7 +247,7 @@ some_dict[5] = "Python" --- -### ▶ Return return everywhere! +### ▶ Keep trying? * ```py def some_func(): @@ -256,18 +255,55 @@ def some_func(): return 'from_try' finally: return 'from_finally' + +def another_func(): + for _ in range(3): + try: + continue + finally: + print("Finally!") + +def one_more_func(): # A gotcha! + try: + for i in range(3): + try: + 1 / i + except ZeroDivisionError: + # Let's throw it here and handle it outside for loop + raise ZeroDivisionError("A trivial divide by zero error") + finally: + print("Iteration", i) + break + except ZeroDivisionError as e: + print("Zero division error ocurred", e) ``` **Output:** + ```py >>> some_func() 'from_finally' + +>>> another_func() +Finally! +Finally! +Finally! + +>>> 1 / 0 +Traceback (most recent call last): + File "", line 1, in +ZeroDivisionError: division by zero + +>>> one_more_func() +Iteration 0 + ``` #### 💡 Explanation: - 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. - 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. +- The caveat here is, if the finally clause executes a `return` or `break` statement, the temporarily saved exception is discarded. --- @@ -531,11 +567,11 @@ We didn't assign 3 "X"s or did we? When we initialize `row` variable, this visualization explains what happens in the memory -![image](/images/tic-tac-toe/after_row_initialized.png) +![image](images/tic-tac-toe/after_row_initialized.png) And 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`) -![image](/images/tic-tac-toe/after_board_initialized.png) +![image](images/tic-tac-toe/after_board_initialized.png) We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue). @@ -1185,8 +1221,9 @@ a, b = a[b] = {}, 5 (target_list "=")+ (expression_list | yield_expression) ``` and - > 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. - + +> 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. + * 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`). * After the expression list is evaluated, it's 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`. @@ -1320,6 +1357,7 @@ Shouldn't that be 100? * **Don't mix tabs and spaces!** The character just preceding return is a "tab", and the code is indented by multiple of "4 spaces" elsewhere in the example. * This is how Python handles tabs: + > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...> * So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. * Python 3 is kind enough to throw an error for such cases automatically. @@ -2041,6 +2079,7 @@ There we go. #### 💡 Explanation: - This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means). - Quoting from the PEP-401 + > Recognized that the != inequality operator in Python 3.0 was a horrible, finger pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. - There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/). From f8a7d38b70ce00411c752797a3101f38c1a3c57d Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Fri, 7 Jun 2019 23:48:51 +0530 Subject: [PATCH 051/221] Update content.md --- wtfpython-pypi/content.md | 79 ++++++++++++++++++++++----------------- 1 file changed, 44 insertions(+), 35 deletions(-) diff --git a/wtfpython-pypi/content.md b/wtfpython-pypi/content.md index 486a98e7..9827fc46 100644 --- a/wtfpython-pypi/content.md +++ b/wtfpython-pypi/content.md @@ -1,9 +1,10 @@

-

What the f*ck Python! 🐍

-

An interesting collection of surprising snippets and lesser-known Python features.

+

What the f*ck Python! 🐍

+

An interesting collection of surprising snippets and lesser-known Python features.

[![WTFPL 2.0][license-image]][license-url] +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) 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 to a regular user at first sight. @@ -13,7 +14,7 @@ While some of the examples you see below may not be WTFs in the truest sense, bu If you're an experienced Python programmer, you can take it as a challenge to get most of them right in first attempt. You may be already familiar with some of these examples, and I might be able to revive sweet old memories of yours being bitten by these gotchas :sweat_smile: -If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). +PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). So, here we go... @@ -77,7 +78,7 @@ So, here we go... - [▶ Yes, it exists!](#-yes-it-exists) - [▶ Inpinity *](#-inpinity-) - [▶ Mangling time! *](#-mangling-time-) - - [Section: Miscallaneous](#section-miscallaneous) + - [Section: Miscellaneous](#section-miscellaneous) - [▶ `+=` is faster](#--is-faster) - [▶ Let's make a giant string!](#-lets-make-a-giant-string) - [▶ Explicit typecast of strings](#-explicit-typecast-of-strings) @@ -97,22 +98,22 @@ All the examples are structured like below: > ### ▶ Some fancy Title * > The asterisk at the end of the title indicates the example was not present in the first release and has been recently added. -> +> > ```py > # Setting up the code. > # Preparation for the magic... > ``` -> +> > **Output (Python version):** > ```py > >>> triggering_statement > Probably unexpected output > ``` > (Optional): One line describing the unexpected output. -> -> +> +> > #### 💡 Explanation: -> +> > * Brief explanation of what's happening and why is it happening. > ```py > Setting up examples for clarification (if necessary) @@ -200,10 +201,10 @@ Makes sense, right? + In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation dependent. There are some facts that can be used to guess if a string will be interned or not: * All length 0 and length 1 strings are interned. * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) - * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. + * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) + When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. -+ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. But since the python bytecode generated after compilation is stored in `.pyc` files, the strings greater than length of 20 are discarded for peephole optimization (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`) ++ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. --- @@ -241,7 +242,7 @@ some_dict[5] = "Python" True ``` **Note:** Objects with different values may also have same hash (known as hash collision). -* When the statement `some_dict[5] = "Python"` is executed, the existing value "JavaScript" is overwritten with "Python" because Python recongnizes `5` and `5.0` as the same keys of the dictionary `some_dict`. +* When the statement `some_dict[5] = "Python"` is executed, the existing value "JavaScript" is overwritten with "Python" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`. * This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains beautifully the rationale behind it. --- @@ -296,16 +297,24 @@ True * But why did the `is` operator evaluated to `False`? Let's see with this snippet. ```py class WTF(object): - def __init__(self): print("I ") - def __del__(self): print("D ") + def __init__(self): print("I") + def __del__(self): print("D") ``` **Output:** ```py >>> WTF() is WTF() - I I D D + I + I + D + D + False >>> id(WTF()) == id(WTF()) - I D I D + I + D + I + D + True ``` As you may observe, the order in which the objects are destroyed is what made all the difference here. @@ -530,7 +539,7 @@ And when the `board` is initialized by multiplying the `row`, this is what happe We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue). ```py ->>> board = [(['']*3)*3] # board = = [['']*3 for _ in range(3)] +>>> board = [['']*3 for _ in range(3)] >>> board[0][0] = "X" >>> board [['X', '', ''], ['', '', ''], ['', '', '']] @@ -547,7 +556,7 @@ for x in range(7): def some_func(): return x funcs.append(some_func) - results.append(some_func()) + results.append(some_func()) # note the function call here funcs_results = [func() for func in funcs] ``` @@ -766,10 +775,10 @@ for item in mixed_list: **Output:** ```py ->>> booleans_found_so_far -0 >>> integers_found_so_far 4 +>>> booleans_found_so_far +0 ``` 2\. @@ -830,7 +839,7 @@ class C(A): pass ``` -**Ouptut:** +**Output:** ```py >>> A.x, B.x, C.x (1, 1, 1) @@ -1135,7 +1144,7 @@ str and type(other) is SomeClass and super().__eq__(other) ) - + # When we define a custom __eq__, Python stops automatically inheriting the # __hash__ method, so we need to define it as well __hash__ = str.__hash__ @@ -1148,7 +1157,7 @@ str >>> s = SomeClass('s') >>> some_dict[s] = 40 >>> some_dict - {'s': 40} + {'s': 40, 's': 42} >>> keys = list(some_dict.keys()) >>> type(keys[0]), type(keys[1]) (__main__.SomeClass, str) @@ -1313,7 +1322,7 @@ Shouldn't that be 100? > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...> * So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. * Python 3 is kind enough to throw an error for such cases automatically. - + **Output (Python 3.x):** ```py TabError: inconsistent use of tabs and spaces in indentation @@ -1697,7 +1706,7 @@ a += [5, 6, 7, 8] * The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged. -* The expression `a + =[5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. +* The expression `a += [5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. --- @@ -1731,7 +1740,7 @@ UnboundLocalError: local variable 'a' referenced before assignment a += 1 return a ``` - + **Output:** ```py >>> another_func() @@ -1895,7 +1904,7 @@ Sshh.. It's a super secret. #### 💡 Explanation: + `antigravity` module is one of the few easter eggs released by Python developers. + `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python. -+ Well, there's more to it. There's **another easter egg inside the easter egg**. If look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/). ++ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/). --- @@ -2115,7 +2124,7 @@ AttributeError: 'Yo' object has no attribute '__honey' True ``` -Why did `Yo()._Yo__honey` worked? Only Indian readers would understand. +Why did `Yo()._Yo__honey` work? Only Indian readers would understand. #### 💡 Explanation: @@ -2127,7 +2136,7 @@ Why did `Yo()._Yo__honey` worked? Only Indian readers would understand. --- -## Section: Miscallaneous +## Section: Miscellaneous ### ▶ `+=` is faster @@ -2272,7 +2281,7 @@ nan ### ▶ Minor Ones * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) - + **💡 Explanation:** If `join()` is a method on a string then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API. @@ -2350,7 +2359,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' * https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines * https://stackoverflow.com/questions/1011431/common-pitfalls-in-python * https://www.python.org/doc/humor/ -* https://www.satwikkansal.xyz/archives/posts/python/My-Python-archives/ +* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 # 🎓 License @@ -2365,12 +2374,12 @@ The idea and design for this collection were initially inspired by Denys Dovhan' If you have any wtfs, ideas or suggestions, please share. -## Want to share wtfpython with friends? +## Surprise your geeky pythonist friends? -You can use these quick links for Twitter and Linkedin. +You can use these quick links to recommend wtfpython to your friends, -[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) | -[Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) +[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) + | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) ## Need a pdf version? From dbbabbe564d63331a364514a18b68a9dcb16c2ff Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 00:23:33 +0530 Subject: [PATCH 052/221] Update evaluation time discrepency example: Add another snippet Resolves https://github.com/satwikkansal/wtfpython/issues/41 --- README.md | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7fffe0cd..266ddcbe 100644 --- a/README.md +++ b/README.md @@ -410,7 +410,7 @@ for i, some_dict[i] in enumerate(some_string): --- -### ▶ Evaluation time discrepancy +### ▶ Evaluation time discrepancy ^ 1\. ```py @@ -446,6 +446,23 @@ array_2[:] = [1,2,3,4,5] [1,2,3,4,5] ``` +3\. + +```py +array_3 = [1, 2, 3] +array_4 = [10, 20, 30] +g = (i + j for i in array_3 for j in array_4) + +array_3 = [4, 5, 6] +array_4 = [400, 500, 600] +``` + +**Output:** +```py +>>> print(list(g)) +[401, 501, 601, 402, 502, 602, 403, 503, 603] +``` + #### 💡 Explanation - In a [generator](https://wiki.python.org/moin/Generators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at runtime. @@ -453,6 +470,9 @@ array_2[:] = [1,2,3,4,5] - 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. - In the first case, `array_1` is binded 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). - 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]`). +- Okay, going by the logic discussed so far, shouldn't be the value of `list(g)` 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://www.python.org/dev/peps/pep-0289/#the-details) + > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run. + --- @@ -1223,7 +1243,7 @@ a, b = a[b] = {}, 5 and > 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. - + * 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`). * After the expression list is evaluated, it's 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`. From a0832c4459087bfcad7c506a7efcef3bb587077d Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 00:41:58 +0530 Subject: [PATCH 053/221] Modifying a dictionary while iterating over it: Add note Resolves https://github.com/satwikkansal/wtfpython/issues/53 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 266ddcbe..be6e5b07 100644 --- a/README.md +++ b/README.md @@ -471,8 +471,8 @@ array_4 = [400, 500, 600] - In the first case, `array_1` is binded 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). - 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]`). - Okay, going by the logic discussed so far, shouldn't be the value of `list(g)` 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://www.python.org/dev/peps/pep-0289/#the-details) + > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run. - --- @@ -1425,7 +1425,7 @@ Yes, it runs for exactly **eight** times and stops. * Iteration over a dictionary that you edit at the same time is not supported. * It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. * How deleted keys are handled and when the resize occurs might be different for different Python implementations. -* For more information, you may refer to this StackOverflow [thread](https://stackoverflow.com/questions/44763802/bug-in-python-dict) explaining a similar example in detail. +* So for Python versions other than Python 2.7 - Python 3.5 the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. --- From f3b96e4d7fa713b3bb27a75d3d14feb22904efd0 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 02:53:53 +0530 Subject: [PATCH 054/221] Expand strings and backslashes Resolves https://github.com/satwikkansal/wtfpython/issues/69 --- README.md | 51 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index be6e5b07..11405be9 100644 --- a/README.md +++ b/README.md @@ -471,7 +471,7 @@ array_4 = [400, 500, 600] - In the first case, `array_1` is binded 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). - 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]`). - Okay, going by the logic discussed so far, shouldn't be the value of `list(g)` 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://www.python.org/dev/peps/pep-0289/#the-details) - + > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run. --- @@ -704,30 +704,47 @@ SyntaxError: invalid syntax --- -### ▶ Backslashes at the end of string +### ▶ Strings and the backslashes\ **Output:** -``` ->>> print("\\ C:\\") -\ C:\ ->>> print(r"\ C:") -\ C: ->>> print(r"\ C:\") +```py +>>> print("\"") +" - File "", line 1 - print(r"\ C:\") - ^ +>>> print(r"\"") +\" + +>>> print(r"\") +File "", line 1 + print(r"\") + ^ SyntaxError: EOL while scanning string literal + +>>> r'\'' == "\\'" +True ``` #### 💡 Explanation -- In a raw string literal, as indicated by the prefix `r`, the backslash doesn't have the special meaning. - ```py - >>> print(repr(r"wt\"f")) - 'wt\\"f' - ``` -- What the interpreter actually does, though, is simply change the behavior of backslashes, so they pass themselves and the following character through. That's why backslashes don't work at the end of a raw string. +- In a normal python string, the backslash is used to escape characters that may have special meaning (like single-quote, double-quote and the backslash itself). + ```py + >>> 'wt\"f' + 'wt"f' + ``` +- 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. + ```py + >>> r'wt\"f' == 'wt\\"f' + True + >>> print(repr(r'wt\"f') + 'wt\\"f' + + >>> print("\n") + + + >>> print(r"\\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. --- From e3118ed4dacd6f189a599f77866e09d7bfa88098 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 14:21:19 +0530 Subject: [PATCH 055/221] Add new snippet: Splitsies Resolves https://github.com/satwikkansal/wtfpython/issues/80 --- README.md | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 11405be9..877a5a28 100644 --- a/README.md +++ b/README.md @@ -209,6 +209,44 @@ Makes sense, right? --- +### ▶ Splitsies ^ + +```py +>>> 'a'.split() +['a'] + +# is same as +>>> 'a'.split(' ') +['a'] + +# but +>>> len(''.split()) +0 + +# isn't the same as +>>> len(''.split(' ')) +1 +``` + +#### 💡 Explanation: + +- It might appear at first that the default seperator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split), + > If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`. + > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`. +- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear, + ```py + >>> ' a '.split(' ') + ['', 'a', ''] + >>> ' a '.split() + ['a'] + >>> ''.split(' ') + [''] + ``` + +--- + + + ### ▶ Time for some hash brownies! 1\. @@ -704,7 +742,7 @@ SyntaxError: invalid syntax --- -### ▶ Strings and the backslashes\ +### ▶ Strings and the backslashes\ ^ **Output:** ```py From 89c56c236616c363343862e04a1324fe1a921e1e Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 14:49:59 +0530 Subject: [PATCH 056/221] Let's meet Friendly Language Uncle For Life: Add notes for non-interactive evn Resolves https://github.com/satwikkansal/wtfpython/issues/94 --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 877a5a28..a2e5e38d 100644 --- a/README.md +++ b/README.md @@ -2134,7 +2134,7 @@ Braces? No way! If you think that's disappointing, use Java. --- -### ▶ Let's meet Friendly Language Uncle For Life * +### ▶ Let's meet Friendly Language Uncle For Life ^ **Output (Python 3.x)** ```py @@ -2157,6 +2157,11 @@ There we go. > Recognized that the != inequality operator in Python 3.0 was a horrible, finger pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. - There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/). +- It works well on interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working, + ```py + from __future__ import barry_as_FLUFL + print(eval('"Ruby" <> "Python"')) + ``` --- From 5373d0f1844fcf72e7350a37335cb74e53d49048 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 16:30:53 +0530 Subject: [PATCH 057/221] Add example: Ellipsis Resolves https://github.com/satwikkansal/wtfpython/issues/96 --- README.md | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/README.md b/README.md index a2e5e38d..f05f91de 100644 --- a/README.md +++ b/README.md @@ -2266,6 +2266,66 @@ Try block executed successfully... - `else` clause after try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. --- +### ▶ Ellipsis ^ + +```py +def some_func(): + Ellipsis +``` + +**Output** +```py +>>> some_func() +# No output, No Error + +>>> SomeRandomString +Traceback (most recent call last): + File "", line 1, in +NameError: name 'SomeRandomString' is not defined + +>>> Ellipsis +Ellipsis +``` + +#### 💡 Explanation +- In Python, `Ellipsis` is a globally available builtin object which is equivalent to `...`. + ```py + >>> ... + Ellipsis + ``` +- Eliipsis can be used for several purposes, + + As a placeholder for code that hasn't been written yet (just like `pass` statement) + + In slicing syntax to represent the full slices in remaining direction + ```py + >>> import numpy as np + >>> three_dimensional_array = np.arange(8).reshape(2, 2, 2) + array([ + [ + [0, 1], + [2, 3] + ], + + [ + [4, 5], + [6, 7] + ] + ]) + ``` + So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions + ```py + >>> three_dimensional_array[:,:,1] + array([[1, 3], + [5, 7]]) + >>> three_dimensional_array[..., 1] # using Ellipsis. + array([[1, 3], + [5, 7]]) + ``` + Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`) + + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`)) + + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the "no argument passed" and "None value passed" scenarios). + + +--- ### ▶ Inpinity * From 9b3b367b450e1de567cd21d9850958a999d06a99 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 8 Jun 2019 23:25:37 +0530 Subject: [PATCH 058/221] Update example "is is not what it is" Related to https://github.com/satwikkansal/wtfpython/issues/100 --- README.md | 49 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f05f91de..888a6760 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,7 @@ True >>> a is b False ->>> a, b = "wtf!", "wtf!" +>>> a = "wtf!"; b = "wtf!"; >>> a is b True ``` @@ -514,10 +514,11 @@ array_4 = [400, 500, 600] --- -### ▶ `is` is not what it is! +### ▶ Messing around with `is` operator^ The following is a very famous example present all over the internet. +1\. ```py >>> a = 256 >>> b = 256 @@ -528,6 +529,37 @@ True >>> b = 257 >>> a is b False +``` + +2\. + +```py +>>> a = [] +>>> b = [] +>>> a is b +False + +>>> a = tuple() +>>> b = tuple() +>>> a is b +True +``` + +3\. +**Output (< Python 3.7)** +``` +>>> a, b = 257, 257 +True + +>>> a = 257; b = 257 +>>> a is b +True +``` + +**Output (Python 3.7)** +``` +>>> a, b = 257, 257 +False >>> a = 257; b = 257 >>> a is b @@ -542,9 +574,8 @@ True * `==` operator compares the values of both the operands and checks if they are the same. * So `is` is for reference equality and `==` is for value equality. An example to clear things up, ```py - >>> [] == [] - True - >>> [] is [] # These are two empty lists at two different memory locations. + >>> class A: pass + >>> A() is A() # These are two empty objects at two different memory locations. False ``` @@ -576,8 +607,11 @@ Quoting from https://docs.python.org/3/c-api/long.html Here 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. +Similar 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, + **Both `a` and `b` refer to the same object when initialized with same value in the same line.** +**Output (< Python 3.7)** ```py >>> a, b = 257, 257 >>> id(a) @@ -594,6 +628,7 @@ Here the interpreter isn't smart enough while executing `y = 257` to recognize t * 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. * 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. +* 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://github.com/satwikkansal/wtfpython/issues/100) for updates. --- @@ -777,6 +812,7 @@ True 'wt\\"f' >>> print("\n") + ``` >>> print(r"\\n") @@ -2324,8 +2360,7 @@ Ellipsis + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`)) + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the "no argument passed" and "None value passed" scenarios). - ---- +--- ### ▶ Inpinity * From f365271df3363fc503ba59c33fd7157caa860a8c Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 00:07:02 +0530 Subject: [PATCH 059/221] New example: The chicken-egg problem Closes https://github.com/satwikkansal/wtfpython/issues/101 --- README.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/README.md b/README.md index 888a6760..6777d95b 100644 --- a/README.md +++ b/README.md @@ -731,6 +731,54 @@ Even when the values of `x` were different in every iteration prior to appending --- +### ▶ The chicken-egg problem ^ + +1\. +```py +>>> isinstance(3, int) +True +>>> isinstance(type, object) +True +>>> isinstance(object, type) +True +``` + +2\. So which is the ultimate, base class? And wait, there's more to the confusion + +```py +>>> class A: pass +>>> isinstance(A, A) +False +>>> isinstance(type, type) +True +>>> isinstance(object, object) +True +``` + +3\. + +```py +>>> issubclass(int, object) +True +>>> issubclass(type, object) +True +>>> issubclass(object, type) +False +``` + + +#### 💡 Explanation + +- `type` is a [metaclass](https://realpython.com/python-metaclasses/) in Python. +- **Everything** is an `object` in Python, which includes classes as well as their objects (instances). +- class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`. +- There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking 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, + + class A is instance of class B, and class B is an instance of class A. + + class A is an instance of itself. +- These relationships between `object` and `type` (both being instances of eachother as well as themselves) exist in Python because of "cheating" at implementation level. + +--- + ### ▶ `is not ...` is not `is (not ...)` ```py From 2295fb24b700a78c9b3d87a98d7393c193c92e5c Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 03:59:09 +0530 Subject: [PATCH 060/221] Let's make a giant string: Use %timeit for measuring time Fixes https://github.com/satwikkansal/wtfpython/issues/106 --- README.md | 63 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 6777d95b..6f262a42 100644 --- a/README.md +++ b/README.md @@ -2512,40 +2512,47 @@ def convert_list_to_string(l, iters): ``` **Output:** + ```py ->>> timeit(add_string_with_plus(10000)) -1000 loops, best of 3: 972 µs per loop ->>> timeit(add_bytes_with_plus(10000)) -1000 loops, best of 3: 815 µs per loop ->>> timeit(add_string_with_format(10000)) -1000 loops, best of 3: 508 µs per loop ->>> timeit(add_string_with_join(10000)) -1000 loops, best of 3: 878 µs per loop ->>> l = ["xyz"]*10000 ->>> timeit(convert_list_to_string(l, 10000)) -10000 loops, best of 3: 80 µs per loop +# Executed in ipython shell using %timeit for better readablity of results. +# You can also use the timeit module in normal python shell/scriptm=, example usage below +# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) + +>>> NUM_ITERS = 1000 +>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) +124 µs ± 4.73 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) +>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) +211 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_format(NUM_ITERS) +61 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_join(NUM_ITERS) +117 µs ± 3.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> l = ["xyz"]*NUM_ITERS +>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) +10.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` Let's increase the number of iterations by a factor of 10. ```py ->>> timeit(add_string_with_plus(100000)) # Linear increase in execution time -100 loops, best of 3: 9.75 ms per loop ->>> timeit(add_bytes_with_plus(100000)) # Quadratic increase -1000 loops, best of 3: 974 ms per loop ->>> timeit(add_string_with_format(100000)) # Linear increase -100 loops, best of 3: 5.25 ms per loop ->>> timeit(add_string_with_join(100000)) # Linear increase -100 loops, best of 3: 9.85 ms per loop ->>> l = ["xyz"]*100000 ->>> timeit(convert_list_to_string(l, 100000)) # Linear increase -1000 loops, best of 3: 723 µs per loop +>>> NUM_ITERS = 10000 +>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time +1.26 ms ± 76.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase +6.82 ms ± 134 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase +645 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase +1.17 ms ± 7.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> l = ["xyz"]*NUM_ITERS +>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase +86.3 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` #### 💡 Explanation -- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) from here. It is generally used to measure the execution time of snippets. +- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces. - Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function) -- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for short strings). +- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings). - Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster. - `add_string_with_plus` didn't show a quadratic increase in execution time unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example. Had the statement been `s = s + "x" + "y" + "z"` instead of `s += "xyz"`, the increase would have been quadratic. ```py @@ -2555,10 +2562,10 @@ Let's increase the number of iterations by a factor of 10. s = s + "x" + "y" + "z" assert len(s) == 3*iters - >>> timeit(add_string_with_plus(10000)) - 100 loops, best of 3: 9.87 ms per loop - >>> timeit(add_string_with_plus(100000)) # Quadratic increase in execution time - 1 loops, best of 3: 1.09 s per loop + >>> %timeit -n100 add_string_with_plus(1000) + 388 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) + >>> %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time + 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` --- From ae05101d705420001d6698d98f4ac7995acf2fef Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 17:34:50 +0530 Subject: [PATCH 061/221] Brace yourself: Add to explanation Resolves https://github.com/satwikkansal/wtfpython/issues/114 --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6f262a42..c2af07f2 100644 --- a/README.md +++ b/README.md @@ -2210,11 +2210,13 @@ from __future__ import braces SyntaxError: not a chance ``` -Braces? No way! If you think that's disappointing, use Java. +Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)? #### 💡 Explanation: -+ The `__future__` module is normally used to provide features from future versions of Python. The "future" here is however ironic. ++ The `__future__` module is normally used to provide features from future versions of Python. The "future" in this specific context is however ironic. + This is an easter egg concerned with the community's feelings on this issue. ++ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file. ++ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement. --- From 330f7da1d349c289edf6517cd3788f66cc0e8253 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 17:56:36 +0530 Subject: [PATCH 062/221] String can be tricky: Remove outdated snippet Related to https://github.com/satwikkansal/wtfpython/issues/120 --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c2af07f2..ab387d13 100644 --- a/README.md +++ b/README.md @@ -180,13 +180,12 @@ True >>> b = "wtf!" >>> a is b False - ->>> a = "wtf!"; b = "wtf!"; ->>> a is b -True ``` 3\. + +**Output (< Python3.7 )** + ```py >>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' True @@ -204,8 +203,9 @@ Makes sense, right? * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) -+ When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. -+ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than or equal to 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. ++ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. ++ Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). +>>>>>>> String can be tricky: Remove outdated snippet --- From 055bd0246dfedf84752bf5eb6d4fb80b4e38538b Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 9 Jun 2019 19:45:13 +0530 Subject: [PATCH 063/221] New example: Lossy zip of iterators Resolves https://github.com/satwikkansal/wtfpython/issues/121 --- README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/README.md b/README.md index ab387d13..d70ff8a4 100644 --- a/README.md +++ b/README.md @@ -1253,6 +1253,55 @@ I've lost faith in truth! --- +### ▶ Lossy zip of iterators + +```py +>>> numbers = list(range(7)) +>>> numbers +[0, 1, 2, 3, 4, 5, 6] +>>> first_three, remaining = numbers[:3], numbers[3:] +>>> first_three, remaining +([0, 1, 2], [3, 4, 5, 6]) +>>> numbers_iter = iter(numbers) +>>> list(zip(numbers_iter, first_three)) +[(0, 0), (1, 1), (2, 2)] +# so far so good, let's zip the remaining +>>> list(zip(numbers_iter, remaining)) +[(4, 3), (5, 4), (6, 5)] +``` +Where did element `3` go from the `numbers` list? + +#### 💡 Explanation: + +- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function, + ```py + def zip(*iterables): + sentinel = object() + iterators = [iter(it) for it in iterables] + while iterators: + result = [] + for it in iterators: + elem = next(it, sentinel) + if elem is sentinel: + return + result.append(elem) + yield tuple(result) + ``` +- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. +- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`. +- The correct way to do the above using `zip` would be, + ```py + >>> numbers = list(range(7)) + >>> numbers_iter = iter(numbers) + >>> list(zip(first_three, numbers_iter)) + [(0, 0), (1, 1), (2, 2)] + >>> list(zip(remaining, numbers_iter)) + [(3, 3), (4, 4), (5, 5), (6, 6)] + ``` + The first argument of zip should be the one with fewest elements. + +--- + ### ▶ From filled to None in one instruction... ```py From 7b22f84f97723b5b8b49435a5810c37bcbbbd582 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 10 Jun 2019 00:14:01 +0530 Subject: [PATCH 064/221] Add new example: Disorder within order Resolves https://github.com/satwikkansal/wtfpython/issues/77 --- README.md | 115 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 109 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index d70ff8a4..73922358 100644 --- a/README.md +++ b/README.md @@ -263,26 +263,131 @@ some_dict[5] = "Python" "Ruby" >>> some_dict[5.0] "Python" ->>> some_dict[5] +>>> some_dict[5] # "Python" destroyed the existence of "JavaScript"? +"Python" + +>>> complex_five = 5 + 0j +>>> type(complex_five) +complex +>>> some_dict[complex_five] "Python" ``` -"Python" destroyed the existence of "JavaScript"? +So, why is Python all over the place? + #### 💡 Explanation * Python dictionaries check for equality and compare the hash value to determine if two keys are the same. * Immutable objects with same value always have the same hash in Python. ```py - >>> 5 == 5.0 + >>> 5 == 5.0 == 5 + 0j True - >>> hash(5) == hash(5.0) + >>> hash(5) == hash(5.0) == hash(5 + 0j) True ``` **Note:** Objects with different values may also have same hash (known as hash collision). * When the statement `some_dict[5] = "Python"` is executed, the existing value "JavaScript" is overwritten with "Python" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`. * This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains beautifully the rationale behind it. +--- + +### ▶ The disorder within order ^ + +```py +from collections import OrderedDict + +dictionary = dict() +dictionary[1] = 'a'; dictionary[2] = 'b'; + +ordered_dict = OrderedDict() +ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; + +another_ordered_dict = OrderedDict() +another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; + +class DictWithHash(dict): + """ + A dict that also implements __hash__ magic. + """ + __hash__ = lambda self: 0 + +class OrderedDictWithHash(OrderedDict): + """ + A dict that also implements __hash__ magic. + """ + __hash__ = lambda self: 0 +``` + +**Output** +```py +>>> dictionary == ordered_dict # If a == b +True +>>> dictionary == another_ordered_dict # and b == c +True +>>> ordered_dict == another_ordered_dict # the why isn't c == a ?? +False + +# We all know that a set consists of only unique elements, +# let's try making a set of these dictionaries and see what happens... + +>>> len({dictionary, ordered_dict, another_ordered_dict}) +Traceback (most recent call last): + File "", line 1, in +TypeError: unhashable type: 'dict' + +# Makes sense since dict don't have __hash__ implemented, let's use +# our wrapper classes. +>>> dictionary = DictWithHash() +>>> dictionary[1] = 'a'; dictionary[2] = 'b'; +>>> ordered_dict = OrderedDictWithHash() +>>> ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; +>>> another_ordered_dict = OrderedDictWithHash() +>>> another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; +>>> len({dictionary, ordered_dict, another_ordered_dict}) +1 +>>> len({ordered_dict, another_ordered_dict, dictionary}) # changing the order +2 +``` + +What is going on here? + +#### 💡 Explanation: + +- 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://docs.python.org/3/library/collections.html#ordereddict-objects) + > 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. +- The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. +- Okay, so why did changing the order affect the lenght 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, + ```py + >>> some_set = set() + >>> some_set.add(dictionary) # these are the mapping objects from the snippets above + >>> ordered_dict in some_set + True + >>> some_set.add(ordered_dict) + >>> len(some_set) + 1 + >>> another_ordered_dict in some_set + True + >>> some_set.add(another_ordered_dict) + >>> len(some_set) + 1 + + >>> another_set = set() + >>> another_set.add(ordered_dict) + >>> another_ordered_dict in another_set + False + >>> another_set.add(another_ordered_dict) + >>> len(another_set) + 2 + >>> dictionary in another_set + True + >>> another_set.add(another_ordered_dict) + >>> len(another_set) + 2 + ``` + 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`. + + --- ### ▶ Keep trying? * @@ -860,8 +965,6 @@ True 'wt\\"f' >>> print("\n") - ``` - >>> print(r"\\n") '\\\\n' From 6934d942221ccb5bc723e847554ca7cfa021bf6d Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 10 Jun 2019 23:22:08 +0530 Subject: [PATCH 065/221] Some minor changes, and add assertion example --- README.md | 51 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 73922358..8202d25c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Python, being a beautifully designed high-level and interpreter-based programmin Here is a fun project to collect such tricky & counter-intuitive examples and lesser-known features in Python, attempting to discuss what exactly is happening under the hood! -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 think you'll find them interesting as well! +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! If you're an experienced Python programmer, you can take it as a challenge to get most of them right in first attempt. You may be already familiar with some of these examples, and I might be able to revive sweet old memories of yours being bitten by these gotchas :sweat_smile: @@ -105,10 +105,10 @@ All the examples are structured like below: > # Preparation for the magic... > ``` > -> **Output (Python version):** +> **Output (Python version(s)):** > ```py > >>> triggering_statement -> Probably unexpected output +> Some unexpected output > ``` > (Optional): One line describing the unexpected output. > @@ -119,7 +119,7 @@ All the examples are structured like below: > ```py > Setting up examples for clarification (if necessary) > ``` -> **Output:** +> **Output Output (Python version(s)):** > ```py > >>> trigger # some example that makes it easy to unveil the magic > # some justified output @@ -129,15 +129,15 @@ All the examples are structured like below: # Usage -A nice way to get the most out of these examples, in my opinion, will be just to read the examples chronologically, and for every example: +A nice way to get the most out of these examples, in my opinion, will be to just read them chronologically, and for every example: - Carefully read the initial code for setting up the example. If you're an experienced Python programmer, most of the times you will successfully anticipate what's going to happen next. - Read the output snippets and, + Check if the outputs are the same as you'd expect. + Make sure if you know the exact reason behind the output being the way it is. - - If no, 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)). + - 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)). - If yes, give a gentle pat on your back, and you may skip to the next example. -PS: You can also read WTFpython at the command line. There's a pypi package and an npm package (supports colored formatting) for the same. +PS: You can also read WTFPython at the command line. There's a pypi package and an npm package (which supports colored formatting) for the same. To install the npm package [`wtfpython`](https://www.npmjs.com/package/wtfpython) ```sh @@ -2187,7 +2187,10 @@ class SomeClass: --- -### ▶ Needle in a Haystack + +--- + +### ▶ Needles in a Haystack 1\. ```py @@ -2226,10 +2229,40 @@ e tuple() ``` +3\. Not asserting strongly enough + +```py +a = "python" +b = "javascript" +``` +**Output:** +```py +# An assert statement with an assertion failure message. +>>> assert(a == b, "Both languages are different") +# No AssertionError is raised +``` + #### 💡 Explanation: * For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. * For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. * `()` is a special token and denotes empty `tuple`. +* For 3, no `AssertionError` was raised because we're asserting entire tuple, instead of asserting the individual expression `a == b`. The following snippet will clear things up, + ```py + >>> a = "python" + >>> b = "javascript" + >>> assert a == b + Traceback (most recent call last): + File "", line 1, in + AssertionError + + >>> assert (a == b, "Values are not equal") + :1: SyntaxWarning: assertion is always true, perhaps remove parentheses? + + >>> assert a == b, "Values are not equal" + Traceback (most recent call last): + File "", line 1, in + AssertionError: Values aren not equal + ``` --- @@ -2721,6 +2754,8 @@ Let's increase the number of iterations by a factor of 10. >>> %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` +- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which, + > There should be one-- and preferably only one --obvious way to do it. --- From 9939ff6a1f7f375a25153ea16007828f966bcebf Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Tue, 11 Jun 2019 00:43:32 +0530 Subject: [PATCH 066/221] Add new example: Wild imports --- README.md | 117 +++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 102 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 8202d25c..9cc27bad 100644 --- a/README.md +++ b/README.md @@ -1858,21 +1858,22 @@ print(x, ': x in global') ``` 3\. -``` -x = 1 -print([x for x in range(5)]) -print(x, ': x in global') -``` -**Output (on Python 2.x):** +**Output (Python 2.x):** ``` +>>> x = 1 +>>> print([x for x in range(5)]) [0, 1, 2, 3, 4] +>>> print(x, ': x in global') (4, ': x in global') ``` -**Output (on Python 3.x):** +**Output (Python 3.x):** ``` +>>> x = 1 +>>> print([x for x in range(5)]) [0, 1, 2, 3, 4] +>>> print(x, ': x in global') 1 : x in global ``` @@ -2185,12 +2186,10 @@ class SomeClass: - A generator expression has its own scope. - Starting from Python 3.X, list comprehensions also have their own scope. ---- - --- -### ▶ Needles in a Haystack +### ▶ Needles in a Haystack ^ 1\. ```py @@ -2229,7 +2228,31 @@ e tuple() ``` -3\. Not asserting strongly enough +3\. + +``` +ten_words_list = [ + "some", + "very", + "big", + "list", + "that" + "consists", + "of", + "exactly", + "ten", + "words" +] +``` + +**Output** + +```py +>>> len(ten_words_list) +9 +``` + +4\. Not asserting strongly enough ```py a = "python" @@ -2246,7 +2269,12 @@ b = "javascript" * For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. * For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. * `()` is a special token and denotes empty `tuple`. -* For 3, no `AssertionError` was raised because we're asserting entire tuple, instead of asserting the individual expression `a == b`. The following snippet will clear things up, +* In 3, as you might have already figured out, there's a missing comma after 5th element (`"that"`) in the list. So by implicit string literal concatenation, + ```py + >>> ten_words_list + ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] + ``` +* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up, ```py >>> a = "python" >>> b = "javascript" @@ -2324,7 +2352,62 @@ Same result, that didn't work either. ["wtf"] ``` +--- + +### ▶ Wild imports + +```py +# File: module.py + +def some_weird_name_func_(): + print("works!") + +def _another_weird_name_func(): + print("works!") + +``` + +**Output** + +```py +>>> from module import * +>>> some_weird_name_func_() +"works!" +>>> _another_weird_name_func() +Traceback (most recent call last): + File "", line 1, in +NameError: name '_another_weird_name_func' is not defined +``` + +#### 💡 Explanation: + +- It if often adivsable to not use wildcard imports. In wildcard imports, the names with leading underscore are be imported. This may lead to errors in runtime. +- Had we used `from ... import a, b, c` syntax, the above `NameError` won't have occurred. + ```py + >>> from module import some_weird_name_func_, _another_weird_name_func + >>> _another_weird_name_func() + works! + ``` +- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports. +```py +__all__ = ['_another_weird_name_func'] + +def some_weird_name_func_(): + print("works!") +def _another_weird_name_func(): + print("works!") +``` +**Output** + +```py +>>> _another_weird_name_func() +"works!" +>>> some_weird_name_func_() +Traceback (most recent call last): + File "", line 1, in +NameError: name 'some_weird_name_func_' is not defined +``` --- --- @@ -2622,12 +2705,12 @@ The spelling is intended. Please, don't submit a patch for this. class Yo(object): def __init__(self): self.__honey = True - self.bitch = True + self.bro = True ``` **Output:** ```py ->>> Yo().bitch +>>> Yo().bro True >>> Yo().__honey AttributeError: 'Yo' object has no attribute '__honey' @@ -2635,7 +2718,7 @@ AttributeError: 'Yo' object has no attribute '__honey' True ``` -Why did `Yo()._Yo__honey` work? Only Indian readers would understand. +Why did `Yo()._Yo__honey` work? #### 💡 Explanation: @@ -2645,6 +2728,10 @@ Why did `Yo()._Yo__honey` work? Only Indian readers would understand. --- + + + + --- ## Section: Miscellaneous From edeb98f40618623d8db50141a8c9fff648aa42d2 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 7 Jul 2019 22:17:33 +0530 Subject: [PATCH 067/221] Update the booleans example Fix some technically incorrect terminologies and snippets. --- README.md | 96 ++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 71 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 9cc27bad..13835aff 100644 --- a/README.md +++ b/README.md @@ -1059,7 +1059,7 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t 1\. ```py -# A simple example to count the number of boolean and +# A simple example to count the number of booleans and # integers in an iterable of mixed data types. mixed_list = [False, 1.0, "some_string", 3, True, [], False] integers_found_so_far = 0 @@ -1080,33 +1080,27 @@ for item in mixed_list: 0 ``` -2\. -```py -another_dict = {} -another_dict[True] = "JavaScript" -another_dict[1] = "Ruby" -another_dict[1.0] = "Python" -``` - -**Output:** -```py ->>> another_dict[True] -"Python" -``` -3\. +2\. ```py >>> some_bool = True ->>> "wtf"*some_bool +>>> "wtf" * some_bool 'wtf' >>> some_bool = False ->>> "wtf"*some_bool +>>> "wtf" * some_bool '' ``` #### 💡 Explanation: -* Booleans are a subclass of `int` +* `bool` is a subclass of `int` in Python + ```py + >>> issubclass(bool, int) + True + >>> issubclass(int, bool) + False + ``` +* And thus, `True` and `False` are instances of `int` ```py >>> isinstance(True, int) True @@ -1116,8 +1110,10 @@ another_dict[1.0] = "Python" * The integer value of `True` is `1` and that of `False` is `0`. ```py - >>> True == 1 == 1.0 and False == 0 == 0.0 - True + >>> int(True) + 1 + >>> int(False) + 0 ``` * See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for the rationale behind it. @@ -1720,7 +1716,7 @@ Yes, it runs for exactly **eight** times and stops. --- -### ▶ Stubborn `del` operator * +### ▶ Stubborn `del` operation * ```py class SomeClass: @@ -2381,7 +2377,7 @@ NameError: name '_another_weird_name_func' is not defined #### 💡 Explanation: -- It if often adivsable to not use wildcard imports. In wildcard imports, the names with leading underscore are be imported. This may lead to errors in runtime. +- It if often adivsable to not use wildcard imports. The first obvious reason for this is In wildcard imports, the names with leading underscore are be imported. This may lead to errors in runtime. - Had we used `from ... import a, b, c` syntax, the above `NameError` won't have occurred. ```py >>> from module import some_weird_name_func_, _another_weird_name_func @@ -2699,8 +2695,9 @@ The spelling is intended. Please, don't submit a patch for this. --- -### ▶ Mangling time! * +### ▶ Let's mangle ^ +1\. ```py class Yo(object): def __init__(self): @@ -2718,13 +2715,62 @@ AttributeError: 'Yo' object has no attribute '__honey' True ``` +2\. +```py +class Yo(object): + def __init__(self): + # Let's try something symmetrical this time + self.__honey__ = True + self.bro = True +``` + +**Output:** +```py +>>> Yo().bro +True + +>>> Yo()._Yo__honey__ +Traceback (most recent call last): + File "", line 1, in +AttributeError: 'Yo' object has no attribute '_Yo__honey__' +``` + Why did `Yo()._Yo__honey` work? +2\. + +```py +_A__variable = "Some value" + +class A(object): + def some_func(self): + return __variable # not initiatlized anywhere yet +``` + +**Output:** +```py +Traceback (most recent call last): + File "", line 1, in +AttributeError: 'A' object has no attribute '__variable' + +>>> >>> A().some_func() +'Some value' +``` + +3\. + +```py + +``` + + #### 💡 Explanation: * [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces. -* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore) and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. -* So, to access `__honey` attribute, we are required to append `_Yo` to the front which would prevent conflicts with the same name attribute defined in any other class. +* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a "dunder") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. +* So, to access `__honey` attribute in first snippet, we had to append `_Yo` to the front which would prevent conflicts with the same name attribute defined in any other class. +* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores. +* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable` which also happens to be the name of the variable we declared in outer scope. --- From 162458c88e3790e73b3e11d44c1f8d863333929d Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 7 Jul 2019 22:18:35 +0530 Subject: [PATCH 068/221] Update TOC --- README.md | 168 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 116 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 13835aff..7f3a3549 100644 --- a/README.md +++ b/README.md @@ -28,67 +28,131 @@ So, here we go... - [Usage](#usage) - [👀 Examples](#-examples) - [Section: Strain your brain!](#section-strain-your-brain) - - [▶ Strings can be tricky sometimes *](#-strings-can-be-tricky-sometimes-) - - [▶ Time for some hash brownies!](#-time-for-some-hash-brownies) - - [▶ Return return everywhere!](#-return-return-everywhere) - - [▶ Deep down, we're all the same. *](#-deep-down-were-all-the-same-) - - [▶ For what?](#-for-what) - - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - - [▶ `is` is not what it is!](#-is-is-not-what-it-is) - - [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - - [▶ The sticky output function](#-the-sticky-output-function) - - [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) - - [▶ The surprising comma](#-the-surprising-comma) - - [▶ Backslashes at the end of string](#-backslashes-at-the-end-of-string) - - [▶ not knot!](#-not-knot) - - [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - - [▶ yielding None](#-yielding-none) - - [▶ Mutating the immutable!](#-mutating-the-immutable) - - [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) - - [▶ When True is actually False](#-when-true-is-actually-false) - - [▶ From filled to None in one instruction...](#-from-filled-to-none-in-one-instruction) - - [▶ Subclass relationships *](#-subclass-relationships-) - - [▶ The mysterious key type conversion *](#-the-mysterious-key-type-conversion-) - - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + - [▶ Strings can be tricky sometimes *](#%E2%96%B6-strings-can-be-tricky-sometimes-) + - [💡 Explanation:](#-explanation) + - [▶ Splitsies ^](#%E2%96%B6-splitsies-%5E) + - [💡 Explanation:](#-explanation-1) + - [▶ Time for some hash brownies!](#%E2%96%B6-time-for-some-hash-brownies) + - [💡 Explanation](#-explanation) + - [▶ The disorder within order ^](#%E2%96%B6-the-disorder-within-order-%5E) + - [💡 Explanation:](#-explanation-2) + - [▶ Keep trying? *](#%E2%96%B6-keep-trying-) + - [💡 Explanation:](#-explanation-3) + - [▶ Deep down, we're all the same. *](#%E2%96%B6-deep-down-were-all-the-same-) + - [💡 Explanation:](#-explanation-4) + - [▶ For what?](#%E2%96%B6-for-what) + - [💡 Explanation:](#-explanation-5) + - [▶ Evaluation time discrepancy ^](#%E2%96%B6-evaluation-time-discrepancy-%5E) + - [💡 Explanation](#-explanation-1) + - [▶ Messing around with `is` operator^](#%E2%96%B6-messing-around-with-is-operator%5E) + - [💡 Explanation:](#-explanation-6) + - [▶ A tic-tac-toe where X wins in the first attempt!](#%E2%96%B6-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + - [💡 Explanation:](#-explanation-7) + - [▶ The sticky output function](#%E2%96%B6-the-sticky-output-function) + - [💡 Explanation](#-explanation-2) + - [▶ The chicken-egg problem ^](#%E2%96%B6-the-chicken-egg-problem-%5E) + - [💡 Explanation](#-explanation-3) + - [▶ `is not ...` is not `is (not ...)`](#%E2%96%B6-is-not--is-not-is-not-) + - [💡 Explanation](#-explanation-4) + - [▶ The surprising comma](#%E2%96%B6-the-surprising-comma) + - [💡 Explanation:](#-explanation-8) + - [▶ Strings and the backslashes\ ^](#%E2%96%B6-strings-and-the-backslashes%5C-%5E) + - [💡 Explanation](#-explanation-5) + - [▶ not knot!](#%E2%96%B6-not-knot) + - [💡 Explanation:](#-explanation-9) + - [▶ Half triple-quoted strings](#%E2%96%B6-half-triple-quoted-strings) + - [💡 Explanation:](#-explanation-10) + - [▶ Midnight time doesn't exist?](#%E2%96%B6-midnight-time-doesnt-exist) + - [💡 Explanation:](#-explanation-11) + - [▶ What's wrong with booleans?](#%E2%96%B6-whats-wrong-with-booleans) + - [💡 Explanation:](#-explanation-12) + - [▶ Class attributes and instance attributes](#%E2%96%B6-class-attributes-and-instance-attributes) + - [💡 Explanation:](#-explanation-13) + - [▶ yielding None](#%E2%96%B6-yielding-none) + - [💡 Explanation:](#-explanation-14) + - [▶ Mutating the immutable!](#%E2%96%B6-mutating-the-immutable) + - [💡 Explanation:](#-explanation-15) + - [▶ The disappearing variable from outer scope](#%E2%96%B6-the-disappearing-variable-from-outer-scope) + - [💡 Explanation:](#-explanation-16) + - [▶ When True is actually False](#%E2%96%B6-when-true-is-actually-false) + - [💡 Explanation:](#-explanation-17) + - [▶ Lossy zip of iterators](#%E2%96%B6-lossy-zip-of-iterators) + - [💡 Explanation:](#-explanation-18) + - [▶ From filled to None in one instruction...](#%E2%96%B6-from-filled-to-none-in-one-instruction) + - [💡 Explanation](#-explanation-6) + - [▶ Subclass relationships *](#%E2%96%B6-subclass-relationships-) + - [💡 Explanation:](#-explanation-19) + - [▶ The mysterious key type conversion *](#%E2%96%B6-the-mysterious-key-type-conversion-) + - [💡 Explanation:](#-explanation-20) + - [▶ Let's see if you can guess this?](#%E2%96%B6-lets-see-if-you-can-guess-this) + - [💡 Explanation:](#-explanation-21) - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - - [▶ Skipping lines?](#-skipping-lines) - - [▶ Teleportation *](#-teleportation-) - - [▶ Well, something is fishy...](#-well-something-is-fishy) + - [▶ Skipping lines?](#%E2%96%B6-skipping-lines) + - [💡 Explanation](#-explanation-7) + - [▶ Teleportation *](#%E2%96%B6-teleportation-) + - [💡 Explanation:](#-explanation-22) + - [▶ Well, something is fishy...](#%E2%96%B6-well-something-is-fishy) + - [💡 Explanation](#-explanation-8) - [Section: Watch out for the landmines!](#section-watch-out-for-the-landmines) - - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) - - [▶ Stubborn `del` operator *](#-stubborn-del-operator-) - - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - - [▶ Loop variables leaking out!](#-loop-variables-leaking-out) - - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - - [▶ Catching the Exceptions](#-catching-the-exceptions) - - [▶ Same operands, different story!](#-same-operands-different-story) - - [▶ The out of scope variable](#-the-out-of-scope-variable) - - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - - [▶ Needle in a Haystack](#-needle-in-a-haystack) + - [▶ Modifying a dictionary while iterating over it](#%E2%96%B6-modifying-a-dictionary-while-iterating-over-it) + - [💡 Explanation:](#-explanation-23) + - [▶ Stubborn `del` operation *](#%E2%96%B6-stubborn-del-operation-) + - [💡 Explanation:](#-explanation-24) + - [▶ Deleting a list item while iterating](#%E2%96%B6-deleting-a-list-item-while-iterating) + - [💡 Explanation:](#-explanation-25) + - [▶ Loop variables leaking out!](#%E2%96%B6-loop-variables-leaking-out) + - [💡 Explanation:](#-explanation-26) + - [▶ Beware of default mutable arguments!](#%E2%96%B6-beware-of-default-mutable-arguments) + - [💡 Explanation:](#-explanation-27) + - [▶ Catching the Exceptions](#%E2%96%B6-catching-the-exceptions) + - [💡 Explanation](#-explanation-9) + - [▶ Same operands, different story!](#%E2%96%B6-same-operands-different-story) + - [💡 Explanation:](#-explanation-28) + - [▶ The out of scope variable](#%E2%96%B6-the-out-of-scope-variable) + - [💡 Explanation:](#-explanation-29) + - [▶ Be careful with chained operations](#%E2%96%B6-be-careful-with-chained-operations) + - [💡 Explanation:](#-explanation-30) + - [▶ Name resolution ignoring class scope](#%E2%96%B6-name-resolution-ignoring-class-scope) + - [💡 Explanation](#-explanation-10) + - [▶ Needles in a Haystack ^](#%E2%96%B6-needles-in-a-haystack-%5E) + - [💡 Explanation:](#-explanation-31) - [▶ Yielding from... return!](#-yielding-from-return) + - [💡 Explanation:](#-explanation-31) + - [▶ Wild imports](#%E2%96%B6-wild-imports) + - [💡 Explanation:](#-explanation-32) - [Section: The Hidden treasures!](#section-the-hidden-treasures) - - [▶ Okay Python, Can you make me fly? *](#-okay-python-can-you-make-me-fly-) - - [▶ `goto`, but why? *](#-goto-but-why-) - - [▶ Brace yourself! *](#-brace-yourself-) - - [▶ Let's meet Friendly Language Uncle For Life *](#-lets-meet-friendly-language-uncle-for-life-) - - [▶ Even Python understands that love is complicated *](#-even-python-understands-that-love-is-complicated-) - - [▶ Yes, it exists!](#-yes-it-exists) - - [▶ Inpinity *](#-inpinity-) - - [▶ Mangling time! *](#-mangling-time-) + - [▶ Okay Python, Can you make me fly? *](#%E2%96%B6-okay-python-can-you-make-me-fly-) + - [💡 Explanation:](#-explanation-33) + - [▶ `goto`, but why? *](#%E2%96%B6-goto-but-why-) + - [💡 Explanation:](#-explanation-34) + - [▶ Brace yourself! *](#%E2%96%B6-brace-yourself-) + - [💡 Explanation:](#-explanation-35) + - [▶ Let's meet Friendly Language Uncle For Life ^](#%E2%96%B6-lets-meet-friendly-language-uncle-for-life-%5E) + - [💡 Explanation:](#-explanation-36) + - [▶ Even Python understands that love is complicated *](#%E2%96%B6-even-python-understands-that-love-is-complicated-) + - [💡 Explanation:](#-explanation-37) + - [▶ Yes, it exists!](#%E2%96%B6-yes-it-exists) + - [💡 Explanation:](#-explanation-38) + - [▶ Ellipsis ^](#%E2%96%B6-ellipsis-%5E) + - [💡 Explanation](#-explanation-11) + - [▶ Inpinity *](#%E2%96%B6-inpinity-) + - [💡 Explanation:](#-explanation-39) + - [▶ Let's mangle ^](#%E2%96%B6-lets-mangle-%5E) + - [💡 Explanation:](#-explanation-40) - [Section: Miscellaneous](#section-miscellaneous) - - [▶ `+=` is faster](#--is-faster) - - [▶ Let's make a giant string!](#-lets-make-a-giant-string) - - [▶ Explicit typecast of strings](#-explicit-typecast-of-strings) - - [▶ Minor Ones](#-minor-ones) + - [▶ `+=` is faster](#%E2%96%B6--is-faster) + - [💡 Explanation:](#-explanation-41) + - [▶ Let's make a giant string!](#%E2%96%B6-lets-make-a-giant-string) + - [💡 Explanation](#-explanation-12) + - [▶ Explicit typecast of strings](#%E2%96%B6-explicit-typecast-of-strings) + - [💡 Explanation:](#-explanation-42) + - [▶ Minor Ones](#%E2%96%B6-minor-ones) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) + - [Some nice Links!](#some-nice-links) - [🎓 License](#-license) - [Help](#help) - - [Want to share wtfpython with friends?](#want-to-share-wtfpython-with-friends) + - [Surprise your geeky pythonist friends?](#surprise-your-geeky-pythonist-friends) - [Need a pdf version?](#need-a-pdf-version) From 45638fa6b1cde184dba3acf0da97d56d2147b0c0 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 8 Jul 2019 02:54:49 +0530 Subject: [PATCH 069/221] Add uuids to examples --- README.md | 114 +++++++++++++++++++++++++++--------------------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 7f3a3549..5b9977b8 100644 --- a/README.md +++ b/README.md @@ -223,7 +223,7 @@ Now, just run `wtfpython` at the command line which will open this collection in ## Section: Strain your brain! ### ▶ Strings can be tricky sometimes * - + 1\. ```py >>> a = "some_string" @@ -274,7 +274,7 @@ Makes sense, right? --- ### ▶ Splitsies ^ - + ```py >>> 'a'.split() ['a'] @@ -312,7 +312,7 @@ Makes sense, right? ### ▶ Time for some hash brownies! - + 1\. ```py some_dict = {} @@ -357,7 +357,7 @@ So, why is Python all over the place? --- ### ▶ The disorder within order ^ - + ```py from collections import OrderedDict @@ -455,7 +455,7 @@ What is going on here? --- ### ▶ Keep trying? * - + ```py def some_func(): try: @@ -515,7 +515,7 @@ Iteration 0 --- ### ▶ Deep down, we're all the same. * - + ```py class WTF: pass @@ -565,7 +565,7 @@ True --- ### ▶ For what? - + ```py some_string = "wtf" some_dict = {} @@ -618,7 +618,7 @@ for i, some_dict[i] in enumerate(some_string): --- ### ▶ Evaluation time discrepancy ^ - + 1\. ```py array = [1, 8, 15] @@ -684,7 +684,7 @@ array_4 = [400, 500, 600] --- ### ▶ Messing around with `is` operator^ - + The following is a very famous example present all over the internet. 1\. @@ -802,7 +802,7 @@ Similar optimization applies to other **immutable** objects like empty tuples as --- ### ▶ A tic-tac-toe where X wins in the first attempt! - + ```py # Let's initialize a row row = [""]*3 #row i['', '', ''] @@ -847,7 +847,7 @@ We can avoid this scenario here by not using `row` variable to generate `board`. --- ### ▶ The sticky output function - + ```py funcs = [] results = [] @@ -901,7 +901,7 @@ Even when the values of `x` were different in every iteration prior to appending --- ### ▶ The chicken-egg problem ^ - + 1\. ```py >>> isinstance(3, int) @@ -949,7 +949,7 @@ False --- ### ▶ `is not ...` is not `is (not ...)` - + ```py >>> 'something' is not None True @@ -965,7 +965,7 @@ False --- ### ▶ The surprising comma - + **Output:** ```py >>> def f(x, y,): @@ -995,7 +995,7 @@ SyntaxError: invalid syntax --- ### ▶ Strings and the backslashes\ ^ - + **Output:** ```py >>> print("\"") @@ -1038,7 +1038,7 @@ True --- ### ▶ not knot! - + ```py x = True y = False @@ -1065,7 +1065,7 @@ SyntaxError: invalid syntax --- ### ▶ Half triple-quoted strings - + **Output:** ```py >>> print('wtfpython''') @@ -1090,7 +1090,7 @@ wtfpython --- ### ▶ Midnight time doesn't exist? - + ```py from datetime import datetime @@ -1120,7 +1120,7 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t --- ### ▶ What's wrong with booleans? - + 1\. ```py # A simple example to count the number of booleans and @@ -1185,7 +1185,7 @@ for item in mixed_list: --- ### ▶ Class attributes and instance attributes - + 1\. ```py class A: @@ -1255,7 +1255,7 @@ True --- ### ▶ yielding None - + ```py some_iterable = ('a', 'b') @@ -1284,7 +1284,7 @@ def some_func(val): --- ### ▶ Mutating the immutable! - + ```py some_tuple = ("A", "tuple", "with", "values") another_tuple = ([1, 2], [3, 4], [5, 6]) @@ -1317,7 +1317,7 @@ But I thought tuples were immutable... --- ### ▶ The disappearing variable from outer scope - + ```py e = 7 try: @@ -1397,7 +1397,7 @@ NameError: name 'e' is not defined --- ### ▶ When True is actually False - + ```py True = False if True == False: @@ -1417,7 +1417,7 @@ I've lost faith in truth! --- ### ▶ Lossy zip of iterators - + ```py >>> numbers = list(range(7)) >>> numbers @@ -1466,7 +1466,7 @@ Where did element `3` go from the `numbers` list? --- ### ▶ From filled to None in one instruction... - + ```py some_list = [1, 2, 3] some_dict = { @@ -1494,7 +1494,7 @@ Most methods that modify the items of sequence/mapping objects like `list.append --- ### ▶ Subclass relationships * - + **Output:** ```py >>> from collections import Hashable @@ -1518,7 +1518,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` --- ### ▶ The mysterious key type conversion * - + ```py class SomeClass(str): pass @@ -1574,7 +1574,7 @@ str --- ### ▶ Let's see if you can guess this? - + ```py a, b = a[b] = {}, 5 ``` @@ -1635,7 +1635,7 @@ a, b = a[b] = {}, 5 ## Section: Appearances are deceptive! ### ▶ Skipping lines? - + **Output:** ```py >>> value = 11 @@ -1671,7 +1671,7 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ --- ### ▶ Teleportation * - + ```py import numpy as np @@ -1701,7 +1701,7 @@ Where's the Nobel Prize? --- ### ▶ Well, something is fishy... - + ```py def square(x): """ @@ -1746,7 +1746,7 @@ Shouldn't that be 100? ### ▶ Modifying a dictionary while iterating over it - + ```py x = {0: None} @@ -1781,7 +1781,7 @@ Yes, it runs for exactly **eight** times and stops. --- ### ▶ Stubborn `del` operation * - + ```py class SomeClass: def __del__(self): @@ -1824,7 +1824,7 @@ Okay, now it's deleted :confused: --- ### ▶ Deleting a list item while iterating - + ```py list_1 = [1, 2, 3, 4] list_2 = [1, 2, 3, 4] @@ -1884,7 +1884,7 @@ Can you guess why the output is `[2, 4]`? --- ### ▶ Loop variables leaking out! - + 1\. ```py for x in range(7): @@ -1948,7 +1948,7 @@ print(x, ': x in global') --- ### ▶ Beware of default mutable arguments! - + ```py def some_func(default_arg=[]): default_arg.append("some_string") @@ -2005,7 +2005,7 @@ def some_func(default_arg=[]): --- ### ▶ Catching the Exceptions - + ```py some_list = [1, 2, 3] try: @@ -2080,7 +2080,7 @@ SyntaxError: invalid syntax --- ### ▶ Same operands, different story! - + 1\. ```py a = [1, 2, 3, 4] @@ -2122,7 +2122,7 @@ a += [5, 6, 7, 8] --- ### ▶ The out of scope variable - + ```py a = 1 def some_func(): @@ -2161,7 +2161,7 @@ UnboundLocalError: local variable 'a' referenced before assignment --- ### ▶ Be careful with chained operations - + ```py >>> (False == False) in [False] # makes sense False @@ -2206,7 +2206,7 @@ While such behavior might seem silly to you in the above examples, it's fantasti --- ### ▶ Name resolution ignoring class scope - + 1\. ```py x = 5 @@ -2250,7 +2250,7 @@ class SomeClass: --- ### ▶ Needles in a Haystack ^ - + 1\. ```py x, y = (0, 1) if True else None, None @@ -2415,7 +2415,7 @@ Same result, that didn't work either. --- ### ▶ Wild imports - + ```py # File: module.py @@ -2478,7 +2478,7 @@ NameError: name 'some_weird_name_func_' is not defined This section contains few of the lesser-known interesting things about Python that most beginners like me are unaware of (well, not anymore). ### ▶ Okay Python, Can you make me fly? * - + Well, here you go ```py @@ -2496,7 +2496,7 @@ Sshh.. It's a super secret. --- ### ▶ `goto`, but why? * - + ```py from goto import goto, label for i in range(9): @@ -2524,7 +2524,7 @@ Freedom! --- ### ▶ Brace yourself! * - + If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing, ```py @@ -2549,7 +2549,7 @@ Braces? No way! If you think that's disappointing, use Java. Okay, another surpr --- ### ▶ Let's meet Friendly Language Uncle For Life ^ - + **Output (Python 3.x)** ```py >>> from __future__ import barry_as_FLUFL @@ -2580,7 +2580,7 @@ There we go. --- ### ▶ Even Python understands that love is complicated * - + ```py import this ``` @@ -2637,7 +2637,7 @@ True --- ### ▶ Yes, it exists! - + **The `else` clause for loops.** One typical example might be: ```py @@ -2681,7 +2681,7 @@ Try block executed successfully... --- ### ▶ Ellipsis ^ - + ```py def some_func(): Ellipsis @@ -2741,7 +2741,7 @@ Ellipsis --- ### ▶ Inpinity * - + The spelling is intended. Please, don't submit a patch for this. **Output (Python 3.x):** @@ -2760,7 +2760,7 @@ The spelling is intended. Please, don't submit a patch for this. --- ### ▶ Let's mangle ^ - + 1\. ```py class Yo(object): @@ -2848,7 +2848,7 @@ AttributeError: 'A' object has no attribute '__variable' ### ▶ `+=` is faster - + ```py # using "+", three strings: >>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) @@ -2864,7 +2864,7 @@ AttributeError: 'A' object has no attribute '__variable' --- ### ▶ Let's make a giant string! - + ```py def add_string_with_plus(iters): s = "" @@ -2957,7 +2957,7 @@ Let's increase the number of iterations by a factor of 10. --- ### ▶ Explicit typecast of strings - + ```py a = float('inf') b = float('nan') @@ -2996,7 +2996,7 @@ nan --- ### ▶ Minor Ones - + * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) **💡 Explanation:** From e8fcce27c28f8bb956ec542daa5b3e9f33ad3a2a Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 8 Jul 2019 03:00:33 +0530 Subject: [PATCH 070/221] Fix uuid comments --- README.md | 114 +++++++++++++++++++++++++++--------------------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 5b9977b8..07f1a5cc 100644 --- a/README.md +++ b/README.md @@ -223,7 +223,7 @@ Now, just run `wtfpython` at the command line which will open this collection in ## Section: Strain your brain! ### ▶ Strings can be tricky sometimes * - + 1\. ```py >>> a = "some_string" @@ -274,7 +274,7 @@ Makes sense, right? --- ### ▶ Splitsies ^ - + ```py >>> 'a'.split() ['a'] @@ -312,7 +312,7 @@ Makes sense, right? ### ▶ Time for some hash brownies! - + 1\. ```py some_dict = {} @@ -357,7 +357,7 @@ So, why is Python all over the place? --- ### ▶ The disorder within order ^ - + ```py from collections import OrderedDict @@ -455,7 +455,7 @@ What is going on here? --- ### ▶ Keep trying? * - + ```py def some_func(): try: @@ -515,7 +515,7 @@ Iteration 0 --- ### ▶ Deep down, we're all the same. * - + ```py class WTF: pass @@ -565,7 +565,7 @@ True --- ### ▶ For what? - + ```py some_string = "wtf" some_dict = {} @@ -618,7 +618,7 @@ for i, some_dict[i] in enumerate(some_string): --- ### ▶ Evaluation time discrepancy ^ - + 1\. ```py array = [1, 8, 15] @@ -684,7 +684,7 @@ array_4 = [400, 500, 600] --- ### ▶ Messing around with `is` operator^ - + The following is a very famous example present all over the internet. 1\. @@ -802,7 +802,7 @@ Similar optimization applies to other **immutable** objects like empty tuples as --- ### ▶ A tic-tac-toe where X wins in the first attempt! - + ```py # Let's initialize a row row = [""]*3 #row i['', '', ''] @@ -847,7 +847,7 @@ We can avoid this scenario here by not using `row` variable to generate `board`. --- ### ▶ The sticky output function - + ```py funcs = [] results = [] @@ -901,7 +901,7 @@ Even when the values of `x` were different in every iteration prior to appending --- ### ▶ The chicken-egg problem ^ - + 1\. ```py >>> isinstance(3, int) @@ -949,7 +949,7 @@ False --- ### ▶ `is not ...` is not `is (not ...)` - + ```py >>> 'something' is not None True @@ -965,7 +965,7 @@ False --- ### ▶ The surprising comma - + **Output:** ```py >>> def f(x, y,): @@ -995,7 +995,7 @@ SyntaxError: invalid syntax --- ### ▶ Strings and the backslashes\ ^ - + **Output:** ```py >>> print("\"") @@ -1038,7 +1038,7 @@ True --- ### ▶ not knot! - + ```py x = True y = False @@ -1065,7 +1065,7 @@ SyntaxError: invalid syntax --- ### ▶ Half triple-quoted strings - + **Output:** ```py >>> print('wtfpython''') @@ -1090,7 +1090,7 @@ wtfpython --- ### ▶ Midnight time doesn't exist? - + ```py from datetime import datetime @@ -1120,7 +1120,7 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t --- ### ▶ What's wrong with booleans? - + 1\. ```py # A simple example to count the number of booleans and @@ -1185,7 +1185,7 @@ for item in mixed_list: --- ### ▶ Class attributes and instance attributes - + 1\. ```py class A: @@ -1255,7 +1255,7 @@ True --- ### ▶ yielding None - + ```py some_iterable = ('a', 'b') @@ -1284,7 +1284,7 @@ def some_func(val): --- ### ▶ Mutating the immutable! - + ```py some_tuple = ("A", "tuple", "with", "values") another_tuple = ([1, 2], [3, 4], [5, 6]) @@ -1317,7 +1317,7 @@ But I thought tuples were immutable... --- ### ▶ The disappearing variable from outer scope - + ```py e = 7 try: @@ -1397,7 +1397,7 @@ NameError: name 'e' is not defined --- ### ▶ When True is actually False - + ```py True = False if True == False: @@ -1417,7 +1417,7 @@ I've lost faith in truth! --- ### ▶ Lossy zip of iterators - + ```py >>> numbers = list(range(7)) >>> numbers @@ -1466,7 +1466,7 @@ Where did element `3` go from the `numbers` list? --- ### ▶ From filled to None in one instruction... - + ```py some_list = [1, 2, 3] some_dict = { @@ -1494,7 +1494,7 @@ Most methods that modify the items of sequence/mapping objects like `list.append --- ### ▶ Subclass relationships * - + **Output:** ```py >>> from collections import Hashable @@ -1518,7 +1518,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` --- ### ▶ The mysterious key type conversion * - + ```py class SomeClass(str): pass @@ -1574,7 +1574,7 @@ str --- ### ▶ Let's see if you can guess this? - + ```py a, b = a[b] = {}, 5 ``` @@ -1635,7 +1635,7 @@ a, b = a[b] = {}, 5 ## Section: Appearances are deceptive! ### ▶ Skipping lines? - + **Output:** ```py >>> value = 11 @@ -1671,7 +1671,7 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ --- ### ▶ Teleportation * - + ```py import numpy as np @@ -1701,7 +1701,7 @@ Where's the Nobel Prize? --- ### ▶ Well, something is fishy... - + ```py def square(x): """ @@ -1746,7 +1746,7 @@ Shouldn't that be 100? ### ▶ Modifying a dictionary while iterating over it - + ```py x = {0: None} @@ -1781,7 +1781,7 @@ Yes, it runs for exactly **eight** times and stops. --- ### ▶ Stubborn `del` operation * - + ```py class SomeClass: def __del__(self): @@ -1824,7 +1824,7 @@ Okay, now it's deleted :confused: --- ### ▶ Deleting a list item while iterating - + ```py list_1 = [1, 2, 3, 4] list_2 = [1, 2, 3, 4] @@ -1884,7 +1884,7 @@ Can you guess why the output is `[2, 4]`? --- ### ▶ Loop variables leaking out! - + 1\. ```py for x in range(7): @@ -1948,7 +1948,7 @@ print(x, ': x in global') --- ### ▶ Beware of default mutable arguments! - + ```py def some_func(default_arg=[]): default_arg.append("some_string") @@ -2005,7 +2005,7 @@ def some_func(default_arg=[]): --- ### ▶ Catching the Exceptions - + ```py some_list = [1, 2, 3] try: @@ -2080,7 +2080,7 @@ SyntaxError: invalid syntax --- ### ▶ Same operands, different story! - + 1\. ```py a = [1, 2, 3, 4] @@ -2122,7 +2122,7 @@ a += [5, 6, 7, 8] --- ### ▶ The out of scope variable - + ```py a = 1 def some_func(): @@ -2161,7 +2161,7 @@ UnboundLocalError: local variable 'a' referenced before assignment --- ### ▶ Be careful with chained operations - + ```py >>> (False == False) in [False] # makes sense False @@ -2206,7 +2206,7 @@ While such behavior might seem silly to you in the above examples, it's fantasti --- ### ▶ Name resolution ignoring class scope - + 1\. ```py x = 5 @@ -2250,7 +2250,7 @@ class SomeClass: --- ### ▶ Needles in a Haystack ^ - + 1\. ```py x, y = (0, 1) if True else None, None @@ -2415,7 +2415,7 @@ Same result, that didn't work either. --- ### ▶ Wild imports - + ```py # File: module.py @@ -2478,7 +2478,7 @@ NameError: name 'some_weird_name_func_' is not defined This section contains few of the lesser-known interesting things about Python that most beginners like me are unaware of (well, not anymore). ### ▶ Okay Python, Can you make me fly? * - + Well, here you go ```py @@ -2496,7 +2496,7 @@ Sshh.. It's a super secret. --- ### ▶ `goto`, but why? * - + ```py from goto import goto, label for i in range(9): @@ -2524,7 +2524,7 @@ Freedom! --- ### ▶ Brace yourself! * - + If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing, ```py @@ -2549,7 +2549,7 @@ Braces? No way! If you think that's disappointing, use Java. Okay, another surpr --- ### ▶ Let's meet Friendly Language Uncle For Life ^ - + **Output (Python 3.x)** ```py >>> from __future__ import barry_as_FLUFL @@ -2580,7 +2580,7 @@ There we go. --- ### ▶ Even Python understands that love is complicated * - + ```py import this ``` @@ -2637,7 +2637,7 @@ True --- ### ▶ Yes, it exists! - + **The `else` clause for loops.** One typical example might be: ```py @@ -2681,7 +2681,7 @@ Try block executed successfully... --- ### ▶ Ellipsis ^ - + ```py def some_func(): Ellipsis @@ -2741,7 +2741,7 @@ Ellipsis --- ### ▶ Inpinity * - + The spelling is intended. Please, don't submit a patch for this. **Output (Python 3.x):** @@ -2760,7 +2760,7 @@ The spelling is intended. Please, don't submit a patch for this. --- ### ▶ Let's mangle ^ - + 1\. ```py class Yo(object): @@ -2848,7 +2848,7 @@ AttributeError: 'A' object has no attribute '__variable' ### ▶ `+=` is faster - + ```py # using "+", three strings: >>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) @@ -2864,7 +2864,7 @@ AttributeError: 'A' object has no attribute '__variable' --- ### ▶ Let's make a giant string! - + ```py def add_string_with_plus(iters): s = "" @@ -2957,7 +2957,7 @@ Let's increase the number of iterations by a factor of 10. --- ### ▶ Explicit typecast of strings - + ```py a = float('inf') b = float('nan') @@ -2996,7 +2996,7 @@ nan --- ### ▶ Minor Ones - + * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) **💡 Explanation:** From d6b735768c24c7d7c3cee31f68810a3b84d899b6 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 8 Jul 2019 22:01:41 +0530 Subject: [PATCH 071/221] Remove asterisks and carets from titles --- README.md | 145 +++++++++++++++++------------------------------------- 1 file changed, 44 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 07f1a5cc..27d2f447 100644 --- a/README.md +++ b/README.md @@ -28,128 +28,72 @@ So, here we go... - [Usage](#usage) - [👀 Examples](#-examples) - [Section: Strain your brain!](#section-strain-your-brain) - - [▶ Strings can be tricky sometimes *](#%E2%96%B6-strings-can-be-tricky-sometimes-) - - [💡 Explanation:](#-explanation) - - [▶ Splitsies ^](#%E2%96%B6-splitsies-%5E) - - [💡 Explanation:](#-explanation-1) + - [▶ Strings can be tricky sometimes](#%E2%96%B6-strings-can-be-tricky-sometimes) + - [▶ Splitsies](#%E2%96%B6-splitsies) +- [is same as](#is-same-as) +- [but](#but) +- [isn't the same as](#isnt-the-same-as) - [▶ Time for some hash brownies!](#%E2%96%B6-time-for-some-hash-brownies) - - [💡 Explanation](#-explanation) - - [▶ The disorder within order ^](#%E2%96%B6-the-disorder-within-order-%5E) - - [💡 Explanation:](#-explanation-2) - - [▶ Keep trying? *](#%E2%96%B6-keep-trying-) - - [💡 Explanation:](#-explanation-3) - - [▶ Deep down, we're all the same. *](#%E2%96%B6-deep-down-were-all-the-same-) - - [💡 Explanation:](#-explanation-4) + - [▶ The disorder within order](#%E2%96%B6-the-disorder-within-order) + - [▶ Keep trying?](#%E2%96%B6-keep-trying) + - [▶ Deep down, we're all the same](#%E2%96%B6-deep-down-were-all-the-same) - [▶ For what?](#%E2%96%B6-for-what) - - [💡 Explanation:](#-explanation-5) - - [▶ Evaluation time discrepancy ^](#%E2%96%B6-evaluation-time-discrepancy-%5E) - - [💡 Explanation](#-explanation-1) + - [▶ Evaluation time discrepancy](#%E2%96%B6-evaluation-time-discrepancy) - [▶ Messing around with `is` operator^](#%E2%96%B6-messing-around-with-is-operator%5E) - - [💡 Explanation:](#-explanation-6) - [▶ A tic-tac-toe where X wins in the first attempt!](#%E2%96%B6-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - - [💡 Explanation:](#-explanation-7) - [▶ The sticky output function](#%E2%96%B6-the-sticky-output-function) - - [💡 Explanation](#-explanation-2) - - [▶ The chicken-egg problem ^](#%E2%96%B6-the-chicken-egg-problem-%5E) - - [💡 Explanation](#-explanation-3) + - [▶ The chicken-egg problem](#%E2%96%B6-the-chicken-egg-problem) - [▶ `is not ...` is not `is (not ...)`](#%E2%96%B6-is-not--is-not-is-not-) - - [💡 Explanation](#-explanation-4) - [▶ The surprising comma](#%E2%96%B6-the-surprising-comma) - - [💡 Explanation:](#-explanation-8) - - [▶ Strings and the backslashes\ ^](#%E2%96%B6-strings-and-the-backslashes%5C-%5E) - - [💡 Explanation](#-explanation-5) + - [▶ Strings and the backslashes](#%E2%96%B6-strings-and-the-backslashes) - [▶ not knot!](#%E2%96%B6-not-knot) - - [💡 Explanation:](#-explanation-9) - [▶ Half triple-quoted strings](#%E2%96%B6-half-triple-quoted-strings) - - [💡 Explanation:](#-explanation-10) - [▶ Midnight time doesn't exist?](#%E2%96%B6-midnight-time-doesnt-exist) - - [💡 Explanation:](#-explanation-11) - [▶ What's wrong with booleans?](#%E2%96%B6-whats-wrong-with-booleans) - - [💡 Explanation:](#-explanation-12) - [▶ Class attributes and instance attributes](#%E2%96%B6-class-attributes-and-instance-attributes) - - [💡 Explanation:](#-explanation-13) - [▶ yielding None](#%E2%96%B6-yielding-none) - - [💡 Explanation:](#-explanation-14) - [▶ Mutating the immutable!](#%E2%96%B6-mutating-the-immutable) - - [💡 Explanation:](#-explanation-15) - [▶ The disappearing variable from outer scope](#%E2%96%B6-the-disappearing-variable-from-outer-scope) - - [💡 Explanation:](#-explanation-16) - [▶ When True is actually False](#%E2%96%B6-when-true-is-actually-false) - - [💡 Explanation:](#-explanation-17) - [▶ Lossy zip of iterators](#%E2%96%B6-lossy-zip-of-iterators) - - [💡 Explanation:](#-explanation-18) - [▶ From filled to None in one instruction...](#%E2%96%B6-from-filled-to-none-in-one-instruction) - - [💡 Explanation](#-explanation-6) - - [▶ Subclass relationships *](#%E2%96%B6-subclass-relationships-) - - [💡 Explanation:](#-explanation-19) - - [▶ The mysterious key type conversion *](#%E2%96%B6-the-mysterious-key-type-conversion-) - - [💡 Explanation:](#-explanation-20) + - [▶ Subclass relationships](#%E2%96%B6-subclass-relationships) + - [▶ The mysterious key type conversion](#%E2%96%B6-the-mysterious-key-type-conversion) - [▶ Let's see if you can guess this?](#%E2%96%B6-lets-see-if-you-can-guess-this) - - [💡 Explanation:](#-explanation-21) - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - [▶ Skipping lines?](#%E2%96%B6-skipping-lines) - - [💡 Explanation](#-explanation-7) - - [▶ Teleportation *](#%E2%96%B6-teleportation-) - - [💡 Explanation:](#-explanation-22) + - [▶ Teleportation](#%E2%96%B6-teleportation) - [▶ Well, something is fishy...](#%E2%96%B6-well-something-is-fishy) - - [💡 Explanation](#-explanation-8) - [Section: Watch out for the landmines!](#section-watch-out-for-the-landmines) - [▶ Modifying a dictionary while iterating over it](#%E2%96%B6-modifying-a-dictionary-while-iterating-over-it) - - [💡 Explanation:](#-explanation-23) - - [▶ Stubborn `del` operation *](#%E2%96%B6-stubborn-del-operation-) - - [💡 Explanation:](#-explanation-24) - [▶ Deleting a list item while iterating](#%E2%96%B6-deleting-a-list-item-while-iterating) - - [💡 Explanation:](#-explanation-25) - [▶ Loop variables leaking out!](#%E2%96%B6-loop-variables-leaking-out) - - [💡 Explanation:](#-explanation-26) - [▶ Beware of default mutable arguments!](#%E2%96%B6-beware-of-default-mutable-arguments) - - [💡 Explanation:](#-explanation-27) - [▶ Catching the Exceptions](#%E2%96%B6-catching-the-exceptions) - - [💡 Explanation](#-explanation-9) - [▶ Same operands, different story!](#%E2%96%B6-same-operands-different-story) - - [💡 Explanation:](#-explanation-28) - [▶ The out of scope variable](#%E2%96%B6-the-out-of-scope-variable) - - [💡 Explanation:](#-explanation-29) - [▶ Be careful with chained operations](#%E2%96%B6-be-careful-with-chained-operations) - - [💡 Explanation:](#-explanation-30) - [▶ Name resolution ignoring class scope](#%E2%96%B6-name-resolution-ignoring-class-scope) - - [💡 Explanation](#-explanation-10) - [▶ Needles in a Haystack ^](#%E2%96%B6-needles-in-a-haystack-%5E) - - [💡 Explanation:](#-explanation-31) - [▶ Yielding from... return!](#-yielding-from-return) - - [💡 Explanation:](#-explanation-31) - [▶ Wild imports](#%E2%96%B6-wild-imports) - - [💡 Explanation:](#-explanation-32) - [Section: The Hidden treasures!](#section-the-hidden-treasures) - - [▶ Okay Python, Can you make me fly? *](#%E2%96%B6-okay-python-can-you-make-me-fly-) - - [💡 Explanation:](#-explanation-33) - - [▶ `goto`, but why? *](#%E2%96%B6-goto-but-why-) - - [💡 Explanation:](#-explanation-34) - - [▶ Brace yourself! *](#%E2%96%B6-brace-yourself-) - - [💡 Explanation:](#-explanation-35) - - [▶ Let's meet Friendly Language Uncle For Life ^](#%E2%96%B6-lets-meet-friendly-language-uncle-for-life-%5E) - - [💡 Explanation:](#-explanation-36) - - [▶ Even Python understands that love is complicated *](#%E2%96%B6-even-python-understands-that-love-is-complicated-) - - [💡 Explanation:](#-explanation-37) + - [▶ Okay Python, Can you make me fly?](#%E2%96%B6-okay-python-can-you-make-me-fly) + - [▶ `goto`, but why?](#%E2%96%B6-goto-but-why) + - [▶ Brace yourself!](#%E2%96%B6-brace-yourself) + - [▶ Let's meet Friendly Language Uncle For Life](#%E2%96%B6-lets-meet-friendly-language-uncle-for-life) + - [▶ Even Python understands that love is complicated](#%E2%96%B6-even-python-understands-that-love-is-complicated) - [▶ Yes, it exists!](#%E2%96%B6-yes-it-exists) - - [💡 Explanation:](#-explanation-38) - - [▶ Ellipsis ^](#%E2%96%B6-ellipsis-%5E) - - [💡 Explanation](#-explanation-11) - - [▶ Inpinity *](#%E2%96%B6-inpinity-) - - [💡 Explanation:](#-explanation-39) - - [▶ Let's mangle ^](#%E2%96%B6-lets-mangle-%5E) - - [💡 Explanation:](#-explanation-40) + - [▶ Ellipsis](#%E2%96%B6-ellipsis) + - [▶ Inpinity](#%E2%96%B6-inpinity) + - [▶ Let's mangle](#%E2%96%B6-lets-mangle) - [Section: Miscellaneous](#section-miscellaneous) - [▶ `+=` is faster](#%E2%96%B6--is-faster) - - [💡 Explanation:](#-explanation-41) - [▶ Let's make a giant string!](#%E2%96%B6-lets-make-a-giant-string) - - [💡 Explanation](#-explanation-12) - [▶ Explicit typecast of strings](#%E2%96%B6-explicit-typecast-of-strings) - - [💡 Explanation:](#-explanation-42) - [▶ Minor Ones](#%E2%96%B6-minor-ones) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) - - [Some nice Links!](#some-nice-links) - [🎓 License](#-license) - [Help](#help) - [Surprise your geeky pythonist friends?](#surprise-your-geeky-pythonist-friends) @@ -161,8 +105,7 @@ So, here we go... All the examples are structured like below: -> ### ▶ Some fancy Title * -> The asterisk at the end of the title indicates the example was not present in the first release and has been recently added. +> ### ▶ Some fancy Title > > ```py > # Setting up the code. @@ -222,7 +165,7 @@ Now, just run `wtfpython` at the command line which will open this collection in ## Section: Strain your brain! -### ▶ Strings can be tricky sometimes * +### ▶ Strings can be tricky sometimes 1\. ```py @@ -273,7 +216,7 @@ Makes sense, right? --- -### ▶ Splitsies ^ +### ▶ Splitsies ```py >>> 'a'.split() @@ -356,7 +299,7 @@ So, why is Python all over the place? --- -### ▶ The disorder within order ^ +### ▶ The disorder within order ```py from collections import OrderedDict @@ -454,7 +397,7 @@ What is going on here? --- -### ▶ Keep trying? * +### ▶ Keep trying? ```py def some_func(): @@ -514,7 +457,7 @@ Iteration 0 --- -### ▶ Deep down, we're all the same. * +### ▶ Deep down, we're all the same ```py class WTF: @@ -617,7 +560,7 @@ for i, some_dict[i] in enumerate(some_string): --- -### ▶ Evaluation time discrepancy ^ +### ▶ Evaluation time discrepancy 1\. ```py @@ -900,7 +843,7 @@ Even when the values of `x` were different in every iteration prior to appending --- -### ▶ The chicken-egg problem ^ +### ▶ The chicken-egg problem 1\. ```py @@ -994,7 +937,7 @@ SyntaxError: invalid syntax --- -### ▶ Strings and the backslashes\ ^ +### ▶ Strings and the backslashes **Output:** ```py @@ -1493,7 +1436,7 @@ Most methods that modify the items of sequence/mapping objects like `list.append --- -### ▶ Subclass relationships * +### ▶ Subclass relationships **Output:** ```py @@ -1517,7 +1460,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` --- -### ▶ The mysterious key type conversion * +### ▶ The mysterious key type conversion ```py class SomeClass(str): @@ -1670,7 +1613,7 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ --- -### ▶ Teleportation * +### ▶ Teleportation ```py import numpy as np @@ -1780,7 +1723,7 @@ Yes, it runs for exactly **eight** times and stops. --- -### ▶ Stubborn `del` operation * +### ▶ Stubborn `del` operation ```py class SomeClass: @@ -2249,7 +2192,7 @@ class SomeClass: --- -### ▶ Needles in a Haystack ^ +### ▶ Needles in a Haystack 1\. ```py @@ -2477,7 +2420,7 @@ NameError: name 'some_weird_name_func_' is not defined This section contains few of the lesser-known interesting things about Python that most beginners like me are unaware of (well, not anymore). -### ▶ Okay Python, Can you make me fly? * +### ▶ Okay Python, Can you make me fly? Well, here you go @@ -2495,7 +2438,7 @@ Sshh.. It's a super secret. --- -### ▶ `goto`, but why? * +### ▶ `goto`, but why? ```py from goto import goto, label @@ -2523,7 +2466,7 @@ Freedom! --- -### ▶ Brace yourself! * +### ▶ Brace yourself! If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing, @@ -2548,7 +2491,7 @@ Braces? No way! If you think that's disappointing, use Java. Okay, another surpr --- -### ▶ Let's meet Friendly Language Uncle For Life ^ +### ▶ Let's meet Friendly Language Uncle For Life **Output (Python 3.x)** ```py @@ -2579,7 +2522,7 @@ There we go. --- -### ▶ Even Python understands that love is complicated * +### ▶ Even Python understands that love is complicated ```py import this @@ -2680,7 +2623,7 @@ Try block executed successfully... - `else` clause after try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. --- -### ▶ Ellipsis ^ +### ▶ Ellipsis ```py def some_func(): @@ -2740,7 +2683,7 @@ Ellipsis --- -### ▶ Inpinity * +### ▶ Inpinity The spelling is intended. Please, don't submit a patch for this. @@ -2759,7 +2702,7 @@ The spelling is intended. Please, don't submit a patch for this. --- -### ▶ Let's mangle ^ +### ▶ Let's mangle 1\. ```py From 2a1c28ee4d850b10f15b6bff7a805b6cb875923f Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 8 Jul 2019 22:22:04 +0530 Subject: [PATCH 072/221] Fix toc --- README.md | 80 +++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 69 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 27d2f447..e9cd41ba 100644 --- a/README.md +++ b/README.md @@ -20,19 +20,15 @@ So, here we go... # Table of Contents - - - + - [Structure of the Examples](#structure-of-the-examples) + + [▶ Some fancy Title](#-some-fancy-title) - [Usage](#usage) - [👀 Examples](#-examples) - [Section: Strain your brain!](#section-strain-your-brain) - [▶ Strings can be tricky sometimes](#%E2%96%B6-strings-can-be-tricky-sometimes) - [▶ Splitsies](#%E2%96%B6-splitsies) -- [is same as](#is-same-as) -- [but](#but) -- [isn't the same as](#isnt-the-same-as) - [▶ Time for some hash brownies!](#%E2%96%B6-time-for-some-hash-brownies) - [▶ The disorder within order](#%E2%96%B6-the-disorder-within-order) - [▶ Keep trying?](#%E2%96%B6-keep-trying) @@ -92,14 +88,76 @@ So, here we go... - [▶ Let's make a giant string!](#%E2%96%B6-lets-make-a-giant-string) - [▶ Explicit typecast of strings](#%E2%96%B6-explicit-typecast-of-strings) - [▶ Minor Ones](#%E2%96%B6-minor-ones) + * [Section: Strain your brain!](#section-strain-your-brain) + + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) + + [▶ Splitsies](#-splitsies) + + [▶ Time for some hash brownies!](#-time-for-some-hash-brownies) + + [▶ The disorder within order](#-the-disorder-within-order) + + [▶ Keep trying?](#-keep-trying) + + [▶ Deep down, we're all the same](#-deep-down-were-all-the-same) + + [▶ For what?](#-for-what) + + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) + + [▶ Messing around with `is` operator](#-messing-around-with-is-operator) + + [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + + [▶ The sticky output function](#-the-sticky-output-function) + + [▶ The chicken-egg problem](#-the-chicken-egg-problem) + + [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) + + [▶ The surprising comma](#-the-surprising-comma) + + [▶ Strings and the backslashes](#-strings-and-the-backslashes) + + [▶ not knot!](#-not-knot) + + [▶ Half triple-quoted strings](#-half-triple-quoted-strings) + + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) + + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) + + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) + + [▶ yielding None](#-yielding-none) + + [▶ Mutating the immutable!](#-mutating-the-immutable) + + [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) + + [▶ When True is actually False](#-when-true-is-actually-false) + + [▶ Lossy zip of iterators](#-lossy-zip-of-iterators) + + [▶ From filled to None in one instruction...](#-from-filled-to-none-in-one-instruction) + + [▶ Subclass relationships](#-subclass-relationships) + + [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) + + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + * [Section: Appearances are deceptive!](#section-appearances-are-deceptive) + + [▶ Skipping lines?](#-skipping-lines) + + [▶ Teleportation](#-teleportation) + + [▶ Well, something is fishy...](#-well-something-is-fishy) + * [Section: Watch out for the landmines!](#section-watch-out-for-the-landmines) + + [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + + [▶ Stubborn `del` operation](#-stubborn-del-operation) + + [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) + + [▶ Loop variables leaking out!](#-loop-variables-leaking-out) + + [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) + + [▶ Catching the Exceptions](#-catching-the-exceptions) + + [▶ Same operands, different story!](#-same-operands-different-story) + + [▶ The out of scope variable](#-the-out-of-scope-variable) + + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + + [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) + + [▶ Needles in a Haystack](#-needles-in-a-haystack) + + [▶ Wild imports](#-wild-imports) + * [Section: The Hidden treasures!](#section-the-hidden-treasures) + + [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) + + [▶ `goto`, but why?](#-goto-but-why) + + [▶ Brace yourself!](#-brace-yourself) + + [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) + + [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) + + [▶ Yes, it exists!](#-yes-it-exists) + + [▶ Ellipsis](#-ellipsis) + + [▶ Inpinity](#-inpinity) + + [▶ Let's mangle](#-lets-mangle) + * [Section: Miscellaneous](#section-miscellaneous) + + [▶ `+=` is faster](#--is-faster) + + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + + [▶ Explicit typecast of strings](#-explicit-typecast-of-strings) + + [▶ Minor Ones](#-minor-ones) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) - [🎓 License](#-license) - - [Help](#help) - - [Surprise your geeky pythonist friends?](#surprise-your-geeky-pythonist-friends) - - [Need a pdf version?](#need-a-pdf-version) + * [Help](#help) + * [Surprise your geeky pythonist friends?](#surprise-your-geeky-pythonist-friends) + * [Need a pdf version?](#need-a-pdf-version) - + # Structure of the Examples @@ -626,7 +684,7 @@ array_4 = [400, 500, 600] --- -### ▶ Messing around with `is` operator^ +### ▶ Messing around with `is` operator The following is a very famous example present all over the internet. From 62237157251d68aef0a3a3ae16b285bbc4dd2383 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sat, 13 Jul 2019 22:41:27 +0530 Subject: [PATCH 073/221] change order --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e9cd41ba..70d73d49 100644 --- a/README.md +++ b/README.md @@ -326,9 +326,9 @@ some_dict[5] = "Python" ```py >>> some_dict[5.5] "Ruby" ->>> some_dict[5.0] +>>> some_dict[5.0] # "Python" destroyed the existence of "JavaScript"? "Python" ->>> some_dict[5] # "Python" destroyed the existence of "JavaScript"? +>>> some_dict[5] "Python" >>> complex_five = 5 + 0j From fc491c5dd637c1bce61fca254def98cf8f6410b5 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 21 Jul 2019 18:57:01 +0530 Subject: [PATCH 074/221] Commit insert_ids script --- irrelevant/insert_ids.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 irrelevant/insert_ids.py diff --git a/irrelevant/insert_ids.py b/irrelevant/insert_ids.py new file mode 100644 index 00000000..a16bf5f5 --- /dev/null +++ b/irrelevant/insert_ids.py @@ -0,0 +1,24 @@ +import uuid + +new_file = [] +original_file = [] + +fname = "../README.md" + + +def generate_random_id_comment(): + random_id = uuid.uuid4() + return f"" + + +with open(fname, "r") as f: + original_file = f.readlines() + + +for line in original_file: + new_file.append(line) + if line.strip().startswith("### "): + new_file.append(generate_random_id_comment()) + +with open(fname, "w") as f: + f.write("".join(new_file)) From d143f972b8a6a43b0e16c3ca4b26bd965e94a2d4 Mon Sep 17 00:00:00 2001 From: mitcom Date: Sun, 6 Oct 2019 13:06:38 +0200 Subject: [PATCH 075/221] Add space-invader operator case --- README.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/README.md b/README.md index be27847b..27940e57 100644 --- a/README.md +++ b/README.md @@ -2368,6 +2368,24 @@ nan + `++a` parses as `+(+a)` which translates to `a`. Similarly, the output of the statement `--a` can be justified. + This StackOverflow [thread](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) discusses the rationale behind the absence of increment and decrement operators in Python. +* There is a lack of incrementation operator known from different languages, but have you ever heard about _the space-invader operator_? + ```py + >>> a = 42 + >>> a -=- 1 + >>> a + 43 + ``` + + + together with another: + ```py + >>> a +=+ 1 + >>> a + >>> 44 + ``` + + **💡 Explanation:** + This prank comes from [Raymond Hettinger's twit](https://twitter.com/raymondh/status/1131103570856632321?lang=en) and it is actually just malformatted `a -= (-1)`. Which is eqivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case. + * Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!): ```py import dis From f8acf49d0544108684d3fa66337e14a11bf9c6f1 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Wed, 9 Oct 2019 18:48:41 +0530 Subject: [PATCH 076/221] Update README.md --- README.md | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 27940e57..c31017e0 100644 --- a/README.md +++ b/README.md @@ -2368,23 +2368,21 @@ nan + `++a` parses as `+(+a)` which translates to `a`. Similarly, the output of the statement `--a` can be justified. + This StackOverflow [thread](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) discusses the rationale behind the absence of increment and decrement operators in Python. -* There is a lack of incrementation operator known from different languages, but have you ever heard about _the space-invader operator_? +* Have you ever heard about _the space-invader operator_ in Python? ```py >>> a = 42 >>> a -=- 1 >>> a 43 ``` - - + together with another: - ```py - >>> a +=+ 1 - >>> a - >>> 44 - ``` - + It is used as an alternative incrementation operator, together with another one + ```py + >>> a +=+ 1 + >>> a + >>> 44 + ``` **💡 Explanation:** - This prank comes from [Raymond Hettinger's twit](https://twitter.com/raymondh/status/1131103570856632321?lang=en) and it is actually just malformatted `a -= (-1)`. Which is eqivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case. + This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is eqivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case. * Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!): ```py From bef3f2a33db59a65b159dec661c13c36850501f0 Mon Sep 17 00:00:00 2001 From: monujee Date: Fri, 25 Oct 2019 14:28:25 +0530 Subject: [PATCH 077/221] Update README.md Typo corrected. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c31017e0..b1354cc5 100644 --- a/README.md +++ b/README.md @@ -2336,7 +2336,7 @@ nan #### 💡 Explanation: -`'inf'` and `'nan'` are special strings (case-insensitive), which when explicitly typecasted to `float` type, are used to represent mathematical "infinity" and "not a number" respectively. +`'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. --- @@ -2382,7 +2382,7 @@ nan >>> 44 ``` **💡 Explanation:** - This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is eqivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case. + This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case. * Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!): ```py @@ -2390,7 +2390,7 @@ nan exec(""" def f(): """ + """ - """.join(["X"+str(x)+"=" + str(x) for x in range(65539)])) + """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) f() From d823aa922055a9c299092cb428f99282f64c03a3 Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 28 Oct 2019 19:23:06 +0530 Subject: [PATCH 078/221] Ignore DS_Store --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 523a028e..a252b5a5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +.DS_Store + node_modules npm-debug.log wtfpython-pypi/build/ From 82c37ccb32588ccf74592d541e43c14e71d98531 Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 28 Oct 2019 22:17:12 +0530 Subject: [PATCH 079/221] Perhaps some editing --- README.md | 266 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 165 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 907ebdf6..f2743e8d 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,13 @@ Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) -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 to a regular user at first sight. +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. -Here is a fun project to collect such tricky & counter-intuitive examples and lesser-known features in Python, attempting to discuss what exactly is happening under the hood! +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. 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! -If you're an experienced Python programmer, you can take it as a challenge to get most of them right in first attempt. You may be already familiar with some of these examples, and I might be able to revive sweet old memories of yours being bitten by these gotchas :sweat_smile: +If you're an experienced Python programmer, you can take it as a challenge to get most of them right in 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: PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). @@ -104,11 +104,12 @@ All the examples are structured like below: > ### ▶ Some fancy Title > > ```py -> # Setting up the code. +> # Set up the code. > # Preparation for the magic... > ``` > > **Output (Python version(s)):** +> > ```py > >>> triggering_statement > Some unexpected output @@ -119,16 +120,18 @@ All the examples are structured like below: > #### 💡 Explanation: > > * Brief explanation of what's happening and why is it happening. -> ```py -> Setting up examples for clarification (if necessary) -> ``` -> **Output Output (Python version(s)):** -> ```py -> >>> trigger # some example that makes it easy to unveil the magic -> # some justified output -> ``` +> ```py +> # Set up code +> # More examples for further clarification (if necessary) +> ``` +> **Output (Python version(s)):** +> +> ```py +> >>> trigger # some example that makes it easy to unveil the magic +> # some justified output +> ``` -**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 in the description. +**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. # Usage @@ -199,14 +202,14 @@ False Makes sense, right? #### 💡 Explanation: -+ Such behavior is due to CPython optimization (called string interning) that tries to use existing immutable objects in some cases rather than creating a new object every time. -+ After being interned, many variables may point to the same string object in memory (thereby saving memory). -+ In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation dependent. There are some facts that can be used to guess if a string will be interned or not: ++ The behavior in first and second snippets is due to a CPython optimization (called string interning) that tries to use existing immutable objects in some cases rather than creating a new object every time. ++ After being "interned", many variables may reference the same string object in memory (saving memory thereby). ++ In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation dependent. There are some rules that can be used to guess if a string will be interned or not: * All length 0 and length 1 strings are interned. * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) -+ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. ++ The abrupt change in output of the third snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. + Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). --- @@ -232,8 +235,8 @@ Makes sense, right? #### 💡 Explanation: -- It might appear at first that the default seperator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split), - > If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`. +- It might appear at first that the default seperator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split) + > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`. > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`. - Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear, ```py @@ -249,21 +252,22 @@ Makes sense, right? -### ▶ Time for some hash brownies! +### ▶ Hash brownies 1\. ```py some_dict = {} -some_dict[5.5] = "Ruby" -some_dict[5.0] = "JavaScript" +some_dict[5.5] = "JavaScript" +some_dict[5.0] = "Ruby" some_dict[5] = "Python" ``` **Output:** + ```py >>> some_dict[5.5] "Ruby" ->>> some_dict[5.0] # "Python" destroyed the existence of "JavaScript"? +>>> some_dict[5.0] # "Python" destroyed the existence of "Ruby"? "Python" >>> some_dict[5] "Python" @@ -288,13 +292,13 @@ So, why is Python all over the place? >>> hash(5) == hash(5.0) == hash(5 + 0j) True ``` - **Note:** Objects with different values may also have same hash (known as hash collision). -* When the statement `some_dict[5] = "Python"` is executed, the existing value "JavaScript" is overwritten with "Python" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`. -* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains beautifully the rationale behind it. + **Note:** Objects with different values may also have same hash (known as [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science))). +* When the statement `some_dict[5] = "Python"` is executed, the existing value "Ruby" is overwritten with "Python" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`. +* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains the rationale behind it. --- -### ▶ The disorder within order +### ▶ Disorder within order ```py from collections import OrderedDict @@ -316,7 +320,7 @@ class DictWithHash(dict): class OrderedDictWithHash(OrderedDict): """ - A dict that also implements __hash__ magic. + An OrderedDict that also implements __hash__ magic. """ __hash__ = lambda self: 0 ``` @@ -357,6 +361,7 @@ What is going on here? #### 💡 Explanation: - 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://docs.python.org/3/library/collections.html#ordereddict-objects) + > 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. - The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. - Okay, so why did changing the order affect the lenght 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, @@ -387,12 +392,11 @@ What is going on here? >>> len(another_set) 2 ``` - 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`. - + 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`. --- -### ▶ Keep trying? +### ▶ Keep trying... ```py def some_func(): @@ -446,13 +450,13 @@ Iteration 0 #### 💡 Explanation: -- 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. +- 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. - 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. - The caveat here is, if the finally clause executes a `return` or `break` statement, the temporarily saved exception is discarded. --- -### ▶ Deep down, we're all the same +### ▶ Deep down, we're all the same. ```py class WTF: @@ -508,12 +512,12 @@ True some_string = "wtf" some_dict = {} for i, some_dict[i] in enumerate(some_string): - pass + i = 10 ``` **Output:** ```py ->>> some_dict # An indexed dict is created. +>>> some_dict # An indexed dict appears. {0: 'w', 1: 't', 2: 'f'} ``` @@ -545,7 +549,7 @@ for i, some_dict[i] in enumerate(some_string): - 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)` this case) is unpacked and assigned the target list variables (`i` in this case). -* 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: +* 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: ```py >>> i, some_dict[i] = (0, 'w') >>> i, some_dict[i] = (1, 't') @@ -560,13 +564,15 @@ for i, some_dict[i] in enumerate(some_string): 1\. ```py array = [1, 8, 15] -g = (x for x in array if array.count(x) > 0) +# A typical generator expresion +gen = (x for x in array if array.count(x) > 0) array = [2, 8, 22] ``` **Output:** + ```py ->>> print(list(g)) +>>> print(list(gen)) # Where did the other values go? [8] ``` @@ -574,20 +580,20 @@ array = [2, 8, 22] ```py array_1 = [1,2,3,4] -g1 = (x for x in array_1) +gen_1 = (x for x in array_1) array_1 = [1,2,3,4,5] array_2 = [1,2,3,4] -g2 = (x for x in array_2) +gen_2 = (x for x in array_2) array_2[:] = [1,2,3,4,5] ``` **Output:** ```py ->>> print(list(g1)) +>>> print(list(gen_1)) [1,2,3,4] ->>> print(list(g2)) +>>> print(list(gen_2)) [1,2,3,4,5] ``` @@ -596,7 +602,7 @@ array_2[:] = [1,2,3,4,5] ```py array_3 = [1, 2, 3] array_4 = [10, 20, 30] -g = (i + j for i in array_3 for j in array_4) +gen = (i + j for i in array_3 for j in array_4) array_3 = [4, 5, 6] array_4 = [400, 500, 600] @@ -604,7 +610,7 @@ array_4 = [400, 500, 600] **Output:** ```py ->>> print(list(g)) +>>> print(list(gen)) [401, 501, 601, 402, 502, 602, 403, 503, 603] ``` @@ -621,11 +627,12 @@ array_4 = [400, 500, 600] --- -### ▶ Messing around with `is` operator +### ▶ How not to use `is` operator The following is a very famous example present all over the internet. 1\. + ```py >>> a = 256 >>> b = 256 @@ -741,14 +748,16 @@ Similar optimization applies to other **immutable** objects like empty tuples as ### ▶ A tic-tac-toe where X wins in the first attempt! + ```py # Let's initialize a row -row = [""]*3 #row i['', '', ''] +row = [""] * 3 #row i['', '', ''] # Let's make a board -board = [row]*3 +board = [row] * 3 ``` **Output:** + ```py >>> board [['', '', ''], ['', '', ''], ['', '', '']] @@ -761,7 +770,7 @@ board = [row]*3 [['X', '', ''], ['X', '', ''], ['X', '', '']] ``` -We didn't assign 3 "X"s or did we? +We didn't assign three `"X"`s, did we? #### 💡 Explanation: @@ -786,6 +795,9 @@ We can avoid this scenario here by not using `row` variable to generate `board`. ### ▶ The sticky output function + +1\. + ```py funcs = [] results = [] @@ -799,6 +811,7 @@ funcs_results = [func() for func in funcs] ``` **Output:** + ```py >>> results [0, 1, 2, 3, 4, 5, 6] @@ -807,7 +820,7 @@ funcs_results = [func() for func in funcs] ``` Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6. -//OR +2\. ```py >>> powers_of_x = [lambda x: x**i for i in range(10)] @@ -850,7 +863,9 @@ True True ``` -2\. So which is the ultimate, base class? And wait, there's more to the confusion +So which is the "ultimate" base class? There's more to the confusion by the way, + +2\. ```py >>> class A: pass @@ -904,7 +919,8 @@ False ### ▶ The surprising comma -**Output:** +**Output (< 3.6):** + ```py >>> def f(x, y,): ... print(x, y) @@ -917,6 +933,7 @@ False def h(x, **kwargs,): ^ SyntaxError: invalid syntax + >>> def h(*args,): File "", line 1 def h(*args,): @@ -1045,7 +1062,8 @@ if noon_time: print("Time at noon is", noon_time) ``` -**Output:** +**Output (< 3.5):** + ```sh ('Time at noon is', datetime.time(12, 0)) ``` @@ -1202,6 +1220,7 @@ def some_func(val): ``` **Output:** + ```py >>> [x for x in some_iterable] ['a', 'b'] @@ -1216,6 +1235,7 @@ def some_func(val): ``` #### 💡 Explanation: +- This is bug in CPython's handling of `yield` in generators and comprehensions. - Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions - Related bug report: http://bugs.python.org/issue10544 @@ -1223,6 +1243,9 @@ def some_func(val): ### ▶ Mutating the immutable! + +This might seem trivial if you know how references works in Python. + ```py some_tuple = ("A", "tuple", "with", "values") another_tuple = ([1, 2], [3, 4], [5, 6]) @@ -1342,7 +1365,8 @@ if True == False: print("I've lost faith in truth!") ``` -**Output:** +**Output (< 3.x):** + ``` I've lost faith in truth! ``` @@ -1403,34 +1427,6 @@ Where did element `3` go from the `numbers` list? --- -### ▶ From filled to None in one instruction... - -```py -some_list = [1, 2, 3] -some_dict = { - "key_1": 1, - "key_2": 2, - "key_3": 3 -} - -some_list = some_list.append(4) -some_dict = some_dict.update({"key_4": 4}) -``` - -**Output:** -```py ->>> print(some_list) -None ->>> print(some_dict) -None -``` - -#### 💡 Explanation - -Most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)) - ---- - ### ▶ Subclass relationships **Output:** @@ -2184,24 +2180,60 @@ class SomeClass: - A generator expression has its own scope. - Starting from Python 3.X, list comprehensions also have their own scope. +--- + +### ▶ From full to None in one instruction + + + +```py +some_list = [1, 2, 3] +some_dict = { + "key_1": 1, + "key_2": 2, + "key_3": 3 +} + +some_list = some_list.append(4) +some_dict = some_dict.update({"key_4": 4}) +``` + +**Output:** + +```py +>>> print(some_list) +None +>>> print(some_dict) +None +``` + +#### 💡 Explanation + + --- + + ### ▶ Needles in a Haystack + + +I haven't met even a single experience Pythonist till date who has not came across one or more of the following scenarios, + 1\. + ```py x, y = (0, 1) if True else None, None ``` **Output:** + ```py >>> x, y # expected (0, 1) ((0, 1), None) ``` -Almost every Python programmer has faced a similar situation. - 2\. ```py t = ('one', 'two') @@ -2263,15 +2295,45 @@ b = "javascript" # No AssertionError is raised ``` +5\. + +```py +some_list = [1, 2, 3] +some_dict = { + "key_1": 1, + "key_2": 2, + "key_3": 3 +} + +some_list = some_list.append(4) +some_dict = some_dict.update({"key_4": 4}) +``` + +**Output:** + +```py +>>> print(some_list) +None +>>> print(some_dict) +None +``` + + + #### 💡 Explanation: + * For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. + * For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. + * `()` is a special token and denotes empty `tuple`. + * In 3, as you might have already figured out, there's a missing comma after 5th element (`"that"`) in the list. So by implicit string literal concatenation, ```py >>> ten_words_list ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] ``` + * No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up, ```py >>> a = "python" @@ -2289,15 +2351,17 @@ b = "javascript" File "", line 1, in AssertionError: Values aren not equal ``` + +* As for the last snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). ---- - -``` +* Being aware of these knitpicks can save you hours of degugging effort in long run. +--- ### ▶ Yielding from... return! 1\. + ```py def some_func(x): if x == 3: @@ -2307,6 +2371,7 @@ def some_func(x): ``` **Output:** + ```py >>> list(some_func(3)) [] @@ -2315,6 +2380,7 @@ def some_func(x): Where did the `"wtf"` go? Is it due to some special effect of `yield from`? Let's validate that, 2\. + ```py def some_func(x): if x == 3: @@ -2324,7 +2390,8 @@ def some_func(x): yield i ``` -**Output:** +**Output (> 3.3):** + ```py >>> list(some_func(3)) [] @@ -2573,7 +2640,7 @@ True * `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)). * And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, the code for the Zen violates itself (and that's probably the only place where this happens). -* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory. +* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators). --- @@ -2781,8 +2848,6 @@ AttributeError: 'A' object has no attribute '__variable' - - --- ## Section: Miscellaneous @@ -2790,6 +2855,7 @@ AttributeError: 'A' object has no attribute '__variable' ### ▶ `+=` is faster + ```py # using "+", three strings: >>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) @@ -2893,6 +2959,7 @@ Let's increase the number of iterations by a factor of 10. 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` - So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which, + > There should be one-- and preferably only one --obvious way to do it. --- @@ -3016,11 +3083,13 @@ nan --- -# Contributing +
~~~ That's all folks! ~~~
+ +--- -All patches are Welcome! Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for further details. +# Contributing -For discussions, you can either create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) or ping on the Gitter [channel](https://gitter.im/wtfpython/Lobby) +All patches are welcome! Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for further details. For discussions, you can either create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) or ping on the Gitter [channel](https://gitter.im/wtfpython/Lobby). # Acknowledgements @@ -3044,16 +3113,11 @@ The idea and design for this collection were initially inspired by Denys Dovhan' [license-url]: http://www.wtfpl.net [license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square -## Help - -If you have any wtfs, ideas or suggestions, please share. - -## Surprise your geeky pythonist friends? +## Surprise your friends too? -You can use these quick links to recommend wtfpython to your friends, +If you liked the project, you can use these quick links to recommend wtfpython to your friends, -[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) - | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) +[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) ## Need a pdf version? From 28bcbfd311a6f5314bc1159c022eff5cc53e2f2e Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 28 Oct 2019 22:40:32 +0530 Subject: [PATCH 080/221] More changes to order and aesthetics --- README.md | 228 ++++++++++++++++++++++++------------------------------ 1 file changed, 103 insertions(+), 125 deletions(-) diff --git a/README.md b/README.md index f2743e8d..5ac74625 100644 --- a/README.md +++ b/README.md @@ -1303,7 +1303,7 @@ NameError: name 'e' is not defined * Source: https://docs.python.org/3/reference/compound_stmts.html#except - When an exception has been assigned using `as` target, it is cleared at the end of the except clause. This is as if + When an exception has been assigned using `as` target, it is cleared at the end of the `except` clause. This is as if ```py except E as N: @@ -1378,8 +1378,75 @@ I've lost faith in truth! --- +### ▶ Yielding from... return! + +1\. + +```py +def some_func(x): + if x == 3: + return ["wtf"] + else: + yield from range(x) +``` + +**Output:** + +```py +>>> list(some_func(3)) +[] +``` + +Where did the `"wtf"` go? Is it due to some special effect of `yield from`? Let's validate that, + +2\. + +```py +def some_func(x): + if x == 3: + return ["wtf"] + else: + for i in range(x): + yield i +``` + +**Output (> 3.3):** + +```py +>>> list(some_func(3)) +[] +``` + +Same result, that didn't work either. + +#### 💡 Explanation: + ++ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that, + +> "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." + ++ In case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically catched inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. + ++ To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, + + ```py + try: + next(some_func(3)) + except StopIteration as e: + some_string = e.value + ``` + + ```py + >>> some_string + ["wtf"] + ``` + +--- + ### ▶ Lossy zip of iterators + + ```py >>> numbers = list(range(7)) >>> numbers @@ -1407,8 +1474,7 @@ Where did element `3` go from the `numbers` list? result = [] for it in iterators: elem = next(it, sentinel) - if elem is sentinel: - return + if elem is sentinel: return result.append(elem) yield tuple(result) ``` @@ -1605,7 +1671,9 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ --- ### ▶ Teleportation + + ```py import numpy as np @@ -1858,8 +1926,8 @@ print(x, ': x in global') >>> x = 1 >>> print([x for x in range(5)]) [0, 1, 2, 3, 4] ->>> print(x, ': x in global') -(4, ': x in global') +>>> print(x) +4 ``` **Output (Python 3.x):** @@ -1867,15 +1935,15 @@ print(x, ': x in global') >>> x = 1 >>> print([x for x in range(5)]) [0, 1, 2, 3, 4] ->>> print(x, ': x in global') -1 : x in global +>>> print(x) +1 ``` #### 💡 Explanation: - In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable. -- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) documentation: +- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) change log: > "List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular the loop control variables are no longer leaked into the surrounding scope." @@ -1883,6 +1951,7 @@ print(x, ': x in global') ### ▶ Beware of default mutable arguments! + ```py def some_func(default_arg=[]): default_arg.append("some_string") @@ -2182,39 +2251,6 @@ class SomeClass: --- -### ▶ From full to None in one instruction - - - -```py -some_list = [1, 2, 3] -some_dict = { - "key_1": 1, - "key_2": 2, - "key_3": 3 -} - -some_list = some_list.append(4) -some_dict = some_dict.update({"key_4": 4}) -``` - -**Output:** - -```py ->>> print(some_list) -None ->>> print(some_dict) -None -``` - -#### 💡 Explanation - - - ---- - - - ### ▶ Needles in a Haystack @@ -2235,6 +2271,7 @@ x, y = (0, 1) if True else None, None ``` 2\. + ```py t = ('one', 'two') for i in t: @@ -2249,6 +2286,7 @@ print(t) ``` **Output:** + ```py one two @@ -2288,7 +2326,9 @@ ten_words_list = [ a = "python" b = "javascript" ``` + **Output:** + ```py # An assert statement with an assertion failure message. >>> assert(a == b, "Both languages are different") @@ -2329,97 +2369,35 @@ None * `()` is a special token and denotes empty `tuple`. * In 3, as you might have already figured out, there's a missing comma after 5th element (`"that"`) in the list. So by implicit string literal concatenation, - ```py - >>> ten_words_list - ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] - ``` - -* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up, - ```py - >>> a = "python" - >>> b = "javascript" - >>> assert a == b - Traceback (most recent call last): - File "", line 1, in - AssertionError - - >>> assert (a == b, "Values are not equal") - :1: SyntaxWarning: assertion is always true, perhaps remove parentheses? - - >>> assert a == b, "Values are not equal" - Traceback (most recent call last): - File "", line 1, in - AssertionError: Values aren not equal - ``` - -* As for the last snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). - -* Being aware of these knitpicks can save you hours of degugging effort in long run. - ---- - -### ▶ Yielding from... return! - -1\. - -```py -def some_func(x): - if x == 3: - return ["wtf"] - else: - yield from range(x) -``` - -**Output:** - -```py ->>> list(some_func(3)) -[] -``` -Where did the `"wtf"` go? Is it due to some special effect of `yield from`? Let's validate that, - -2\. - -```py -def some_func(x): - if x == 3: - return ["wtf"] - else: - for i in range(x): - yield i -``` - -**Output (> 3.3):** - -```py ->>> list(some_func(3)) -[] -``` - -Same result, that didn't work either. - -#### 💡 Explanation: - -+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that, - -> "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." - -+ In case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically catched inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. - -+ To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, ```py - try: - next(some_func(3)) - except StopIteration as e: - some_string = e.value + >>> ten_words_list + ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] ``` +* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up, + ```py - >>> some_string - ["wtf"] + >>> a = "python" + >>> b = "javascript" + >>> assert a == b + Traceback (most recent call last): + File "", line 1, in + AssertionError + + >>> assert (a == b, "Values are not equal") + :1: SyntaxWarning: assertion is always true, perhaps remove parentheses? + + >>> assert a == b, "Values are not equal" + Traceback (most recent call last): + File "", line 1, in + AssertionError: Values aren not equal ``` +* As for the last snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). + +* Being aware of these knitpicks can save you hours of degugging effort in long run. + --- ### ▶ Wild imports From ce8adb0417b6821f95747c2e4cf81b931da4b547 Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 28 Oct 2019 22:48:15 +0530 Subject: [PATCH 081/221] Update TOC --- README.md | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 5ac74625..5033a908 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,6 @@

What the f*ck Python! 🐍

An interesting collection of surprising snippets and lesser-known Python features.

- [![WTFPL 2.0][license-image]][license-url] Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) @@ -20,22 +19,22 @@ So, here we go... # Table of Contents - + - [Structure of the Examples](#structure-of-the-examples) + [▶ Some fancy Title](#-some-fancy-title) - [Usage](#usage) -- [👀 Examples](#-examples) +- [👀 Examples](#%F0%9F%91%80-examples) * [Section: Strain your brain!](#section-strain-your-brain) + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) + [▶ Splitsies](#-splitsies) - + [▶ Time for some hash brownies!](#-time-for-some-hash-brownies) - + [▶ The disorder within order](#-the-disorder-within-order) - + [▶ Keep trying?](#-keep-trying) - + [▶ Deep down, we're all the same](#-deep-down-were-all-the-same) + + [▶ Hash brownies](#-hash-brownies) + + [▶ Disorder within order](#-disorder-within-order) + + [▶ Keep trying...](#-keep-trying) + + [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) + [▶ For what?](#-for-what) + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - + [▶ Messing around with `is` operator](#-messing-around-with-is-operator) + + [▶ How not to use `is` operator](#-how-not-to-use-is-operator) + [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + [▶ The sticky output function](#-the-sticky-output-function) + [▶ The chicken-egg problem](#-the-chicken-egg-problem) @@ -51,8 +50,8 @@ So, here we go... + [▶ Mutating the immutable!](#-mutating-the-immutable) + [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) + [▶ When True is actually False](#-when-true-is-actually-false) + + [▶ Yielding from... return!](#-yielding-from-return) + [▶ Lossy zip of iterators](#-lossy-zip-of-iterators) - + [▶ From filled to None in one instruction...](#-from-filled-to-none-in-one-instruction) + [▶ Subclass relationships](#-subclass-relationships) + [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) @@ -88,11 +87,11 @@ So, here we go... + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + [▶ Explicit typecast of strings](#-explicit-typecast-of-strings) + [▶ Minor Ones](#-minor-ones) + * [~~~ That's all folks! ~~~](#-thats-all-folks-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) -- [🎓 License](#-license) - * [Help](#help) - * [Surprise your geeky pythonist friends?](#surprise-your-geeky-pythonist-friends) +- [🎓 License](#%F0%9F%8E%93-license) + * [Surprise your friends too?](#surprise-your-friends-too) * [Need a pdf version?](#need-a-pdf-version) @@ -361,7 +360,7 @@ What is going on here? #### 💡 Explanation: - 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://docs.python.org/3/library/collections.html#ordereddict-objects) - + > 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. - The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. - Okay, so why did changing the order affect the lenght 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, @@ -2937,7 +2936,7 @@ Let's increase the number of iterations by a factor of 10. 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` - So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which, - + > There should be one-- and preferably only one --obvious way to do it. --- @@ -3062,7 +3061,6 @@ nan ---
~~~ That's all folks! ~~~
- --- # Contributing From bd798f2966b7c3be801fbb3ed868bea7fe97d24f Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 28 Oct 2019 22:51:03 +0530 Subject: [PATCH 082/221] Update alignment --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5033a908..dcafc440 100644 --- a/README.md +++ b/README.md @@ -3060,7 +3060,8 @@ nan --- -
~~~ That's all folks! ~~~
+

~~~ That's all folks! ~~~

+ --- # Contributing From 34e97d53fb12970945d05a2853a7102c980f1e20 Mon Sep 17 00:00:00 2001 From: Satwik Date: Tue, 29 Oct 2019 01:07:28 +0530 Subject: [PATCH 083/221] Add example related to the Walrus operator Closes https://github.com/satwikkansal/wtfpython/issues/145 --- README.md | 118 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 115 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index dcafc440..58bbdb70 100644 --- a/README.md +++ b/README.md @@ -160,12 +160,124 @@ Now, just run `wtfpython` at the command line which will open this collection in # 👀 Examples - ## Section: Strain your brain! +### ▶ First things first! + + + +For some reasons, "Walrus" operator (`:=`) has become a very popular feature in the language. Let's check it out, + +1\. + +```py +>>> a = "wtf_walrus" +>>> a +'wtf_walrus' +>>> a := "wtf_walrus" +File "", line 1 + a := "wtf_walrus" + ^ +SyntaxError: invalid syntax + +>>> (a := "wtf_walrus") # This works though +>>> a +'wtf_walrus' +``` + +2 \. + +```py +>>> a = 6, 9 +>>> a +(6, 9) + +>>> (a := 6, 9) +>>> a +6 + +>>> a, b = 6, 9 # Typcial unpacking +>>> a, b +(6, 9) +>>> (a, b = 16, 19) # Oops + File "", line 1 + (a, b = 6, 9) + ^ +SyntaxError: invalid syntax + +>>> (a, b := 16, 19) # This prints out a weird 3-tuple +(6, 16, 19) + +>>> a # a is still unchanged? +6 +16 +``` + + + +💡 Explanation + +**Quick walrus operator refresher** + +The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situatitions where you'd want to assing values to variables within an expression. + +```py +def some_func(): + # Assume some expensive computation here + # time.sleep(1000) + return 5 + +# So instead of, +if some_func(): + print(some_func()) # Which is bad practice since computation is happening twice + +# or +a = some_func() +if a: + print(a) + +# Now you can concisely write +if a := some_func(): + print(a) +``` + +**Output (> 3.8):** + +```py +5 +5 +5 +``` + +This helped save one line of code, and implicitly prevented invoking `some_func` twice. + +- Unparenthesized "assignment expression" (use of walrus operator), is restricted at top level, hence the `SyntaxError` in the `a := "wtf_walrus"` statement of first snippet. Parenthesizing it worked as expected and assigned `a`. + +- As usual, parenthesizing of expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. + +- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, + + - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6') + + ```py + >>> (a := 6, 9) == ((a := 6), 9) + True + >>> x = (a := 696, 9) + >>> x + (696, 9) + >>> x[0] is a # Both reference same memory location + True + ``` + + - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. + +--- + ### ▶ Strings can be tricky sometimes + 1\. + ```py >>> a = "some_string" >>> id(a) @@ -3066,7 +3178,7 @@ nan # Contributing -All patches are welcome! Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for further details. For discussions, you can either create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) or ping on the Gitter [channel](https://gitter.im/wtfpython/Lobby). +All patches are welcome! Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for further details. For discussions, you can either create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) or ping on the Gitter [channel](https://gitter.im/wtfpython/Lobby) # Acknowledgements @@ -3092,7 +3204,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' ## Surprise your friends too? -If you liked the project, you can use these quick links to recommend wtfpython to your friends, +If you liked wtfpython, you can use these quick links to share it with your friends, [Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) From 133baac11c7c1f4edf591c22966219897de9308f Mon Sep 17 00:00:00 2001 From: Satwik Date: Tue, 29 Oct 2019 21:45:41 +0530 Subject: [PATCH 084/221] Add minor snippet related to output buffer flushing Closes https://github.com/satwikkansal/wtfpython/issues/140 --- README.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 58bbdb70..1c927bf2 100644 --- a/README.md +++ b/README.md @@ -3120,7 +3120,7 @@ nan + `++a` parses as `+(+a)` which translates to `a`. Similarly, the output of the statement `--a` can be justified. + This StackOverflow [thread](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) discusses the rationale behind the absence of increment and decrement operators in Python. -* Have you ever heard about _the space-invader operator_ in Python? +* You must be aware of the Walrus operator in Python. But have you ever heard about _the space-invader operator_? ```py >>> a = 42 >>> a -=- 1 @@ -3151,6 +3151,18 @@ nan * Multiple Python threads won't run your *Python code* concurrently (yes you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module. +* Sometimes the `print` method might not print values immediately. For example, + + ```py + # File some_file.py + import time + + print("wtfpython", end="_") + time.sleep(3) + ``` + + This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument. + * List slicing with out of the bounds indices throws no errors ```py >>> some_list = [1, 2, 3, 4, 5] From b10b3ad346548bbe18b95fe5e4f33442c0329231 Mon Sep 17 00:00:00 2001 From: Satwik Date: Tue, 29 Oct 2019 22:31:37 +0530 Subject: [PATCH 085/221] Add another needle-like example Closes https://github.com/satwikkansal/wtfpython/issues/137 --- README.md | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 1c927bf2..7d9b2772 100644 --- a/README.md +++ b/README.md @@ -2469,6 +2469,33 @@ None None ``` +6\. + +```py +def some_recursive_func(a): + if a[0] == 0: + return + a[0] -= 1 + some_func(a) + return a + +def similar_recursive_func(a): + if a == 0: + return a + a -= 1 + another_func() + return a +``` + +**Output:** + +```py +>>> some_recursive_func([5, 0]) +[0, 0] +>>> similar_recursive_func(5) +4 +``` + #### 💡 Explanation: @@ -2505,7 +2532,9 @@ None AssertionError: Values aren not equal ``` -* As for the last snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). +* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). + +* Last one should be fairly obvious, passing mutable object (like `list` ) results in call by reference, whereas an immutable object (like `int`) results in call by value. * Being aware of these knitpicks can save you hours of degugging effort in long run. @@ -2898,7 +2927,7 @@ AttributeError: 'Yo' object has no attribute '_Yo__honey__' Why did `Yo()._Yo__honey` work? -2\. +3\. ```py _A__variable = "Some value" @@ -2918,12 +2947,6 @@ AttributeError: 'A' object has no attribute '__variable' 'Some value' ``` -3\. - -```py - -``` - #### 💡 Explanation: From 4af4f9debf9d95fdcb992e027c4ba2e964dd5869 Mon Sep 17 00:00:00 2001 From: Satwik Date: Tue, 29 Oct 2019 23:53:42 +0530 Subject: [PATCH 086/221] Add more examples --- README.md | 103 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7d9b2772..d4075de9 100644 --- a/README.md +++ b/README.md @@ -2598,6 +2598,92 @@ NameError: name 'some_weird_name_func_' is not defined --- +## Section: Read the docs + +### ▶ All sorted? + + + +```py +>>> x = 7, 8, 9 +>>> sorted(x) == x +False +>>> sorted(x) == sorted(x) +True + +>>> y = reversed(x) +>>> sorted(y) == sorted(y) +False +``` + +#### 💡 Explanation: + +- The `sorted` method always returns a list, and comparing list and tuples always returns `False` in Python. + +- ```py + >>> [] == tuple() + False + >>> x = 7, 8, 9 + >>> type(x), type(sorted(x)) + (tuple, list) + ``` + +- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use extra container (a list), whereas reversing can simple work by iterating from the last index to the first. + +- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list. + + ```py + >>> x = 7, 8, 9 + >>> y = reversed(x) + >>> sorted(y), sorted(y) + ([7, 8, 9], []) + ``` + + + +--- + +### ▶ All-true-ation + + + +```py +>>> all([True, True, True]) +True +>>> all([True, True, False]) +False + +>>> all([]) +True +>>> all([[]]) +False +>>> all([[[]]]) +True +``` + +Why's this True-False alteration? + +#### 💡 Explanation: + +- The implementation of `all` function is equivalent to + +- ```py + def all(iterable): + for element in iterable: + if not element: + return False + return True + ``` + +- `all([])` returns `True` since the iterable is empty. +- `all([[]])` returns `False` because `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty. +- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`. + +--- + +--- + + ## Section: The Hidden treasures! @@ -3195,6 +3281,21 @@ nan * `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python. +* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. + + ```py + >>> False ** False == True + True + >>> False ** True == False + True + >>> True ** False == True + True + >>> True ** True == True + True + ``` + + If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator)). + * `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear ```py def count(s, sub): @@ -3208,7 +3309,6 @@ nan ---

~~~ That's all folks! ~~~

- --- # Contributing @@ -3226,6 +3326,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' * https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines * https://stackoverflow.com/questions/1011431/common-pitfalls-in-python * https://www.python.org/doc/humor/ +* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator * https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 # 🎓 License From 312c5d542c875056de6ad595eca0ee47765a27fa Mon Sep 17 00:00:00 2001 From: Satwik Date: Wed, 30 Oct 2019 01:03:07 +0530 Subject: [PATCH 087/221] Add non reflexive class method and the matmul operator examples --- README.md | 110 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 80 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index d4075de9..3bc4b24e 100644 --- a/README.md +++ b/README.md @@ -1321,6 +1321,48 @@ True --- +### ▶ Non-reflexive class methods + + + +```py +class SomeClass: + def instance_method(self): + pass + + @classmethod + def class_method(cls): + pass +``` + +**Output:** + +```py +>>> SomeClass.instance_method is SomeClass.instance_method +True +>>> SomeClass.class_method is SomeClass.class_method +False +>>> id(SomeClass.class_method) == id(SomeClass.class_method) +True +``` + +#### 💡 Explanation: + +- The reason `SomeClass.class_method is SomeClass.class_method` is `False` is due to the `@classmethod` decorator. + + ```py + >>> SomeClass.instance_method + + >>> SomeClass.class_method + + ``` + + A new bound method everytime `SomeClass.class_method` is accessed. + +- `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). + +--- + ### ▶ yielding None ```py @@ -2843,7 +2885,7 @@ True #### 💡 Explanation: * `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)). -* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, the code for the Zen violates itself (and that's probably the only place where this happens). +* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens). * Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators). --- @@ -2888,7 +2930,7 @@ Try block executed successfully... ``` #### 💡 Explanation: -- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. +- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a "nobreak" clause. - `else` clause after try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. --- @@ -3041,11 +3083,10 @@ AttributeError: 'A' object has no attribute '__variable' * So, to access `__honey` attribute in first snippet, we had to append `_Yo` to the front which would prevent conflicts with the same name attribute defined in any other class. * But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores. * The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable` which also happens to be the name of the variable we declared in outer scope. +* Also, if the mangled name is longer than 255 characters truncation will happen. --- - - --- ## Section: Miscellaneous @@ -3205,9 +3246,8 @@ nan * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) - **💡 Explanation:** - If `join()` is a method on a string then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API. - + **💡 Explanation:** If `join()` is a method on a string then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API. + * Few weird looking but semantically correct statements: + `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`) + `'a'[0][0][0][0][0]` is also a semantically correct statement as strings are [sequences](https://docs.python.org/3/glossary.html#term-sequence)(iterables supporting element access using integer indices) in Python. @@ -3242,22 +3282,47 @@ nan >>> a >>> 44 ``` - **💡 Explanation:** - This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case. + **💡 Explanation:** This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case. + +* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. + + ```py + >>> False ** False == True + True + >>> False ** True == False + True +>>> True ** False == True + True +>>> True ** True == True + True + ``` + + **💡 Explanation:** If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator)) + +* Since we are talking operators, there's also `@` operator for matrix multiplication (don't worry, this time it's for real). + + ```py + >>> import numpy as np + >>> np.array([2, 2, 2]) @ np.array([7, 8, 8]) + 46 + ``` + + **💡 Explanation:** The `@` operator was added in Python 3.5 keeping scientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator. * Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!): + ```py import dis exec(""" def f(): """ + """ - """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) - - f() - + """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) + +f() + print(dis.dis(f)) - ``` - +``` + * Multiple Python threads won't run your *Python code* concurrently (yes you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module. * Sometimes the `print` method might not print values immediately. For example, @@ -3281,21 +3346,6 @@ nan * `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python. -* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. - - ```py - >>> False ** False == True - True - >>> False ** True == False - True - >>> True ** False == True - True - >>> True ** True == True - True - ``` - - If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator)). - * `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear ```py def count(s, sub): From 5bf46f66af9f308eda3a9fbc37c07172eaa41f68 Mon Sep 17 00:00:00 2001 From: Satwik Date: Wed, 30 Oct 2019 23:04:50 +0530 Subject: [PATCH 088/221] Bring compiler optimisation stuff back, and add minor updates. --- README.md | 81 ++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 56 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 3bc4b24e..992810f2 100644 --- a/README.md +++ b/README.md @@ -297,6 +297,10 @@ True >>> b = "wtf!" >>> a is b False + +>>> a, b = "wtf!", "wtf!" +>>> a is b +True ``` 3\. @@ -320,6 +324,7 @@ Makes sense, right? * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) ++ When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). + The abrupt change in output of the third snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. + Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). @@ -771,7 +776,8 @@ True ``` 3\. -**Output (< Python 3.7)** +**Output** + ``` >>> a, b = 257, 257 True @@ -781,7 +787,8 @@ True True ``` -**Output (Python 3.7)** +**Output (Python 3.7.x specifically)** + ``` >>> a, b = 257, 257 False @@ -836,7 +843,8 @@ Similar optimization applies to other **immutable** objects like empty tuples as **Both `a` and `b` refer to the same object when initialized with same value in the same line.** -**Output (< Python 3.7)** +**Output** + ```py >>> a, b = 257, 257 >>> id(a) @@ -852,7 +860,17 @@ Similar optimization applies to other **immutable** objects like empty tuples as ``` * 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. -* 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. + +* 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 and floats as well. + + ```py + >>> a, b = 257.0, 257.0 + >>> a is b + True + ``` + + + * 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://github.com/satwikkansal/wtfpython/issues/100) for updates. --- @@ -1189,6 +1207,7 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t ### ▶ What's wrong with booleans? 1\. + ```py # A simple example to count the number of booleans and # integers in an iterable of mixed data types. @@ -1222,15 +1241,33 @@ for item in mixed_list: '' ``` +3\. + +```py +True = False +if True == False: + print("I've lost faith in truth!") +``` + +**Output (< 3.x):** + +``` +I've lost faith in truth! +``` + + + #### 💡 Explanation: * `bool` is a subclass of `int` in Python + ```py >>> issubclass(bool, int) True >>> issubclass(int, bool) False ``` + * And thus, `True` and `False` are instances of `int` ```py >>> isinstance(True, int) @@ -1249,6 +1286,10 @@ for item in mixed_list: * See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for the rationale behind it. +* 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 + +* Python 3 was backward-incompatible, the issue was finally fixed, and thus the last snippet won't work with Python 3.x! + --- ### ▶ Class attributes and instance attributes @@ -1510,27 +1551,6 @@ NameError: name 'e' is not defined --- -### ▶ When True is actually False - -```py -True = False -if True == False: - print("I've lost faith in truth!") -``` - -**Output (< 3.x):** - -``` -I've lost faith in truth! -``` - -#### 💡 Explanation: - -- Initially, Python used to have no `bool` type (people used 0 for false and non-zero value like 1 for true). Then they added `True`, `False`, and a `bool` type, but, for backward compatibility, they couldn't make `True` and `False` constants- they just were built-in variables. -- Python 3 was backward-incompatible, so it was now finally possible to fix that, and so this example won't work with Python 3.x! - ---- - ### ▶ Yielding from... return! 1\. @@ -3346,6 +3366,17 @@ f() * `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python. +* You can seperate numeric literals with underscores (for better readablity) from Python 3 onwards. + + ```py + >>> six_million = 6_000_000 + >>> six_million + 6000000 + >>> hex_address = 0xF00D_CAFE + >>> hex_address + 4027435774 + ``` + * `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear ```py def count(s, sub): From af6d1799d9800d7acd0c628ffe46685027737775 Mon Sep 17 00:00:00 2001 From: Satwik Date: Wed, 30 Oct 2019 23:24:07 +0530 Subject: [PATCH 089/221] Add more details to compile time optimisation snippets. --- README.md | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 992810f2..bfbd48d8 100644 --- a/README.md +++ b/README.md @@ -298,12 +298,30 @@ True >>> a is b False +``` + +3\. + +```py >>> a, b = "wtf!", "wtf!" ->>> a is b +>>> a is b # All versions except 3.7.x True + +>>> a = "wtf!"; b = "wtf!" +>>> a is b +False ``` -3\. +```py +# This time in file some_file.py +a = "wtf!" +b = "wtf!" +print(a is b) + +# prints True when the module is invoked! +``` + +4\. **Output (< Python3.7 )** @@ -324,8 +342,9 @@ Makes sense, right? * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) -+ When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). -+ The abrupt change in output of the third snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. ++ When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's an compile time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). ++ The compile unit in interactive environment consists of single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are 2 statements in single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` ++ The abrupt change in output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. + Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). --- @@ -861,7 +880,7 @@ Similar optimization applies to other **immutable** objects like empty tuples as * 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. -* 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 and floats as well. +* 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, ```py >>> a, b = 257.0, 257.0 @@ -869,8 +888,6 @@ Similar optimization applies to other **immutable** objects like empty tuples as True ``` - - * 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://github.com/satwikkansal/wtfpython/issues/100) for updates. --- From 7df49cd8184956023ca18db6d840f721bc1371d6 Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 31 Oct 2019 00:51:48 +0530 Subject: [PATCH 090/221] Change section name to Slippery Slopes and modify nan-reflexivity example --- README.md | 116 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 76 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index bfbd48d8..c80f3ffe 100644 --- a/README.md +++ b/README.md @@ -1452,7 +1452,82 @@ def some_func(val): --- +### ▶ Nan-reflexivity + + + +1\. + +```py +a = float('inf') +b = float('nan') +c = float('-iNf') # These strings are case-insensitive +d = float('nan') +``` + +**Output:** + +```py +>>> a +inf +>>> b +nan +>>> c +-inf +>>> float('some_other_string') +ValueError: could not convert string to float: some_other_string +>>> a == -c # inf==inf +True +>>> None == None # None == None +True +>>> b == d # but nan!=nan +False +>>> 50 / a +0.0 +>>> a / a +nan +>>> 23 + b +nan +``` + +2\. + +```py +>>> x = float('nan') +>>> y = x / x +>>> y is y # identity holds +True +>>> y == y # equality fails of y +False +>>> [y] == [y] # but the equality succeeds for the list containing y +True +``` + + + +#### 💡 Explanation: + +- `'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. + +- Since according to standards ` NaN != NaN`, implementing this breaks the reflexivity assumption of a collection element in Python i.e if `x` is a part of 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) whlie comparing two elements, and the values are compared only when the identities mismatch. Following snippet will make things clearer + + ```py + >>> x = float('nan') + >>> x == x, [x] == [x] + (False, True) + >>> y = float('nan') + >>> y == y, [y] == [y] + (False, True) + >>> x == y, [x] == [y] + (False, False) + ``` + + Since the identities of `x` and `y` are different, the values are considered, which are also different, hence the comparison returns `False` this time. + +--- + ### ▶ Mutating the immutable! + This might seem trivial if you know how references works in Python. @@ -1934,7 +2009,7 @@ Shouldn't that be 100? --- -## Section: Watch out for the landmines! +## Section: Slippery Slopes ### ▶ Modifying a dictionary while iterating over it @@ -2575,8 +2650,6 @@ def similar_recursive_func(a): 4 ``` - - #### 💡 Explanation: * For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. @@ -3238,44 +3311,7 @@ Let's increase the number of iterations by a factor of 10. > There should be one-- and preferably only one --obvious way to do it. ---- - -### ▶ Explicit typecast of strings - -```py -a = float('inf') -b = float('nan') -c = float('-iNf') #These strings are case-insensitive -d = float('nan') -``` - -**Output:** -```py ->>> a -inf ->>> b -nan ->>> c --inf ->>> float('some_other_string') -ValueError: could not convert string to float: some_other_string ->>> a == -c #inf==inf -True ->>> None == None # None==None -True ->>> b == d #but nan!=nan -False ->>> 50/a -0.0 ->>> a/a -nan ->>> 23 + b -nan -``` - -#### 💡 Explanation: -`'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. --- From a5593c42e0b6d37caed49667197c0060cd9169c2 Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 31 Oct 2019 00:59:57 +0530 Subject: [PATCH 091/221] Update comments --- irrelevant/json_generator.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py index cfebf4f5..11eab866 100644 --- a/irrelevant/json_generator.py +++ b/irrelevant/json_generator.py @@ -2,12 +2,19 @@ An inefficient monolithic piece of code that'll generate jupyter notebook from the projects main README. -TODO +PS: If you are a recruiter, please don't judge me by this piece of code. I wrote it +in hurry. I know this is messy and can be simplified, but I don't want to change it +much because it just works. -- CLI arguments for running this thing. +Simplifictions and improvements through patches are more than welcome however :) + + +#TODOs + +- CLI arguments for running this thing - Add it to prepush hook +- Add support for skip comments, to skip examples that are not meant for notebook environment. - Use templates? - """ import json From 0160d5019b6c724af81ebd94a4a05fd67c94308e Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 31 Oct 2019 01:01:45 +0530 Subject: [PATCH 092/221] Remove un-necessary file --- irrelevant/generated.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 irrelevant/generated.md diff --git a/irrelevant/generated.md b/irrelevant/generated.md deleted file mode 100644 index e69de29b..00000000 From 1d467287ef3e9d379a80c28f6f91cc8da1f26737 Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 31 Oct 2019 01:05:23 +0530 Subject: [PATCH 093/221] Move stuff to obsolete package. Not deleting it for quick future reference for contributors and myself. --- irrelevant/{ => obsolete}/add_categories | 0 irrelevant/{ => obsolete}/generate_contributions.py | 0 irrelevant/{ => obsolete}/initial.md | 0 irrelevant/{ => obsolete}/parse_readme.py | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename irrelevant/{ => obsolete}/add_categories (100%) rename irrelevant/{ => obsolete}/generate_contributions.py (100%) rename irrelevant/{ => obsolete}/initial.md (100%) rename irrelevant/{ => obsolete}/parse_readme.py (100%) diff --git a/irrelevant/add_categories b/irrelevant/obsolete/add_categories similarity index 100% rename from irrelevant/add_categories rename to irrelevant/obsolete/add_categories diff --git a/irrelevant/generate_contributions.py b/irrelevant/obsolete/generate_contributions.py similarity index 100% rename from irrelevant/generate_contributions.py rename to irrelevant/obsolete/generate_contributions.py diff --git a/irrelevant/initial.md b/irrelevant/obsolete/initial.md similarity index 100% rename from irrelevant/initial.md rename to irrelevant/obsolete/initial.md diff --git a/irrelevant/parse_readme.py b/irrelevant/obsolete/parse_readme.py similarity index 100% rename from irrelevant/parse_readme.py rename to irrelevant/obsolete/parse_readme.py From d4021862f060c231847db801da219e5137cfb477 Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 31 Oct 2019 01:07:04 +0530 Subject: [PATCH 094/221] Add no longer working note. --- irrelevant/obsolete/generate_contributions.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/irrelevant/obsolete/generate_contributions.py b/irrelevant/obsolete/generate_contributions.py index f396f32b..1394e0ec 100644 --- a/irrelevant/obsolete/generate_contributions.py +++ b/irrelevant/obsolete/generate_contributions.py @@ -1,6 +1,8 @@ """ -Parses the README.md and generated the table +This script parses the README.md and generates the table `CONTRIBUTORS.md`. + +No longer works since we've moved on contributors to CONTRIBUTORS.md entirely. """ import pprint From a553ea00706f2988723c3a92b2b0319a5c4bf0cb Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 31 Oct 2019 23:50:23 +0530 Subject: [PATCH 095/221] Some meta tags and corrections after running on Python 3.8 --- README.md | 74 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 45 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index c80f3ffe..e2111cc4 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Python, being a beautifully designed high-level and interpreter-based programmin 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. -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! +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 beliereve that you'll find it interesting too! If you're an experienced Python programmer, you can take it as a challenge to get most of them right in 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: @@ -175,7 +175,7 @@ For some reasons, "Walrus" operator (`:=`) has become a very popular feature in >>> a 'wtf_walrus' >>> a := "wtf_walrus" -File "", line 1 +File "", line 1 a := "wtf_walrus" ^ SyntaxError: invalid syntax @@ -200,7 +200,7 @@ SyntaxError: invalid syntax >>> a, b (6, 9) >>> (a, b = 16, 19) # Oops - File "", line 1 + File "", line 1 (a, b = 6, 9) ^ SyntaxError: invalid syntax @@ -210,6 +210,8 @@ SyntaxError: invalid syntax >>> a # a is still unchanged? 6 + +>>> b 16 ``` @@ -308,7 +310,7 @@ False True >>> a = "wtf!"; b = "wtf!" ->>> a is b +>>> a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script) False ``` @@ -343,7 +345,7 @@ Makes sense, right? * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) + When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's an compile time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). -+ The compile unit in interactive environment consists of single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are 2 statements in single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` ++ The compile unit in interactive environment like ipython consists of single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are 2 statements in single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` + The abrupt change in output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. + Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). @@ -401,7 +403,7 @@ some_dict[5] = "Python" ```py >>> some_dict[5.5] -"Ruby" +"JavaScript" >>> some_dict[5.0] # "Python" destroyed the existence of "Ruby"? "Python" >>> some_dict[5] @@ -726,10 +728,10 @@ array_2[:] = [1,2,3,4,5] **Output:** ```py >>> print(list(gen_1)) -[1,2,3,4] +[1, 2, 3, 4] >>> print(list(gen_2)) -[1,2,3,4,5] +[1, 2, 3, 4, 5] ``` 3\. @@ -797,24 +799,18 @@ True 3\. **Output** -``` +```py >>> a, b = 257, 257 -True - ->>> a = 257; b = 257 >>> a is b True ``` **Output (Python 3.7.x specifically)** -``` +```py >>> a, b = 257, 257 +>> a is b False - ->>> a = 257; b = 257 ->>> a is b -True ``` #### 💡 Explanation: @@ -1176,6 +1172,10 @@ wtfpython >>> # The following statements raise `SyntaxError` >>> # print('''wtfpython') >>> # print("""wtfpython") + File "", line 3 + print("""wtfpython") + ^ +SyntaxError: EOF while scanning triple-quoted string literal ``` #### 💡 Explanation: @@ -1261,15 +1261,17 @@ for item in mixed_list: 3\. ```py -True = False -if True == False: - print("I've lost faith in truth!") +def tell_truth(): + True = False + if True == False: + print("I have lost faith in truth!") ``` **Output (< 3.x):** -``` -I've lost faith in truth! +```py +>>> tell_truth() +I have lost faith in truth! ``` @@ -1331,7 +1333,7 @@ class C(A): >>> A.x, B.x, C.x (1, 2, 1) >>> A.x = 3 ->>> A.x, B.x, C.x +>>> A.x, B.x, C.x # C.x changed, but B.x didn't (3, 2, 3) >>> a = A() >>> a.x, A.x @@ -1379,7 +1381,7 @@ True --- -### ▶ Non-reflexive class methods +### ▶ Non-reflexive class method @@ -1430,7 +1432,7 @@ def some_func(val): return "something" ``` -**Output:** +**Output (<= 3.7.x):** ```py >>> [x for x in some_iterable] @@ -1449,6 +1451,7 @@ def some_func(val): - This is bug in CPython's handling of `yield` in generators and comprehensions. - Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions - Related bug report: http://bugs.python.org/issue10544 +- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`. --- @@ -1509,7 +1512,7 @@ True - `'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. -- Since according to standards ` NaN != NaN`, implementing this breaks the reflexivity assumption of a collection element in Python i.e if `x` is a part of 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) whlie comparing two elements, and the values are compared only when the identities mismatch. Following snippet will make things clearer +- 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 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) whlie comparing two elements, and the values are compared only when the identities mismatch. Following snippet will make things clearer ```py >>> x = float('nan') @@ -1524,6 +1527,8 @@ True Since the identities of `x` and `y` are different, the values are considered, which are also different, hence the comparison returns `False` this time. +- Interesting read: [Reflexivity, and other pilliars of civilization](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) + --- ### ▶ Mutating the immutable! @@ -1565,6 +1570,8 @@ But I thought tuples were immutable... ### ▶ The disappearing variable from outer scope + + ```py e = 7 try: @@ -1788,7 +1795,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` class SomeClass(str): pass -some_dict = {'s':42} +some_dict = {'s': 42} ``` **Output:** @@ -2014,6 +2021,7 @@ Shouldn't that be 100? ### ▶ Modifying a dictionary while iterating over it + ```py x = {0: None} @@ -2044,11 +2052,14 @@ Yes, it runs for exactly **eight** times and stops. * It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. * How deleted keys are handled and when the resize occurs might be different for different Python implementations. * So for Python versions other than Python 2.7 - Python 3.5 the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. +* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. --- ### ▶ Stubborn `del` operation + + ```py class SomeClass: def __del__(self): @@ -2152,6 +2163,7 @@ Can you guess why the output is `[2, 4]`? ### ▶ Loop variables leaking out! + 1\. ```py for x in range(7): @@ -2630,14 +2642,14 @@ def some_recursive_func(a): if a[0] == 0: return a[0] -= 1 - some_func(a) + some_recursive_func(a) return a def similar_recursive_func(a): if a == 0: return a a -= 1 - another_func() + similar_recursive_func(a) return a ``` @@ -2694,6 +2706,8 @@ def similar_recursive_func(a): ### ▶ Wild imports + + ```py # File: module.py @@ -2861,6 +2875,8 @@ Sshh.. It's a super secret. ### ▶ `goto`, but why? + + ```py from goto import goto, label for i in range(9): From 2160dad717fcd56cb159af795e28f04f03167a28 Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 31 Oct 2019 23:50:50 +0530 Subject: [PATCH 096/221] Use dynamic path instead of fixed one --- irrelevant/json_generator.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py index 11eab866..c62499a4 100644 --- a/irrelevant/json_generator.py +++ b/irrelevant/json_generator.py @@ -18,8 +18,10 @@ """ import json +import os import pprint -fname = "/Users/300041709/code/self/wtfpython/README.md" + +fpath = os.path.join(os.path.dirname( __file__ ), '..', 'README.md') examples = [] # The globals @@ -250,7 +252,7 @@ def convert_to_notebook(parsed_json): -with open(fname, 'r+', encoding="utf-8") as f: +with open(fpath, 'r+', encoding="utf-8") as f: lines = iter(f.readlines()) line = next(lines) result = [] From 08302ba0c89ffab3dcb1cb5890049bead3fceb9f Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 31 Oct 2019 23:51:47 +0530 Subject: [PATCH 097/221] Ignore environment and checkpoint files --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index a252b5a5..36f9a1fd 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,7 @@ wtfpython-pypi/wtfpython.egg-info __pycache__/ *.py[cod] *$py.class + +irrelevant/.ipynb_checkpoints/ + +irrelevant/.python-version From 321e7196d06e7df601ca7eab334a12d6dc5668d9 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 2 Nov 2019 23:02:47 +0530 Subject: [PATCH 098/221] Some change of example orders --- README.md | 1112 ++++++++++++++++++++++++++--------------------------- 1 file changed, 555 insertions(+), 557 deletions(-) diff --git a/README.md b/README.md index e2111cc4..04a0d1b3 100644 --- a/README.md +++ b/README.md @@ -19,74 +19,79 @@ So, here we go... # Table of Contents - + + - [Structure of the Examples](#structure-of-the-examples) - + [▶ Some fancy Title](#-some-fancy-title) + + [▶ Some fancy Title](#%E2%96%B6-some-fancy-title) - [Usage](#usage) - [👀 Examples](#%F0%9F%91%80-examples) * [Section: Strain your brain!](#section-strain-your-brain) - + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) - + [▶ Splitsies](#-splitsies) - + [▶ Hash brownies](#-hash-brownies) - + [▶ Disorder within order](#-disorder-within-order) - + [▶ Keep trying...](#-keep-trying) - + [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) - + [▶ For what?](#-for-what) - + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - + [▶ How not to use `is` operator](#-how-not-to-use-is-operator) - + [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - + [▶ The sticky output function](#-the-sticky-output-function) - + [▶ The chicken-egg problem](#-the-chicken-egg-problem) - + [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) - + [▶ The surprising comma](#-the-surprising-comma) - + [▶ Strings and the backslashes](#-strings-and-the-backslashes) - + [▶ not knot!](#-not-knot) - + [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - + [▶ yielding None](#-yielding-none) - + [▶ Mutating the immutable!](#-mutating-the-immutable) - + [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) - + [▶ When True is actually False](#-when-true-is-actually-false) - + [▶ Yielding from... return!](#-yielding-from-return) - + [▶ Lossy zip of iterators](#-lossy-zip-of-iterators) - + [▶ Subclass relationships](#-subclass-relationships) - + [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) - + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + + [▶ First things first!](#%E2%96%B6-first-things-first) + + [▶ Strings can be tricky sometimes](#%E2%96%B6-strings-can-be-tricky-sometimes) + + [▶ Splitsies](#%E2%96%B6-splitsies) + + [▶ Hash brownies](#%E2%96%B6-hash-brownies) + + [▶ Disorder within order](#%E2%96%B6-disorder-within-order) + + [▶ Keep trying...](#%E2%96%B6-keep-trying) + + [▶ Deep down, we're all the same.](#%E2%96%B6-deep-down-were-all-the-same) + + [▶ For what?](#%E2%96%B6-for-what) + + [▶ Evaluation time discrepancy](#%E2%96%B6-evaluation-time-discrepancy) + + [▶ How not to use `is` operator](#%E2%96%B6-how-not-to-use-is-operator) + + [▶ A tic-tac-toe where X wins in the first attempt!](#%E2%96%B6-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + + [▶ The sticky output function](#%E2%96%B6-the-sticky-output-function) + + [▶ The chicken-egg problem](#%E2%96%B6-the-chicken-egg-problem) + + [▶ `is not ...` is not `is (not ...)`](#%E2%96%B6-is-not--is-not-is-not-) + + [▶ The surprising comma](#%E2%96%B6-the-surprising-comma) + + [▶ Strings and the backslashes](#%E2%96%B6-strings-and-the-backslashes) + + [▶ not knot!](#%E2%96%B6-not-knot) + + [▶ Half triple-quoted strings](#%E2%96%B6-half-triple-quoted-strings) + + [▶ Midnight time doesn't exist?](#%E2%96%B6-midnight-time-doesnt-exist) + + [▶ What's wrong with booleans?](#%E2%96%B6-whats-wrong-with-booleans) + + [▶ Class attributes and instance attributes](#%E2%96%B6-class-attributes-and-instance-attributes) + + [▶ Non-reflexive class method](#%E2%96%B6-non-reflexive-class-method) + + [▶ yielding None](#%E2%96%B6-yielding-none) + + [▶ Nan-reflexivity](#%E2%96%B6-nan-reflexivity) + + [▶ Mutating the immutable!](#%E2%96%B6-mutating-the-immutable) + + [▶ The disappearing variable from outer scope](#%E2%96%B6-the-disappearing-variable-from-outer-scope) + + [▶ Yielding from... return!](#%E2%96%B6-yielding-from-return) + + [▶ Lossy zip of iterators](#%E2%96%B6-lossy-zip-of-iterators) + + [▶ Subclass relationships](#%E2%96%B6-subclass-relationships) + + [▶ The mysterious key type conversion](#%E2%96%B6-the-mysterious-key-type-conversion) + + [▶ Let's see if you can guess this?](#%E2%96%B6-lets-see-if-you-can-guess-this) * [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - + [▶ Skipping lines?](#-skipping-lines) - + [▶ Teleportation](#-teleportation) - + [▶ Well, something is fishy...](#-well-something-is-fishy) - * [Section: Watch out for the landmines!](#section-watch-out-for-the-landmines) - + [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) - + [▶ Stubborn `del` operation](#-stubborn-del-operation) - + [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - + [▶ Loop variables leaking out!](#-loop-variables-leaking-out) - + [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - + [▶ Catching the Exceptions](#-catching-the-exceptions) - + [▶ Same operands, different story!](#-same-operands-different-story) - + [▶ The out of scope variable](#-the-out-of-scope-variable) - + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - + [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - + [▶ Needles in a Haystack](#-needles-in-a-haystack) - + [▶ Wild imports](#-wild-imports) + + [▶ Skipping lines?](#%E2%96%B6-skipping-lines) + + [▶ Teleportation](#%E2%96%B6-teleportation) + + [▶ Well, something is fishy...](#%E2%96%B6-well-something-is-fishy) + * [Section: Slippery Slopes](#section-slippery-slopes) + + [▶ Modifying a dictionary while iterating over it](#%E2%96%B6-modifying-a-dictionary-while-iterating-over-it) + + [▶ Stubborn `del` operation](#%E2%96%B6-stubborn-del-operation) + + [▶ Deleting a list item while iterating](#%E2%96%B6-deleting-a-list-item-while-iterating) + + [▶ Loop variables leaking out!](#%E2%96%B6-loop-variables-leaking-out) + + [▶ Beware of default mutable arguments!](#%E2%96%B6-beware-of-default-mutable-arguments) + + [▶ Catching the Exceptions](#%E2%96%B6-catching-the-exceptions) + + [▶ Same operands, different story!](#%E2%96%B6-same-operands-different-story) + + [▶ The out of scope variable](#%E2%96%B6-the-out-of-scope-variable) + + [▶ Be careful with chained operations](#%E2%96%B6-be-careful-with-chained-operations) + + [▶ Name resolution ignoring class scope](#%E2%96%B6-name-resolution-ignoring-class-scope) + + [▶ Needles in a Haystack](#%E2%96%B6-needles-in-a-haystack) + + [▶ Wild imports](#%E2%96%B6-wild-imports) + * [Section: Read the docs](#section-read-the-docs) + + [▶ All sorted?](#%E2%96%B6-all-sorted) + + [▶ All-true-ation](#%E2%96%B6-all-true-ation) * [Section: The Hidden treasures!](#section-the-hidden-treasures) - + [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) - + [▶ `goto`, but why?](#-goto-but-why) - + [▶ Brace yourself!](#-brace-yourself) - + [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) - + [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) - + [▶ Yes, it exists!](#-yes-it-exists) - + [▶ Ellipsis](#-ellipsis) - + [▶ Inpinity](#-inpinity) - + [▶ Let's mangle](#-lets-mangle) + + [▶ Okay Python, Can you make me fly?](#%E2%96%B6-okay-python-can-you-make-me-fly) + + [▶ `goto`, but why?](#%E2%96%B6-goto-but-why) + + [▶ Brace yourself!](#%E2%96%B6-brace-yourself) + + [▶ Let's meet Friendly Language Uncle For Life](#%E2%96%B6-lets-meet-friendly-language-uncle-for-life) + + [▶ Even Python understands that love is complicated](#%E2%96%B6-even-python-understands-that-love-is-complicated) + + [▶ Yes, it exists!](#%E2%96%B6-yes-it-exists) + + [▶ Ellipsis](#%E2%96%B6-ellipsis) + + [▶ Inpinity](#%E2%96%B6-inpinity) + + [▶ Let's mangle](#%E2%96%B6-lets-mangle) * [Section: Miscellaneous](#section-miscellaneous) - + [▶ `+=` is faster](#--is-faster) - + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ Explicit typecast of strings](#-explicit-typecast-of-strings) - + [▶ Minor Ones](#-minor-ones) + + [▶ `+=` is faster](#%E2%96%B6--is-faster) + + [▶ Let's make a giant string!](#%E2%96%B6-lets-make-a-giant-string) + + [▶ Minor Ones](#%E2%96%B6-minor-ones) * [~~~ That's all folks! ~~~](#-thats-all-folks-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -351,44 +356,6 @@ Makes sense, right? --- -### ▶ Splitsies - -```py ->>> 'a'.split() -['a'] - -# is same as ->>> 'a'.split(' ') -['a'] - -# but ->>> len(''.split()) -0 - -# isn't the same as ->>> len(''.split(' ')) -1 -``` - -#### 💡 Explanation: - -- It might appear at first that the default seperator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split) - > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`. - > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`. -- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear, - ```py - >>> ' a '.split(' ') - ['', 'a', ''] - >>> ' a '.split() - ['a'] - >>> ''.split(' ') - [''] - ``` - ---- - - - ### ▶ Hash brownies 1\. @@ -435,6 +402,56 @@ So, why is Python all over the place? --- +### ▶ Deep down, we're all the same. + +```py +class WTF: + pass +``` + +**Output:** +```py +>>> WTF() == WTF() # two different instances can't be equal +False +>>> WTF() is WTF() # identities are also different +False +>>> hash(WTF()) == hash(WTF()) # hashes _should_ be different as well +True +>>> id(WTF()) == id(WTF()) +True +``` + +#### 💡 Explanation: + +* 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. +* 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. +* So, 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. +* But why did the `is` operator evaluated to `False`? Let's see with this snippet. + ```py + class WTF(object): + def __init__(self): print("I") + def __del__(self): print("D") + ``` + + **Output:** + ```py + >>> WTF() is WTF() + I + I + D + D + False + >>> id(WTF()) == id(WTF()) + I + D + I + D + True + ``` + As you may observe, the order in which the objects are destroyed is what made all the difference here. + +--- + ### ▶ Disorder within order ```py @@ -500,7 +517,7 @@ What is going on here? - 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://docs.python.org/3/library/collections.html#ordereddict-objects) > 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. -- The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. +- The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. - Okay, so why did changing the order affect the lenght 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, ```py >>> some_set = set() @@ -593,55 +610,6 @@ Iteration 0 --- -### ▶ Deep down, we're all the same. - -```py -class WTF: - pass -``` - -**Output:** -```py ->>> WTF() == WTF() # two different instances can't be equal -False ->>> WTF() is WTF() # identities are also different -False ->>> hash(WTF()) == hash(WTF()) # hashes _should_ be different as well -True ->>> id(WTF()) == id(WTF()) -True -``` - -#### 💡 Explanation: - -* 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. -* 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. -* So, 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. -* But why did the `is` operator evaluated to `False`? Let's see with this snippet. - ```py - class WTF(object): - def __init__(self): print("I") - def __del__(self): print("D") - ``` - - **Output:** - ```py - >>> WTF() is WTF() - I - I - D - D - False - >>> id(WTF()) == id(WTF()) - I - D - I - D - True - ``` - As you may observe, the order in which the objects are destroyed is what made all the difference here. - ---- ### ▶ For what? @@ -888,6 +856,22 @@ Similar optimization applies to other **immutable** objects like empty tuples as --- +### ▶ `is not ...` is not `is (not ...)` + +```py +>>> 'something' is not None +True +>>> 'something' is (not None) +False +``` + +#### 💡 Explanation + +- `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. +- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. + +--- + ### ▶ A tic-tac-toe where X wins in the first attempt! @@ -1043,19 +1027,65 @@ False --- -### ▶ `is not ...` is not `is (not ...)` - +### ▶ Subclass relationships + +**Output:** ```py ->>> 'something' is not None +>>> from collections import Hashable +>>> issubclass(list, object) True ->>> 'something' is (not None) +>>> issubclass(object, Hashable) +True +>>> issubclass(list, Hashable) False ``` -#### 💡 Explanation +The 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`) -- `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. -- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. +#### 💡 Explanation: + +* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass. +* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey "`__hash__`" method in `cls` or anything it inherits from. +* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation. +* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/). + +--- + +### ▶ All-true-ation + + + +```py +>>> all([True, True, True]) +True +>>> all([True, True, False]) +False + +>>> all([]) +True +>>> all([[]]) +False +>>> all([[[]]]) +True +``` + +Why's this True-False alteration? + +#### 💡 Explanation: + +- The implementation of `all` function is equivalent to + +- ```py + def all(iterable): + for element in iterable: + if not element: + return False + return True + ``` + +- `all([])` returns `True` since the iterable is empty. +- `all([[]])` returns `False` because `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty. +- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`. --- @@ -1190,37 +1220,6 @@ SyntaxError: EOF while scanning triple-quoted string literal --- -### ▶ Midnight time doesn't exist? - -```py -from datetime import datetime - -midnight = datetime(2018, 1, 1, 0, 0) -midnight_time = midnight.time() - -noon = datetime(2018, 1, 1, 12, 0) -noon_time = noon.time() - -if midnight_time: - print("Time at midnight is", midnight_time) - -if noon_time: - print("Time at noon is", noon_time) -``` - -**Output (< 3.5):** - -```sh -('Time at noon is', datetime.time(12, 0)) -``` -The midnight time is not printed. - -#### 💡 Explanation: - -Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of "empty." - ---- - ### ▶ What's wrong with booleans? 1\. @@ -1423,6 +1422,7 @@ True --- + ### ▶ yielding None ```py @@ -1455,21 +1455,87 @@ def some_func(val): --- -### ▶ Nan-reflexivity - +### ▶ Yielding from... return! 1\. ```py -a = float('inf') -b = float('nan') -c = float('-iNf') # These strings are case-insensitive -d = float('nan') -``` - -**Output:** - +def some_func(x): + if x == 3: + return ["wtf"] + else: + yield from range(x) +``` + +**Output (> 3.3):** + +```py +>>> list(some_func(3)) +[] +``` + +Where did the `"wtf"` go? Is it due to some special effect of `yield from`? Let's validate that, + +2\. + +```py +def some_func(x): + if x == 3: + return ["wtf"] + else: + for i in range(x): + yield i +``` + +**Output:** + +```py +>>> list(some_func(3)) +[] +``` + +Same result, that didn't work either. + +#### 💡 Explanation: + ++ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that, + +> "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." + ++ In case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically catched inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. + ++ To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, + + ```py + try: + next(some_func(3)) + except StopIteration as e: + some_string = e.value + ``` + + ```py + >>> some_string + ["wtf"] + ``` + +--- + +### ▶ Nan-reflexivity + + + +1\. + +```py +a = float('inf') +b = float('nan') +c = float('-iNf') # These strings are case-insensitive +d = float('nan') +``` + +**Output:** + ```py >>> a inf @@ -1650,144 +1716,6 @@ NameError: name 'e' is not defined --- -### ▶ Yielding from... return! - -1\. - -```py -def some_func(x): - if x == 3: - return ["wtf"] - else: - yield from range(x) -``` - -**Output:** - -```py ->>> list(some_func(3)) -[] -``` - -Where did the `"wtf"` go? Is it due to some special effect of `yield from`? Let's validate that, - -2\. - -```py -def some_func(x): - if x == 3: - return ["wtf"] - else: - for i in range(x): - yield i -``` - -**Output (> 3.3):** - -```py ->>> list(some_func(3)) -[] -``` - -Same result, that didn't work either. - -#### 💡 Explanation: - -+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that, - -> "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." - -+ In case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically catched inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. - -+ To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, - - ```py - try: - next(some_func(3)) - except StopIteration as e: - some_string = e.value - ``` - - ```py - >>> some_string - ["wtf"] - ``` - ---- - -### ▶ Lossy zip of iterators - - - -```py ->>> numbers = list(range(7)) ->>> numbers -[0, 1, 2, 3, 4, 5, 6] ->>> first_three, remaining = numbers[:3], numbers[3:] ->>> first_three, remaining -([0, 1, 2], [3, 4, 5, 6]) ->>> numbers_iter = iter(numbers) ->>> list(zip(numbers_iter, first_three)) -[(0, 0), (1, 1), (2, 2)] -# so far so good, let's zip the remaining ->>> list(zip(numbers_iter, remaining)) -[(4, 3), (5, 4), (6, 5)] -``` -Where did element `3` go from the `numbers` list? - -#### 💡 Explanation: - -- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function, - ```py - def zip(*iterables): - sentinel = object() - iterators = [iter(it) for it in iterables] - while iterators: - result = [] - for it in iterators: - elem = next(it, sentinel) - if elem is sentinel: return - result.append(elem) - yield tuple(result) - ``` -- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. -- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`. -- The correct way to do the above using `zip` would be, - ```py - >>> numbers = list(range(7)) - >>> numbers_iter = iter(numbers) - >>> list(zip(first_three, numbers_iter)) - [(0, 0), (1, 1), (2, 2)] - >>> list(zip(remaining, numbers_iter)) - [(3, 3), (4, 4), (5, 5), (6, 6)] - ``` - The first argument of zip should be the one with fewest elements. - ---- - -### ▶ Subclass relationships - -**Output:** -```py ->>> from collections import Hashable ->>> issubclass(list, object) -True ->>> issubclass(object, Hashable) -True ->>> issubclass(list, Hashable) -False -``` - -The 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`) - -#### 💡 Explanation: - -* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass. -* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey "`__hash__`" method in `cls` or anything it inherits from. -* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation. -* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/). - ---- ### ▶ The mysterious key type conversion @@ -1901,124 +1829,10 @@ a, b = a[b] = {}, 5 ``` --- - ---- - -## Section: Appearances are deceptive! - -### ▶ Skipping lines? - -**Output:** -```py ->>> value = 11 ->>> valuе = 32 ->>> value -11 -``` - -Wut? - -**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell. - -#### 💡 Explanation - -Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter. - -```py ->>> ord('е') # cyrillic 'e' (Ye) -1077 ->>> ord('e') # latin 'e', as used in English and typed using standard keyboard -101 ->>> 'е' == 'e' -False - ->>> value = 42 # latin e ->>> valuе = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here ->>> value -42 -``` - -The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example. - ---- - -### ▶ Teleportation - - - -```py -import numpy as np - -def energy_send(x): - # Initializing a numpy array - np.array([float(x)]) - -def energy_receive(): - # Return an empty numpy array - return np.empty((), dtype=np.float).tolist() -``` - -**Output:** -```py ->>> energy_send(123.456) ->>> energy_receive() -123.456 -``` - -Where's the Nobel Prize? - -#### 💡 Explanation: - -* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate. -* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always). - ---- - -### ▶ Well, something is fishy... - -```py -def square(x): - """ - A simple function to calculate the square of a number by addition. - """ - sum_so_far = 0 - for counter in range(x): - sum_so_far = sum_so_far + x - return sum_so_far -``` - -**Output (Python 2.x):** - -```py ->>> square(10) -10 -``` - -Shouldn't that be 100? - -**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell. - -#### 💡 Explanation - -* **Don't mix tabs and spaces!** The character just preceding return is a "tab", and the code is indented by multiple of "4 spaces" elsewhere in the example. -* This is how Python handles tabs: - - > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...> -* So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. -* Python 3 is kind enough to throw an error for such cases automatically. - - **Output (Python 3.x):** - ```py - TabError: inconsistent use of tabs and spaces in indentation - ``` - ---- - --- ## Section: Slippery Slopes - ### ▶ Modifying a dictionary while iterating over it @@ -2101,6 +1915,45 @@ Okay, now it's deleted :confused: --- +### ▶ The out of scope variable + +```py +a = 1 +def some_func(): + return a + +def another_func(): + a += 1 + return a +``` + +**Output:** +```py +>>> some_func() +1 +>>> another_func() +UnboundLocalError: local variable 'a' referenced before assignment +``` + +#### 💡 Explanation: +* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope which throws an error. +* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. +* To modify the outer scope variable `a` in `another_func`, use `global` keyword. + ```py + def another_func() + global a + a += 1 + return a + ``` + + **Output:** + ```py + >>> another_func() + 2 + ``` + +--- + ### ▶ Deleting a list item while iterating ```py @@ -2161,6 +2014,57 @@ Can you guess why the output is `[2, 4]`? --- + +### ▶ Lossy zip of iterators + + + +```py +>>> numbers = list(range(7)) +>>> numbers +[0, 1, 2, 3, 4, 5, 6] +>>> first_three, remaining = numbers[:3], numbers[3:] +>>> first_three, remaining +([0, 1, 2], [3, 4, 5, 6]) +>>> numbers_iter = iter(numbers) +>>> list(zip(numbers_iter, first_three)) +[(0, 0), (1, 1), (2, 2)] +# so far so good, let's zip the remaining +>>> list(zip(numbers_iter, remaining)) +[(4, 3), (5, 4), (6, 5)] +``` +Where did element `3` go from the `numbers` list? + +#### 💡 Explanation: + +- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function, + ```py + def zip(*iterables): + sentinel = object() + iterators = [iter(it) for it in iterables] + while iterators: + result = [] + for it in iterators: + elem = next(it, sentinel) + if elem is sentinel: return + result.append(elem) + yield tuple(result) + ``` +- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. +- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`. +- The correct way to do the above using `zip` would be, + ```py + >>> numbers = list(range(7)) + >>> numbers_iter = iter(numbers) + >>> list(zip(first_three, numbers_iter)) + [(0, 0), (1, 1), (2, 2)] + >>> list(zip(remaining, numbers_iter)) + [(3, 3), (4, 4), (5, 5), (6, 6)] + ``` + The first argument of zip should be the one with fewest elements. + +--- + ### ▶ Loop variables leaking out! @@ -2199,7 +2103,7 @@ print(x, ': x in global') 3\. **Output (Python 2.x):** -``` +```py >>> x = 1 >>> print([x for x in range(5)]) [0, 1, 2, 3, 4] @@ -2208,7 +2112,7 @@ print(x, ': x in global') ``` **Output (Python 3.x):** -``` +```py >>> x = 1 >>> print([x for x in range(5)]) [0, 1, 2, 3, 4] @@ -2376,70 +2280,32 @@ a = a + [5, 6, 7, 8] [1, 2, 3, 4] ``` -2\. -```py -a = [1, 2, 3, 4] -b = a -a += [5, 6, 7, 8] -``` - -**Output:** -```py ->>> a -[1, 2, 3, 4, 5, 6, 7, 8] ->>> b -[1, 2, 3, 4, 5, 6, 7, 8] -``` - -#### 💡 Explanation: - -* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this. - -* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged. - -* The expression `a += [5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. - ---- - -### ▶ The out of scope variable - -```py -a = 1 -def some_func(): - return a - -def another_func(): - a += 1 - return a -``` - +2\. +```py +a = [1, 2, 3, 4] +b = a +a += [5, 6, 7, 8] +``` + **Output:** ```py ->>> some_func() -1 ->>> another_func() -UnboundLocalError: local variable 'a' referenced before assignment +>>> a +[1, 2, 3, 4, 5, 6, 7, 8] +>>> b +[1, 2, 3, 4, 5, 6, 7, 8] ``` #### 💡 Explanation: -* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope which throws an error. -* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. -* To modify the outer scope variable `a` in `another_func`, use `global` keyword. - ```py - def another_func() - global a - a += 1 - return a - ``` - **Output:** - ```py - >>> another_func() - 2 - ``` +* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this. + +* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged. + +* The expression `a += [5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. --- + ### ▶ Be careful with chained operations ```py @@ -2622,7 +2488,7 @@ some_dict = { "key_3": 3 } -some_list = some_list.append(4) +some_list = some_list.append(4) some_dict = some_dict.update({"key_4": 4}) ``` @@ -2704,6 +2570,43 @@ def similar_recursive_func(a): --- + +### ▶ Splitsies + +```py +>>> 'a'.split() +['a'] + +# is same as +>>> 'a'.split(' ') +['a'] + +# but +>>> len(''.split()) +0 + +# isn't the same as +>>> len(''.split(' ')) +1 +``` + +#### 💡 Explanation: + +- It might appear at first that the default seperator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split) + > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`. + > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`. +- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear, + ```py + >>> ' a '.split(' ') + ['', 'a', ''] + >>> ' a '.split() + ['a'] + >>> ''.split(' ') + [''] + ``` + +--- + ### ▶ Wild imports @@ -2741,31 +2644,28 @@ NameError: name '_another_weird_name_func' is not defined works! ``` - If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports. -```py -__all__ = ['_another_weird_name_func'] + ```py + __all__ = ['_another_weird_name_func'] -def some_weird_name_func_(): - print("works!") + def some_weird_name_func_(): + print("works!") -def _another_weird_name_func(): - print("works!") -``` -**Output** + def _another_weird_name_func(): + print("works!") + ``` + **Output** -```py ->>> _another_weird_name_func() -"works!" ->>> some_weird_name_func_() -Traceback (most recent call last): - File "", line 1, in -NameError: name 'some_weird_name_func_' is not defined -``` ---- + ```py + >>> _another_weird_name_func() + "works!" + >>> some_weird_name_func_() + Traceback (most recent call last): + File "", line 1, in + NameError: name 'some_weird_name_func_' is not defined + ``` --- -## Section: Read the docs - ### ▶ All sorted? @@ -2805,48 +2705,38 @@ False ([7, 8, 9], []) ``` - - --- -### ▶ All-true-ation +### ▶ Midnight time doesn't exist? + +```py +from datetime import datetime - +midnight = datetime(2018, 1, 1, 0, 0) +midnight_time = midnight.time() -```py ->>> all([True, True, True]) -True ->>> all([True, True, False]) -False +noon = datetime(2018, 1, 1, 12, 0) +noon_time = noon.time() ->>> all([]) -True ->>> all([[]]) -False ->>> all([[[]]]) -True -``` +if midnight_time: + print("Time at midnight is", midnight_time) -Why's this True-False alteration? +if noon_time: + print("Time at noon is", noon_time) +``` -#### 💡 Explanation: +**Output (< 3.5):** -- The implementation of `all` function is equivalent to +```sh +('Time at noon is', datetime.time(12, 0)) +``` +The midnight time is not printed. -- ```py - def all(iterable): - for element in iterable: - if not element: - return False - return True - ``` +#### 💡 Explanation: -- `all([])` returns `True` since the iterable is empty. -- `all([[]])` returns `False` because `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty. -- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`. +Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of "empty." --- - --- @@ -3212,7 +3102,117 @@ AttributeError: 'A' object has no attribute '__variable' * Also, if the mangled name is longer than 255 characters truncation will happen. --- +--- + +## Section: Appearances are deceptive! + +### ▶ Skipping lines? + +**Output:** +```py +>>> value = 11 +>>> valuе = 32 +>>> value +11 +``` + +Wut? + +**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell. + +#### 💡 Explanation + +Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter. + +```py +>>> ord('е') # cyrillic 'e' (Ye) +1077 +>>> ord('e') # latin 'e', as used in English and typed using standard keyboard +101 +>>> 'е' == 'e' +False + +>>> value = 42 # latin e +>>> valuе = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here +>>> value +42 +``` + +The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example. + +--- + +### ▶ Teleportation + + + +```py +import numpy as np + +def energy_send(x): + # Initializing a numpy array + np.array([float(x)]) + +def energy_receive(): + # Return an empty numpy array + return np.empty((), dtype=np.float).tolist() +``` + +**Output:** +```py +>>> energy_send(123.456) +>>> energy_receive() +123.456 +``` + +Where's the Nobel Prize? + +#### 💡 Explanation: + +* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate. +* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always). + +--- + +### ▶ Well, something is fishy... + +```py +def square(x): + """ + A simple function to calculate the square of a number by addition. + """ + sum_so_far = 0 + for counter in range(x): + sum_so_far = sum_so_far + x + return sum_so_far +``` + +**Output (Python 2.x):** + +```py +>>> square(10) +10 +``` + +Shouldn't that be 100? + +**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell. + +#### 💡 Explanation + +* **Don't mix tabs and spaces!** The character just preceding return is a "tab", and the code is indented by multiple of "4 spaces" elsewhere in the example. +* This is how Python handles tabs: + + > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...> +* So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. +* Python 3 is kind enough to throw an error for such cases automatically. + **Output (Python 3.x):** + ```py + TabError: inconsistent use of tabs and spaces in indentation + ``` + +--- --- ## Section: Miscellaneous @@ -3327,8 +3327,6 @@ Let's increase the number of iterations by a factor of 10. > There should be one-- and preferably only one --obvious way to do it. - - --- ### ▶ Minor Ones From 2161c48e8e56dd545c97848bb202e1274097879b Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 2 Nov 2019 23:25:58 +0530 Subject: [PATCH 099/221] Parse nested examples --- irrelevant/json_generator.py | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py index c62499a4..6d4a32e8 100644 --- a/irrelevant/json_generator.py +++ b/irrelevant/json_generator.py @@ -21,7 +21,7 @@ import os import pprint -fpath = os.path.join(os.path.dirname( __file__ ), '..', 'README.md') +fpath = os.path.join(os.path.dirname( __file__ ), '..', 'test_nb.md') examples = [] # The globals @@ -55,12 +55,14 @@ def generate_markdown_block(lines): sequence_num += 1 return result + def is_interactive_statement(line): for prefix in STATEMENT_PREFIXES: - if line.startswith(prefix): + if line.lstrip().startswith(prefix): return True return False + def parse_example_parts(lines, example_title_line): parts = { "build_up": [], @@ -117,20 +119,20 @@ def parse_example_parts(lines, example_title_line): # store lines again until --- or another H3 is encountered while not (next_line.startswith("---") or next_line.startswith("### ")): - if next_line.startswith("```"): + if next_line.lstrip().startswith("```"): # It's a snippet, whatever found until now is text is_interactive = False if content: - parts["build_up"].append(generate_markdown_block(content)) + parts["explanation"].append(generate_markdown_block(content)) content = [] next_line = next(lines) - while not next_line.startswith("```"): + while not next_line.lstrip().startswith("```"): if is_interactive_statement(next_line): is_interactive = True if (output_so_far): - parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + parts["explanation"].append(generate_code_block(statements_so_far, output_so_far)) statements_so_far, output_so_far = [], [] statements_so_far.append(next_line) else: @@ -142,7 +144,7 @@ def parse_example_parts(lines, example_title_line): next_line = next(lines) # Snippet is over - parts["build_up"].append(generate_code_block(statements_so_far, output_so_far)) + parts["explanation"].append(generate_code_block(statements_so_far, output_so_far)) statements_so_far, output_so_far = [], [] next_line = next(lines) else: @@ -156,9 +158,10 @@ def parse_example_parts(lines, example_title_line): return next_line, parts + def remove_from_beginning(tokens, line): for token in tokens: - if line.startswith(token): + if line.lstrip().startswith(token): line = line.replace(token, "") return line @@ -174,6 +177,7 @@ def inspect_and_sanitize_code_lines(lines): result.append(line) return is_print_present, result + def convert_to_cells(cell_contents): cells = [] for stuff in cell_contents: @@ -240,10 +244,10 @@ def convert_to_notebook(parsed_json): explanation = parts.get("explanation") notebook_path = "test.ipynb" - if(build_up): + if build_up: result["cells"] += convert_to_cells(build_up) - if(explanation): + if explanation: result["cells"] += convert_to_cells(explanation) pprint.pprint(result, indent=2) @@ -251,14 +255,17 @@ def convert_to_notebook(parsed_json): json.dump(result, f) - with open(fpath, 'r+', encoding="utf-8") as f: lines = iter(f.readlines()) line = next(lines) result = [] + pre_examples_phase = True + pre_stuff = [] + post_stuff = [] try: while True: if line.startswith("## "): + pre_examples_phase = False # A section is encountered current_section_name = line.replace("## ", "").strip() section_text = [] @@ -281,8 +288,13 @@ def convert_to_notebook(parsed_json): section_text.append(line) line = next(lines) else: + if pre_examples_phase: + pre_stuff.append(line) + else: + post_stuff.append(line) line = next(lines) except StopIteration: pprint.pprint(result, indent=2) + print("POST", post_stuff) convert_to_notebook(result) From 2cd7e3fccd81543a056151ac04eef9c080dcca52 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sun, 3 Nov 2019 00:54:04 +0530 Subject: [PATCH 100/221] Fix broken links --- README.md | 125 +++++++++++++++++++++++++++--------------------------- 1 file changed, 62 insertions(+), 63 deletions(-) diff --git a/README.md b/README.md index 04a0d1b3..05f336fc 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,6 @@

What the f*ck Python! 🐍

An interesting collection of surprising snippets and lesser-known Python features.

-[![WTFPL 2.0][license-image]][license-url] Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) @@ -23,75 +22,75 @@ So, here we go... - [Structure of the Examples](#structure-of-the-examples) - + [▶ Some fancy Title](#%E2%96%B6-some-fancy-title) + + [▶ Some fancy Title](#-some-fancy-title) - [Usage](#usage) - [👀 Examples](#%F0%9F%91%80-examples) * [Section: Strain your brain!](#section-strain-your-brain) - + [▶ First things first!](#%E2%96%B6-first-things-first) - + [▶ Strings can be tricky sometimes](#%E2%96%B6-strings-can-be-tricky-sometimes) - + [▶ Splitsies](#%E2%96%B6-splitsies) - + [▶ Hash brownies](#%E2%96%B6-hash-brownies) - + [▶ Disorder within order](#%E2%96%B6-disorder-within-order) - + [▶ Keep trying...](#%E2%96%B6-keep-trying) - + [▶ Deep down, we're all the same.](#%E2%96%B6-deep-down-were-all-the-same) - + [▶ For what?](#%E2%96%B6-for-what) - + [▶ Evaluation time discrepancy](#%E2%96%B6-evaluation-time-discrepancy) - + [▶ How not to use `is` operator](#%E2%96%B6-how-not-to-use-is-operator) - + [▶ A tic-tac-toe where X wins in the first attempt!](#%E2%96%B6-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - + [▶ The sticky output function](#%E2%96%B6-the-sticky-output-function) - + [▶ The chicken-egg problem](#%E2%96%B6-the-chicken-egg-problem) - + [▶ `is not ...` is not `is (not ...)`](#%E2%96%B6-is-not--is-not-is-not-) - + [▶ The surprising comma](#%E2%96%B6-the-surprising-comma) - + [▶ Strings and the backslashes](#%E2%96%B6-strings-and-the-backslashes) - + [▶ not knot!](#%E2%96%B6-not-knot) - + [▶ Half triple-quoted strings](#%E2%96%B6-half-triple-quoted-strings) - + [▶ Midnight time doesn't exist?](#%E2%96%B6-midnight-time-doesnt-exist) - + [▶ What's wrong with booleans?](#%E2%96%B6-whats-wrong-with-booleans) - + [▶ Class attributes and instance attributes](#%E2%96%B6-class-attributes-and-instance-attributes) - + [▶ Non-reflexive class method](#%E2%96%B6-non-reflexive-class-method) - + [▶ yielding None](#%E2%96%B6-yielding-none) - + [▶ Nan-reflexivity](#%E2%96%B6-nan-reflexivity) - + [▶ Mutating the immutable!](#%E2%96%B6-mutating-the-immutable) - + [▶ The disappearing variable from outer scope](#%E2%96%B6-the-disappearing-variable-from-outer-scope) - + [▶ Yielding from... return!](#%E2%96%B6-yielding-from-return) - + [▶ Lossy zip of iterators](#%E2%96%B6-lossy-zip-of-iterators) - + [▶ Subclass relationships](#%E2%96%B6-subclass-relationships) - + [▶ The mysterious key type conversion](#%E2%96%B6-the-mysterious-key-type-conversion) - + [▶ Let's see if you can guess this?](#%E2%96%B6-lets-see-if-you-can-guess-this) + + [▶ First things first!](#-first-things-first) + + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) + + [▶ Splitsies](#-splitsies) + + [▶ Hash brownies](#-hash-brownies) + + [▶ Disorder within order](#-disorder-within-order) + + [▶ Keep trying...](#-keep-trying) + + [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) + + [▶ For what?](#-for-what) + + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) + + [▶ How not to use `is` operator](#-how-not-to-use-is-operator) + + [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + + [▶ The sticky output function](#-the-sticky-output-function) + + [▶ The chicken-egg problem](#-the-chicken-egg-problem) + + [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) + + [▶ The surprising comma](#-the-surprising-comma) + + [▶ Strings and the backslashes](#-strings-and-the-backslashes) + + [▶ not knot!](#-not-knot) + + [▶ Half triple-quoted strings](#-half-triple-quoted-strings) + + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) + + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) + + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) + + [▶ Non-reflexive class method](#-non-reflexive-class-method) + + [▶ yielding None](#-yielding-none) + + [▶ Nan-reflexivity](#-nan-reflexivity) + + [▶ Mutating the immutable!](#-mutating-the-immutable) + + [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) + + [▶ Yielding from... return!](#-yielding-from-return) + + [▶ Lossy zip of iterators](#-lossy-zip-of-iterators) + + [▶ Subclass relationships](#-subclass-relationships) + + [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) + + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) * [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - + [▶ Skipping lines?](#%E2%96%B6-skipping-lines) - + [▶ Teleportation](#%E2%96%B6-teleportation) - + [▶ Well, something is fishy...](#%E2%96%B6-well-something-is-fishy) + + [▶ Skipping lines?](#-skipping-lines) + + [▶ Teleportation](#-teleportation) + + [▶ Well, something is fishy...](#-well-something-is-fishy) * [Section: Slippery Slopes](#section-slippery-slopes) - + [▶ Modifying a dictionary while iterating over it](#%E2%96%B6-modifying-a-dictionary-while-iterating-over-it) - + [▶ Stubborn `del` operation](#%E2%96%B6-stubborn-del-operation) - + [▶ Deleting a list item while iterating](#%E2%96%B6-deleting-a-list-item-while-iterating) - + [▶ Loop variables leaking out!](#%E2%96%B6-loop-variables-leaking-out) - + [▶ Beware of default mutable arguments!](#%E2%96%B6-beware-of-default-mutable-arguments) - + [▶ Catching the Exceptions](#%E2%96%B6-catching-the-exceptions) - + [▶ Same operands, different story!](#%E2%96%B6-same-operands-different-story) - + [▶ The out of scope variable](#%E2%96%B6-the-out-of-scope-variable) - + [▶ Be careful with chained operations](#%E2%96%B6-be-careful-with-chained-operations) - + [▶ Name resolution ignoring class scope](#%E2%96%B6-name-resolution-ignoring-class-scope) - + [▶ Needles in a Haystack](#%E2%96%B6-needles-in-a-haystack) - + [▶ Wild imports](#%E2%96%B6-wild-imports) + + [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + + [▶ Stubborn `del` operation](#-stubborn-del-operation) + + [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) + + [▶ Loop variables leaking out!](#-loop-variables-leaking-out) + + [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) + + [▶ Catching the Exceptions](#-catching-the-exceptions) + + [▶ Same operands, different story!](#-same-operands-different-story) + + [▶ The out of scope variable](#-the-out-of-scope-variable) + + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + + [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) + + [▶ Needles in a Haystack](#-needles-in-a-haystack) + + [▶ Wild imports](#-wild-imports) * [Section: Read the docs](#section-read-the-docs) - + [▶ All sorted?](#%E2%96%B6-all-sorted) - + [▶ All-true-ation](#%E2%96%B6-all-true-ation) + + [▶ All sorted?](#-all-sorted) + + [▶ All-true-ation](#-all-true-ation) * [Section: The Hidden treasures!](#section-the-hidden-treasures) - + [▶ Okay Python, Can you make me fly?](#%E2%96%B6-okay-python-can-you-make-me-fly) - + [▶ `goto`, but why?](#%E2%96%B6-goto-but-why) - + [▶ Brace yourself!](#%E2%96%B6-brace-yourself) - + [▶ Let's meet Friendly Language Uncle For Life](#%E2%96%B6-lets-meet-friendly-language-uncle-for-life) - + [▶ Even Python understands that love is complicated](#%E2%96%B6-even-python-understands-that-love-is-complicated) - + [▶ Yes, it exists!](#%E2%96%B6-yes-it-exists) - + [▶ Ellipsis](#%E2%96%B6-ellipsis) - + [▶ Inpinity](#%E2%96%B6-inpinity) - + [▶ Let's mangle](#%E2%96%B6-lets-mangle) + + [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) + + [▶ `goto`, but why?](#-goto-but-why) + + [▶ Brace yourself!](#-brace-yourself) + + [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) + + [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) + + [▶ Yes, it exists!](#-yes-it-exists) + + [▶ Ellipsis](#-ellipsis) + + [▶ Inpinity](#-inpinity) + + [▶ Let's mangle](#-lets-mangle) * [Section: Miscellaneous](#section-miscellaneous) - + [▶ `+=` is faster](#%E2%96%B6--is-faster) - + [▶ Let's make a giant string!](#%E2%96%B6-lets-make-a-giant-string) - + [▶ Minor Ones](#%E2%96%B6-minor-ones) + + [▶ `+=` is faster](#--is-faster) + + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + + [▶ Minor Ones](#-minor-ones) * [~~~ That's all folks! ~~~](#-thats-all-folks-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -3479,7 +3478,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' # 🎓 License -[![CC 4.0][license-image]][license-url] +[![WTFPL 2.0][license-image]][license-url] © [Satwik Kansal](https://satwikkansal.xyz) From e18e56eba341d51d0f5dc4d517dfb4eebc05997b Mon Sep 17 00:00:00 2001 From: Satwik Date: Sun, 3 Nov 2019 00:54:27 +0530 Subject: [PATCH 101/221] Working experimental notebook generator --- irrelevant/json_generator.py | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py index 6d4a32e8..73be9817 100644 --- a/irrelevant/json_generator.py +++ b/irrelevant/json_generator.py @@ -21,7 +21,7 @@ import os import pprint -fpath = os.path.join(os.path.dirname( __file__ ), '..', 'test_nb.md') +fpath = os.path.join(os.path.dirname( __file__ ), '..', 'README.md') examples = [] # The globals @@ -73,11 +73,12 @@ def parse_example_parts(lines, example_title_line): output_so_far = [] next_line = example_title_line # store build_up till an H4 (explanation) is encountered - while not next_line.startswith("#### "): + while not (next_line.startswith("#### ")or next_line.startswith('---')): # Watching out for the snippets - if next_line.startswith("```"): + if next_line.startswith("```py"): # It's a snippet, whatever found until now is text is_interactive = False + output_encountered = False if content: parts["build_up"].append(generate_markdown_block(content)) content = [] @@ -95,6 +96,8 @@ def parse_example_parts(lines, example_title_line): # can be either output or normal code if is_interactive: output_so_far.append(next_line) + elif output_encountered: + output_so_far.append(next_line) else: statements_so_far.append(next_line) next_line = next(lines) @@ -119,7 +122,7 @@ def parse_example_parts(lines, example_title_line): # store lines again until --- or another H3 is encountered while not (next_line.startswith("---") or next_line.startswith("### ")): - if next_line.lstrip().startswith("```"): + if next_line.lstrip().startswith("```py"): # It's a snippet, whatever found until now is text is_interactive = False if content: @@ -231,18 +234,22 @@ def convert_to_cells(cell_contents): return cells -def convert_to_notebook(parsed_json): +def convert_to_notebook(pre_examples_content, parsed_json, post_examples_content): result = { "cells": [], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 } + + notebook_path = "test.ipynb" + + result["cells"] += convert_to_cells([generate_markdown_block(pre_examples_content)]) + for example in parsed_json: parts = example["parts"] build_up = parts.get("build_up") explanation = parts.get("explanation") - notebook_path = "test.ipynb" if build_up: result["cells"] += convert_to_cells(build_up) @@ -250,6 +257,8 @@ def convert_to_notebook(parsed_json): if explanation: result["cells"] += convert_to_cells(explanation) + result["cells"] += convert_to_cells([generate_markdown_block(post_examples_content)]) + pprint.pprint(result, indent=2) with open(notebook_path, "w") as f: json.dump(result, f) @@ -271,7 +280,7 @@ def convert_to_notebook(parsed_json): section_text = [] line = next(lines) # Until a new section is encountered - while not (line.startswith("## " )): + while not (line.startswith("## ") or line.startswith("# ")): # check if it's a H3 if line.startswith("### "): # An example is encountered @@ -294,7 +303,6 @@ def convert_to_notebook(parsed_json): post_stuff.append(line) line = next(lines) - except StopIteration: + except StopIteration as e: pprint.pprint(result, indent=2) - print("POST", post_stuff) - convert_to_notebook(result) + convert_to_notebook(pre_stuff, result, post_stuff) From 888c9e126106300a20a3fcfbb6f0d11605a092c0 Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 4 Nov 2019 23:18:52 +0530 Subject: [PATCH 102/221] Fix indenting, add a minor example, and update contributing message --- README.md | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 05f336fc..1313bf39 100644 --- a/README.md +++ b/README.md @@ -3377,9 +3377,9 @@ Let's increase the number of iterations by a factor of 10. True >>> False ** True == False True ->>> True ** False == True + >>> True ** False == True True ->>> True ** True == True + >>> True ** True == True True ``` @@ -3395,6 +3395,13 @@ Let's increase the number of iterations by a factor of 10. **💡 Explanation:** The `@` operator was added in Python 3.5 keeping scientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator. +* From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example, + ```py + >>> some_string = "wtfpython" + >>> f'{some_string=}' + "string='wtfpython'" + ``` + * Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!): ```py @@ -3454,17 +3461,25 @@ f() The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string. --- - -

~~~ That's all folks! ~~~

--- # Contributing -All patches are welcome! Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for further details. For discussions, you can either create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) or ping on the Gitter [channel](https://gitter.im/wtfpython/Lobby) +Here are a few ways that you can contribute to wtfpython, + +- Suggesting new examples +- Helping with translation (See issues labeled translation) +- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc +- Identifying gaps (things inadequate explanation, redundancy, etc) +- Suggestions in general for making this project more fun and useful + +Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new). + +PS: Please don't reach out with backlinking requests, no links will be added unless they're highly relevant to the project. # Acknowledgements -The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by the community gave it the shape it is in right now. +The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by the community gave it the shape it is in right now. #### Some nice Links! * https://www.youtube.com/watch?v=sH4XF6pKKmk From 65c8a9ef8c97376c59fa048a4251546cfc39c233 Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 4 Nov 2019 23:19:13 +0530 Subject: [PATCH 103/221] Update contributors list. --- CONTRIBUTORS.md | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a5e440ed..313c024f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1,4 +1,4 @@ -I'm really grateful to all the contributors. Following are the wonderful people (in no specific order) who have contributed their examples to wtfpython. +Following are the wonderful people (in no specific order) who have contributed their examples to wtfpython. | Contributor | Github | Issues | |-------------|--------|--------| @@ -10,5 +10,19 @@ I'm really grateful to all the contributors. Following are the wonderful people | PiaFraus | [PiaFraus](https://github.com/PiaFraus) | [#9](https://github.com/satwikkansal/wtfpython/issues/9) | | chris-rands | [chris-rands](https://github.com/chris-rands) | [#32](https://github.com/satwikkansal/wtfpython/issues/32) | | sohaibfarooqi | [sohaibfarooqi](https://github.com/sohaibfarooqi) | [#63](https://github.com/satwikkansal/wtfpython/issues/63) | +| ipid | [ipid](https://github.com/ipid) | [#145](https://github.com/satwikkansal/wtfpython/issues/145) | +| roshnet | [roshnet](https://github.com/roshnet) | [#140](https://github.com/satwikkansal/wtfpython/issues/140) | +| daidai21 | [daidai21](https://github.com/daidai21) | [#137](https://github.com/satwikkansal/wtfpython/issues/137) | +| scidam | [scidam](https://github.com/scidam) | [#136](https://github.com/satwikkansal/wtfpython/issues/136) | +| pmjpawelec | [pmjpawelec](https://github.com/pmjpawelec) | [#121](https://github.com/satwikkansal/wtfpython/issues/121) | +| leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [#112](https://github.com/satwikkansal/wtfpython/issues/112) | +| mishaturnbull | [mishaturnbull](https://github.com/mishaturnbull) | [#108](https://github.com/satwikkansal/wtfpython/issues/108) | +| MuseBoy | [MuseBoy](https://github.com/MuseBoy) | [#101](https://github.com/satwikkansal/wtfpython/issues/101) | +| Ghost account | N/A | [#96](https://github.com/satwikkansal/wtfpython/issues/96) +| koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) | +| jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) | -Thank you all for taking out the time to make this project more awesome! :smile: + +Thank you all for your time and making wtfpython more awesome! :smile: + +PS: This list is updated after every major release, if I forgot to add your contribution here, please feel free to raise a Pull request. From d9e71224e2dfb36c20d696e0ef3d0ae8280f8538 Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 7 Nov 2019 17:27:52 +0530 Subject: [PATCH 104/221] Add minor example --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 1313bf39..3985612a 100644 --- a/README.md +++ b/README.md @@ -3437,6 +3437,16 @@ f() [] ``` +* Slicing an iterable not always creates a new object. For example, + ```py + >>> some_str = "wtfpython" + >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n'] + >>> some_list is some_list[:] # False expected because a new object is created. + False + >>> some_str is some_str[:] # True because strings are immutable, so making a new object is of not much use. + True + ``` + * `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python. * You can seperate numeric literals with underscores (for better readablity) from Python 3 onwards. From e899e385530b1bcfb29e71f94c74648f23553574 Mon Sep 17 00:00:00 2001 From: Nikita Sobolev Date: Sun, 1 Dec 2019 15:51:18 +0300 Subject: [PATCH 105/221] Adds wemake-python-styleguide Link: https://github.com/wemake-services/wemake-python-styleguide Docs: https://wemake-python-stylegui.de/en/latest/ --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b1354cc5..17a74872 100644 --- a/README.md +++ b/README.md @@ -2438,6 +2438,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' * https://stackoverflow.com/questions/1011431/common-pitfalls-in-python * https://www.python.org/doc/humor/ * https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 +* https://github.com/wemake-services/wemake-python-styleguide # 🎓 License From d7c8b73731eb0eeb8f660d244017c6d8b3e03d9e Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 19 Dec 2019 15:49:40 +0530 Subject: [PATCH 106/221] Remove lobby link --- CONTRIBUTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e9c43dbf..e89821db 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ All kinds of patches are welcome. Feel free to even suggest some catchy and funny titles for the existing Examples. The goal is to make this collection as interesting to read as possible. -If you are interested in translating the project to another language (some people have done that in the past), please feel free to open up an issue or ping on the [gitter channel](https://gitter.im/wtfpython/Lobby) if you need any kind of help. +If you are interested in translating the project to another language (some people have done that in the past), please feel free to open up an issue, and let me know if you need any kind of help. If the changes you suggest are significant, filing an issue before submitting the actual patch will be appreciated. If you'd like to work on the issue (highly encouraged), you can mention that you're interested in working on it while creating the issue and get assigned to it. @@ -42,4 +42,4 @@ Few things that you can consider while writing an example, - Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's strictly enforced scheme in the project, but you can take a glance at other examples to get a gist. - Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write. -- Also, please don't forget to add your name to the [contributors list](/CONTRIBUTING.md). \ No newline at end of file +- Also, please don't forget to add your name to the [contributors list](/CONTRIBUTING.md). From f3c7afebd7e04fc4db2243bbec906fb7319fb4e5 Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 19 Dec 2019 15:49:52 +0530 Subject: [PATCH 107/221] Minor corrections --- README.md | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 3985612a..96953851 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 🐍

An interesting collection of surprising snippets and lesser-known Python features.

-Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) +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].) 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. @@ -24,7 +24,7 @@ So, here we go... - [Structure of the Examples](#structure-of-the-examples) + [▶ Some fancy Title](#-some-fancy-title) - [Usage](#usage) -- [👀 Examples](#%F0%9F%91%80-examples) +- [👀 Examples](#-examples) * [Section: Strain your brain!](#section-strain-your-brain) + [▶ First things first!](#-first-things-first) + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) @@ -91,7 +91,6 @@ So, here we go... + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + [▶ Minor Ones](#-minor-ones) - * [~~~ That's all folks! ~~~](#-thats-all-folks-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) - [🎓 License](#%F0%9F%8E%93-license) @@ -221,7 +220,7 @@ SyntaxError: invalid syntax -💡 Explanation +####💡 Explanation **Quick walrus operator refresher** @@ -3355,7 +3354,7 @@ Let's increase the number of iterations by a factor of 10. + `++a` parses as `+(+a)` which translates to `a`. Similarly, the output of the statement `--a` can be justified. + This StackOverflow [thread](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) discusses the rationale behind the absence of increment and decrement operators in Python. -* You must be aware of the Walrus operator in Python. But have you ever heard about _the space-invader operator_? +* You must be aware of the Walrus operator in Python. But have you ever heard about *the space-invader operator*? ```py >>> a = 42 >>> a -=- 1 @@ -3470,26 +3469,28 @@ f() ``` The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string. +**That's all folks!** + --- --- # Contributing -Here are a few ways that you can contribute to wtfpython, +A few ways that you can contribute to wtfpython, - Suggesting new examples -- Helping with translation (See issues labeled translation) -- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc -- Identifying gaps (things inadequate explanation, redundancy, etc) -- Suggestions in general for making this project more fun and useful +- Helping with translation (See [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation)) +- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc. +- Identifying gaps (things like inadequate explanation, redundant examples, etc.) +- Any creative suggestions to make this project more fun and useful -Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new). +Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) to discuss things. PS: Please don't reach out with backlinking requests, no links will be added unless they're highly relevant to the project. # Acknowledgements -The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by the community gave it the shape it is in right now. +The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by pythonistas gave it the shape it is in right now. #### Some nice Links! * https://www.youtube.com/watch?v=sH4XF6pKKmk @@ -3510,7 +3511,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' [license-url]: http://www.wtfpl.net [license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square -## Surprise your friends too? +## Surprise your friends as well! If you liked wtfpython, you can use these quick links to share it with your friends, From 8522964105057162c144db30211090c598c69f9a Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 19 Dec 2019 21:47:20 +0530 Subject: [PATCH 108/221] Read only meta tag, and minor fixes --- README.md | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 96953851..2e846cf1 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,7 @@ Now, just run `wtfpython` at the command line which will open this collection in ### ▶ First things first! + For some reasons, "Walrus" operator (`:=`) has become a very popular feature in the language. Let's check it out, @@ -220,7 +221,7 @@ SyntaxError: invalid syntax -####💡 Explanation +#### 💡 Explanation **Quick walrus operator refresher** @@ -1455,7 +1456,7 @@ def some_func(val): ### ▶ Yielding from... return! - + 1\. ```py @@ -1634,7 +1635,6 @@ But I thought tuples were immutable... ### ▶ The disappearing variable from outer scope - ```py e = 7 @@ -1833,7 +1833,6 @@ a, b = a[b] = {}, 5 ### ▶ Modifying a dictionary while iterating over it - ```py x = {0: None} @@ -1870,7 +1869,7 @@ Yes, it runs for exactly **eight** times and stops. ### ▶ Stubborn `del` operation - + ```py class SomeClass: @@ -2065,7 +2064,6 @@ Where did element `3` go from the `numbers` list? ### ▶ Loop variables leaking out! - 1\. ```py for x in range(7): @@ -2607,7 +2605,7 @@ def similar_recursive_func(a): ### ▶ Wild imports - + ```py # File: module.py @@ -2725,7 +2723,7 @@ if noon_time: **Output (< 3.5):** -```sh +```py ('Time at noon is', datetime.time(12, 0)) ``` The midnight time is not printed. @@ -2763,7 +2761,6 @@ Sshh.. It's a super secret. ### ▶ `goto`, but why? - ```py from goto import goto, label From ef68d1b482af9ba826d5206bb8fd19fc9cb84171 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 00:27:21 +0530 Subject: [PATCH 109/221] Add markers for new content --- README.md | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 2e846cf1..57b89874 100644 --- a/README.md +++ b/README.md @@ -165,7 +165,7 @@ Now, just run `wtfpython` at the command line which will open this collection in ## Section: Strain your brain! -### ▶ First things first! +### ▶ First things first! * @@ -451,7 +451,7 @@ True --- -### ▶ Disorder within order +### ▶ Disorder within order * ```py from collections import OrderedDict @@ -549,7 +549,7 @@ What is going on here? --- -### ▶ Keep trying... +### ▶ Keep trying... * ```py def some_func(): @@ -976,7 +976,7 @@ Even when the values of `x` were different in every iteration prior to appending --- -### ▶ The chicken-egg problem +### ▶ The chicken-egg problem * 1\. ```py @@ -1050,7 +1050,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` --- -### ▶ All-true-ation +### ▶ All-true-ation * @@ -1379,7 +1379,7 @@ True --- -### ▶ Non-reflexive class method +### ▶ Non-reflexive class method * @@ -1455,7 +1455,7 @@ def some_func(val): --- -### ▶ Yielding from... return! +### ▶ Yielding from... return! * 1\. @@ -1520,7 +1520,7 @@ Same result, that didn't work either. --- -### ▶ Nan-reflexivity +### ▶ Nan-reflexivity * @@ -2012,8 +2012,7 @@ Can you guess why the output is `[2, 4]`? --- -### ▶ Lossy zip of iterators - +### ▶ Lossy zip of iterators * ```py @@ -2390,7 +2389,7 @@ class SomeClass: --- -### ▶ Needles in a Haystack +### ▶ Needles in a Haystack * @@ -2567,7 +2566,7 @@ def similar_recursive_func(a): --- -### ▶ Splitsies +### ▶ Splitsies * ```py >>> 'a'.split() @@ -2603,7 +2602,7 @@ def similar_recursive_func(a): --- -### ▶ Wild imports +### ▶ Wild imports * @@ -2662,7 +2661,7 @@ NameError: name '_another_weird_name_func' is not defined --- -### ▶ All sorted? +### ▶ All sorted? * @@ -2767,7 +2766,7 @@ from goto import goto, label for i in range(9): for j in range(9): for k in range(9): - print("I'm trapped, please rescue!") + print("I am trapped, please rescue!") if k == 2: goto .breakout # breaking out from a deeply nested loop label .breakout @@ -2776,8 +2775,8 @@ print("Freedom!") **Output (Python 2.3):** ```py -I'm trapped, please rescue! -I'm trapped, please rescue! +I am trapped, please rescue! +I am trapped, please rescue! Freedom! ``` @@ -2945,7 +2944,7 @@ Try block executed successfully... - `else` clause after try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. --- -### ▶ Ellipsis +### ▶ Ellipsis * ```py def some_func(): @@ -3324,7 +3323,7 @@ Let's increase the number of iterations by a factor of 10. --- -### ▶ Minor Ones +### ▶ Minor Ones * * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) @@ -3512,7 +3511,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' If you liked wtfpython, you can use these quick links to share it with your friends, -[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) +[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&text=If%20you%20really%20think%20you%20know%20Python,%20think%20once%20more!%20Check%20out%20wtfpython&hastags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=If%20you%20really%20thing%20you%20know%20Python,%20think%20once%20more!) | [Facebook](https://www.facebook.com/dialog/share?app_id=536779657179021&display=page&href=https%3A%2F%2Fgithub.com%2Fsatwikkansal%2Fwtfpython"e=If%20you%20really%20think%20you%20know%20Python%2C%20think%20once%20more!) ## Need a pdf version? From b96e2fb6a981528522477fdc330a1976005eb2b5 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 00:31:42 +0530 Subject: [PATCH 110/221] Respect the read_only rule --- irrelevant/json_generator.py | 53 ++++++++++++++++++++++++++---------- 1 file changed, 38 insertions(+), 15 deletions(-) diff --git a/irrelevant/json_generator.py b/irrelevant/json_generator.py index 73be9817..2c77a6eb 100644 --- a/irrelevant/json_generator.py +++ b/irrelevant/json_generator.py @@ -63,15 +63,15 @@ def is_interactive_statement(line): return False -def parse_example_parts(lines, example_title_line): +def parse_example_parts(lines, title, current_line): parts = { "build_up": [], "explanation": [] } - content = [] + content = [title] statements_so_far = [] output_so_far = [] - next_line = example_title_line + next_line = current_line # store build_up till an H4 (explanation) is encountered while not (next_line.startswith("#### ")or next_line.startswith('---')): # Watching out for the snippets @@ -181,7 +181,7 @@ def inspect_and_sanitize_code_lines(lines): return is_print_present, result -def convert_to_cells(cell_contents): +def convert_to_cells(cell_contents, read_only): cells = [] for stuff in cell_contents: if stuff["type"] == "markdown": @@ -194,13 +194,26 @@ def convert_to_cells(cell_contents): } ) elif stuff["type"] == "code": + if read_only: + # Skip read only + # TODO: Fix + cells.append( + { + "cell_type": "markdown", + "metadata": {}, + "source": ["```py\n"] + stuff["statements"] + ["```\n"] + ["```py\n"] + stuff['output'] + ["```\n"] + } + ) + continue + is_print_present, sanitized_code = inspect_and_sanitize_code_lines(stuff["statements"]) if is_print_present: cells.append( { "cell_type": "code", "metadata": { - "collapsed": True + "collapsed": True, + }, "execution_count": None, "outputs": [{ @@ -244,22 +257,23 @@ def convert_to_notebook(pre_examples_content, parsed_json, post_examples_content notebook_path = "test.ipynb" - result["cells"] += convert_to_cells([generate_markdown_block(pre_examples_content)]) + result["cells"] += convert_to_cells([generate_markdown_block(pre_examples_content)], False) for example in parsed_json: parts = example["parts"] build_up = parts.get("build_up") explanation = parts.get("explanation") + read_only = example.get("read_only") if build_up: - result["cells"] += convert_to_cells(build_up) + result["cells"] += convert_to_cells(build_up, read_only) if explanation: - result["cells"] += convert_to_cells(explanation) + result["cells"] += convert_to_cells(explanation, read_only) - result["cells"] += convert_to_cells([generate_markdown_block(post_examples_content)]) + result["cells"] += convert_to_cells([generate_markdown_block(post_examples_content)], False) - pprint.pprint(result, indent=2) + #pprint.pprint(result, indent=2) with open(notebook_path, "w") as f: json.dump(result, f) @@ -284,13 +298,22 @@ def convert_to_notebook(pre_examples_content, parsed_json, post_examples_content # check if it's a H3 if line.startswith("### "): # An example is encountered - title = line.replace("### ", "") + title_line = line + line = next(lines) + read_only = False + while line.strip() == "" or line.startswith('' in line: + read_only = True + line = next(lines) + example_details = { "id": current_example, - "title": line.replace("### ", ""), - "section": current_section_name + "title": title_line.replace("### ", ""), + "section": current_section_name, + "read_only": read_only } - line, example_details["parts"] = parse_example_parts(lines, line) + line, example_details["parts"] = parse_example_parts(lines, title_line, line) result.append(example_details) current_example += 1 else: @@ -304,5 +327,5 @@ def convert_to_notebook(pre_examples_content, parsed_json, post_examples_content line = next(lines) except StopIteration as e: - pprint.pprint(result, indent=2) + #pprint.pprint(result, indent=2) convert_to_notebook(pre_stuff, result, post_stuff) From 0c461ee66af878553c072d2ca3d94cf05f492aa4 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 00:36:19 +0530 Subject: [PATCH 111/221] Ignore IDE files --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 36f9a1fd..057dcb0c 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ __pycache__/ irrelevant/.ipynb_checkpoints/ irrelevant/.python-version + +.idea/ From 68904d3f6fe2e474c10af27b9d96616cbd7b9cab Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 01:13:18 +0530 Subject: [PATCH 112/221] Remove mention of npm package --- README.md | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 445755c5..482f7b13 100644 --- a/README.md +++ b/README.md @@ -145,20 +145,11 @@ A nice way to get the most out of these examples, in my opinion, will be to just - 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)). - If yes, give a gentle pat on your back, and you may skip to the next example. -PS: You can also read WTFPython at the command line. There's a pypi package and an npm package (which supports colored formatting) for the same. - -To install the npm package [`wtfpython`](https://www.npmjs.com/package/wtfpython) -```sh -$ npm install -g wtfpython -``` - -Alternatively, to install the pypi package [`wtfpython`](https://pypi.python.org/pypi/wtfpython) +PS: You can also read WTFPython at the command line using the [pypi package](https://pypi.python.org/pypi/wtfpython), ```sh $ pip install wtfpython -U +$ wtfpython ``` - -Now, just run `wtfpython` at the command line which will open this collection in your selected `$PAGER`. - --- # 👀 Examples @@ -3497,7 +3488,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' * https://www.python.org/doc/humor/ * https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator * https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 -* https://github.com/wemake-services/wemake-python-styleguide +* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues # 🎓 License From dd3c62d49d155093753a4bc3e35b4fca7ca6e9a6 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 01:14:09 +0530 Subject: [PATCH 113/221] Remove npm related stuff --- .npmignore | 1 - package.json | 41 ----------------------------------------- 2 files changed, 42 deletions(-) delete mode 100644 .npmignore delete mode 100644 package.json diff --git a/.npmignore b/.npmignore deleted file mode 100644 index 9b7aaab0..00000000 --- a/.npmignore +++ /dev/null @@ -1 +0,0 @@ -irrelevant/ diff --git a/package.json b/package.json deleted file mode 100644 index f6170911..00000000 --- a/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "wtfpython", - "version": "2.1.0", - "description": "A collection of surprising Python snippets and lesser known features.", - "bin": "wtfpython", - "scripts": { - "postpublish": "git push origin master", - "toc": "doctoc --github --title '# Table of Contents' --maxlevel 3 README.md" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/satwikkansal/wtfPython.git" - }, - "keywords": [ - "python", - "specification", - "notes", - "wtf", - "learning", - "guide", - "handbook" - ], - "author": "Satwik Kansal (https://satwikkansal.xyz)", - "license": "WTFPL 2.0", - "bugs": { - "url": "https://github.com/satwikkansal/wtfPython/issues" - }, - "homepage": "https://github.com/satwikkansal/wtfPython#readme", - "devDependencies": { - "doctoc": "^1.3.0" - }, - "dependencies": { - "boxen": "^1.1.0", - "chalk": "^1.1.1", - "default-pager": "^1.1.0", - "meow": "^3.7.0", - "msee": "^0.3.3", - "through2": "^2.0.2", - "update-notifier": "^2.0.0" - } -} From 44e885a09c18209b152d3ff82749d1cf5dfd9204 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 01:19:31 +0530 Subject: [PATCH 114/221] Ignore unnecessary stuff in npm package --- .npmignore | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.npmignore b/.npmignore index 9b7aaab0..42ef7286 100644 --- a/.npmignore +++ b/.npmignore @@ -1 +1,9 @@ irrelevant/ +wtfpython-pypi/build/ +wtfpython-pypi/dist/ +wtfpython-pypi/wtfpython.egg-info + +# Python-specific byte-compiled files should be ignored +__pycache__/ +*.py[cod] +*$py.class From 176bcc8a253de967c62d33c0604d4d154ca79794 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 01:19:49 +0530 Subject: [PATCH 115/221] Bump npm version --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index f6170911..68472df1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "wtfpython", - "version": "2.1.0", - "description": "A collection of surprising Python snippets and lesser known features.", + "version": "2.2.0", + "description": "A collection of surprising Python snippets and lesser known features. [ARCHIVED]", "bin": "wtfpython", "scripts": { "postpublish": "git push origin master", From 8e798af4fcf5e1c20cb18ce75267496e7f7fb5b6 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 01:20:48 +0530 Subject: [PATCH 116/221] Ignore IDE files and Bump npm version --- .npmignore | 2 ++ package.json | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.npmignore b/.npmignore index 42ef7286..5b48b067 100644 --- a/.npmignore +++ b/.npmignore @@ -1,3 +1,5 @@ +.idea/ + irrelevant/ wtfpython-pypi/build/ wtfpython-pypi/dist/ diff --git a/package.json b/package.json index 68472df1..bdfa76f1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wtfpython", - "version": "2.2.0", + "version": "2.2.1", "description": "A collection of surprising Python snippets and lesser known features. [ARCHIVED]", "bin": "wtfpython", "scripts": { From 6e5278e30a59b6cfcf2ea1484c73cce49523e9a5 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 01:23:20 +0530 Subject: [PATCH 117/221] More cleanup and another version bump --- .npmignore | 5 ++--- package.json | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.npmignore b/.npmignore index 5b48b067..57de941b 100644 --- a/.npmignore +++ b/.npmignore @@ -1,9 +1,8 @@ +.DS_Store .idea/ irrelevant/ -wtfpython-pypi/build/ -wtfpython-pypi/dist/ -wtfpython-pypi/wtfpython.egg-info +wtfpython-pypi/** # Python-specific byte-compiled files should be ignored __pycache__/ diff --git a/package.json b/package.json index bdfa76f1..eae9e958 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wtfpython", - "version": "2.2.1", + "version": "2.2.2", "description": "A collection of surprising Python snippets and lesser known features. [ARCHIVED]", "bin": "wtfpython", "scripts": { From 264b93a633af0d29d6dca7637ca2e7779dd262cb Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 01:27:34 +0530 Subject: [PATCH 118/221] Remove every existence of npm --- .npmignore | 10 ------- package.json | 41 ------------------------- wtfpython | 85 ---------------------------------------------------- 3 files changed, 136 deletions(-) delete mode 100644 .npmignore delete mode 100644 package.json delete mode 100644 wtfpython diff --git a/.npmignore b/.npmignore deleted file mode 100644 index 57de941b..00000000 --- a/.npmignore +++ /dev/null @@ -1,10 +0,0 @@ -.DS_Store -.idea/ - -irrelevant/ -wtfpython-pypi/** - -# Python-specific byte-compiled files should be ignored -__pycache__/ -*.py[cod] -*$py.class diff --git a/package.json b/package.json deleted file mode 100644 index eae9e958..00000000 --- a/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "wtfpython", - "version": "2.2.2", - "description": "A collection of surprising Python snippets and lesser known features. [ARCHIVED]", - "bin": "wtfpython", - "scripts": { - "postpublish": "git push origin master", - "toc": "doctoc --github --title '# Table of Contents' --maxlevel 3 README.md" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/satwikkansal/wtfPython.git" - }, - "keywords": [ - "python", - "specification", - "notes", - "wtf", - "learning", - "guide", - "handbook" - ], - "author": "Satwik Kansal (https://satwikkansal.xyz)", - "license": "WTFPL 2.0", - "bugs": { - "url": "https://github.com/satwikkansal/wtfPython/issues" - }, - "homepage": "https://github.com/satwikkansal/wtfPython#readme", - "devDependencies": { - "doctoc": "^1.3.0" - }, - "dependencies": { - "boxen": "^1.1.0", - "chalk": "^1.1.1", - "default-pager": "^1.1.0", - "meow": "^3.7.0", - "msee": "^0.3.3", - "through2": "^2.0.2", - "update-notifier": "^2.0.0" - } -} diff --git a/wtfpython b/wtfpython deleted file mode 100644 index b8a3fa6a..00000000 --- a/wtfpython +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs'); -const obj = require('through2').obj; -const pager = require('default-pager'); -const msee = require('msee'); -const join = require('path').join; -const boxen = require('boxen'); -const chalk = require('chalk'); -const updateNotifier = require('update-notifier'); -const pkg = require('./package.json'); -const meow = require('meow'); - -const cli = meow([ - 'Usage', - ' bash-handbook', - '', - 'Options', - ' --lang, -l Translation language', - '', - 'Examples', - ' bash-handbook', - ' bash-handbook --lang pt-br' -], { - string: [ - 'lang' - ], - alias: { - l: 'lang', - h: 'help' - }, - default: { - lang: '' - } -}); - -const boxenOpts = { - borderColor: 'yellow', - margin: { - bottom: 1 - }, - padding: { - right: 1, - left: 1 - } -}; - -const mseeOpts = { - paragraphEnd: '\n\n' -}; - -const notifier = updateNotifier({ pkg }); - -process.env.PAGER = process.env.PAGER || 'less'; -process.env.LESS = process.env.LESS || 'FRX'; - -const lang = cli.flags.lang - .toLowerCase() - .split('-') - .map((l, i) => i === 0 ? l : l.toUpperCase()) - .join('-'); - -const translation = join(__dirname, !lang ? './README.md' : `./README-${lang}.md`); - -fs.stat(translation, function (err, stats) { - if (err) { - console.log('The %s translation does not exist', chalk.bold(lang)); - return; - } - - fs.createReadStream(translation) - .pipe(obj(function (chunk, enc, cb) { - const message = []; - - if (notifier.update) { - message.push(`Update available: {green.bold ${notifier.update.latest}} {dim current: ${notifier.update.current}}`); - message.push(`Run {blue npm install -g ${pkg.name}} to update.`); - this.push(boxen(message.join('\n'), boxenOpts)); - } - - this.push(msee.parse(chunk.toString(), mseeOpts)); - cb(); - })) - .pipe(pager()); -}); From 9fb381c4f3064d304654c5d046698ceb13a262e8 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 02:05:53 +0530 Subject: [PATCH 119/221] Fix soo many typos, sigh. --- README.md | 176 +++++++++++++++++++++++++++--------------------------- 1 file changed, 88 insertions(+), 88 deletions(-) diff --git a/README.md b/README.md index 482f7b13..974359a6 100644 --- a/README.md +++ b/README.md @@ -8,9 +8,9 @@ Python, being a beautifully designed high-level and interpreter-based programmin 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. -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 beliereve that you'll find it interesting too! +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! -If you're an experienced Python programmer, you can take it as a challenge to get most of them right in 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: +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: PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). @@ -137,8 +137,8 @@ All the examples are structured like below: # Usage -A nice way to get the most out of these examples, in my opinion, will be to just read them chronologically, and for every example: -- Carefully read the initial code for setting up the example. If you're an experienced Python programmer, most of the times you will successfully anticipate what's going to happen next. +A nice way to get the most out of these examples, in my opinion, is to read them chronologically, and for every example: +- 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. - Read the output snippets and, + Check if the outputs are the same as you'd expect. + Make sure if you know the exact reason behind the output being the way it is. @@ -161,7 +161,7 @@ $ wtfpython -For some reasons, "Walrus" operator (`:=`) has become a very popular feature in the language. Let's check it out, +For some reason, the "Walrus" operator (`:=`) has become a popular feature in the language. Let's check it out, 1\. @@ -216,26 +216,26 @@ SyntaxError: invalid syntax **Quick walrus operator refresher** -The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situatitions where you'd want to assing values to variables within an expression. +The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression. ```py def some_func(): - # Assume some expensive computation here - # time.sleep(1000) - return 5 + # Assume some expensive computation here + # time.sleep(1000) + return 5 # So instead of, if some_func(): - print(some_func()) # Which is bad practice since computation is happening twice + print(some_func()) # Which is bad practice since computation is happening twice # or a = some_func() if a: - print(a) + print(a) # Now you can concisely write if a := some_func(): - print(a) + print(a) ``` **Output (> 3.8):** @@ -246,13 +246,13 @@ if a := some_func(): 5 ``` -This helped save one line of code, and implicitly prevented invoking `some_func` twice. +This saved one line of code, and implicitly prevented invoking `some_func` twice. -- Unparenthesized "assignment expression" (use of walrus operator), is restricted at top level, hence the `SyntaxError` in the `a := "wtf_walrus"` statement of first snippet. Parenthesizing it worked as expected and assigned `a`. +- Unparenthesized "assignment expression" (use of walrus operator), is restricted at the top level, hence the `SyntaxError` in the `a := "wtf_walrus"` statement of the first snippet. Parenthesizing it worked as expected and assigned `a`. -- As usual, parenthesizing of expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. +- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. -- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, +- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6') @@ -333,15 +333,15 @@ Makes sense, right? #### 💡 Explanation: + The behavior in first and second snippets is due to a CPython optimization (called string interning) that tries to use existing immutable objects in some cases rather than creating a new object every time. -+ After being "interned", many variables may reference the same string object in memory (saving memory thereby). -+ In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation dependent. There are some rules that can be used to guess if a string will be interned or not: ++ After being "interned," many variables may reference the same string object in memory (saving memory thereby). ++ In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation-dependent. There are some rules that can be used to guess if a string will be interned or not: * All length 0 and length 1 strings are interned. * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) - * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) + * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) -+ When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's an compile time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). -+ The compile unit in interactive environment like ipython consists of single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are 2 statements in single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` -+ The abrupt change in output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. ++ When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). ++ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are two statements in a single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` ++ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. + Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). --- @@ -379,7 +379,7 @@ So, why is Python all over the place? #### 💡 Explanation * Python dictionaries check for equality and compare the hash value to determine if two keys are the same. -* Immutable objects with same value always have the same hash in Python. +* Immutable objects with the same value always have the same hash in Python. ```py >>> 5 == 5.0 == 5 + 0j True @@ -415,7 +415,7 @@ True * 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. * 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. -* So, 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. +* 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. * But why did the `is` operator evaluated to `False`? Let's see with this snippet. ```py class WTF(object): @@ -1010,10 +1010,10 @@ False - `type` is a [metaclass](https://realpython.com/python-metaclasses/) in Python. - **Everything** is an `object` in Python, which includes classes as well as their objects (instances). - class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`. -- There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking 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, - + class A is instance of class B, and class B is an instance of class A. +- 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, + + class A is an instance of class B, and class B is an instance of class A. + class A is an instance of itself. -- These relationships between `object` and `type` (both being instances of eachother as well as themselves) exist in Python because of "cheating" at implementation level. +- 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. --- @@ -1133,7 +1133,7 @@ True #### 💡 Explanation -- In a normal python string, the backslash is used to escape characters that may have special meaning (like single-quote, double-quote and the backslash itself). +- 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). ```py >>> 'wt\"f' 'wt"f' @@ -1376,12 +1376,12 @@ True ```py class SomeClass: - def instance_method(self): - pass - - @classmethod - def class_method(cls): - pass + def instance_method(self): + pass + + @classmethod + def class_method(cls): + pass ``` **Output:** @@ -1406,7 +1406,7 @@ True ``` - A new bound method everytime `SomeClass.class_method` is accessed. + A new bound method every time `SomeClass.class_method` is accessed. - `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). @@ -1438,7 +1438,7 @@ def some_func(val): ``` #### 💡 Explanation: -- This is bug in CPython's handling of `yield` in generators and comprehensions. +- This is a bug in CPython's handling of `yield` in generators and comprehensions. - Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions - Related bug report: http://bugs.python.org/issue10544 - Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`. @@ -1485,7 +1485,7 @@ def some_func(x): [] ``` -Same result, that didn't work either. +The same result, this didn't work either. #### 💡 Explanation: @@ -1493,7 +1493,7 @@ Same result, that didn't work either. > "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." -+ In case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically catched inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. ++ 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. + To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, @@ -1566,9 +1566,9 @@ True #### 💡 Explanation: -- `'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. +- `'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. -- 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 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) whlie comparing two elements, and the values are compared only when the identities mismatch. Following snippet will make things clearer +- 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, ```py >>> x = float('nan') @@ -1581,9 +1581,9 @@ True (False, False) ``` - Since the identities of `x` and `y` are different, the values are considered, which are also different, hence the comparison returns `False` this time. + Since the identities of `x` and `y` are different, the values are considered, which are also different; hence the comparison returns `False` this time. -- Interesting read: [Reflexivity, and other pilliars of civilization](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) +- Interesting read: [Reflexivity, and other pillars of civilization](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) --- @@ -1591,7 +1591,7 @@ True -This might seem trivial if you know how references works in Python. +This might seem trivial if you know how references work in Python. ```py some_tuple = ("A", "tuple", "with", "values") @@ -1670,7 +1670,7 @@ NameError: name 'e' is not defined 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. -* 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 which have their separate inner-scopes. The example below illustrates this: +* 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: ```py def f(x): @@ -1693,7 +1693,7 @@ NameError: name 'e' is not defined [5, 4, 3] ``` -* In Python 2.x the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing. +* In Python 2.x, the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing. **Output (Python 2.x):** ```py @@ -1786,9 +1786,9 @@ a, b = a[b] = {}, 5 * 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`). -* After the expression list is evaluated, it's 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`. +* 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`. -* `a` is now assigned to `{}` which is a mutable object. +* `a` is now assigned to `{}`, which is a mutable object. * 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`). @@ -1853,7 +1853,7 @@ Yes, it runs for exactly **eight** times and stops. * Iteration over a dictionary that you edit at the same time is not supported. * It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. * How deleted keys are handled and when the resize occurs might be different for different Python implementations. -* So for Python versions other than Python 2.7 - Python 3.5 the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. +* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. * Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. --- @@ -1878,7 +1878,7 @@ class SomeClass: Deleted! ``` -Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twist to the example. +Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example. 2\. ```py @@ -1898,8 +1898,8 @@ Okay, now it's deleted :confused: #### 💡 Explanation: + `del x` doesn’t directly call `x.__del__()`. + Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero. -+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count to reach zero when `del y` was encountered. -+ Calling `globals` caused the existing reference to be destroyed and hence we can see "Deleted!" being printed (finally!). ++ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered. ++ Calling `globals` caused the existing reference to be destroyed, and hence we can see "Deleted!" being printed (finally!). --- @@ -1924,7 +1924,7 @@ UnboundLocalError: local variable 'a' referenced before assignment ``` #### 💡 Explanation: -* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope which throws an error. +* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error. * Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. * To modify the outer scope variable `a` in `another_func`, use `global` keyword. ```py @@ -2110,9 +2110,9 @@ print(x, ': x in global') - In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable. -- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) change log: +- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog: - > "List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular the loop control variables are no longer leaked into the surrounding scope." + > "List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope." --- @@ -2384,7 +2384,7 @@ class SomeClass: -I haven't met even a single experience Pythonist till date who has not came across one or more of the following scenarios, +I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios, 1\. @@ -2498,11 +2498,11 @@ def some_recursive_func(a): return a def similar_recursive_func(a): - if a == 0: - return a - a -= 1 - similar_recursive_func(a) - return a + if a == 0: + return a + a -= 1 + similar_recursive_func(a) + return a ``` **Output:** @@ -2550,9 +2550,9 @@ def similar_recursive_func(a): * As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). -* Last one should be fairly obvious, passing mutable object (like `list` ) results in call by reference, whereas an immutable object (like `int`) results in call by value. +* Last one should be fairly obvious, passing mutable object (like `list` ) results in a call by reference, whereas an immutable object (like `int`) results in a call by value. -* Being aware of these knitpicks can save you hours of degugging effort in long run. +* Being aware of these nitpicks can save you hours of debugging effort in the long run. --- @@ -2578,7 +2578,7 @@ def similar_recursive_func(a): #### 💡 Explanation: -- It might appear at first that the default seperator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split) +- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split) > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`. > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`. - Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear, @@ -2622,8 +2622,8 @@ NameError: name '_another_weird_name_func' is not defined #### 💡 Explanation: -- It if often adivsable to not use wildcard imports. The first obvious reason for this is In wildcard imports, the names with leading underscore are be imported. This may lead to errors in runtime. -- Had we used `from ... import a, b, c` syntax, the above `NameError` won't have occurred. +- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime. +- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred. ```py >>> from module import some_weird_name_func_, _another_weird_name_func >>> _another_weird_name_func() @@ -2670,7 +2670,7 @@ False #### 💡 Explanation: -- The `sorted` method always returns a list, and comparing list and tuples always returns `False` in Python. +- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. - ```py >>> [] == tuple() @@ -2680,7 +2680,7 @@ False (tuple, list) ``` -- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use extra container (a list), whereas reversing can simple work by iterating from the last index to the first. +- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first. - So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list. @@ -2729,7 +2729,7 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t ## Section: The Hidden treasures! -This section contains few of the lesser-known interesting things about Python that most beginners like me are unaware of (well, not anymore). +This section contains a few lesser-known and interesting things about Python that most beginners like me are unaware of (well, not anymore). ### ▶ Okay Python, Can you make me fly? @@ -2740,7 +2740,7 @@ import antigravity ``` **Output:** -Sshh.. It's a super secret. +Sshh... It's a super-secret. #### 💡 Explanation: + `antigravity` module is one of the few easter eggs released by Python developers. @@ -2796,7 +2796,7 @@ SyntaxError: not a chance Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)? #### 💡 Explanation: -+ The `__future__` module is normally used to provide features from future versions of Python. The "future" in this specific context is however ironic. ++ The `__future__` module is normally used to provide features from future versions of Python. The "future" in this specific context is however, ironic. + This is an easter egg concerned with the community's feelings on this issue. + The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file. + When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement. @@ -2824,9 +2824,9 @@ There we go. - This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means). - Quoting from the PEP-401 - > Recognized that the != inequality operator in Python 3.0 was a horrible, finger pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. + > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. - There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/). -- It works well on interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working, +- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working, ```py from __future__ import barry_as_FLUFL print(eval('"Ruby" <> "Python"')) @@ -2932,7 +2932,7 @@ Try block executed successfully... #### 💡 Explanation: - The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a "nobreak" clause. -- `else` clause after try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. +- `else` clause after a try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. --- ### ▶ Ellipsis * @@ -2957,7 +2957,7 @@ Ellipsis ``` #### 💡 Explanation -- In Python, `Ellipsis` is a globally available builtin object which is equivalent to `...`. +- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`. ```py >>> ... Ellipsis @@ -3081,10 +3081,10 @@ AttributeError: 'A' object has no attribute '__variable' * [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces. * In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a "dunder") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. -* So, to access `__honey` attribute in first snippet, we had to append `_Yo` to the front which would prevent conflicts with the same name attribute defined in any other class. +* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class. * But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores. -* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable` which also happens to be the name of the variable we declared in outer scope. -* Also, if the mangled name is longer than 255 characters truncation will happen. +* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope. +* Also, if the mangled name is longer than 255 characters, truncation will happen. --- --- @@ -3295,7 +3295,7 @@ Let's increase the number of iterations by a factor of 10. - Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function) - Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings). - Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster. -- `add_string_with_plus` didn't show a quadratic increase in execution time unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example. Had the statement been `s = s + "x" + "y" + "z"` instead of `s += "xyz"`, the increase would have been quadratic. +- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + "x" + "y" + "z"` instead of `s += "xyz"`, the increase would have been quadratic. ```py def add_string_with_plus(iters): s = "" @@ -3318,14 +3318,14 @@ Let's increase the number of iterations by a factor of 10. * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) - **💡 Explanation:** If `join()` is a method on a string then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API. + **💡 Explanation:** If `join()` is a method on a string, then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API. * Few weird looking but semantically correct statements: + `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`) + `'a'[0][0][0][0][0]` is also a semantically correct statement as strings are [sequences](https://docs.python.org/3/glossary.html#term-sequence)(iterables supporting element access using integer indices) in Python. + `3 --0-- 5 == 8` and `--5 == 5` are both semantically correct statements and evaluate to `True`. -* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++ or Java. +* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java. ```py >>> a = 5 >>> a @@ -3369,7 +3369,7 @@ Let's increase the number of iterations by a factor of 10. True ``` - **💡 Explanation:** If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator)) + **💡 Explanation:** If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to a converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator)) * Since we are talking operators, there's also `@` operator for matrix multiplication (don't worry, this time it's for real). @@ -3379,7 +3379,7 @@ Let's increase the number of iterations by a factor of 10. 46 ``` - **💡 Explanation:** The `@` operator was added in Python 3.5 keeping scientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator. + **💡 Explanation:** The `@` operator was added in Python 3.5 keeping sthe cientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator. * From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example, ```py @@ -3402,9 +3402,9 @@ f() print(dis.dis(f)) ``` -* Multiple Python threads won't run your *Python code* concurrently (yes you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module. +* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module. -* Sometimes the `print` method might not print values immediately. For example, +* Sometimes, the `print` method might not print values immediately. For example, ```py # File some_file.py @@ -3477,7 +3477,7 @@ PS: Please don't reach out with backlinking requests, no links will be added unl # Acknowledgements -The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by pythonistas gave it the shape it is in right now. +The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by Pythonistas gave it the shape it is in right now. #### Some nice Links! * https://www.youtube.com/watch?v=sH4XF6pKKmk @@ -3501,10 +3501,10 @@ The idea and design for this collection were initially inspired by Denys Dovhan' ## Surprise your friends as well! -If you liked wtfpython, you can use these quick links to share it with your friends, +If you like wtfpython, you can use these quick links to share it with your friends, [Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&text=If%20you%20really%20think%20you%20know%20Python,%20think%20once%20more!%20Check%20out%20wtfpython&hastags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=If%20you%20really%20thing%20you%20know%20Python,%20think%20once%20more!) | [Facebook](https://www.facebook.com/dialog/share?app_id=536779657179021&display=page&href=https%3A%2F%2Fgithub.com%2Fsatwikkansal%2Fwtfpython"e=If%20you%20really%20think%20you%20know%20Python%2C%20think%20once%20more!) -## Need a pdf version? +## More content like this? -I've received a few requests for the pdf version of wtfpython. You can add your details [here](https://satwikkansal.xyz/wtfpython-pdf/) to get the pdf as soon as it is finished. +If you're interested in more content like this, you can share your email [here](https://satwikkansal.xyz/wtfpython-pdf/). From a9cbcdd95a691ee09bbf4404098b2c2e17057f50 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 23:27:25 +0530 Subject: [PATCH 120/221] Rename json_generator to notebook_generator --- irrelevant/{json_generator.py => notebook_generator.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename irrelevant/{json_generator.py => notebook_generator.py} (100%) diff --git a/irrelevant/json_generator.py b/irrelevant/notebook_generator.py similarity index 100% rename from irrelevant/json_generator.py rename to irrelevant/notebook_generator.py From 7006084c120ef1fb317969b1643437920182f21e Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 23:39:10 +0530 Subject: [PATCH 121/221] Fix URLs --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 974359a6..67957cc5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

+

What the f*ck Python! 🐍

An interesting collection of surprising snippets and lesser-known Python features.

@@ -338,7 +338,7 @@ Makes sense, right? * All length 0 and length 1 strings are interned. * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) - + ![image](/images/string-intern/string_intern.png) + When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). + A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are two statements in a single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` + The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. @@ -892,11 +892,11 @@ We didn't assign three `"X"`s, did we? When we initialize `row` variable, this visualization explains what happens in the memory -![image](images/tic-tac-toe/after_row_initialized.png) +![image](/images/tic-tac-toe/after_row_initialized.png) And 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`) -![image](images/tic-tac-toe/after_board_initialized.png) +![image](/images/tic-tac-toe/after_board_initialized.png) We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue). @@ -3507,4 +3507,4 @@ If you like wtfpython, you can use these quick links to share it with your frien ## More content like this? -If you're interested in more content like this, you can share your email [here](https://satwikkansal.xyz/wtfpython-pdf/). +If you're interested in more content like this, you can share your email [here](https://satwikkansal.xyz/content-like-wtfpython/). From 56c0347dd1596bf3f96d294e22ade14fe6004e12 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 20 Dec 2019 23:56:35 +0530 Subject: [PATCH 122/221] Minor correction --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 67957cc5..a068090b 100644 --- a/README.md +++ b/README.md @@ -161,14 +161,17 @@ $ wtfpython -For some reason, the "Walrus" operator (`:=`) has become a popular feature in the language. Let's check it out, +For some reason, the Python 3.8's "Walrus" operator (`:=`) has become quite popular. Let's check it out, 1\. ```py +# Python version 3.8+ + >>> a = "wtf_walrus" >>> a 'wtf_walrus' + >>> a := "wtf_walrus" File "", line 1 a := "wtf_walrus" @@ -183,6 +186,8 @@ SyntaxError: invalid syntax 2 \. ```py +# Python version 3.8+ + >>> a = 6, 9 >>> a (6, 9) From 49ed35e0996f2c5af725970a0499807fe4697299 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 21 Dec 2019 00:16:19 +0530 Subject: [PATCH 123/221] Add hosted notebook instructions --- irrelevant/notebook_generator.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/irrelevant/notebook_generator.py b/irrelevant/notebook_generator.py index 2c77a6eb..d9818b3f 100644 --- a/irrelevant/notebook_generator.py +++ b/irrelevant/notebook_generator.py @@ -32,6 +32,27 @@ STATEMENT_PREFIXES = ["...", ">>> ", "$ "] +HOSTED_NOTEBOOK_INSTRUCTIONS = """ + +# Hosted notebook instructions + +This is just an experimental attempt of browsing wtfpython through jupyter notebooks. Some examples are read-only because, +- they either require a version of Python that's not supported in the hosted runtime. +- or they can't be reproduced in the notebook envrinonment. + +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 + +```py +>>> import sys +>>> sys.version +# Prints out Python version here. +``` + +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! + +--- +""" + def generate_code_block(statements, output): global sequence_num @@ -255,7 +276,7 @@ def convert_to_notebook(pre_examples_content, parsed_json, post_examples_content "nbformat_minor": 2 } - notebook_path = "test.ipynb" + notebook_path = "wtf.ipynb" result["cells"] += convert_to_cells([generate_markdown_block(pre_examples_content)], False) @@ -328,4 +349,5 @@ def convert_to_notebook(pre_examples_content, parsed_json, post_examples_content except StopIteration as e: #pprint.pprint(result, indent=2) + pre_stuff.append(HOSTED_NOTEBOOK_INSTRUCTIONS) convert_to_notebook(pre_stuff, result, post_stuff) From 1b1a5bc10d869163f8e3089146f1f4aa1acdc629 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 21 Dec 2019 00:16:34 +0530 Subject: [PATCH 124/221] Add generated notebook --- irrelevant/wtf.ipynb | 12427 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 12427 insertions(+) create mode 100644 irrelevant/wtf.ipynb diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb new file mode 100644 index 00000000..64e315b7 --- /dev/null +++ b/irrelevant/wtf.ipynb @@ -0,0 +1,12427 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

\"\"

\n", + "

What the f*ck Python! 🐍

\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 \"\", line 1\n", + " a := \"wtf_walrus\"\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a := \"wtf_walrus\") # This works though\n", + ">>> a\n", + "```\n", + "```py\n", + "'wtf_walrus'\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2 \\.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "# Python version 3.8+\n", + "\n", + ">>> a = 6, 9\n", + ">>> a\n", + "```\n", + "```py\n", + "(6, 9)\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a := 6, 9)\n", + ">>> a\n", + "```\n", + "```py\n", + "6\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> a, b = 6, 9 # Typcial unpacking\n", + ">>> a, b\n", + "```\n", + "```py\n", + "(6, 9)\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a, b = 16, 19) # Oops\n", + "```\n", + "```py\n", + " File \"\", line 1\n", + " (a, b = 6, 9)\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a, b := 16, 19) # This prints out a weird 3-tuple\n", + "```\n", + "```py\n", + "(6, 16, 19)\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> a # a is still unchanged?\n", + "```\n", + "```py\n", + "6\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> b\n", + "```\n", + "```py\n", + "16\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "\n", + "**Quick walrus operator refresher**\n", + "\n", + "The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "def some_func():\n", + " # Assume some expensive computation here\n", + " # time.sleep(1000)\n", + " return 5\n", + "\n", + "# So instead of,\n", + "if some_func():\n", + " print(some_func()) # Which is bad practice since computation is happening twice\n", + "\n", + "# or\n", + "a = some_func()\n", + "if a:\n", + " print(a)\n", + "\n", + "# Now you can concisely write\n", + "if a := some_func():\n", + " print(a)\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (> 3.8):**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "5\n", + "5\n", + "5\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "This 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, hence the `SyntaxError` in the `a := \"wtf_walrus\"` statement of the first snippet. Parenthesizing it worked as expected and assigned `a`. \n", + "\n", + "- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. \n", + "\n", + "- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", + "\n", + " - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6')\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> (a := 6, 9) == ((a := 6), 9)\n", + "```\n", + "```py\n", + " True\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> x = (a := 696, 9)\n", + " >>> x\n", + "```\n", + "```py\n", + " (696, 9)\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> x[0] is a # Both reference same memory location\n", + "```\n", + "```py\n", + " True\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Strings can be tricky sometimes\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140420665652016\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = \"some_string\"\n", + "id(a)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140420665652016\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "id(\"some\" + \"_\" + \"string\") # Notice that both the ids are same.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = \"wtf\"\n", + "b = \"wtf\"\n", + "a is b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = \"wtf!\"\n", + "b = \"wtf!\"\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a, b = \"wtf!\", \"wtf!\"\n", + "a is b # All versions except 3.7.x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = \"wtf!\"; b = \"wtf!\"\n", + "a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "# This time in file some_file.py\n", + "a = \"wtf!\"\n", + "b = \"wtf!\"\n", + "print(a is b)\n", + "\n", + "# prints True when the module is invoked!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "4\\.\n", + "\n", + "**Output (< Python3.7 )**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Makes sense, right?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "+ The behavior in first and second snippets is due to a CPython optimization (called string interning) 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 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. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", + " ![image](/images/string-intern/string_intern.png)\n", + "+ When `a` and `b` are set to `\"wtf!\"` 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 `wtf!` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", + "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, 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 [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.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 with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Hash brownies\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_dict = {}\n", + "some_dict[5.5] = \"JavaScript\"\n", + "some_dict[5.0] = \"Ruby\"\n", + "some_dict[5] = \"Python\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"JavaScript\"\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_dict[5.5]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"Python\"\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"Python\"\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_dict[5] \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "complex\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "complex_five = 5 + 0j\n", + "type(complex_five)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"Python\"\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_dict[complex_five]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "So, why is Python all over the place?\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "\n", + "* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.\n", + "* Immutable objects with the same value always have the same hash in Python.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " 5 == 5.0 == 5 + 0j\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " hash(5) == hash(5.0) == hash(5 + 0j)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Note:** Objects with different values may also have same hash (known as [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science))).\n", + "* When the statement `some_dict[5] = \"Python\"` is executed, the existing value \"Ruby\" is overwritten with \"Python\" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`.\n", + "* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains the rationale behind it.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Deep down, we're all the same.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "class WTF:\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "WTF() == WTF() # two different instances can't be equal\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "WTF() is WTF() # identities are also different\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "id(WTF()) == id(WTF())\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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 evaluated to `False`? Let's see with this snippet.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " class WTF(object):\n", + " def __init__(self): print(\"I\")\n", + " def __del__(self): print(\"D\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " I\n", + " I\n", + " D\n", + " D\n", + " False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " WTF() is WTF()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " I\n", + " D\n", + " I\n", + " D\n", + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " id(WTF()) == id(WTF())\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " As you may observe, the order in which the objects are destroyed is what made all the difference here.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Disorder within order *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from collections import OrderedDict\n", + "\n", + "dictionary = dict()\n", + "dictionary[1] = 'a'; dictionary[2] = 'b';\n", + "\n", + "ordered_dict = OrderedDict()\n", + "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", + "\n", + "another_ordered_dict = OrderedDict()\n", + "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", + "\n", + "class DictWithHash(dict):\n", + " \"\"\"\n", + " A dict that also implements __hash__ magic.\n", + " \"\"\"\n", + " __hash__ = lambda self: 0\n", + "\n", + "class OrderedDictWithHash(OrderedDict):\n", + " \"\"\"\n", + " An OrderedDict that also implements __hash__ magic.\n", + " \"\"\"\n", + " __hash__ = lambda self: 0\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary == ordered_dict # If a == b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "dictionary == another_ordered_dict # and b == c\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\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" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ordered_dict == another_ordered_dict # the why isn't c == a ??\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "TypeError: unhashable type: 'dict'\n", + "\n", + "# Makes sense since dict don't have __hash__ implemented, let's use\n", + "# our wrapper classes.\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len({dictionary, ordered_dict, another_ordered_dict})\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "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})\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "2\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "What is going on here?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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://docs.python.org/3/library/collections.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", + "- The reason for this equality is 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 lenght 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_set = set()\n", + " some_set.add(dictionary) # these are the mapping objects from the snippets above\n", + " ordered_dict in some_set\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 1\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_set.add(ordered_dict)\n", + " len(some_set)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " another_ordered_dict in some_set\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 1\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_set.add(another_ordered_dict)\n", + " len(some_set)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " another_set = set()\n", + " another_set.add(ordered_dict)\n", + " another_ordered_dict in another_set\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 2\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " another_set.add(another_ordered_dict)\n", + " len(another_set)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " dictionary in another_set\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 2\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " another_set.add(another_ordered_dict)\n", + " len(another_set)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Keep trying... *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def some_func():\n", + " try:\n", + " return 'from_try'\n", + " finally:\n", + " return 'from_finally'\n", + "\n", + "def another_func(): \n", + " for _ in range(3):\n", + " try:\n", + " continue\n", + " finally:\n", + " print(\"Finally!\")\n", + "\n", + "def one_more_func(): # A gotcha!\n", + " try:\n", + " for i in range(3):\n", + " try:\n", + " 1 / 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 ocurred\", e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'from_finally'\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Finally!\n", + "Finally!\n", + "Finally!\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "another_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "ZeroDivisionError: division by zero\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1 / 0\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Iteration 0\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "one_more_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ For what?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_string = \"wtf\"\n", + "some_dict = {}\n", + "for i, some_dict[i] in enumerate(some_string):\n", + " i = 10\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{0: 'w', 1: 't', 2: 'f'}\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_dict # An indexed dict appears.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as:\n", + " ```\n", + " for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " for i in range(4):\n", + " print(i)\n", + " i = 10\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\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)` 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " i, some_dict[i] = (0, 'w')\n", + " i, some_dict[i] = (1, 't')\n", + " i, some_dict[i] = (2, 'f')\n", + " some_dict\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Evaluation time discrepancy\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "array = [1, 8, 15]\n", + "# A typical generator expresion\n", + "gen = (x for x in array if array.count(x) > 0)\n", + "array = [2, 8, 22]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[8]\n" + ] + } + ], + "source": [ + "print(list(gen)) # Where did the other values go?\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "array_1 = [1,2,3,4]\n", + "gen_1 = (x for x in array_1)\n", + "array_1 = [1,2,3,4,5]\n", + "\n", + "array_2 = [1,2,3,4]\n", + "gen_2 = (x for x in array_2)\n", + "array_2[:] = [1,2,3,4,5]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4]\n", + "\n" + ] + } + ], + "source": [ + "print(list(gen_1))\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5]\n" + ] + } + ], + "source": [ + "print(list(gen_2))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "array_3 = [1, 2, 3]\n", + "array_4 = [10, 20, 30]\n", + "gen = (i + j for i in array_3 for j in array_4)\n", + "\n", + "array_3 = [4, 5, 6]\n", + "array_4 = [400, 500, 600]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[401, 501, 601, 402, 502, 602, 403, 503, 603]\n" + ] + } + ], + "source": [ + "print(list(gen))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "\n", + "- In a [generator](https://wiki.python.org/moin/Generators) 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 binded 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(g)` 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://www.python.org/dev/peps/pep-0289/#the-details)\n", + " \n", + " > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ How not to use `is` operator\n", + "The following is a very famous example present all over the internet.\n", + "\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 256\n", + "b = 256\n", + "a is b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 257\n", + "b = 257\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = []\n", + "b = []\n", + "a is b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = tuple()\n", + "b = tuple()\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "**Output**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a, b = 257, 257\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.7.x specifically)**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + ">> a is b\n", + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a, b = 257, 257\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " class A: pass\n", + " A() is A() # These are two empty objects at two different memory locations.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**`256` is an existing object but `257` isn't**\n", + "\n", + "When 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", + "\n", + "Quoting from https://docs.python.org/3/c-api/long.html\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10922528\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "id(256)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10922528\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 256\n", + "b = 256\n", + "id(a)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10922528\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "id(b)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140084850247312\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "id(257)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140084850247440\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x = 257\n", + "y = 257\n", + "id(x)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140084850247344\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "id(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Here 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", + "\n", + "Similar 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140640774013296\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a, b = 257, 257\n", + "id(a)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140640774013296\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "id(b)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140640774013392\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 257\n", + "b = 257\n", + "id(a)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140640774013488\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "id(b)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " a, b = 257.0, 257.0\n", + " a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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://github.com/satwikkansal/wtfpython/issues/100) for updates.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ `is not ...` is not `is (not ...)`\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'something' is not None\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'something' is (not None)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ A tic-tac-toe where X wins in the first attempt!\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Let's initialize a row\n", + "row = [\"\"] * 3 #row i['', '', '']\n", + "# Let's make a board\n", + "board = [row] * 3\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[['', '', ''], ['', '', ''], ['', '', '']]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "board\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['', '', '']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "board[0]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "''\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "board[0][0]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[['X', '', ''], ['X', '', ''], ['X', '', '']]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "board[0][0] = \"X\"\n", + "board\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "We didn't assign three `\"X\"`s, did we?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "When we initialize `row` variable, this visualization explains what happens in the memory\n", + "\n", + "![image](/images/tic-tac-toe/after_row_initialized.png)\n", + "\n", + "And 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", + "![image](/images/tic-tac-toe/after_board_initialized.png)\n", + "\n", + "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[['X', '', ''], ['', '', ''], ['', '', '']]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "board = [['']*3 for _ in range(3)]\n", + "board[0][0] = \"X\"\n", + "board\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ The sticky output function\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "funcs = []\n", + "results = []\n", + "for 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", + "\n", + "funcs_results = [func() for func in funcs]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "results\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[6, 6, 6, 6, 6, 6, 6]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "funcs_results\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.\n", + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "powers_of_x = [lambda x: x**i for i in range(10)]\n", + "[f(2) for f in powers_of_x]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "\n", + "- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.\n", + "\n", + "- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " funcs = []\n", + " for x in range(7):\n", + " def some_func(x=x):\n", + " return x\n", + " funcs.append(some_func)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [0, 1, 2, 3, 4, 5, 6]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " funcs_results = [func() for func in funcs]\n", + " funcs_results\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ The chicken-egg problem *\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "isinstance(3, int)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "isinstance(type, object)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "isinstance(object, type)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "So which is the \"ultimate\" base class? There's more to the confusion by the way,\n", + "\n", + "2\\. \n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "class A: pass\n", + "isinstance(A, A)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "isinstance(type, type)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "isinstance(object, object)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "issubclass(int, object)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "issubclass(type, object)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "issubclass(object, type)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "\n", + "- `type` is a [metaclass](https://realpython.com/python-metaclasses/) 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Subclass relationships\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from collections import Hashable\n", + "issubclass(list, object)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "issubclass(object, Hashable)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "issubclass(list, Hashable)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "The 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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://www.naftaliharris.com/blog/python-subclass-intransitivity/).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ All-true-ation *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "all([True, True, True])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "all([True, True, False])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "all([])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "all([[]])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "all([[[]]])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Why's this True-False alteration?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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 `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty.\n", + "- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ The surprising comma\n", + "**Output (< 3.6):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"\", line 1\n", + " def h(x, **kwargs,):\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"\", line 1\n", + " def h(*args,):\n", + " ^\n", + "SyntaxError: invalid syntax\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def h(*args,):\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Strings and the backslashes\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\"\n", + "\n" + ] + } + ], + "source": [ + "print(\"\\\"\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\\\"\n", + "\n" + ] + } + ], + "source": [ + "print(r\"\\\"\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "File \"\", line 1\n", + " print(r\"\\\")\n", + " ^\n", + "SyntaxError: EOL while scanning string literal\n", + "\n" + ] + } + ], + "source": [ + "print(r\"\\\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "r'\\'' == \"\\\\'\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 'wt\"f'\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " 'wt\\\"f'\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " r'wt\\\"f' == 'wt\\\\\"f'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 'wt\\\\\"f'\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " print(repr(r'wt\\\"f')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " print(\"\\n\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " '\\\\\\\\n'\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " print(r\"\\\\n\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ not knot!\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x = True\n", + "y = False\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "not x == y\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"\", line 1\n", + " x == not y\n", + " ^\n", + "SyntaxError: invalid syntax\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x == not y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Half triple-quoted strings\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "wtfpython\n" + ] + } + ], + "source": [ + "print('wtfpython''')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "wtfpython\n" + ] + } + ], + "source": [ + "print(\"wtfpython\"\"\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"\", line 3\n", + " print(\"\"\"wtfpython\")\n", + " ^\n", + "SyntaxError: EOF while scanning triple-quoted string literal\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# The following statements raise `SyntaxError`\n", + "# print('''wtfpython')\n", + "# print(\"\"\"wtfpython\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "+ Python supports implicit [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation), Example,\n", + " ```\n", + " >>> print(\"wtf\" \"python\")\n", + " wtfpython\n", + " >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n", + " wtf\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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ What's wrong with booleans?\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# A simple example to count the number of booleans and\n", + "# integers in an iterable of mixed data types.\n", + "mixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\n", + "integers_found_so_far = 0\n", + "booleans_found_so_far = 0\n", + "\n", + "for 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "integers_found_so_far\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "booleans_found_so_far\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'wtf'\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_bool = True\n", + "\"wtf\" * some_bool\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "''\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_bool = False\n", + "\"wtf\" * some_bool\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def tell_truth():\n", + " True = False\n", + " if True == False:\n", + " print(\"I have lost faith in truth!\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (< 3.x):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "I have lost faith in truth!\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "tell_truth()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* `bool` is a subclass of `int` in Python\n", + " \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " issubclass(bool, int)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " issubclass(int, bool)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " \n", + "* And thus, `True` and `False` are instances of `int`\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " isinstance(True, int)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " isinstance(False, int)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* The integer value of `True` is `1` and that of `False` is `0`.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 1\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " int(True)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 0\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " int(False)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Class attributes and instance attributes\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "class A:\n", + " x = 1\n", + "\n", + "class B(A):\n", + " pass\n", + "\n", + "class C(A):\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(1, 1, 1)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A.x, B.x, C.x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(1, 2, 1)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "B.x = 2\n", + "A.x, B.x, C.x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(3, 2, 3)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A.x = 3\n", + "A.x, B.x, C.x # C.x changed, but B.x didn't\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(3, 3)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = A()\n", + "a.x, A.x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(4, 3)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a.x += 1\n", + "a.x, A.x\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "class 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 420]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_obj = SomeClass(420)\n", + "some_obj.some_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 420]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_obj.another_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 111]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "another_obj = SomeClass(111)\n", + "another_obj.some_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 420, 111]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "another_obj.another_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "another_obj.another_list is SomeClass.another_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "another_obj.another_list is some_obj.another_list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Non-reflexive class method *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "class SomeClass:\n", + " def instance_method(self):\n", + " pass\n", + " \n", + " @classmethod\n", + " def class_method(cls):\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "SomeClass.instance_method is SomeClass.instance_method\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "SomeClass.class_method is SomeClass.class_method\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "id(SomeClass.class_method) == id(SomeClass.class_method)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "- The reason `SomeClass.class_method is SomeClass.class_method` is `False` is due to the `@classmethod` decorator. \n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " \n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " SomeClass.instance_method\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " \n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " SomeClass.class_method\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " A new bound method every time `SomeClass.class_method` is accessed.\n", + "\n", + "- `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ yielding None\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_iterable = ('a', 'b')\n", + "\n", + "def some_func(val):\n", + " return \"something\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (<= 3.7.x):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[x for x in some_iterable]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " at 0x7f70b0a4ad58>\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[(yield x) for x in some_iterable]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list([(yield x) for x in some_iterable])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', None, 'b', None]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list((yield x) for x in some_iterable)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'something', 'b', 'something']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(some_func((yield x)) for x in some_iterable)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n", + "- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n", + "- Related bug report: http://bugs.python.org/issue10544\n", + "- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Yielding from... return! *\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def some_func(x):\n", + " if x == 3:\n", + " return [\"wtf\"]\n", + " else:\n", + " yield from range(x)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (> 3.3):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(some_func(3))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Where did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n", + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def some_func(x):\n", + " if x == 3:\n", + " return [\"wtf\"]\n", + " else:\n", + " for i in range(x):\n", + " yield i\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(some_func(3))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "The same result, this didn't work either.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " try:\n", + " next(some_func(3))\n", + " except StopIteration as e:\n", + " some_string = e.value\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [\"wtf\"]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_string\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Nan-reflexivity *\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = float('inf')\n", + "b = float('nan')\n", + "c = float('-iNf') # These strings are case-insensitive\n", + "d = float('nan')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "inf\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "nan\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "-inf\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "ValueError: could not convert string to float: some_other_string\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "float('some_other_string')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a == -c # inf==inf\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "None == None # None == None\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b == d # but nan!=nan\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.0\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "50 / a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "nan\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a / a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "nan\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "23 + b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x = float('nan')\n", + "y = x / x\n", + "y is y # identity holds\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "y == y # equality fails of y\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[y] == [y] # but the equality succeeds for the list containing y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (False, True)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " x = float('nan')\n", + " x == x, [x] == [x]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (False, True)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " y = float('nan')\n", + " y == y, [y] == [y]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (False, False)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " x == y, [x] == [y]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Mutating the immutable!\n", + "This might seem trivial if you know how references work in Python.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_tuple = (\"A\", \"tuple\", \"with\", \"values\")\n", + "another_tuple = ([1, 2], [3, 4], [5, 6])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "TypeError: 'tuple' object does not support item assignment\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_tuple[2] = \"change this\"\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "([1, 2], [3, 4], [5, 6, 1000])\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "another_tuple[2].append(1000) #This throws no error\n", + "another_tuple\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "TypeError: 'tuple' object does not support item assignment\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "another_tuple[2] += [99, 999]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "another_tuple\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "But I thought tuples were immutable...\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* Quoting from https://docs.python.org/2/reference/datamodel.html\n", + "\n", + " > Immutable sequences\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", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ The disappearing variable from outer scope\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "e = 7\n", + "try:\n", + " raise Exception()\n", + "except Exception as e:\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "# prints nothing\n" + ] + } + ], + "source": [ + "print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "NameError: name 'e' is not defined\n" + ] + } + ], + "source": [ + "print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* Source: https://docs.python.org/3/reference/compound_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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " except E as N:\n", + " foo\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " was translated into\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " except E as N:\n", + " try:\n", + " foo\n", + " finally:\n", + " del N\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " def f(x):\n", + " del(x)\n", + " print(x)\n", + "\n", + " x = 5\n", + " y = [5, 4, 3]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 5\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " >>>f(x)\n", + " UnboundLocalError: local variable 'x' referenced before assignment\n", + " >>>f(y)\n", + " UnboundLocalError: local variable 'x' referenced before assignment\n", + " x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [5, 4, 3]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Exception()\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " e\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " # Nothing is printed!\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " print e\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ The mysterious key type conversion\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "class SomeClass(str):\n", + " pass\n", + "\n", + "some_dict = {'s': 42}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(list(some_dict.keys())[0])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{'s': 40}\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s = SomeClass('s')\n", + "some_dict[s] = 40\n", + "some_dict # expected: Two different keys-value pairs\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(list(some_dict.keys())[0])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " {'s': 40, 's': 42}\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " s = SomeClass('s')\n", + " some_dict[s] = 40\n", + " some_dict\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (__main__.SomeClass, str)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " keys = list(some_dict.keys())\n", + " type(keys[0]), type(keys[1])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Let's see if you can guess this?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a, b = a[b] = {}, 5\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{5: ({...}, 5)}\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form\n", + " ```\n", + " (target_list \"=\")+ (expression_list | yield_expression)\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [[...]]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_list = some_list[0] = [0]\n", + " some_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [[...]]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_list[0]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_list is some_list[0]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_list[0][0][0][0][0][0] == some_list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " a, b = {}, 5\n", + " a[b] = a, b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " a[b][0] is a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Modifying a dictionary while iterating over it\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x = {0: None}\n", + "\n", + "for i in x:\n", + " del x[i]\n", + " x[i+1] = None\n", + " print(i)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.7- Python 3.5):**\n", + "\n", + "```\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "```\n", + "\n", + "Yes, it runs for exactly **eight** times and stops.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* Iteration over a dictionary that you edit at the same time is not supported.\n", + "* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.\n", + "* How deleted keys are handled and when the resize occurs might be different for different Python implementations.\n", + "* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread.\n", + "* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Stubborn `del` operation\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "class SomeClass:\n", + " def __del__(self):\n", + " print(\"Deleted!\")\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "1\\.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> x = SomeClass()\n", + ">>> y = x\n", + ">>> del x # this should print \"Deleted!\"\n", + ">>> del y\n", + "```\n", + "```py\n", + "Deleted!\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.\n", + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> x = SomeClass()\n", + ">>> y = x\n", + ">>> del x\n", + ">>> y # check if y exists\n", + "```\n", + "```py\n", + "<__main__.SomeClass instance at 0x7f98a1a67fc8>\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> del y # Like previously, this should print \"Deleted!\"\n", + ">>> globals() # oh, it didn't. Let's check all our global variables and confirm\n", + "```\n", + "```py\n", + "Deleted!\n", + "{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None}\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Okay, now it's deleted :confused:\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "+ `del x` doesn’t directly call `x.__del__()`.\n", + "+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero.\n", + "+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.\n", + "+ Calling `globals` caused the existing reference to be destroyed, and hence we can see \"Deleted!\" being printed (finally!).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ The out of scope variable\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 1\n", + "def some_func():\n", + " return a\n", + "\n", + "def another_func():\n", + " a += 1\n", + " return a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "UnboundLocalError: local variable 'a' referenced before assignment\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "another_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.\n", + "* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.\n", + "* To modify the outer scope variable `a` in `another_func`, use `global` keyword.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " def another_func()\n", + " global a\n", + " a += 1\n", + " return a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 2\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " another_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Deleting a list item while iterating\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list_1 = [1, 2, 3, 4]\n", + "list_2 = [1, 2, 3, 4]\n", + "list_3 = [1, 2, 3, 4]\n", + "list_4 = [1, 2, 3, 4]\n", + "\n", + "for idx, item in enumerate(list_1):\n", + " del item\n", + "\n", + "for idx, item in enumerate(list_2):\n", + " list_2.remove(item)\n", + "\n", + "for idx, item in enumerate(list_3[:]):\n", + " list_3.remove(item)\n", + "\n", + "for idx, item in enumerate(list_4):\n", + " list_4.pop(idx)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list_1\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 4]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list_2\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list_3\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 4]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list_4\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Can you guess why the output is `[2, 4]`?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 139798789457608\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_list = [1, 2, 3, 4]\n", + " id(some_list)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 139798779601192\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " id(some_list[:]) # Notice that python creates new object for sliced list.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Difference between `del`, `remove`, and `pop`:**\n", + "* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).\n", + "* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.\n", + "* `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified.\n", + "\n", + "**Why the output is `[2, 4]`?**\n", + "- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.\n", + "\n", + "* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example\n", + "* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Lossy zip of iterators *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "numbers = list(range(7))\n", + "numbers\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "([0, 1, 2], [3, 4, 5, 6])\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "first_three, remaining = numbers[:3], numbers[3:]\n", + "first_three, remaining\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[(0, 0), (1, 1), (2, 2)]\n", + "# so far so good, let's zip the remaining\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "numbers_iter = iter(numbers)\n", + "list(zip(numbers_iter, first_three)) \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[(4, 3), (5, 4), (6, 5)]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(zip(numbers_iter, remaining))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Where did element `3` go from the `numbers` list?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " def zip(*iterables):\n", + " sentinel = object()\n", + " iterators = [iter(it) for it in iterables]\n", + " while iterators:\n", + " result = []\n", + " for it in iterators:\n", + " elem = next(it, sentinel)\n", + " if elem is sentinel: return\n", + " result.append(elem)\n", + " yield tuple(result)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. \n", + "- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.\n", + "- The correct way to do the above using `zip` would be,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [(0, 0), (1, 1), (2, 2)]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " numbers = list(range(7))\n", + " numbers_iter = iter(numbers)\n", + " list(zip(first_three, numbers_iter))\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [(3, 3), (4, 4), (5, 5), (6, 6)]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " list(zip(remaining, numbers_iter))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " The first argument of zip should be the one with fewest elements.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Loop variables leaking out!\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "for x in range(7):\n", + " if x == 6:\n", + " print(x, ': for x inside loop')\n", + "print(x, ': x in global')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "6 : for x inside loop\n", + "6 : x in global\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "But `x` was never defined outside the scope of for loop...\n", + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "# This time let's initialize x first\n", + "x = -1\n", + "for x in range(7):\n", + " if x == 6:\n", + " print(x, ': for x inside loop')\n", + "print(x, ': x in global')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "6 : for x inside loop\n", + "6 : x in global\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 2, 3, 4]\n" + ] + } + ], + "source": [ + "x = 1\n", + "print([x for x in range(5)])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n" + ] + } + ], + "source": [ + "print(x)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 2, 3, 4]\n" + ] + } + ], + "source": [ + "x = 1\n", + "print([x for x in range(5)])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n" + ] + } + ], + "source": [ + "print(x)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.\n", + "\n", + "- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog:\n", + "\n", + " > \"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.\"\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Beware of default mutable arguments!\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def some_func(default_arg=[]):\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string', 'some_string']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_func([])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string', 'some_string', 'some_string']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " def some_func(default_arg=[]):\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ([],)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_func.__defaults__ #This will show the default argument values for the function\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string'],)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_func()\n", + " some_func.__defaults__\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string', 'some_string'],)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_func()\n", + " some_func.__defaults__\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string', 'some_string'],)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_func([])\n", + " some_func.__defaults__\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " def some_func(default_arg=None):\n", + " if not default_arg:\n", + " default_arg = []\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Catching the Exceptions\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_list = [1, 2, 3]\n", + "try:\n", + " # This should raise an ``IndexError``\n", + " print(some_list[4])\n", + "except IndexError, ValueError:\n", + " print(\"Caught!\")\n", + "\n", + "try:\n", + " # This should raise a ``ValueError``\n", + " some_list.remove(4)\n", + "except IndexError, ValueError:\n", + " print(\"Caught again!\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Caught!\n", + "\n", + "ValueError: list.remove(x): x not in list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " File \"\", line 3\n", + " except IndexError, ValueError:\n", + " ^\n", + "SyntaxError: invalid syntax\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "\n", + "* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_list = [1, 2, 3]\n", + " try:\n", + " # This should raise a ``ValueError``\n", + " some_list.remove(4)\n", + " except (IndexError, ValueError), e:\n", + " print(\"Caught again!\")\n", + " print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Output (Python 2.x):**\n", + " ```\n", + " Caught again!\n", + " list.remove(x): x not in list\n", + " ```\n", + " **Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " File \"\", line 4\n", + " except (IndexError, ValueError), e:\n", + " ^\n", + " IndentationError: unindent does not match any outer indentation level\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " some_list = [1, 2, 3]\n", + " try:\n", + " some_list.remove(4)\n", + "\n", + " except (IndexError, ValueError) as e:\n", + " print(\"Caught again!\")\n", + " print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Output:**\n", + " ```\n", + " Caught again!\n", + " list.remove(x): x not in list\n", + " ```\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Same operands, different story!\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = [1, 2, 3, 4]\n", + "b = a\n", + "a = a + [5, 6, 7, 8]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = [1, 2, 3, 4]\n", + "b = a\n", + "a += [5, 6, 7, 8]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this.\n", + "\n", + "* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged.\n", + "\n", + "* The expression `a += [5,6,7,8]` is actually mapped to an \"extend\" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Be careful with chained operations\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "(False == False) in [False] # makes sense\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "False == (False in [False]) # makes sense\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "False == False in [False] # now what?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "True is False == False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "False is False is False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1 > 0 < 1\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "(1 > 0) < 1\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1 > (0 < 1)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "As per https://docs.python.org/2/reference/expressions.html#not-in\n", + "\n", + "> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.\n", + "\n", + "While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 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` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n", + "* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`.\n", + "* The expression `(1 > 0) < 1` is equivalent to `True < 1` and\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 1\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " int(True)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 2\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " True + 1 #not relevant for this example, but just for fun\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " So, `1 < 1` evaluates to `False`\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Name resolution ignoring class scope\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x = 5\n", + "class SomeClass:\n", + " x = 17\n", + " y = (x for i in range(10))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(SomeClass.y)[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x = 5\n", + "class SomeClass:\n", + " x = 17\n", + " y = [x for i in range(10)]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "17\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "SomeClass.y[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "SomeClass.y[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "- Scopes nested inside class definition ignore names bound at the class level.\n", + "- A generator expression has its own scope.\n", + "- Starting from Python 3.X, list comprehensions also have their own scope.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Needles in a Haystack *\n", + "I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios,\n", + "\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x, y = (0, 1) if True else None, None\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "((0, 1), None)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x, y # expected (0, 1)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "t = ('one', 'two')\n", + "for i in t:\n", + " print(i)\n", + "\n", + "t = ('one')\n", + "for i in t:\n", + " print(i)\n", + "\n", + "t = ()\n", + "print(t)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "one\n", + "two\n", + "o\n", + "n\n", + "e\n", + "tuple()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n", + "```\n", + "ten_words_list = [\n", + " \"some\",\n", + " \"very\",\n", + " \"big\",\n", + " \"list\",\n", + " \"that\"\n", + " \"consists\",\n", + " \"of\",\n", + " \"exactly\",\n", + " \"ten\",\n", + " \"words\"\n", + "]\n", + "```\n", + "\n", + "**Output**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "9\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len(ten_words_list)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "4\\. Not asserting strongly enough\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = \"python\"\n", + "b = \"javascript\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "# No AssertionError is raised\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# An assert statement with an assertion failure message.\n", + "assert(a == b, \"Both languages are different\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "5\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_list = [1, 2, 3]\n", + "some_dict = {\n", + " \"key_1\": 1,\n", + " \"key_2\": 2,\n", + " \"key_3\": 3\n", + "}\n", + "\n", + "some_list = some_list.append(4) \n", + "some_dict = some_dict.update({\"key_4\": 4})\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "print(some_list)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "print(some_dict)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "6\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def some_recursive_func(a):\n", + " if a[0] == 0:\n", + " return \n", + " a[0] -= 1\n", + " some_recursive_func(a)\n", + " return a\n", + "\n", + "def similar_recursive_func(a):\n", + " if a == 0:\n", + " return a\n", + " a -= 1\n", + " similar_recursive_func(a)\n", + " return a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 0]\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_recursive_func([5, 0])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "similar_recursive_func(5)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`.\n", + "\n", + "* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character.\n", + "\n", + "* `()` is a special token and denotes empty `tuple`.\n", + "\n", + "* In 3, as you might have already figured out, there's a missing comma after 5th element (`\"that\"`) in the list. So by implicit string literal concatenation,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " ten_words_list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " AssertionError\n", + " \n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " a = \"python\"\n", + " b = \"javascript\"\n", + " assert a == b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " :1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n", + " \n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " assert (a == b, \"Values are not equal\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " AssertionError: Values aren not equal\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " assert a == b, \"Values are not equal\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).\n", + "\n", + "* Last one should be fairly obvious, passing mutable object (like `list` ) results in a call by reference, whereas an immutable object (like `int`) results in a call by value.\n", + "\n", + "* Being aware of these nitpicks can save you hours of debugging effort in the long run. \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Splitsies *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a']\n", + "\n", + "# is same as\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'a'.split()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a']\n", + "\n", + "# but\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'a'.split(' ')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0\n", + "\n", + "# isn't the same as\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len(''.split())\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len(''.split(' '))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split)\n", + " > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.\n", + " > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.\n", + "- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['', 'a', '']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " ' a '.split(' ')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['a']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " ' a '.split()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['']\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " ''.split(' ')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Wild imports *\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "# File: module.py\n", + "\n", + "def some_weird_name_func_():\n", + " print(\"works!\")\n", + "\n", + "def _another_weird_name_func():\n", + " print(\"works!\")\n", + "\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> from module import *\n", + ">>> some_weird_name_func_()\n", + "```\n", + "```py\n", + "\"works!\"\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> _another_weird_name_func()\n", + "```\n", + "```py\n", + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "NameError: name '_another_weird_name_func' is not defined\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime.\n", + "- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> from module import some_weird_name_func_, _another_weird_name_func\n", + " >>> _another_weird_name_func()\n", + "```\n", + "```py\n", + " works!\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " __all__ = ['_another_weird_name_func']\n", + "\n", + " def some_weird_name_func_():\n", + " print(\"works!\")\n", + "\n", + " def _another_weird_name_func():\n", + " print(\"works!\")\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Output**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> _another_weird_name_func()\n", + "```\n", + "```py\n", + " \"works!\"\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> some_weird_name_func_()\n", + "```\n", + "```py\n", + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " NameError: name 'some_weird_name_func_' is not defined\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ All sorted? *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x = 7, 8, 9\n", + "sorted(x) == x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sorted(x) == sorted(x)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "y = reversed(x)\n", + "sorted(y) == sorted(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. \n", + "\n", + "- ```py\n", + " >>> [] == tuple()\n", + " False\n", + " >>> x = 7, 8, 9\n", + " >>> type(x), type(sorted(x))\n", + " (tuple, list)\n", + " ```\n", + "\n", + "- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first.\n", + "\n", + "- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ([7, 8, 9], [])\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " x = 7, 8, 9\n", + " y = reversed(x)\n", + " sorted(y), sorted(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Midnight time doesn't exist?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from datetime import datetime\n", + "\n", + "midnight = datetime(2018, 1, 1, 0, 0)\n", + "midnight_time = midnight.time()\n", + "\n", + "noon = datetime(2018, 1, 1, 12, 0)\n", + "noon_time = noon.time()\n", + "\n", + "if midnight_time:\n", + " print(\"Time at midnight is\", midnight_time)\n", + "\n", + "if noon_time:\n", + " print(\"Time at noon is\", noon_time)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (< 3.5):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "('Time at noon is', datetime.time(12, 0))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The midnight time is not printed.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of \"empty.\"\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Okay Python, Can you make me fly?\n", + "Well, here you go\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import antigravity\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "Sshh... It's a super-secret.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "+ `antigravity` module is one of the few easter eggs released by Python developers.\n", + "+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python.\n", + "+ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ `goto`, but why?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "from goto import goto, label\n", + "for i in range(9):\n", + " for j in range(9):\n", + " for k in range(9):\n", + " print(\"I am trapped, please rescue!\")\n", + " if k == 2:\n", + " goto .breakout # breaking out from a deeply nested loop\n", + "label .breakout\n", + "print(\"Freedom!\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.3):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "I am trapped, please rescue!\n", + "I am trapped, please rescue!\n", + "Freedom!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004.\n", + "- Current versions of Python do not have this module.\n", + "- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Brace yourself!\n", + "If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from __future__ import braces\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " File \"some_file.py\", line 1\n", + " from __future__ import braces\n", + "SyntaxError: not a chance\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "+ The `__future__` module is normally used to provide features from future versions of Python. The \"future\" in this specific context is however, ironic.\n", + "+ This is an easter egg concerned with the community's feelings on this issue.\n", + "+ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file.\n", + "+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Let's meet Friendly Language Uncle For Life\n", + "**Output (Python 3.x)**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"some_file.py\", line 1\n", + " \"Ruby\" != \"Python\"\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from __future__ import barry_as_FLUFL\n", + "\"Ruby\" != \"Python\" # there's no doubt about it\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"Ruby\" <> \"Python\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "There we go.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means).\n", + "- Quoting from the PEP-401\n", + " \n", + " > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.\n", + "- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/).\n", + "- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " from __future__ import barry_as_FLUFL\n", + " print(eval('\"Ruby\" <> \"Python\"'))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Even Python understands that love is complicated\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import this\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Wait, what's **this**? `this` is love :heart:\n", + "\n", + "**Output:**\n", + "```\n", + "The Zen of Python, by Tim Peters\n", + "\n", + "Beautiful is better than ugly.\n", + "Explicit is better than implicit.\n", + "Simple is better than complex.\n", + "Complex is better than complicated.\n", + "Flat is better than nested.\n", + "Sparse is better than dense.\n", + "Readability counts.\n", + "Special cases aren't special enough to break the rules.\n", + "Although practicality beats purity.\n", + "Errors should never pass silently.\n", + "Unless explicitly silenced.\n", + "In the face of ambiguity, refuse the temptation to guess.\n", + "There should be one-- and preferably only one --obvious way to do it.\n", + "Although that way may not be obvious at first unless you're Dutch.\n", + "Now is better than never.\n", + "Although never is often better than *right* now.\n", + "If the implementation is hard to explain, it's a bad idea.\n", + "If the implementation is easy to explain, it may be a good idea.\n", + "Namespaces are one honking great idea -- let's do more of those!\n", + "```\n", + "\n", + "It's the Zen of Python!\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "love = this\n", + "this is love\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "love is True\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "love is False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "love is not True or False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "love is not True or False; love is love # Love is complicated\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)).\n", + "* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens).\n", + "* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Yes, it exists!\n", + "**The `else` clause for loops.** One typical example might be:\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " def does_exists_num(l, to_find):\n", + " for num in l:\n", + " if num == to_find:\n", + " print(\"Exists!\")\n", + " break\n", + " else:\n", + " print(\"Does not exist\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Exists!\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_list = [1, 2, 3, 4, 5]\n", + "does_exists_num(some_list, 4)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Does not exist\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "does_exists_num(some_list, -1)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**The `else` clause in exception handling.** An example,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "try:\n", + " pass\n", + "except:\n", + " print(\"Exception occurred!!!\")\n", + "else:\n", + " print(\"Try block executed successfully...\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Try block executed successfully...\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a \"nobreak\" clause.\n", + "- `else` clause after a try block is also called \"completion clause\" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Ellipsis *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def some_func():\n", + " Ellipsis\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "# No output, No Error\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "NameError: name 'SomeRandomString' is not defined\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "SomeRandomString\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Ellipsis\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Ellipsis\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Ellipsis\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " ...\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Eliipsis can be used for several purposes,\n", + " + As a placeholder for code that hasn't been written yet (just like `pass` statement)\n", + " + In slicing syntax to represent the full slices in remaining direction\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " array([\n", + " [\n", + " [0, 1],\n", + " [2, 3]\n", + " ],\n", + "\n", + " [\n", + " [4, 5],\n", + " [6, 7]\n", + " ]\n", + " ])\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " import numpy as np\n", + " three_dimensional_array = np.arange(8).reshape(2, 2, 2)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " array([[1, 3],\n", + " [5, 7]])\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " three_dimensional_array[:,:,1]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " array([[1, 3],\n", + " [5, 7]])\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " three_dimensional_array[..., 1] # using Ellipsis.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`)\n", + " + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`))\n", + " + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the \"no argument passed\" and \"None value passed\" scenarios).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Inpinity\n", + "The spelling is intended. Please, don't submit a patch for this.\n", + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "314159\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "infinity = float('infinity')\n", + "hash(infinity)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "-314159\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "hash(float('-inf'))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "- Hash of infinity is 10⁵ x π.\n", + "- Interestingly, the hash of `float('-inf')` is \"-10⁵ x π\" in Python 3, whereas \"-10⁵ x e\" in Python 2.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Let's mangle\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "class Yo(object):\n", + " def __init__(self):\n", + " self.__honey = True\n", + " self.bro = True\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Yo().bro\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "AttributeError: 'Yo' object has no attribute '__honey'\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Yo().__honey\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Yo()._Yo__honey\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "class Yo(object):\n", + " def __init__(self):\n", + " # Let's try something symmetrical this time\n", + " self.__honey__ = True\n", + " self.bro = True\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Yo().bro\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "AttributeError: 'Yo' object has no attribute '_Yo__honey__'\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Yo()._Yo__honey__\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Why did `Yo()._Yo__honey` work?\n", + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "_A__variable = \"Some value\"\n", + "\n", + "class A(object):\n", + " def some_func(self):\n", + " return __variable # not initiatlized anywhere yet\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Some value'\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "AttributeError: 'A' object has no attribute '__variable'\n", + "\n", + "A().some_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.\n", + "* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a \"dunder\") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front.\n", + "* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class.\n", + "* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores.\n", + "* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope.\n", + "* Also, if the mangled name is longer than 255 characters, truncation will happen.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Skipping lines?\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "11\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "value = 11\n", + "valuе = 32\n", + "value\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Wut?\n", + "\n", + "**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "\n", + "Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1077\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ord('е') # cyrillic 'e' (Ye)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "101\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ord('e') # latin 'e', as used in English and typed using standard keyboard\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'е' == 'e'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "42\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "value = 42 # latin e\n", + "valuе = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here\n", + "value\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Teleportation\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import numpy as np\n", + "\n", + "def energy_send(x):\n", + " # Initializing a numpy array\n", + " np.array([float(x)])\n", + "\n", + "def energy_receive():\n", + " # Return an empty numpy array\n", + " return np.empty((), dtype=np.float).tolist()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "123.456\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "energy_send(123.456)\n", + "energy_receive()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Where's the Nobel Prize?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate.\n", + "* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Well, something is fishy...\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def square(x):\n", + " \"\"\"\n", + " A simple function to calculate the square of a number by addition.\n", + " \"\"\"\n", + " sum_so_far = 0\n", + " for counter in range(x):\n", + " sum_so_far = sum_so_far + x\n", + " return sum_so_far\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(10)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Shouldn't that be 100?\n", + "\n", + "**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "\n", + "* **Don't mix tabs and spaces!** The character just preceding return is a \"tab\", and the code is indented by multiple of \"4 spaces\" elsewhere in the example.\n", + "* This is how Python handles tabs:\n", + " \n", + " > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>\n", + "* So the \"tab\" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.\n", + "* Python 3 is kind enough to throw an error for such cases automatically.\n", + "\n", + " **Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " TabError: inconsistent use of tabs and spaces in indentation\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ `+=` is faster\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.25748300552368164\n", + "# using \"+=\", three strings:\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# using \"+\", three strings:\n", + "timeit.timeit(\"s1 = s1 + s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.012188911437988281\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "timeit.timeit(\"s1 += s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Let's make a giant string!\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def add_string_with_plus(iters):\n", + " s = \"\"\n", + " for i in range(iters):\n", + " s += \"xyz\"\n", + " assert len(s) == 3*iters\n", + "\n", + "def add_bytes_with_plus(iters):\n", + " s = b\"\"\n", + " for i in range(iters):\n", + " s += b\"xyz\"\n", + " assert len(s) == 3*iters\n", + "\n", + "def add_string_with_format(iters):\n", + " fs = \"{}\"*iters\n", + " s = fs.format(*([\"xyz\"]*iters))\n", + " assert len(s) == 3*iters\n", + "\n", + "def add_string_with_join(iters):\n", + " l = []\n", + " for i in range(iters):\n", + " l.append(\"xyz\")\n", + " s = \"\".join(l)\n", + " assert len(s) == 3*iters\n", + "\n", + "def convert_list_to_string(l, iters):\n", + " s = \"\".join(l)\n", + " assert len(s) == 3*iters\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "124 µs ± 4.73 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Executed in ipython shell using %timeit for better readablity of results.\n", + "# You can also use the timeit module in normal python shell/scriptm=, example usage below\n", + "# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())\n", + "\n", + "NUM_ITERS = 1000\n", + "%timeit -n1000 add_string_with_plus(NUM_ITERS)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "211 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "%timeit -n1000 add_bytes_with_plus(NUM_ITERS)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "61 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "%timeit -n1000 add_string_with_format(NUM_ITERS)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "117 µs ± 3.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "%timeit -n1000 add_string_with_join(NUM_ITERS)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = [\"xyz\"]*NUM_ITERS\n", + "%timeit -n1000 convert_list_to_string(l, NUM_ITERS)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Let's increase the number of iterations by a factor of 10.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1.26 ms ± 76.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "NUM_ITERS = 10000\n", + "%timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "6.82 ms ± 134 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "%timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "645 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "%timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1.17 ms ± 7.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "%timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "86.3 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "l = [\"xyz\"]*NUM_ITERS\n", + "%timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces.\n", + "- Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function)\n", + "- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings).\n", + "- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.\n", + "- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + \"x\" + \"y\" + \"z\"` instead of `s += \"xyz\"`, the increase would have been quadratic.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "339 µs ± 28.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" + ] + } + ], + "source": [ + " def add_string_with_plus(iters):\n", + " s = \"\"\n", + " for i in range(iters):\n", + " s = s + \"x\" + \"y\" + \"z\"\n", + " assert len(s) == 3*iters\n", + "\n", + " %timeit -n100 add_string_with_plus(1000)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + " %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which,\n", + " \n", + " > There should be one-- and preferably only one --obvious way to do it.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Minor Ones *\n", + "* `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage)\n", + "\n", + " **💡 Explanation:** If `join()` is a method on a string, then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API.\n", + " \n", + "* Few weird looking but semantically correct statements:\n", + " + `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`)\n", + " + `'a'[0][0][0][0][0]` is also a semantically correct statement as strings are [sequences](https://docs.python.org/3/glossary.html#term-sequence)(iterables supporting element access using integer indices) in Python.\n", + " + `3 --0-- 5 == 8` and `--5 == 5` are both semantically correct statements and evaluate to `True`.\n", + "\n", + "* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java.\n", + " ```py\n", + " >>> a = 5\n", + " >>> a\n", + " 5\n", + " >>> ++a\n", + " 5\n", + " >>> --a\n", + " 5\n", + " ```\n", + "\n", + " **💡 Explanation:**\n", + " + There is no `++` operator in Python grammar. It is actually two `+` operators.\n", + " + `++a` parses as `+(+a)` which translates to `a`. Similarly, the output of the statement `--a` can be justified.\n", + " + This StackOverflow [thread](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) discusses the rationale behind the absence of increment and decrement operators in Python.\n", + "\n", + "* You must be aware of the Walrus operator in Python. But have you ever heard about *the space-invader operator*?\n", + " ```py\n", + " >>> a = 42\n", + " >>> a -=- 1\n", + " >>> a\n", + " 43\n", + " ```\n", + " It is used as an alternative incrementation operator, together with another one\n", + " ```py\n", + " >>> a +=+ 1\n", + " >>> a\n", + " >>> 44\n", + " ```\n", + " **💡 Explanation:** This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case.\n", + " \n", + "* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. \n", + " \n", + " ```py\n", + " >>> False ** False == True\n", + " True\n", + " >>> False ** True == False\n", + " True\n", + " >>> True ** False == True\n", + " True\n", + " >>> True ** True == True\n", + " True\n", + " ```\n", + "\n", + " **💡 Explanation:** If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to a converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator))\n", + " \n", + "* Since we are talking operators, there's also `@` operator for matrix multiplication (don't worry, this time it's for real).\n", + "\n", + " ```py\n", + " >>> import numpy as np\n", + " >>> np.array([2, 2, 2]) @ np.array([7, 8, 8])\n", + " 46\n", + " ```\n", + "\n", + " **💡 Explanation:** The `@` operator was added in Python 3.5 keeping sthe cientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator.\n", + "\n", + "* From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example,\n", + " ```py\n", + " >>> some_string = \"wtfpython\"\n", + " >>> f'{some_string=}'\n", + " \"string='wtfpython'\"\n", + " ``` \n", + "\n", + "* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!):\n", + " \n", + " ```py\n", + " import dis\n", + " exec(\"\"\"\n", + " def f():\n", + " \"\"\" + \"\"\"\n", + " \"\"\".join([\"X\" + str(x) + \"=\" + str(x) for x in range(65539)]))\n", + " \n", + "f()\n", + " \n", + " print(dis.dis(f))\n", + "```\n", + " \n", + "* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module.\n", + "\n", + "* Sometimes, the `print` method might not print values immediately. For example,\n", + "\n", + " ```py\n", + " # File some_file.py\n", + " import time\n", + " \n", + " print(\"wtfpython\", end=\"_\")\n", + " time.sleep(3)\n", + " ```\n", + "\n", + " This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument.\n", + "\n", + "* List slicing with out of the bounds indices throws no errors\n", + " ```py\n", + " >>> some_list = [1, 2, 3, 4, 5]\n", + " >>> some_list[111:]\n", + " []\n", + " ```\n", + "\n", + "* Slicing an iterable not always creates a new object. For example,\n", + " ```py\n", + " >>> some_str = \"wtfpython\"\n", + " >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n']\n", + " >>> some_list is some_list[:] # False expected because a new object is created.\n", + " False\n", + " >>> some_str is some_str[:] # True because strings are immutable, so making a new object is of not much use.\n", + " True\n", + " ```\n", + "\n", + "* `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.\n", + "\n", + "* You can seperate numeric literals with underscores (for better readablity) from Python 3 onwards.\n", + "\n", + " ```py\n", + " >>> six_million = 6_000_000\n", + " >>> six_million\n", + " 6000000\n", + " >>> hex_address = 0xF00D_CAFE\n", + " >>> hex_address\n", + " 4027435774\n", + " ```\n", + "\n", + "* `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear\n", + " ```py\n", + " def count(s, sub):\n", + " result = 0\n", + " for i in range(len(s) + 1 - len(sub)):\n", + " result += (s[i:i + len(sub)] == sub)\n", + " return result\n", + " ```\n", + " The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string.\n", + "\n", + "**That's all folks!**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Contributing\n", + "\n", + "A few ways that you can contribute to wtfpython,\n", + "\n", + "- Suggesting new examples\n", + "- Helping with translation (See [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation))\n", + "- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc.\n", + "- Identifying gaps (things like inadequate explanation, redundant examples, etc.)\n", + "- Any creative suggestions to make this project more fun and useful\n", + "\n", + "Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) to discuss things.\n", + "\n", + "PS: Please don't reach out with backlinking requests, no links will be added unless they're highly relevant to the project.\n", + "\n", + "# Acknowledgements\n", + "\n", + "The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by Pythonistas gave it the shape it is in right now.\n", + "\n", + "#### Some nice Links!\n", + "* https://www.youtube.com/watch?v=sH4XF6pKKmk\n", + "* https://www.reddit.com/r/Python/comments/3cu6ej/what_are_some_wtf_things_about_python\n", + "* https://sopython.com/wiki/Common_Gotchas_In_Python\n", + "* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines\n", + "* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python\n", + "* https://www.python.org/doc/humor/\n", + "* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator\n", + "* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65\n", + "* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues\n", + "\n", + "# 🎓 License\n", + "\n", + "[![WTFPL 2.0][license-image]][license-url]\n", + "\n", + "© [Satwik Kansal](https://satwikkansal.xyz)\n", + "\n", + "[license-url]: http://www.wtfpl.net\n", + "[license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square\n", + "\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.0+" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} From 12b2fc008ecc60ed2abd293c3fbc12f4489db520 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 21 Dec 2019 19:39:28 +0530 Subject: [PATCH 125/221] Fix TOC and links --- README.md | 56 +++++++++++++++++++++++++++---------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index a068090b..57a26e98 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ So, here we go... # Table of Contents + - [Structure of the Examples](#structure-of-the-examples) @@ -26,57 +27,52 @@ So, here we go... - [Usage](#usage) - [👀 Examples](#-examples) * [Section: Strain your brain!](#section-strain-your-brain) - + [▶ First things first!](#-first-things-first) + + [▶ First things first! *](#-first-things-first-) + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) - + [▶ Splitsies](#-splitsies) + [▶ Hash brownies](#-hash-brownies) - + [▶ Disorder within order](#-disorder-within-order) - + [▶ Keep trying...](#-keep-trying) + [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) + + [▶ Disorder within order *](#-disorder-within-order-) + + [▶ Keep trying... *](#-keep-trying-) + [▶ For what?](#-for-what) + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) + [▶ How not to use `is` operator](#-how-not-to-use-is-operator) + + [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) + [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + [▶ The sticky output function](#-the-sticky-output-function) - + [▶ The chicken-egg problem](#-the-chicken-egg-problem) - + [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) + + [▶ The chicken-egg problem *](#-the-chicken-egg-problem-) + + [▶ Subclass relationships](#-subclass-relationships) + + [▶ All-true-ation *](#-all-true-ation-) + [▶ The surprising comma](#-the-surprising-comma) + [▶ Strings and the backslashes](#-strings-and-the-backslashes) + [▶ not knot!](#-not-knot) + [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - + [▶ Non-reflexive class method](#-non-reflexive-class-method) + + [▶ Non-reflexive class method *](#-non-reflexive-class-method-) + [▶ yielding None](#-yielding-none) - + [▶ Nan-reflexivity](#-nan-reflexivity) + + [▶ Yielding from... return! *](#-yielding-from-return-) + + [▶ Nan-reflexivity *](#-nan-reflexivity-) + [▶ Mutating the immutable!](#-mutating-the-immutable) + [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) - + [▶ Yielding from... return!](#-yielding-from-return) - + [▶ Lossy zip of iterators](#-lossy-zip-of-iterators) - + [▶ Subclass relationships](#-subclass-relationships) + [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) - * [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - + [▶ Skipping lines?](#-skipping-lines) - + [▶ Teleportation](#-teleportation) - + [▶ Well, something is fishy...](#-well-something-is-fishy) * [Section: Slippery Slopes](#section-slippery-slopes) + [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + [▶ Stubborn `del` operation](#-stubborn-del-operation) + + [▶ The out of scope variable](#-the-out-of-scope-variable) + [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) + + [▶ Lossy zip of iterators *](#-lossy-zip-of-iterators-) + [▶ Loop variables leaking out!](#-loop-variables-leaking-out) + [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) + [▶ Catching the Exceptions](#-catching-the-exceptions) + [▶ Same operands, different story!](#-same-operands-different-story) - + [▶ The out of scope variable](#-the-out-of-scope-variable) + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - + [▶ Needles in a Haystack](#-needles-in-a-haystack) - + [▶ Wild imports](#-wild-imports) - * [Section: Read the docs](#section-read-the-docs) - + [▶ All sorted?](#-all-sorted) - + [▶ All-true-ation](#-all-true-ation) + + [▶ Needles in a Haystack *](#-needles-in-a-haystack-) + + [▶ Splitsies *](#-splitsies-) + + [▶ Wild imports *](#-wild-imports-) + + [▶ All sorted? *](#-all-sorted-) + + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) * [Section: The Hidden treasures!](#section-the-hidden-treasures) + [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) + [▶ `goto`, but why?](#-goto-but-why) @@ -84,18 +80,22 @@ So, here we go... + [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) + [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) + [▶ Yes, it exists!](#-yes-it-exists) - + [▶ Ellipsis](#-ellipsis) + + [▶ Ellipsis *](#-ellipsis-) + [▶ Inpinity](#-inpinity) + [▶ Let's mangle](#-lets-mangle) + * [Section: Appearances are deceptive!](#section-appearances-are-deceptive) + + [▶ Skipping lines?](#-skipping-lines) + + [▶ Teleportation](#-teleportation) + + [▶ Well, something is fishy...](#-well-something-is-fishy) * [Section: Miscellaneous](#section-miscellaneous) + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ Minor Ones](#-minor-ones) + + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) -- [🎓 License](#%F0%9F%8E%93-license) - * [Surprise your friends too?](#surprise-your-friends-too) - * [Need a pdf version?](#need-a-pdf-version) +- [🎓 License](#-license) + * [Surprise your friends as well!](#surprise-your-friends-as-well) + * [More content like this?](#more-content-like-this) @@ -3508,7 +3508,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' If you like wtfpython, you can use these quick links to share it with your friends, -[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&text=If%20you%20really%20think%20you%20know%20Python,%20think%20once%20more!%20Check%20out%20wtfpython&hastags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=If%20you%20really%20thing%20you%20know%20Python,%20think%20once%20more!) | [Facebook](https://www.facebook.com/dialog/share?app_id=536779657179021&display=page&href=https%3A%2F%2Fgithub.com%2Fsatwikkansal%2Fwtfpython"e=If%20you%20really%20think%20you%20know%20Python%2C%20think%20once%20more!) +[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&text=If%20you%20really%20think%20you%20know%20Python,%20think%20once%20more!%20Check%20out%20wtfpython&hastags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=If%20you%20really%20thing%20you%20know%20Python,%20think%20once%20more!) | [Facebook](https://www.facebook.com/dialog/share?app_id=536779657179021&display=page&href=https%3A%2F%2Fgithub.com%2Fsatwikkansal%2Fwtfpython"e=If%20you%20really%20think%20you%20know%20Python%2C%20think%20once%20more!) ## More content like this? From f914194a875294cba1791afbbc0e86ed723588b7 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 21 Dec 2019 19:39:49 +0530 Subject: [PATCH 126/221] Add instructions --- irrelevant/notebook_generator.py | 5 +- irrelevant/notebook_instructions.md | 26 + irrelevant/wtf.ipynb | 1597 ++++++++++++++------------- 3 files changed, 829 insertions(+), 799 deletions(-) create mode 100644 irrelevant/notebook_instructions.md diff --git a/irrelevant/notebook_generator.py b/irrelevant/notebook_generator.py index d9818b3f..17551dfa 100644 --- a/irrelevant/notebook_generator.py +++ b/irrelevant/notebook_generator.py @@ -34,7 +34,7 @@ HOSTED_NOTEBOOK_INSTRUCTIONS = """ -# Hosted notebook instructions +## Hosted notebook instructions This is just an experimental attempt of browsing wtfpython through jupyter notebooks. Some examples are read-only because, - they either require a version of Python that's not supported in the hosted runtime. @@ -48,7 +48,7 @@ # Prints out Python version here. ``` -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! +That being said, most of the 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! --- """ @@ -350,4 +350,5 @@ def convert_to_notebook(pre_examples_content, parsed_json, post_examples_content except StopIteration as e: #pprint.pprint(result, indent=2) pre_stuff.append(HOSTED_NOTEBOOK_INSTRUCTIONS) + result.sort(key = lambda x: x["read_only"]) convert_to_notebook(pre_stuff, result, post_stuff) diff --git a/irrelevant/notebook_instructions.md b/irrelevant/notebook_instructions.md new file mode 100644 index 00000000..891698ae --- /dev/null +++ b/irrelevant/notebook_instructions.md @@ -0,0 +1,26 @@ +## Generating the notebook + +- Expand the relative links in README.md to absolute ones +- Remove the TOC in README.md (because Google colab generates its own anyway) +- Reorder the examples, so that the ones that work are upfront. +- Run the `notebook_generator.py`, it will generate a notebook named `wtf.ipynb` +- Revert the README.md changes (optional) + + +# Hosted notebook instructions + +This is just an experimental attempt of browsing wtfpython through jupyter notebooks. Some examples are read-only because, +- they either require a version of Python that's not supported in the hosted runtime. +- or they can't be reproduced in the notebook envrinonment. + +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 + +```py +>>> import sys +>>> sys.version +# Prints out Python version here. +``` + +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! + + diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb index 64e315b7..0464b368 100644 --- a/irrelevant/wtf.ipynb +++ b/irrelevant/wtf.ipynb @@ -162,7 +162,7 @@ "\n", "\n", "\n", - "# Hosted notebook instructions\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", @@ -176,7 +176,7 @@ "# 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", + "That being said, most of the 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" ] @@ -185,162 +185,197 @@ "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", + "### ▶ Strings can be tricky sometimes\n", "1\\.\n", "\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140420665652016\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "```py\n", - "# Python version 3.8+\n", - "\n", - ">>> a = \"wtf_walrus\"\n", - ">>> a\n", - "```\n", - "```py\n", - "'wtf_walrus'\n", - "\n", - "```\n" + "a = \"some_string\"\n", + "id(a)\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140420665652016\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "```py\n", - ">>> a := \"wtf_walrus\"\n", - "```\n", - "```py\n", - "File \"\", line 1\n", - " a := \"wtf_walrus\"\n", - " ^\n", - "SyntaxError: invalid syntax\n", - "\n", - "```\n" + "id(\"some\" + \"_\" + \"string\") # Notice that both the ids are same.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "```py\n", - ">>> (a := \"wtf_walrus\") # This works though\n", - ">>> a\n", - "```\n", - "```py\n", - "'wtf_walrus'\n", - "```\n" + "\n", + "2\\.\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "\n", - "2 \\.\n", - "\n" + "a = \"wtf\"\n", + "b = \"wtf\"\n", + "a is b\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "```py\n", - "# Python version 3.8+\n", - "\n", - ">>> a = 6, 9\n", - ">>> a\n", - "```\n", - "```py\n", - "(6, 9)\n", - "\n", - "```\n" + "a = \"wtf!\"\n", + "b = \"wtf!\"\n", + "a is b\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "```py\n", - ">>> (a := 6, 9)\n", - ">>> a\n", - "```\n", - "```py\n", - "6\n", "\n", - "```\n" + "3\\.\n", + "\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "```py\n", - ">>> a, b = 6, 9 # Typcial unpacking\n", - ">>> a, b\n", - "```\n", - "```py\n", - "(6, 9)\n", - "```\n" + "a, b = \"wtf!\", \"wtf!\"\n", + "a is b # All versions except 3.7.x\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "```py\n", - ">>> (a, b = 16, 19) # Oops\n", - "```\n", - "```py\n", - " File \"\", line 1\n", - " (a, b = 6, 9)\n", - " ^\n", - "SyntaxError: invalid syntax\n", - "\n", - "```\n" + "a = \"wtf!\"; b = \"wtf!\"\n", + "a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "```py\n", - ">>> (a, b := 16, 19) # This prints out a weird 3-tuple\n", - "```\n", - "```py\n", - "(6, 16, 19)\n", - "\n", - "```\n" + "\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], "source": [ - "```py\n", - ">>> a # a is still unchanged?\n", - "```\n", - "```py\n", - "6\n", + "# This time in file some_file.py\n", + "a = \"wtf!\"\n", + "b = \"wtf!\"\n", + "print(a is b)\n", "\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> b\n", - "```\n", - "```py\n", - "16\n", - "```\n" + "# prints True when the module is invoked!\n" ] }, { @@ -348,69 +383,54 @@ "metadata": {}, "source": [ "\n", + "4\\.\n", "\n", + "**Output (< Python3.7 )**\n", "\n" ] }, { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "**Quick walrus operator refresher**\n", - "\n", - "The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - "def some_func():\n", - " # Assume some expensive computation here\n", - " # time.sleep(1000)\n", - " return 5\n", - "\n", - "# So instead of,\n", - "if some_func():\n", - " print(some_func()) # Which is bad practice since computation is happening twice\n", - "\n", - "# or\n", - "a = some_func()\n", - "if a:\n", - " print(a)\n", - "\n", - "# Now you can concisely write\n", - "if a := some_func():\n", - " print(a)\n", - "```\n", - "```py\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "\n", - "**Output (> 3.8):**\n", - "\n" + "'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "```py\n", - "5\n", - "5\n", - "5\n", - "```\n", - "```py\n", - "```\n" + "'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'\n" ] }, { @@ -418,15 +438,7 @@ "metadata": {}, "source": [ "\n", - "This 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, hence the `SyntaxError` in the `a := \"wtf_walrus\"` statement of the first snippet. Parenthesizing it worked as expected and assigned `a`. \n", - "\n", - "- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. \n", - "\n", - "- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", - "\n", - " - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6')\n", + "Makes sense, right?\n", "\n" ] }, @@ -434,45 +446,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "```py\n", - " >>> (a := 6, 9) == ((a := 6), 9)\n", - "```\n", - "```py\n", - " True\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> x = (a := 696, 9)\n", - " >>> x\n", - "```\n", - "```py\n", - " (696, 9)\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> x[0] is a # Both reference same memory location\n", - "```\n", - "```py\n", - " True\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. \n", + "#### 💡 Explanation:\n", + "+ The behavior in first and second snippets is due to a CPython optimization (called string interning) 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 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. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", + " ![image](/images/string-intern/string_intern.png)\n", + "+ When `a` and `b` are set to `\"wtf!\"` 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 `wtf!` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", + "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, 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 [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.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 with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", "\n" ] }, @@ -480,9 +465,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### ▶ Strings can be tricky sometimes\n", - "1\\.\n", - "\n" + "### ▶ Hash brownies\n", + "1\\.\n" ] }, { @@ -494,9 +478,7 @@ "outputs": [ { "data": { - "text/plain": [ - "140420665652016\n" - ] + "text/plain": [] }, "execution_count": null, "metadata": {}, @@ -504,8 +486,19 @@ } ], "source": [ - "a = \"some_string\"\n", - "id(a)\n" + "some_dict = {}\n", + "some_dict[5.5] = \"JavaScript\"\n", + "some_dict[5.0] = \"Ruby\"\n", + "some_dict[5] = \"Python\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" ] }, { @@ -518,7 +511,7 @@ { "data": { "text/plain": [ - "140420665652016\n" + "\"JavaScript\"\n" ] }, "execution_count": null, @@ -527,15 +520,7 @@ } ], "source": [ - "id(\"some\" + \"_\" + \"string\") # Notice that both the ids are same.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n" + "some_dict[5.5]\n" ] }, { @@ -548,8 +533,7 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "\"Python\"\n" ] }, "execution_count": null, @@ -558,9 +542,7 @@ } ], "source": [ - "a = \"wtf\"\n", - "b = \"wtf\"\n", - "a is b\n" + "some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n" ] }, { @@ -573,7 +555,7 @@ { "data": { "text/plain": [ - "False\n", + "\"Python\"\n", "\n" ] }, @@ -583,18 +565,7 @@ } ], "source": [ - "a = \"wtf!\"\n", - "b = \"wtf!\"\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n" + "some_dict[5] \n" ] }, { @@ -607,8 +578,7 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "complex\n" ] }, "execution_count": null, @@ -617,8 +587,8 @@ } ], "source": [ - "a, b = \"wtf!\", \"wtf!\"\n", - "a is b # All versions except 3.7.x\n" + "complex_five = 5 + 0j\n", + "type(complex_five)\n" ] }, { @@ -631,7 +601,7 @@ { "data": { "text/plain": [ - "False\n" + "\"Python\"\n" ] }, "execution_count": null, @@ -640,48 +610,27 @@ } ], "source": [ - "a = \"wtf!\"; b = \"wtf!\"\n", - "a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script)\n" + "some_dict[complex_five]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [] - } - ], - "source": [ - "# This time in file some_file.py\n", - "a = \"wtf!\"\n", - "b = \"wtf!\"\n", - "print(a is b)\n", "\n", - "# prints True when the module is invoked!\n" + "So, why is Python all over the place?\n", + "\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### 💡 Explanation\n", "\n", - "4\\.\n", - "\n", - "**Output (< Python3.7 )**\n", - "\n" + "* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.\n", + "* Immutable objects with the same value always have the same hash in Python.\n" ] }, { @@ -694,7 +643,7 @@ { "data": { "text/plain": [ - "True\n" + " True\n" ] }, "execution_count": null, @@ -703,7 +652,7 @@ } ], "source": [ - "'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'\n" + " 5 == 5.0 == 5 + 0j\n" ] }, { @@ -716,7 +665,7 @@ { "data": { "text/plain": [ - "False\n" + " True\n" ] }, "execution_count": null, @@ -725,251 +674,7 @@ } ], "source": [ - "'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Makes sense, right?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "+ The behavior in first and second snippets is due to a CPython optimization (called string interning) 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 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. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", - " ![image](/images/string-intern/string_intern.png)\n", - "+ When `a` and `b` are set to `\"wtf!\"` 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 `wtf!` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", - "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, 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 [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.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 with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Hash brownies\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict = {}\n", - "some_dict[5.5] = \"JavaScript\"\n", - "some_dict[5.0] = \"Ruby\"\n", - "some_dict[5] = \"Python\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "\"JavaScript\"\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict[5.5]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "\"Python\"\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "\"Python\"\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict[5] \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "complex\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "complex_five = 5 + 0j\n", - "type(complex_five)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "\"Python\"\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict[complex_five]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "So, why is Python all over the place?\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.\n", - "* Immutable objects with the same value always have the same hash in Python.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " 5 == 5.0 == 5 + 0j\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " hash(5) == hash(5.0) == hash(5 + 0j)\n" + " hash(5) == hash(5.0) == hash(5 + 0j)\n" ] }, { @@ -1850,9 +1555,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": true - }, + "metadata": {}, "outputs": [ { "data": { @@ -6930,111 +6633,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### ▶ Stubborn `del` operation\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - "class SomeClass:\n", - " def __del__(self):\n", - " print(\"Deleted!\")\n", - "```\n", - "```py\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "1\\.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> x = SomeClass()\n", - ">>> y = x\n", - ">>> del x # this should print \"Deleted!\"\n", - ">>> del y\n", - "```\n", - "```py\n", - "Deleted!\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.\n", - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> x = SomeClass()\n", - ">>> y = x\n", - ">>> del x\n", - ">>> y # check if y exists\n", - "```\n", - "```py\n", - "<__main__.SomeClass instance at 0x7f98a1a67fc8>\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> del y # Like previously, this should print \"Deleted!\"\n", - ">>> globals() # oh, it didn't. Let's check all our global variables and confirm\n", - "```\n", - "```py\n", - "Deleted!\n", - "{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None}\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Okay, now it's deleted :confused:\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "+ `del x` doesn’t directly call `x.__del__()`.\n", - "+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero.\n", - "+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.\n", - "+ Calling `globals` caused the existing reference to be destroyed, and hence we can see \"Deleted!\" being printed (finally!).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ The out of scope variable\n" + "### ▶ The out of scope variable\n" ] }, { @@ -9750,162 +9349,6 @@ "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Wild imports *\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - "# File: module.py\n", - "\n", - "def some_weird_name_func_():\n", - " print(\"works!\")\n", - "\n", - "def _another_weird_name_func():\n", - " print(\"works!\")\n", - "\n", - "```\n", - "```py\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output**\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> from module import *\n", - ">>> some_weird_name_func_()\n", - "```\n", - "```py\n", - "\"works!\"\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> _another_weird_name_func()\n", - "```\n", - "```py\n", - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "NameError: name '_another_weird_name_func' is not defined\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime.\n", - "- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> from module import some_weird_name_func_, _another_weird_name_func\n", - " >>> _another_weird_name_func()\n", - "```\n", - "```py\n", - " works!\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " __all__ = ['_another_weird_name_func']\n", - "\n", - " def some_weird_name_func_():\n", - " print(\"works!\")\n", - "\n", - " def _another_weird_name_func():\n", - " print(\"works!\")\n", - "```\n", - "```py\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " **Output**\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> _another_weird_name_func()\n", - "```\n", - "```py\n", - " \"works!\"\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> some_weird_name_func_()\n", - "```\n", - "```py\n", - " Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - " NameError: name 'some_weird_name_func_' is not defined\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, { "cell_type": "markdown", "metadata": {}, @@ -12156,15 +11599,20 @@ }, { "cell_type": "code", - "execution_count": 1, - "metadata": {}, + "execution_count": null, + "metadata": { + "collapsed": true + }, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "339 µs ± 28.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" - ] + "data": { + "text/plain": [ + " 388 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "execution_count": null, + "metadata": {}, + "output_type": "execute_result" } ], "source": [ @@ -12358,6 +11806,561 @@ "\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 \"\", line 1\n", + " a := \"wtf_walrus\"\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a := \"wtf_walrus\") # This works though\n", + ">>> a\n", + "```\n", + "```py\n", + "'wtf_walrus'\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2 \\.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "# Python version 3.8+\n", + "\n", + ">>> a = 6, 9\n", + ">>> a\n", + "```\n", + "```py\n", + "(6, 9)\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a := 6, 9)\n", + ">>> a\n", + "```\n", + "```py\n", + "6\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> a, b = 6, 9 # Typcial unpacking\n", + ">>> a, b\n", + "```\n", + "```py\n", + "(6, 9)\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a, b = 16, 19) # Oops\n", + "```\n", + "```py\n", + " File \"\", line 1\n", + " (a, b = 6, 9)\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a, b := 16, 19) # This prints out a weird 3-tuple\n", + "```\n", + "```py\n", + "(6, 16, 19)\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> a # a is still unchanged?\n", + "```\n", + "```py\n", + "6\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> b\n", + "```\n", + "```py\n", + "16\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation\n", + "\n", + "**Quick walrus operator refresher**\n", + "\n", + "The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "def some_func():\n", + " # Assume some expensive computation here\n", + " # time.sleep(1000)\n", + " return 5\n", + "\n", + "# So instead of,\n", + "if some_func():\n", + " print(some_func()) # Which is bad practice since computation is happening twice\n", + "\n", + "# or\n", + "a = some_func()\n", + "if a:\n", + " print(a)\n", + "\n", + "# Now you can concisely write\n", + "if a := some_func():\n", + " print(a)\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (> 3.8):**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "5\n", + "5\n", + "5\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "This 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, hence the `SyntaxError` in the `a := \"wtf_walrus\"` statement of the first snippet. Parenthesizing it worked as expected and assigned `a`. \n", + "\n", + "- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. \n", + "\n", + "- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", + "\n", + " - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6')\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> (a := 6, 9) == ((a := 6), 9)\n", + "```\n", + "```py\n", + " True\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> x = (a := 696, 9)\n", + " >>> x\n", + "```\n", + "```py\n", + " (696, 9)\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> x[0] is a # Both reference same memory location\n", + "```\n", + "```py\n", + " True\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Stubborn `del` operation\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "class SomeClass:\n", + " def __del__(self):\n", + " print(\"Deleted!\")\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "1\\.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> x = SomeClass()\n", + ">>> y = x\n", + ">>> del x # this should print \"Deleted!\"\n", + ">>> del y\n", + "```\n", + "```py\n", + "Deleted!\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.\n", + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> x = SomeClass()\n", + ">>> y = x\n", + ">>> del x\n", + ">>> y # check if y exists\n", + "```\n", + "```py\n", + "<__main__.SomeClass instance at 0x7f98a1a67fc8>\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> del y # Like previously, this should print \"Deleted!\"\n", + ">>> globals() # oh, it didn't. Let's check all our global variables and confirm\n", + "```\n", + "```py\n", + "Deleted!\n", + "{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None}\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Okay, now it's deleted :confused:\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "+ `del x` doesn’t directly call `x.__del__()`.\n", + "+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero.\n", + "+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.\n", + "+ Calling `globals` caused the existing reference to be destroyed, and hence we can see \"Deleted!\" being printed (finally!).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### ▶ Wild imports *\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "# File: module.py\n", + "\n", + "def some_weird_name_func_():\n", + " print(\"works!\")\n", + "\n", + "def _another_weird_name_func():\n", + " print(\"works!\")\n", + "\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> from module import *\n", + ">>> some_weird_name_func_()\n", + "```\n", + "```py\n", + "\"works!\"\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> _another_weird_name_func()\n", + "```\n", + "```py\n", + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "NameError: name '_another_weird_name_func' is not defined\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 💡 Explanation:\n", + "\n", + "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime.\n", + "- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> from module import some_weird_name_func_, _another_weird_name_func\n", + " >>> _another_weird_name_func()\n", + "```\n", + "```py\n", + " works!\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " __all__ = ['_another_weird_name_func']\n", + "\n", + " def some_weird_name_func_():\n", + " print(\"works!\")\n", + "\n", + " def _another_weird_name_func():\n", + " print(\"works!\")\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Output**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> _another_weird_name_func()\n", + "```\n", + "```py\n", + " \"works!\"\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> some_weird_name_func_()\n", + "```\n", + "```py\n", + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " NameError: name 'some_weird_name_func_' is not defined\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, { "cell_type": "markdown", "metadata": {}, From 483496d97a2a0be106342efa8c20bdb58d4c1923 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 21 Dec 2019 20:00:21 +0530 Subject: [PATCH 127/221] Aesthetical changes --- README.md | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 57a26e98..fb48b8eb 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@

-

What the f*ck Python! 🐍

-

An interesting collection of surprising snippets and lesser-known Python features.

+

What the f*ck Python! 😱

+

Exploring and understanding Python through surprising snippets.

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].) 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. -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. +Here's a fun project attempting to explain what exactly is happening under the hood for some counter-intuitive snippets and lesser-known features in Python. 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! @@ -3137,6 +3137,7 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ ```py +# `pip install nump` first. import numpy as np def energy_send(x): @@ -3384,7 +3385,7 @@ Let's increase the number of iterations by a factor of 10. 46 ``` - **💡 Explanation:** The `@` operator was added in Python 3.5 keeping sthe cientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator. + **💡 Explanation:** The `@` operator was added in Python 3.5 keeping sthe cientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator. * From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example, ```py @@ -3397,15 +3398,15 @@ Let's increase the number of iterations by a factor of 10. ```py import dis - exec(""" - def f(): - """ + """ - """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) - -f() - - print(dis.dis(f)) -``` + exec(""" + def f(): + """ + """ + """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) + + f() + + print(dis.dis(f)) + ``` * Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module. @@ -3468,7 +3469,7 @@ f() # Contributing -A few ways that you can contribute to wtfpython, +A few ways in which you can contribute to wtfpython, - Suggesting new examples - Helping with translation (See [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation)) From 2fb14be424e9bd63a3f89a3913df7d7c04148b81 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 21 Dec 2019 20:06:48 +0530 Subject: [PATCH 128/221] Update the notebook --- irrelevant/wtf.ipynb | 12431 +---------------------------------------- 1 file changed, 1 insertion(+), 12430 deletions(-) diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb index 0464b368..cd824f4f 100644 --- a/irrelevant/wtf.ipynb +++ b/irrelevant/wtf.ipynb @@ -1,12430 +1 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "

\"\"

\n", - "

What the f*ck Python! 🐍

\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 the 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": [ - "### ▶ Strings can be tricky sometimes\n", - "1\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140420665652016\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = \"some_string\"\n", - "id(a)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140420665652016\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(\"some\" + \"_\" + \"string\") # Notice that both the ids are same.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = \"wtf\"\n", - "b = \"wtf\"\n", - "a is b\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = \"wtf!\"\n", - "b = \"wtf!\"\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a, b = \"wtf!\", \"wtf!\"\n", - "a is b # All versions except 3.7.x\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = \"wtf!\"; b = \"wtf!\"\n", - "a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [] - } - ], - "source": [ - "# This time in file some_file.py\n", - "a = \"wtf!\"\n", - "b = \"wtf!\"\n", - "print(a is b)\n", - "\n", - "# prints True when the module is invoked!\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "4\\.\n", - "\n", - "**Output (< Python3.7 )**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Makes sense, right?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "+ The behavior in first and second snippets is due to a CPython optimization (called string interning) 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 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. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", - " ![image](/images/string-intern/string_intern.png)\n", - "+ When `a` and `b` are set to `\"wtf!\"` 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 `wtf!` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", - "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, 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 [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.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 with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Hash brownies\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict = {}\n", - "some_dict[5.5] = \"JavaScript\"\n", - "some_dict[5.0] = \"Ruby\"\n", - "some_dict[5] = \"Python\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "\"JavaScript\"\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict[5.5]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "\"Python\"\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "\"Python\"\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict[5] \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "complex\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "complex_five = 5 + 0j\n", - "type(complex_five)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "\"Python\"\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict[complex_five]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "So, why is Python all over the place?\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.\n", - "* Immutable objects with the same value always have the same hash in Python.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " 5 == 5.0 == 5 + 0j\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " hash(5) == hash(5.0) == hash(5 + 0j)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " **Note:** Objects with different values may also have same hash (known as [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science))).\n", - "* When the statement `some_dict[5] = \"Python\"` is executed, the existing value \"Ruby\" is overwritten with \"Python\" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`.\n", - "* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains the rationale behind it.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Deep down, we're all the same.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "class WTF:\n", - " pass\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "WTF() == WTF() # two different instances can't be equal\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "WTF() is WTF() # identities are also different\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(WTF()) == id(WTF())\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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 evaluated to `False`? Let's see with this snippet.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " class WTF(object):\n", - " def __init__(self): print(\"I\")\n", - " def __del__(self): print(\"D\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " **Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " I\n", - " I\n", - " D\n", - " D\n", - " False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " WTF() is WTF()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " I\n", - " D\n", - " I\n", - " D\n", - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " id(WTF()) == id(WTF())\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " As you may observe, the order in which the objects are destroyed is what made all the difference here.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Disorder within order *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from collections import OrderedDict\n", - "\n", - "dictionary = dict()\n", - "dictionary[1] = 'a'; dictionary[2] = 'b';\n", - "\n", - "ordered_dict = OrderedDict()\n", - "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", - "\n", - "another_ordered_dict = OrderedDict()\n", - "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", - "\n", - "class DictWithHash(dict):\n", - " \"\"\"\n", - " A dict that also implements __hash__ magic.\n", - " \"\"\"\n", - " __hash__ = lambda self: 0\n", - "\n", - "class OrderedDictWithHash(OrderedDict):\n", - " \"\"\"\n", - " An OrderedDict that also implements __hash__ magic.\n", - " \"\"\"\n", - " __hash__ = lambda self: 0\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "dictionary == ordered_dict # If a == b\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "dictionary == another_ordered_dict # and b == c\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\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" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ordered_dict == another_ordered_dict # the why isn't c == a ??\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "TypeError: unhashable type: 'dict'\n", - "\n", - "# Makes sense since dict don't have __hash__ implemented, let's use\n", - "# our wrapper classes.\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "len({dictionary, ordered_dict, another_ordered_dict})\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "1\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "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})\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "2\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "What is going on here?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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://docs.python.org/3/library/collections.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", - "- The reason for this equality is 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 lenght 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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_set = set()\n", - " some_set.add(dictionary) # these are the mapping objects from the snippets above\n", - " ordered_dict in some_set\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 1\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_set.add(ordered_dict)\n", - " len(some_set)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " another_ordered_dict in some_set\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 1\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_set.add(another_ordered_dict)\n", - " len(some_set)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " another_set = set()\n", - " another_set.add(ordered_dict)\n", - " another_ordered_dict in another_set\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 2\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " another_set.add(another_ordered_dict)\n", - " len(another_set)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " dictionary in another_set\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 2\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " another_set.add(another_ordered_dict)\n", - " len(another_set)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Keep trying... *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def some_func():\n", - " try:\n", - " return 'from_try'\n", - " finally:\n", - " return 'from_finally'\n", - "\n", - "def another_func(): \n", - " for _ in range(3):\n", - " try:\n", - " continue\n", - " finally:\n", - " print(\"Finally!\")\n", - "\n", - "def one_more_func(): # A gotcha!\n", - " try:\n", - " for i in range(3):\n", - " try:\n", - " 1 / 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 ocurred\", e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "'from_finally'\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_func()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Finally!\n", - "Finally!\n", - "Finally!\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "another_func()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "ZeroDivisionError: division by zero\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "1 / 0\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Iteration 0\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "one_more_func()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ For what?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_string = \"wtf\"\n", - "some_dict = {}\n", - "for i, some_dict[i] in enumerate(some_string):\n", - " i = 10\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{0: 'w', 1: 't', 2: 'f'}\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_dict # An indexed dict appears.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as:\n", - " ```\n", - " for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " for i in range(4):\n", - " print(i)\n", - " i = 10\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " **Output:**\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)` 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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " i, some_dict[i] = (0, 'w')\n", - " i, some_dict[i] = (1, 't')\n", - " i, some_dict[i] = (2, 'f')\n", - " some_dict\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Evaluation time discrepancy\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "array = [1, 8, 15]\n", - "# A typical generator expresion\n", - "gen = (x for x in array if array.count(x) > 0)\n", - "array = [2, 8, 22]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[8]\n" - ] - } - ], - "source": [ - "print(list(gen)) # Where did the other values go?\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "array_1 = [1,2,3,4]\n", - "gen_1 = (x for x in array_1)\n", - "array_1 = [1,2,3,4,5]\n", - "\n", - "array_2 = [1,2,3,4]\n", - "gen_2 = (x for x in array_2)\n", - "array_2[:] = [1,2,3,4,5]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, 4]\n", - "\n" - ] - } - ], - "source": [ - "print(list(gen_1))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, 4, 5]\n" - ] - } - ], - "source": [ - "print(list(gen_2))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "array_3 = [1, 2, 3]\n", - "array_4 = [10, 20, 30]\n", - "gen = (i + j for i in array_3 for j in array_4)\n", - "\n", - "array_3 = [4, 5, 6]\n", - "array_4 = [400, 500, 600]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[401, 501, 601, 402, 502, 602, 403, 503, 603]\n" - ] - } - ], - "source": [ - "print(list(gen))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "- In a [generator](https://wiki.python.org/moin/Generators) 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 binded 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(g)` 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://www.python.org/dev/peps/pep-0289/#the-details)\n", - " \n", - " > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ How not to use `is` operator\n", - "The following is a very famous example present all over the internet.\n", - "\n", - "1\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = 256\n", - "b = 256\n", - "a is b\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = 257\n", - "b = 257\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = []\n", - "b = []\n", - "a is b\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = tuple()\n", - "b = tuple()\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "**Output**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a, b = 257, 257\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 3.7.x specifically)**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - ">> a is b\n", - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a, b = 257, 257\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " class A: pass\n", - " A() is A() # These are two empty objects at two different memory locations.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**`256` is an existing object but `257` isn't**\n", - "\n", - "When 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", - "\n", - "Quoting from https://docs.python.org/3/c-api/long.html\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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "10922528\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(256)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "10922528\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = 256\n", - "b = 256\n", - "id(a)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "10922528\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(b)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140084850247312\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(257)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140084850247440\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x = 257\n", - "y = 257\n", - "id(x)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140084850247344\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(y)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Here 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", - "\n", - "Similar 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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140640774013296\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a, b = 257, 257\n", - "id(a)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140640774013296\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(b)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140640774013392\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = 257\n", - "b = 257\n", - "id(a)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140640774013488\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(b)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " a, b = 257.0, 257.0\n", - " a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\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://github.com/satwikkansal/wtfpython/issues/100) for updates.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ `is not ...` is not `is (not ...)`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "'something' is not None\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "'something' is (not None)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ A tic-tac-toe where X wins in the first attempt!\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Let's initialize a row\n", - "row = [\"\"] * 3 #row i['', '', '']\n", - "# Let's make a board\n", - "board = [row] * 3\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[['', '', ''], ['', '', ''], ['', '', '']]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "board\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['', '', '']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "board[0]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "''\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "board[0][0]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[['X', '', ''], ['X', '', ''], ['X', '', '']]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "board[0][0] = \"X\"\n", - "board\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "We didn't assign three `\"X\"`s, did we?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "When we initialize `row` variable, this visualization explains what happens in the memory\n", - "\n", - "![image](/images/tic-tac-toe/after_row_initialized.png)\n", - "\n", - "And 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", - "![image](/images/tic-tac-toe/after_board_initialized.png)\n", - "\n", - "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[['X', '', ''], ['', '', ''], ['', '', '']]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "board = [['']*3 for _ in range(3)]\n", - "board[0][0] = \"X\"\n", - "board\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ The sticky output function\n", - "1\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "funcs = []\n", - "results = []\n", - "for 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", - "\n", - "funcs_results = [func() for func in funcs]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[0, 1, 2, 3, 4, 5, 6]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "results\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[6, 6, 6, 6, 6, 6, 6]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "funcs_results\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.\n", - "\n", - "2\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "powers_of_x = [lambda x: x**i for i in range(10)]\n", - "[f(2) for f in powers_of_x]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.\n", - "\n", - "- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " funcs = []\n", - " for x in range(7):\n", - " def some_func(x=x):\n", - " return x\n", - " funcs.append(some_func)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " **Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " [0, 1, 2, 3, 4, 5, 6]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " funcs_results = [func() for func in funcs]\n", - " funcs_results\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ The chicken-egg problem *\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(3, int)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(type, object)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(object, type)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "So which is the \"ultimate\" base class? There's more to the confusion by the way,\n", - "\n", - "2\\. \n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "class A: pass\n", - "isinstance(A, A)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(type, type)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "isinstance(object, object)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "issubclass(int, object)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "issubclass(type, object)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "issubclass(object, type)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "- `type` is a [metaclass](https://realpython.com/python-metaclasses/) 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Subclass relationships\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from collections import Hashable\n", - "issubclass(list, object)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "issubclass(object, Hashable)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "issubclass(list, Hashable)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "The 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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://www.naftaliharris.com/blog/python-subclass-intransitivity/).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ All-true-ation *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "all([True, True, True])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "all([True, True, False])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "all([])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "all([[]])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "all([[[]]])\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Why's this True-False alteration?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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 `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty.\n", - "- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ The surprising comma\n", - "**Output (< 3.6):**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " File \"\", line 1\n", - " def h(x, **kwargs,):\n", - " ^\n", - "SyntaxError: invalid syntax\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " File \"\", line 1\n", - " def h(*args,):\n", - " ^\n", - "SyntaxError: invalid syntax\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def h(*args,):\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Strings and the backslashes\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\"\n", - "\n" - ] - } - ], - "source": [ - "print(\"\\\"\")\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\\\"\n", - "\n" - ] - } - ], - "source": [ - "print(r\"\\\"\")\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "File \"\", line 1\n", - " print(r\"\\\")\n", - " ^\n", - "SyntaxError: EOL while scanning string literal\n", - "\n" - ] - } - ], - "source": [ - "print(r\"\\\")\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "r'\\'' == \"\\\\'\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 'wt\"f'\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " 'wt\\\"f'\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "- 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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " r'wt\\\"f' == 'wt\\\\\"f'\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 'wt\\\\\"f'\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " print(repr(r'wt\\\"f')\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " print(\"\\n\")\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " '\\\\\\\\n'\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " print(r\"\\\\n\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "- 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ not knot!\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x = True\n", - "y = False\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "not x == y\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " File \"\", line 1\n", - " x == not y\n", - " ^\n", - "SyntaxError: invalid syntax\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x == not y\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Half triple-quoted strings\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "wtfpython\n" - ] - } - ], - "source": [ - "print('wtfpython''')\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "wtfpython\n" - ] - } - ], - "source": [ - "print(\"wtfpython\"\"\")\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " File \"\", line 3\n", - " print(\"\"\"wtfpython\")\n", - " ^\n", - "SyntaxError: EOF while scanning triple-quoted string literal\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# The following statements raise `SyntaxError`\n", - "# print('''wtfpython')\n", - "# print(\"\"\"wtfpython\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "+ Python supports implicit [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation), Example,\n", - " ```\n", - " >>> print(\"wtf\" \"python\")\n", - " wtfpython\n", - " >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n", - " wtf\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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ What's wrong with booleans?\n", - "1\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# A simple example to count the number of booleans and\n", - "# integers in an iterable of mixed data types.\n", - "mixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\n", - "integers_found_so_far = 0\n", - "booleans_found_so_far = 0\n", - "\n", - "for 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "4\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "integers_found_so_far\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "0\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "booleans_found_so_far\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "'wtf'\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_bool = True\n", - "\"wtf\" * some_bool\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "''\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_bool = False\n", - "\"wtf\" * some_bool\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def tell_truth():\n", - " True = False\n", - " if True == False:\n", - " print(\"I have lost faith in truth!\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (< 3.x):**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "I have lost faith in truth!\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "tell_truth()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* `bool` is a subclass of `int` in Python\n", - " \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " issubclass(bool, int)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " issubclass(int, bool)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " \n", - "* And thus, `True` and `False` are instances of `int`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " isinstance(True, int)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " isinstance(False, int)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "* The integer value of `True` is `1` and that of `False` is `0`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 1\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " int(True)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 0\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " int(False)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Class attributes and instance attributes\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "class A:\n", - " x = 1\n", - "\n", - "class B(A):\n", - " pass\n", - "\n", - "class C(A):\n", - " pass\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(1, 1, 1)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "A.x, B.x, C.x\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(1, 2, 1)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "B.x = 2\n", - "A.x, B.x, C.x\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(3, 2, 3)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "A.x = 3\n", - "A.x, B.x, C.x # C.x changed, but B.x didn't\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(3, 3)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = A()\n", - "a.x, A.x\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "(4, 3)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a.x += 1\n", - "a.x, A.x\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "class 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[5, 420]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_obj = SomeClass(420)\n", - "some_obj.some_list\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[5, 420]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_obj.another_list\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[5, 111]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "another_obj = SomeClass(111)\n", - "another_obj.some_list\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[5, 420, 111]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "another_obj.another_list\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "another_obj.another_list is SomeClass.another_list\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "another_obj.another_list is some_obj.another_list\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Non-reflexive class method *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "class SomeClass:\n", - " def instance_method(self):\n", - " pass\n", - " \n", - " @classmethod\n", - " def class_method(cls):\n", - " pass\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "SomeClass.instance_method is SomeClass.instance_method\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "SomeClass.class_method is SomeClass.class_method\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "id(SomeClass.class_method) == id(SomeClass.class_method)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "- The reason `SomeClass.class_method is SomeClass.class_method` is `False` is due to the `@classmethod` decorator. \n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " \n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " SomeClass.instance_method\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " \n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " SomeClass.class_method\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " A new bound method every time `SomeClass.class_method` is accessed.\n", - "\n", - "- `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ yielding None\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_iterable = ('a', 'b')\n", - "\n", - "def some_func(val):\n", - " return \"something\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (<= 3.7.x):**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['a', 'b']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "[x for x in some_iterable]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " at 0x7f70b0a4ad58>\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "[(yield x) for x in some_iterable]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['a', 'b']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list([(yield x) for x in some_iterable])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['a', None, 'b', None]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list((yield x) for x in some_iterable)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['a', 'something', 'b', 'something']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list(some_func((yield x)) for x in some_iterable)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n", - "- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n", - "- Related bug report: http://bugs.python.org/issue10544\n", - "- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Yielding from... return! *\n", - "1\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def some_func(x):\n", - " if x == 3:\n", - " return [\"wtf\"]\n", - " else:\n", - " yield from range(x)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (> 3.3):**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list(some_func(3))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Where did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n", - "\n", - "2\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def some_func(x):\n", - " if x == 3:\n", - " return [\"wtf\"]\n", - " else:\n", - " for i in range(x):\n", - " yield i\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list(some_func(3))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "The same result, this didn't work either.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " try:\n", - " next(some_func(3))\n", - " except StopIteration as e:\n", - " some_string = e.value\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " [\"wtf\"]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_string\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Nan-reflexivity *\n", - "1\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = float('inf')\n", - "b = float('nan')\n", - "c = float('-iNf') # These strings are case-insensitive\n", - "d = float('nan')\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "inf\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "nan\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "b\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "-inf\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "c\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "ValueError: could not convert string to float: some_other_string\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "float('some_other_string')\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a == -c # inf==inf\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "None == None # None == None\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "b == d # but nan!=nan\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "0.0\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "50 / a\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "nan\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a / a\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "nan\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "23 + b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x = float('nan')\n", - "y = x / x\n", - "y is y # identity holds\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "y == y # equality fails of y\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "[y] == [y] # but the equality succeeds for the list containing y\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " (False, True)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " x = float('nan')\n", - " x == x, [x] == [x]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " (False, True)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " y = float('nan')\n", - " y == y, [y] == [y]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " (False, False)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " x == y, [x] == [y]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\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://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Mutating the immutable!\n", - "This might seem trivial if you know how references work in Python.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_tuple = (\"A\", \"tuple\", \"with\", \"values\")\n", - "another_tuple = ([1, 2], [3, 4], [5, 6])\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "TypeError: 'tuple' object does not support item assignment\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_tuple[2] = \"change this\"\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "([1, 2], [3, 4], [5, 6, 1000])\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "another_tuple[2].append(1000) #This throws no error\n", - "another_tuple\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "TypeError: 'tuple' object does not support item assignment\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "another_tuple[2] += [99, 999]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "another_tuple\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "But I thought tuples were immutable...\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* Quoting from https://docs.python.org/2/reference/datamodel.html\n", - "\n", - " > Immutable sequences\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", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ The disappearing variable from outer scope\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "e = 7\n", - "try:\n", - " raise Exception()\n", - "except Exception as e:\n", - " pass\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "# prints nothing\n" - ] - } - ], - "source": [ - "print(e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 3.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "NameError: name 'e' is not defined\n" - ] - } - ], - "source": [ - "print(e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* Source: https://docs.python.org/3/reference/compound_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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " except E as N:\n", - " foo\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " was translated into\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " except E as N:\n", - " try:\n", - " foo\n", - " finally:\n", - " del N\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " def f(x):\n", - " del(x)\n", - " print(x)\n", - "\n", - " x = 5\n", - " y = [5, 4, 3]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " **Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 5\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " >>>f(x)\n", - " UnboundLocalError: local variable 'x' referenced before assignment\n", - " >>>f(y)\n", - " UnboundLocalError: local variable 'x' referenced before assignment\n", - " x\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " [5, 4, 3]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " y\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " Exception()\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " e\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " # Nothing is printed!\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " print e\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ The mysterious key type conversion\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "class SomeClass(str):\n", - " pass\n", - "\n", - "some_dict = {'s': 42}\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "str\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(list(some_dict.keys())[0])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "{'s': 40}\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "s = SomeClass('s')\n", - "some_dict[s] = 40\n", - "some_dict # expected: Two different keys-value pairs\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "str\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "type(list(some_dict.keys())[0])\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " **Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " {'s': 40, 's': 42}\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " s = SomeClass('s')\n", - " some_dict[s] = 40\n", - " some_dict\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " (__main__.SomeClass, str)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " keys = list(some_dict.keys())\n", - " type(keys[0]), type(keys[1])\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Let's see if you can guess this?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a, b = a[b] = {}, 5\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "{5: ({...}, 5)}\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form\n", - " ```\n", - " (target_list \"=\")+ (expression_list | yield_expression)\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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " [[...]]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_list = some_list[0] = [0]\n", - " some_list\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " [[...]]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_list[0]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_list is some_list[0]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_list[0][0][0][0][0][0] == some_list\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " 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" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " a, b = {}, 5\n", - " a[b] = a, b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " a[b][0] is a\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Modifying a dictionary while iterating over it\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x = {0: None}\n", - "\n", - "for i in x:\n", - " del x[i]\n", - " x[i+1] = None\n", - " print(i)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.7- Python 3.5):**\n", - "\n", - "```\n", - "0\n", - "1\n", - "2\n", - "3\n", - "4\n", - "5\n", - "6\n", - "7\n", - "```\n", - "\n", - "Yes, it runs for exactly **eight** times and stops.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* Iteration over a dictionary that you edit at the same time is not supported.\n", - "* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.\n", - "* How deleted keys are handled and when the resize occurs might be different for different Python implementations.\n", - "* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread.\n", - "* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ The out of scope variable\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = 1\n", - "def some_func():\n", - " return a\n", - "\n", - "def another_func():\n", - " a += 1\n", - " return a\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "1\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_func()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "UnboundLocalError: local variable 'a' referenced before assignment\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "another_func()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.\n", - "* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.\n", - "* To modify the outer scope variable `a` in `another_func`, use `global` keyword.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " def another_func()\n", - " global a\n", - " a += 1\n", - " return a\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " **Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 2\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " another_func()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Deleting a list item while iterating\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list_1 = [1, 2, 3, 4]\n", - "list_2 = [1, 2, 3, 4]\n", - "list_3 = [1, 2, 3, 4]\n", - "list_4 = [1, 2, 3, 4]\n", - "\n", - "for idx, item in enumerate(list_1):\n", - " del item\n", - "\n", - "for idx, item in enumerate(list_2):\n", - " list_2.remove(item)\n", - "\n", - "for idx, item in enumerate(list_3[:]):\n", - " list_3.remove(item)\n", - "\n", - "for idx, item in enumerate(list_4):\n", - " list_4.pop(idx)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[1, 2, 3, 4]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list_1\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[2, 4]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list_2\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list_3\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[2, 4]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list_4\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Can you guess why the output is `[2, 4]`?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 139798789457608\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_list = [1, 2, 3, 4]\n", - " id(some_list)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 139798779601192\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " id(some_list[:]) # Notice that python creates new object for sliced list.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Difference between `del`, `remove`, and `pop`:**\n", - "* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).\n", - "* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.\n", - "* `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified.\n", - "\n", - "**Why the output is `[2, 4]`?**\n", - "- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.\n", - "\n", - "* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example\n", - "* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Lossy zip of iterators *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[0, 1, 2, 3, 4, 5, 6]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "numbers = list(range(7))\n", - "numbers\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "([0, 1, 2], [3, 4, 5, 6])\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "first_three, remaining = numbers[:3], numbers[3:]\n", - "first_three, remaining\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[(0, 0), (1, 1), (2, 2)]\n", - "# so far so good, let's zip the remaining\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "numbers_iter = iter(numbers)\n", - "list(zip(numbers_iter, first_three)) \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[(4, 3), (5, 4), (6, 5)]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list(zip(numbers_iter, remaining))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Where did element `3` go from the `numbers` list?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " def zip(*iterables):\n", - " sentinel = object()\n", - " iterators = [iter(it) for it in iterables]\n", - " while iterators:\n", - " result = []\n", - " for it in iterators:\n", - " elem = next(it, sentinel)\n", - " if elem is sentinel: return\n", - " result.append(elem)\n", - " yield tuple(result)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. \n", - "- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.\n", - "- The correct way to do the above using `zip` would be,\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " [(0, 0), (1, 1), (2, 2)]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " numbers = list(range(7))\n", - " numbers_iter = iter(numbers)\n", - " list(zip(first_three, numbers_iter))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " [(3, 3), (4, 4), (5, 5), (6, 6)]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " list(zip(remaining, numbers_iter))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " The first argument of zip should be the one with fewest elements.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Loop variables leaking out!\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [] - } - ], - "source": [ - "for x in range(7):\n", - " if x == 6:\n", - " print(x, ': for x inside loop')\n", - "print(x, ': x in global')\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "6 : for x inside loop\n", - "6 : x in global\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "But `x` was never defined outside the scope of for loop...\n", - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [] - } - ], - "source": [ - "# This time let's initialize x first\n", - "x = -1\n", - "for x in range(7):\n", - " if x == 6:\n", - " print(x, ': for x inside loop')\n", - "print(x, ': x in global')\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "6 : for x inside loop\n", - "6 : x in global\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n", - "**Output (Python 2.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[0, 1, 2, 3, 4]\n" - ] - } - ], - "source": [ - "x = 1\n", - "print([x for x in range(5)])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "4\n" - ] - } - ], - "source": [ - "print(x)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 3.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[0, 1, 2, 3, 4]\n" - ] - } - ], - "source": [ - "x = 1\n", - "print([x for x in range(5)])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n" - ] - } - ], - "source": [ - "print(x)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.\n", - "\n", - "- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog:\n", - "\n", - " > \"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.\"\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Beware of default mutable arguments!\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def some_func(default_arg=[]):\n", - " default_arg.append(\"some_string\")\n", - " return default_arg\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['some_string']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_func()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['some_string', 'some_string']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_func()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['some_string']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_func([])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['some_string', 'some_string', 'some_string']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_func()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " def some_func(default_arg=[]):\n", - " default_arg.append(\"some_string\")\n", - " return default_arg\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " **Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " ([],)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_func.__defaults__ #This will show the default argument values for the function\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " (['some_string'],)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_func()\n", - " some_func.__defaults__\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " (['some_string', 'some_string'],)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_func()\n", - " some_func.__defaults__\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " (['some_string', 'some_string'],)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_func([])\n", - " some_func.__defaults__\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " def some_func(default_arg=None):\n", - " if not default_arg:\n", - " default_arg = []\n", - " default_arg.append(\"some_string\")\n", - " return default_arg\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Catching the Exceptions\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_list = [1, 2, 3]\n", - "try:\n", - " # This should raise an ``IndexError``\n", - " print(some_list[4])\n", - "except IndexError, ValueError:\n", - " print(\"Caught!\")\n", - "\n", - "try:\n", - " # This should raise a ``ValueError``\n", - " some_list.remove(4)\n", - "except IndexError, ValueError:\n", - " print(\"Caught again!\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Caught!\n", - "\n", - "ValueError: list.remove(x): x not in list\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 3.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " File \"\", line 3\n", - " except IndexError, ValueError:\n", - " ^\n", - "SyntaxError: invalid syntax\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example,\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_list = [1, 2, 3]\n", - " try:\n", - " # This should raise a ``ValueError``\n", - " some_list.remove(4)\n", - " except (IndexError, ValueError), e:\n", - " print(\"Caught again!\")\n", - " print(e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " **Output (Python 2.x):**\n", - " ```\n", - " Caught again!\n", - " list.remove(x): x not in list\n", - " ```\n", - " **Output (Python 3.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " File \"\", line 4\n", - " except (IndexError, ValueError), e:\n", - " ^\n", - " IndentationError: unindent does not match any outer indentation level\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example,\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " some_list = [1, 2, 3]\n", - " try:\n", - " some_list.remove(4)\n", - "\n", - " except (IndexError, ValueError) as e:\n", - " print(\"Caught again!\")\n", - " print(e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " **Output:**\n", - " ```\n", - " Caught again!\n", - " list.remove(x): x not in list\n", - " ```\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Same operands, different story!\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = [1, 2, 3, 4]\n", - "b = a\n", - "a = a + [5, 6, 7, 8]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[1, 2, 3, 4, 5, 6, 7, 8]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[1, 2, 3, 4]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = [1, 2, 3, 4]\n", - "b = a\n", - "a += [5, 6, 7, 8]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[1, 2, 3, 4, 5, 6, 7, 8]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[1, 2, 3, 4, 5, 6, 7, 8]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this.\n", - "\n", - "* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged.\n", - "\n", - "* The expression `a += [5,6,7,8]` is actually mapped to an \"extend\" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Be careful with chained operations\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "(False == False) in [False] # makes sense\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "False == (False in [False]) # makes sense\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "False == False in [False] # now what?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "True is False == False\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "False is False is False\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "1 > 0 < 1\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "(1 > 0) < 1\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "1 > (0 < 1)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "As per https://docs.python.org/2/reference/expressions.html#not-in\n", - "\n", - "> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.\n", - "\n", - "While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 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` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n", - "* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`.\n", - "* The expression `(1 > 0) < 1` is equivalent to `True < 1` and\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 1\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " int(True)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 2\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " True + 1 #not relevant for this example, but just for fun\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " So, `1 < 1` evaluates to `False`\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Name resolution ignoring class scope\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x = 5\n", - "class SomeClass:\n", - " x = 17\n", - " y = (x for i in range(10))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "5\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "list(SomeClass.y)[0]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x = 5\n", - "class SomeClass:\n", - " x = 17\n", - " y = [x for i in range(10)]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "17\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "SomeClass.y[0]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 3.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "5\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "SomeClass.y[0]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "- Scopes nested inside class definition ignore names bound at the class level.\n", - "- A generator expression has its own scope.\n", - "- Starting from Python 3.X, list comprehensions also have their own scope.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Needles in a Haystack *\n", - "I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios,\n", - "\n", - "1\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x, y = (0, 1) if True else None, None\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "((0, 1), None)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x, y # expected (0, 1)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [] - } - ], - "source": [ - "t = ('one', 'two')\n", - "for i in t:\n", - " print(i)\n", - "\n", - "t = ('one')\n", - "for i in t:\n", - " print(i)\n", - "\n", - "t = ()\n", - "print(t)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "one\n", - "two\n", - "o\n", - "n\n", - "e\n", - "tuple()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n", - "```\n", - "ten_words_list = [\n", - " \"some\",\n", - " \"very\",\n", - " \"big\",\n", - " \"list\",\n", - " \"that\"\n", - " \"consists\",\n", - " \"of\",\n", - " \"exactly\",\n", - " \"ten\",\n", - " \"words\"\n", - "]\n", - "```\n", - "\n", - "**Output**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "9\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "len(ten_words_list)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "4\\. Not asserting strongly enough\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "a = \"python\"\n", - "b = \"javascript\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "# No AssertionError is raised\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# An assert statement with an assertion failure message.\n", - "assert(a == b, \"Both languages are different\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "5\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_list = [1, 2, 3]\n", - "some_dict = {\n", - " \"key_1\": 1,\n", - " \"key_2\": 2,\n", - " \"key_3\": 3\n", - "}\n", - "\n", - "some_list = some_list.append(4) \n", - "some_dict = some_dict.update({\"key_4\": 4})\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "None\n" - ] - } - ], - "source": [ - "print(some_list)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "None\n" - ] - } - ], - "source": [ - "print(some_dict)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "6\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def some_recursive_func(a):\n", - " if a[0] == 0:\n", - " return \n", - " a[0] -= 1\n", - " some_recursive_func(a)\n", - " return a\n", - "\n", - "def similar_recursive_func(a):\n", - " if a == 0:\n", - " return a\n", - " a -= 1\n", - " similar_recursive_func(a)\n", - " return a\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[0, 0]\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_recursive_func([5, 0])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "4\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "similar_recursive_func(5)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`.\n", - "\n", - "* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character.\n", - "\n", - "* `()` is a special token and denotes empty `tuple`.\n", - "\n", - "* In 3, as you might have already figured out, there's a missing comma after 5th element (`\"that\"`) in the list. So by implicit string literal concatenation,\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " ten_words_list\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up,\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - " AssertionError\n", - " \n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " a = \"python\"\n", - " b = \"javascript\"\n", - " assert a == b\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " :1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n", - " \n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " assert (a == b, \"Values are not equal\")\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - " AssertionError: Values aren not equal\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " assert a == b, \"Values are not equal\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).\n", - "\n", - "* Last one should be fairly obvious, passing mutable object (like `list` ) results in a call by reference, whereas an immutable object (like `int`) results in a call by value.\n", - "\n", - "* Being aware of these nitpicks can save you hours of debugging effort in the long run. \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Splitsies *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['a']\n", - "\n", - "# is same as\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "'a'.split()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['a']\n", - "\n", - "# but\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "'a'.split(' ')\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "0\n", - "\n", - "# isn't the same as\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "len(''.split())\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "1\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "len(''.split(' '))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split)\n", - " > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.\n", - " > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.\n", - "- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " ['', 'a', '']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " ' a '.split(' ')\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " ['a']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " ' a '.split()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " ['']\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " ''.split(' ')\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ All sorted? *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "x = 7, 8, 9\n", - "sorted(x) == x\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sorted(x) == sorted(x)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "y = reversed(x)\n", - "sorted(y) == sorted(y)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. \n", - "\n", - "- ```py\n", - " >>> [] == tuple()\n", - " False\n", - " >>> x = 7, 8, 9\n", - " >>> type(x), type(sorted(x))\n", - " (tuple, list)\n", - " ```\n", - "\n", - "- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first.\n", - "\n", - "- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " ([7, 8, 9], [])\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " x = 7, 8, 9\n", - " y = reversed(x)\n", - " sorted(y), sorted(y)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Midnight time doesn't exist?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from datetime import datetime\n", - "\n", - "midnight = datetime(2018, 1, 1, 0, 0)\n", - "midnight_time = midnight.time()\n", - "\n", - "noon = datetime(2018, 1, 1, 12, 0)\n", - "noon_time = noon.time()\n", - "\n", - "if midnight_time:\n", - " print(\"Time at midnight is\", midnight_time)\n", - "\n", - "if noon_time:\n", - " print(\"Time at noon is\", noon_time)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (< 3.5):**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "('Time at noon is', datetime.time(12, 0))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The midnight time is not printed.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of \"empty.\"\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Okay Python, Can you make me fly?\n", - "Well, here you go\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import antigravity\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "Sshh... It's a super-secret.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "+ `antigravity` module is one of the few easter eggs released by Python developers.\n", - "+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python.\n", - "+ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ `goto`, but why?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [] - } - ], - "source": [ - "from goto import goto, label\n", - "for i in range(9):\n", - " for j in range(9):\n", - " for k in range(9):\n", - " print(\"I am trapped, please rescue!\")\n", - " if k == 2:\n", - " goto .breakout # breaking out from a deeply nested loop\n", - "label .breakout\n", - "print(\"Freedom!\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.3):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "I am trapped, please rescue!\n", - "I am trapped, please rescue!\n", - "Freedom!\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004.\n", - "- Current versions of Python do not have this module.\n", - "- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Brace yourself!\n", - "If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing,\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from __future__ import braces\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " File \"some_file.py\", line 1\n", - " from __future__ import braces\n", - "SyntaxError: not a chance\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "+ The `__future__` module is normally used to provide features from future versions of Python. The \"future\" in this specific context is however, ironic.\n", - "+ This is an easter egg concerned with the community's feelings on this issue.\n", - "+ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file.\n", - "+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Let's meet Friendly Language Uncle For Life\n", - "**Output (Python 3.x)**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " File \"some_file.py\", line 1\n", - " \"Ruby\" != \"Python\"\n", - " ^\n", - "SyntaxError: invalid syntax\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "from __future__ import barry_as_FLUFL\n", - "\"Ruby\" != \"Python\" # there's no doubt about it\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "\"Ruby\" <> \"Python\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "There we go.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means).\n", - "- Quoting from the PEP-401\n", - " \n", - " > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.\n", - "- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/).\n", - "- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working,\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " from __future__ import barry_as_FLUFL\n", - " print(eval('\"Ruby\" <> \"Python\"'))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Even Python understands that love is complicated\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import this\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Wait, what's **this**? `this` is love :heart:\n", - "\n", - "**Output:**\n", - "```\n", - "The Zen of Python, by Tim Peters\n", - "\n", - "Beautiful is better than ugly.\n", - "Explicit is better than implicit.\n", - "Simple is better than complex.\n", - "Complex is better than complicated.\n", - "Flat is better than nested.\n", - "Sparse is better than dense.\n", - "Readability counts.\n", - "Special cases aren't special enough to break the rules.\n", - "Although practicality beats purity.\n", - "Errors should never pass silently.\n", - "Unless explicitly silenced.\n", - "In the face of ambiguity, refuse the temptation to guess.\n", - "There should be one-- and preferably only one --obvious way to do it.\n", - "Although that way may not be obvious at first unless you're Dutch.\n", - "Now is better than never.\n", - "Although never is often better than *right* now.\n", - "If the implementation is hard to explain, it's a bad idea.\n", - "If the implementation is easy to explain, it may be a good idea.\n", - "Namespaces are one honking great idea -- let's do more of those!\n", - "```\n", - "\n", - "It's the Zen of Python!\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "love = this\n", - "this is love\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "love is True\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "love is False\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "love is not True or False\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "love is not True or False; love is love # Love is complicated\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)).\n", - "* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens).\n", - "* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Yes, it exists!\n", - "**The `else` clause for loops.** One typical example might be:\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " def does_exists_num(l, to_find):\n", - " for num in l:\n", - " if num == to_find:\n", - " print(\"Exists!\")\n", - " break\n", - " else:\n", - " print(\"Does not exist\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Exists!\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_list = [1, 2, 3, 4, 5]\n", - "does_exists_num(some_list, 4)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Does not exist\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "does_exists_num(some_list, -1)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**The `else` clause in exception handling.** An example,\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "try:\n", - " pass\n", - "except:\n", - " print(\"Exception occurred!!!\")\n", - "else:\n", - " print(\"Try block executed successfully...\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Try block executed successfully...\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a \"nobreak\" clause.\n", - "- `else` clause after a try block is also called \"completion clause\" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Ellipsis *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def some_func():\n", - " Ellipsis\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "# No output, No Error\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "some_func()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "NameError: name 'SomeRandomString' is not defined\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "SomeRandomString\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Ellipsis\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Ellipsis\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " Ellipsis\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " ...\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "- Eliipsis can be used for several purposes,\n", - " + As a placeholder for code that hasn't been written yet (just like `pass` statement)\n", - " + In slicing syntax to represent the full slices in remaining direction\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " array([\n", - " [\n", - " [0, 1],\n", - " [2, 3]\n", - " ],\n", - "\n", - " [\n", - " [4, 5],\n", - " [6, 7]\n", - " ]\n", - " ])\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " import numpy as np\n", - " three_dimensional_array = np.arange(8).reshape(2, 2, 2)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " array([[1, 3],\n", - " [5, 7]])\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " three_dimensional_array[:,:,1]\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " array([[1, 3],\n", - " [5, 7]])\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " three_dimensional_array[..., 1] # using Ellipsis.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`)\n", - " + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`))\n", - " + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the \"no argument passed\" and \"None value passed\" scenarios).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Inpinity\n", - "The spelling is intended. Please, don't submit a patch for this.\n", - "\n", - "**Output (Python 3.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "314159\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "infinity = float('infinity')\n", - "hash(infinity)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "-314159\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "hash(float('-inf'))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "- Hash of infinity is 10⁵ x π.\n", - "- Interestingly, the hash of `float('-inf')` is \"-10⁵ x π\" in Python 3, whereas \"-10⁵ x e\" in Python 2.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Let's mangle\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "class Yo(object):\n", - " def __init__(self):\n", - " self.__honey = True\n", - " self.bro = True\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Yo().bro\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "AttributeError: 'Yo' object has no attribute '__honey'\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Yo().__honey\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Yo()._Yo__honey\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "class Yo(object):\n", - " def __init__(self):\n", - " # Let's try something symmetrical this time\n", - " self.__honey__ = True\n", - " self.bro = True\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Yo().bro\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "AttributeError: 'Yo' object has no attribute '_Yo__honey__'\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Yo()._Yo__honey__\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Why did `Yo()._Yo__honey` work?\n", - "\n", - "3\\.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "_A__variable = \"Some value\"\n", - "\n", - "class A(object):\n", - " def some_func(self):\n", - " return __variable # not initiatlized anywhere yet\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "'Some value'\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "AttributeError: 'A' object has no attribute '__variable'\n", - "\n", - "A().some_func()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.\n", - "* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a \"dunder\") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front.\n", - "* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class.\n", - "* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores.\n", - "* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope.\n", - "* Also, if the mangled name is longer than 255 characters, truncation will happen.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Skipping lines?\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "11\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "value = 11\n", - "valuе = 32\n", - "value\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Wut?\n", - "\n", - "**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "1077\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ord('е') # cyrillic 'e' (Ye)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "101\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ord('e') # latin 'e', as used in English and typed using standard keyboard\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n", - "\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "'е' == 'e'\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "42\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "value = 42 # latin e\n", - "valuе = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here\n", - "value\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Teleportation\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "import numpy as np\n", - "\n", - "def energy_send(x):\n", - " # Initializing a numpy array\n", - " np.array([float(x)])\n", - "\n", - "def energy_receive():\n", - " # Return an empty numpy array\n", - " return np.empty((), dtype=np.float).tolist()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "123.456\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "energy_send(123.456)\n", - "energy_receive()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Where's the Nobel Prize?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate.\n", - "* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Well, something is fishy...\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def square(x):\n", - " \"\"\"\n", - " A simple function to calculate the square of a number by addition.\n", - " \"\"\"\n", - " sum_so_far = 0\n", - " for counter in range(x):\n", - " sum_so_far = sum_so_far + x\n", - " return sum_so_far\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.x):**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "10\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "square(10)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Shouldn't that be 100?\n", - "\n", - "**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "* **Don't mix tabs and spaces!** The character just preceding return is a \"tab\", and the code is indented by multiple of \"4 spaces\" elsewhere in the example.\n", - "* This is how Python handles tabs:\n", - " \n", - " > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>\n", - "* So the \"tab\" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.\n", - "* Python 3 is kind enough to throw an error for such cases automatically.\n", - "\n", - " **Output (Python 3.x):**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " TabError: inconsistent use of tabs and spaces in indentation\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ `+=` is faster\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "0.25748300552368164\n", - "# using \"+=\", three strings:\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# using \"+\", three strings:\n", - "timeit.timeit(\"s1 = s1 + s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "0.012188911437988281\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "timeit.timeit(\"s1 += s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Let's make a giant string!\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "def add_string_with_plus(iters):\n", - " s = \"\"\n", - " for i in range(iters):\n", - " s += \"xyz\"\n", - " assert len(s) == 3*iters\n", - "\n", - "def add_bytes_with_plus(iters):\n", - " s = b\"\"\n", - " for i in range(iters):\n", - " s += b\"xyz\"\n", - " assert len(s) == 3*iters\n", - "\n", - "def add_string_with_format(iters):\n", - " fs = \"{}\"*iters\n", - " s = fs.format(*([\"xyz\"]*iters))\n", - " assert len(s) == 3*iters\n", - "\n", - "def add_string_with_join(iters):\n", - " l = []\n", - " for i in range(iters):\n", - " l.append(\"xyz\")\n", - " s = \"\".join(l)\n", - " assert len(s) == 3*iters\n", - "\n", - "def convert_list_to_string(l, iters):\n", - " s = \"\".join(l)\n", - " assert len(s) == 3*iters\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "124 µs ± 4.73 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# Executed in ipython shell using %timeit for better readablity of results.\n", - "# You can also use the timeit module in normal python shell/scriptm=, example usage below\n", - "# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())\n", - "\n", - "NUM_ITERS = 1000\n", - "%timeit -n1000 add_string_with_plus(NUM_ITERS)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "211 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%timeit -n1000 add_bytes_with_plus(NUM_ITERS)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "61 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%timeit -n1000 add_string_with_format(NUM_ITERS)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "117 µs ± 3.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%timeit -n1000 add_string_with_join(NUM_ITERS)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "10.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "l = [\"xyz\"]*NUM_ITERS\n", - "%timeit -n1000 convert_list_to_string(l, NUM_ITERS)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Let's increase the number of iterations by a factor of 10.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "1.26 ms ± 76.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "NUM_ITERS = 10000\n", - "%timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "6.82 ms ± 134 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "645 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "1.17 ms ± 7.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "%timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "86.3 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "l = [\"xyz\"]*NUM_ITERS\n", - "%timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces.\n", - "- Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function)\n", - "- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings).\n", - "- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.\n", - "- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + \"x\" + \"y\" + \"z\"` instead of `s += \"xyz\"`, the increase would have been quadratic.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 388 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " def add_string_with_plus(iters):\n", - " s = \"\"\n", - " for i in range(iters):\n", - " s = s + \"x\" + \"y\" + \"z\"\n", - " assert len(s) == 3*iters\n", - "\n", - " %timeit -n100 add_string_with_plus(1000)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" - ] - }, - "execution_count": null, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which,\n", - " \n", - " > There should be one-- and preferably only one --obvious way to do it.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Minor Ones *\n", - "* `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage)\n", - "\n", - " **💡 Explanation:** If `join()` is a method on a string, then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API.\n", - " \n", - "* Few weird looking but semantically correct statements:\n", - " + `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`)\n", - " + `'a'[0][0][0][0][0]` is also a semantically correct statement as strings are [sequences](https://docs.python.org/3/glossary.html#term-sequence)(iterables supporting element access using integer indices) in Python.\n", - " + `3 --0-- 5 == 8` and `--5 == 5` are both semantically correct statements and evaluate to `True`.\n", - "\n", - "* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java.\n", - " ```py\n", - " >>> a = 5\n", - " >>> a\n", - " 5\n", - " >>> ++a\n", - " 5\n", - " >>> --a\n", - " 5\n", - " ```\n", - "\n", - " **💡 Explanation:**\n", - " + There is no `++` operator in Python grammar. It is actually two `+` operators.\n", - " + `++a` parses as `+(+a)` which translates to `a`. Similarly, the output of the statement `--a` can be justified.\n", - " + This StackOverflow [thread](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) discusses the rationale behind the absence of increment and decrement operators in Python.\n", - "\n", - "* You must be aware of the Walrus operator in Python. But have you ever heard about *the space-invader operator*?\n", - " ```py\n", - " >>> a = 42\n", - " >>> a -=- 1\n", - " >>> a\n", - " 43\n", - " ```\n", - " It is used as an alternative incrementation operator, together with another one\n", - " ```py\n", - " >>> a +=+ 1\n", - " >>> a\n", - " >>> 44\n", - " ```\n", - " **💡 Explanation:** This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case.\n", - " \n", - "* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. \n", - " \n", - " ```py\n", - " >>> False ** False == True\n", - " True\n", - " >>> False ** True == False\n", - " True\n", - " >>> True ** False == True\n", - " True\n", - " >>> True ** True == True\n", - " True\n", - " ```\n", - "\n", - " **💡 Explanation:** If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to a converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator))\n", - " \n", - "* Since we are talking operators, there's also `@` operator for matrix multiplication (don't worry, this time it's for real).\n", - "\n", - " ```py\n", - " >>> import numpy as np\n", - " >>> np.array([2, 2, 2]) @ np.array([7, 8, 8])\n", - " 46\n", - " ```\n", - "\n", - " **💡 Explanation:** The `@` operator was added in Python 3.5 keeping sthe cientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator.\n", - "\n", - "* From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example,\n", - " ```py\n", - " >>> some_string = \"wtfpython\"\n", - " >>> f'{some_string=}'\n", - " \"string='wtfpython'\"\n", - " ``` \n", - "\n", - "* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!):\n", - " \n", - " ```py\n", - " import dis\n", - " exec(\"\"\"\n", - " def f():\n", - " \"\"\" + \"\"\"\n", - " \"\"\".join([\"X\" + str(x) + \"=\" + str(x) for x in range(65539)]))\n", - " \n", - "f()\n", - " \n", - " print(dis.dis(f))\n", - "```\n", - " \n", - "* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module.\n", - "\n", - "* Sometimes, the `print` method might not print values immediately. For example,\n", - "\n", - " ```py\n", - " # File some_file.py\n", - " import time\n", - " \n", - " print(\"wtfpython\", end=\"_\")\n", - " time.sleep(3)\n", - " ```\n", - "\n", - " This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument.\n", - "\n", - "* List slicing with out of the bounds indices throws no errors\n", - " ```py\n", - " >>> some_list = [1, 2, 3, 4, 5]\n", - " >>> some_list[111:]\n", - " []\n", - " ```\n", - "\n", - "* Slicing an iterable not always creates a new object. For example,\n", - " ```py\n", - " >>> some_str = \"wtfpython\"\n", - " >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n']\n", - " >>> some_list is some_list[:] # False expected because a new object is created.\n", - " False\n", - " >>> some_str is some_str[:] # True because strings are immutable, so making a new object is of not much use.\n", - " True\n", - " ```\n", - "\n", - "* `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.\n", - "\n", - "* You can seperate numeric literals with underscores (for better readablity) from Python 3 onwards.\n", - "\n", - " ```py\n", - " >>> six_million = 6_000_000\n", - " >>> six_million\n", - " 6000000\n", - " >>> hex_address = 0xF00D_CAFE\n", - " >>> hex_address\n", - " 4027435774\n", - " ```\n", - "\n", - "* `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear\n", - " ```py\n", - " def count(s, sub):\n", - " result = 0\n", - " for i in range(len(s) + 1 - len(sub)):\n", - " result += (s[i:i + len(sub)] == sub)\n", - " return result\n", - " ```\n", - " The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string.\n", - "\n", - "**That's all folks!**\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 \"\", line 1\n", - " a := \"wtf_walrus\"\n", - " ^\n", - "SyntaxError: invalid syntax\n", - "\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> (a := \"wtf_walrus\") # This works though\n", - ">>> a\n", - "```\n", - "```py\n", - "'wtf_walrus'\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2 \\.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - "# Python version 3.8+\n", - "\n", - ">>> a = 6, 9\n", - ">>> a\n", - "```\n", - "```py\n", - "(6, 9)\n", - "\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> (a := 6, 9)\n", - ">>> a\n", - "```\n", - "```py\n", - "6\n", - "\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> a, b = 6, 9 # Typcial unpacking\n", - ">>> a, b\n", - "```\n", - "```py\n", - "(6, 9)\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> (a, b = 16, 19) # Oops\n", - "```\n", - "```py\n", - " File \"\", line 1\n", - " (a, b = 6, 9)\n", - " ^\n", - "SyntaxError: invalid syntax\n", - "\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> (a, b := 16, 19) # This prints out a weird 3-tuple\n", - "```\n", - "```py\n", - "(6, 16, 19)\n", - "\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> a # a is still unchanged?\n", - "```\n", - "```py\n", - "6\n", - "\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> b\n", - "```\n", - "```py\n", - "16\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation\n", - "\n", - "**Quick walrus operator refresher**\n", - "\n", - "The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - "def some_func():\n", - " # Assume some expensive computation here\n", - " # time.sleep(1000)\n", - " return 5\n", - "\n", - "# So instead of,\n", - "if some_func():\n", - " print(some_func()) # Which is bad practice since computation is happening twice\n", - "\n", - "# or\n", - "a = some_func()\n", - "if a:\n", - " print(a)\n", - "\n", - "# Now you can concisely write\n", - "if a := some_func():\n", - " print(a)\n", - "```\n", - "```py\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (> 3.8):**\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - "5\n", - "5\n", - "5\n", - "```\n", - "```py\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "This 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, hence the `SyntaxError` in the `a := \"wtf_walrus\"` statement of the first snippet. Parenthesizing it worked as expected and assigned `a`. \n", - "\n", - "- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. \n", - "\n", - "- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", - "\n", - " - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6')\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> (a := 6, 9) == ((a := 6), 9)\n", - "```\n", - "```py\n", - " True\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> x = (a := 696, 9)\n", - " >>> x\n", - "```\n", - "```py\n", - " (696, 9)\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> x[0] is a # Both reference same memory location\n", - "```\n", - "```py\n", - " True\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Stubborn `del` operation\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - "class SomeClass:\n", - " def __del__(self):\n", - " print(\"Deleted!\")\n", - "```\n", - "```py\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "1\\.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> x = SomeClass()\n", - ">>> y = x\n", - ">>> del x # this should print \"Deleted!\"\n", - ">>> del y\n", - "```\n", - "```py\n", - "Deleted!\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.\n", - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> x = SomeClass()\n", - ">>> y = x\n", - ">>> del x\n", - ">>> y # check if y exists\n", - "```\n", - "```py\n", - "<__main__.SomeClass instance at 0x7f98a1a67fc8>\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> del y # Like previously, this should print \"Deleted!\"\n", - ">>> globals() # oh, it didn't. Let's check all our global variables and confirm\n", - "```\n", - "```py\n", - "Deleted!\n", - "{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None}\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Okay, now it's deleted :confused:\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "+ `del x` doesn’t directly call `x.__del__()`.\n", - "+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero.\n", - "+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.\n", - "+ Calling `globals` caused the existing reference to be destroyed, and hence we can see \"Deleted!\" being printed (finally!).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### ▶ Wild imports *\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - "# File: module.py\n", - "\n", - "def some_weird_name_func_():\n", - " print(\"works!\")\n", - "\n", - "def _another_weird_name_func():\n", - " print(\"works!\")\n", - "\n", - "```\n", - "```py\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output**\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> from module import *\n", - ">>> some_weird_name_func_()\n", - "```\n", - "```py\n", - "\"works!\"\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - ">>> _another_weird_name_func()\n", - "```\n", - "```py\n", - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "NameError: name '_another_weird_name_func' is not defined\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 💡 Explanation:\n", - "\n", - "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime.\n", - "- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> from module import some_weird_name_func_, _another_weird_name_func\n", - " >>> _another_weird_name_func()\n", - "```\n", - "```py\n", - " works!\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " __all__ = ['_another_weird_name_func']\n", - "\n", - " def some_weird_name_func_():\n", - " print(\"works!\")\n", - "\n", - " def _another_weird_name_func():\n", - " print(\"works!\")\n", - "```\n", - "```py\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " **Output**\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> _another_weird_name_func()\n", - "```\n", - "```py\n", - " \"works!\"\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```py\n", - " >>> some_weird_name_func_()\n", - "```\n", - "```py\n", - " Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - " NameError: name 'some_weird_name_func_' is not defined\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Contributing\n", - "\n", - "A few ways that you can contribute to wtfpython,\n", - "\n", - "- Suggesting new examples\n", - "- Helping with translation (See [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation))\n", - "- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc.\n", - "- Identifying gaps (things like inadequate explanation, redundant examples, etc.)\n", - "- Any creative suggestions to make this project more fun and useful\n", - "\n", - "Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) to discuss things.\n", - "\n", - "PS: Please don't reach out with backlinking requests, no links will be added unless they're highly relevant to the project.\n", - "\n", - "# Acknowledgements\n", - "\n", - "The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by Pythonistas gave it the shape it is in right now.\n", - "\n", - "#### Some nice Links!\n", - "* https://www.youtube.com/watch?v=sH4XF6pKKmk\n", - "* https://www.reddit.com/r/Python/comments/3cu6ej/what_are_some_wtf_things_about_python\n", - "* https://sopython.com/wiki/Common_Gotchas_In_Python\n", - "* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines\n", - "* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python\n", - "* https://www.python.org/doc/humor/\n", - "* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator\n", - "* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65\n", - "* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues\n", - "\n", - "# 🎓 License\n", - "\n", - "[![WTFPL 2.0][license-image]][license-url]\n", - "\n", - "© [Satwik Kansal](https://satwikkansal.xyz)\n", - "\n", - "[license-url]: http://www.wtfpl.net\n", - "[license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square\n", - "\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.0+" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} +{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["

\"\"

\n", "

What the f*ck Python! \ud83d\ude31

\n", "

Exploring and understanding Python through surprising snippets.

\n", "\n", "Translations: [Chinese \u4e2d\u6587](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's 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", "# Structure of the Examples\n", "\n", "All the examples are structured like below:\n", "\n", "> ### \u25b6 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", "> #### \ud83d\udca1 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", "# \ud83d\udc40 Examples\n", "\n", "\n\n## Hosted notebook instructions\n\nThis 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\nThe 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\nThat being said, most of the 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": ["### \u25b6 Strings can be tricky sometimes\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140420665652016\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"some_string\"\n", "id(a)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140420665652016\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(\"some\" + \"_\" + \"string\") # Notice that both the ids are same.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"wtf\"\n", "b = \"wtf\"\n", "a is b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"wtf!\"\n", "b = \"wtf!\"\n", "a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = \"wtf!\", \"wtf!\"\n", "a is b # All versions except 3.7.x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"wtf!\"; b = \"wtf!\"\n", "a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["# This time in file some_file.py\n", "a = \"wtf!\"\n", "b = \"wtf!\"\n", "print(a is b)\n", "\n", "# prints True when the module is invoked!\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "4\\.\n", "\n", "**Output (< Python3.7 )**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Makes sense, right?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ The behavior in first and second snippets is due to a CPython optimization (called string interning) 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 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. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", " ![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images//string-intern/string_intern.png)\n", "+ When `a` and `b` are set to `\"wtf!\"` 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 `wtf!` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, 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 [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.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 with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Hash brownies\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict = {}\n", "some_dict[5.5] = \"JavaScript\"\n", "some_dict[5.0] = \"Ruby\"\n", "some_dict[5] = \"Python\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\"JavaScript\"\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict[5.5]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\"Python\"\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\"Python\"\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict[5] \n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["complex\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["complex_five = 5 + 0j\n", "type(complex_five)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\"Python\"\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict[complex_five]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "So, why is Python all over the place?\n", "\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.\n", "* Immutable objects with the same value always have the same hash in Python.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" 5 == 5.0 == 5 + 0j\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" hash(5) == hash(5.0) == hash(5 + 0j)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" **Note:** Objects with different values may also have same hash (known as [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science))).\n", "* When the statement `some_dict[5] = \"Python\"` is executed, the existing value \"Ruby\" is overwritten with \"Python\" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`.\n", "* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains the rationale behind it.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Deep down, we're all the same.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class WTF:\n", " pass\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["WTF() == WTF() # two different instances can't be equal\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["WTF() is WTF() # identities are also different\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(WTF()) == id(WTF())\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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 evaluated to `False`? Let's see with this snippet.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" class WTF(object):\n", " def __init__(self): print(\"I\")\n", " def __del__(self): print(\"D\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" I\n", " I\n", " D\n", " D\n", " False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" WTF() is WTF()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" I\n", " D\n", " I\n", " D\n", " True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" id(WTF()) == id(WTF())\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" As you may observe, the order in which the objects are destroyed is what made all the difference here.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Disorder within order *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from collections import OrderedDict\n", "\n", "dictionary = dict()\n", "dictionary[1] = 'a'; dictionary[2] = 'b';\n", "\n", "ordered_dict = OrderedDict()\n", "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", "\n", "another_ordered_dict = OrderedDict()\n", "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", "\n", "class DictWithHash(dict):\n", " \"\"\"\n", " A dict that also implements __hash__ magic.\n", " \"\"\"\n", " __hash__ = lambda self: 0\n", "\n", "class OrderedDictWithHash(OrderedDict):\n", " \"\"\"\n", " An OrderedDict that also implements __hash__ magic.\n", " \"\"\"\n", " __hash__ = lambda self: 0\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["dictionary == ordered_dict # If a == b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["dictionary == another_ordered_dict # and b == c\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\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"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["ordered_dict == another_ordered_dict # the why isn't c == a ??\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "TypeError: unhashable type: 'dict'\n", "\n", "# Makes sense since dict don't have __hash__ implemented, let's use\n", "# our wrapper classes.\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len({dictionary, ordered_dict, another_ordered_dict})\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["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})\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "What is going on here?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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://docs.python.org/3/library/collections.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", "- The reason for this equality is 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 lenght 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_set = set()\n", " some_set.add(dictionary) # these are the mapping objects from the snippets above\n", " ordered_dict in some_set\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_set.add(ordered_dict)\n", " len(some_set)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_ordered_dict in some_set\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 1\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_set.add(another_ordered_dict)\n", " len(some_set)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_set = set()\n", " another_set.add(ordered_dict)\n", " another_ordered_dict in another_set\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_set.add(another_ordered_dict)\n", " len(another_set)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" dictionary in another_set\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_set.add(another_ordered_dict)\n", " len(another_set)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Keep trying... *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func():\n", " try:\n", " return 'from_try'\n", " finally:\n", " return 'from_finally'\n", "\n", "def another_func(): \n", " for _ in range(3):\n", " try:\n", " continue\n", " finally:\n", " print(\"Finally!\")\n", "\n", "def one_more_func(): # A gotcha!\n", " try:\n", " for i in range(3):\n", " try:\n", " 1 / 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 ocurred\", e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["'from_finally'\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Finally!\n", "Finally!\n", "Finally!\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "ZeroDivisionError: division by zero\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["1 / 0\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Iteration 0\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["one_more_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- When a `return`, `break` or `continue` statement is executed in the `try` suite of a \"try\u2026finally\" 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 For what?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_string = \"wtf\"\n", "some_dict = {}\n", "for i, some_dict[i] in enumerate(some_string):\n", " i = 10\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["{0: 'w', 1: 't', 2: 'f'}\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict # An indexed dict appears.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as:\n", " ```\n", " for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" for i in range(4):\n", " print(i)\n", " i = 10\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n", " ```\n", " 0\n", " 1\n", " 2\n", " 3\n", " ```\n", "\n", " Did you expect the loop to run just once?\n", "\n", " **\ud83d\udca1 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)` 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" i, some_dict[i] = (0, 'w')\n", " i, some_dict[i] = (1, 't')\n", " i, some_dict[i] = (2, 'f')\n", " some_dict\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Evaluation time discrepancy\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["array = [1, 8, 15]\n", "# A typical generator expresion\n", "gen = (x for x in array if array.count(x) > 0)\n", "array = [2, 8, 22]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[8]\n"]}], "source": ["print(list(gen)) # Where did the other values go?\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["array_1 = [1,2,3,4]\n", "gen_1 = (x for x in array_1)\n", "array_1 = [1,2,3,4,5]\n", "\n", "array_2 = [1,2,3,4]\n", "gen_2 = (x for x in array_2)\n", "array_2[:] = [1,2,3,4,5]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[1, 2, 3, 4]\n", "\n"]}], "source": ["print(list(gen_1))\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[1, 2, 3, 4, 5]\n"]}], "source": ["print(list(gen_2))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["array_3 = [1, 2, 3]\n", "array_4 = [10, 20, 30]\n", "gen = (i + j for i in array_3 for j in array_4)\n", "\n", "array_3 = [4, 5, 6]\n", "array_4 = [400, 500, 600]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[401, 501, 601, 402, 502, 602, 403, 503, 603]\n"]}], "source": ["print(list(gen))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "- In a [generator](https://wiki.python.org/moin/Generators) 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 binded 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(g)` 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://www.python.org/dev/peps/pep-0289/#the-details)\n", " \n", " > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 How not to use `is` operator\n", "The following is a very famous example present all over the internet.\n", "\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 256\n", "b = 256\n", "a is b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 257\n", "b = 257\n", "a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = []\n", "b = []\n", "a is b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = tuple()\n", "b = tuple()\n", "a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "**Output**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = 257, 257\n", "a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.7.x specifically)**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [">> a is b\n", "False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = 257, 257\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" class A: pass\n", " A() is A() # These are two empty objects at two different memory locations.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**`256` is an existing object but `257` isn't**\n", "\n", "When 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", "\n", "Quoting from https://docs.python.org/3/c-api/long.html\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10922528\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(256)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10922528\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 256\n", "b = 256\n", "id(a)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10922528\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(b)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140084850247312\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(257)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140084850247440\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = 257\n", "y = 257\n", "id(x)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140084850247344\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(y)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Here 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", "\n", "Similar 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140640774013296\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = 257, 257\n", "id(a)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140640774013296\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(b)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140640774013392\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 257\n", "b = 257\n", "id(a)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140640774013488\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(b)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" a, b = 257.0, 257.0\n", " a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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://github.com/satwikkansal/wtfpython/issues/100) for updates.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 `is not ...` is not `is (not ...)`\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'something' is not None\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'something' is (not None)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 A tic-tac-toe where X wins in the first attempt!\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# Let's initialize a row\n", "row = [\"\"] * 3 #row i['', '', '']\n", "# Let's make a board\n", "board = [row] * 3\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[['', '', ''], ['', '', ''], ['', '', '']]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['', '', '']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board[0]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["''\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board[0][0]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[['X', '', ''], ['X', '', ''], ['X', '', '']]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board[0][0] = \"X\"\n", "board\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "We didn't assign three `\"X\"`s, did we?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "When we initialize `row` variable, this visualization explains what happens in the memory\n", "\n", "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images//tic-tac-toe/after_row_initialized.png)\n", "\n", "And 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", "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images//tic-tac-toe/after_board_initialized.png)\n", "\n", "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[['X', '', ''], ['', '', ''], ['', '', '']]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board = [['']*3 for _ in range(3)]\n", "board[0][0] = \"X\"\n", "board\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The sticky output function\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["funcs = []\n", "results = []\n", "for 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", "\n", "funcs_results = [func() for func in funcs]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[0, 1, 2, 3, 4, 5, 6]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["results\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[6, 6, 6, 6, 6, 6, 6]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["funcs_results\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.\n", "\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["powers_of_x = [lambda x: x**i for i in range(10)]\n", "[f(2) for f in powers_of_x]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.\n", "\n", "- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" funcs = []\n", " for x in range(7):\n", " def some_func(x=x):\n", " return x\n", " funcs.append(some_func)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [0, 1, 2, 3, 4, 5, 6]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" funcs_results = [func() for func in funcs]\n", " funcs_results\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The chicken-egg problem *\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(3, int)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(type, object)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(object, type)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "So which is the \"ultimate\" base class? There's more to the confusion by the way,\n", "\n", "2\\. \n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class A: pass\n", "isinstance(A, A)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(type, type)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(object, object)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(int, object)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(type, object)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(object, type)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "- `type` is a [metaclass](https://realpython.com/python-metaclasses/) 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Subclass relationships\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from collections import Hashable\n", "issubclass(list, object)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(object, Hashable)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(list, Hashable)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "The 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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://www.naftaliharris.com/blog/python-subclass-intransitivity/).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 All-true-ation *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([True, True, True])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([True, True, False])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([[]])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([[[]]])\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Why's this True-False alteration?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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 `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty.\n", "- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The surprising comma\n", "**Output (< 3.6):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"\", line 1\n", " def h(x, **kwargs,):\n", " ^\n", "SyntaxError: invalid syntax\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"\", line 1\n", " def h(*args,):\n", " ^\n", "SyntaxError: invalid syntax\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def h(*args,):\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Strings and the backslashes\n", "**Output:**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["\"\n", "\n"]}], "source": ["print(\"\\\"\")\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["\\\"\n", "\n"]}], "source": ["print(r\"\\\"\")\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["File \"\", line 1\n", " print(r\"\\\")\n", " ^\n", "SyntaxError: EOL while scanning string literal\n", "\n"]}], "source": ["print(r\"\\\")\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["r'\\'' == \"\\\\'\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 'wt\"f'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" 'wt\\\"f'\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" r'wt\\\"f' == 'wt\\\\\"f'\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 'wt\\\\\"f'\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" print(repr(r'wt\\\"f')\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" print(\"\\n\")\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" '\\\\\\\\n'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" print(r\"\\\\n\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 not knot!\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = True\n", "y = False\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["not x == y\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"\", line 1\n", " x == not y\n", " ^\n", "SyntaxError: invalid syntax\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x == not y\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Half triple-quoted strings\n", "**Output:**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["wtfpython\n"]}], "source": ["print('wtfpython''')\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["wtfpython\n"]}], "source": ["print(\"wtfpython\"\"\")\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"\", line 3\n", " print(\"\"\"wtfpython\")\n", " ^\n", "SyntaxError: EOF while scanning triple-quoted string literal\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# The following statements raise `SyntaxError`\n", "# print('''wtfpython')\n", "# print(\"\"\"wtfpython\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ Python supports implicit [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation), Example,\n", " ```\n", " >>> print(\"wtf\" \"python\")\n", " wtfpython\n", " >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n", " wtf\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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 What's wrong with booleans?\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# A simple example to count the number of booleans and\n", "# integers in an iterable of mixed data types.\n", "mixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\n", "integers_found_so_far = 0\n", "booleans_found_so_far = 0\n", "\n", "for 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["4\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["integers_found_so_far\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["booleans_found_so_far\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["'wtf'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_bool = True\n", "\"wtf\" * some_bool\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["''\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_bool = False\n", "\"wtf\" * some_bool\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def tell_truth():\n", " True = False\n", " if True == False:\n", " print(\"I have lost faith in truth!\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (< 3.x):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["I have lost faith in truth!\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["tell_truth()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* `bool` is a subclass of `int` in Python\n", " \n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" issubclass(bool, int)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" issubclass(int, bool)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" \n", "* And thus, `True` and `False` are instances of `int`\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" isinstance(True, int)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" isinstance(False, int)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* The integer value of `True` is `1` and that of `False` is `0`.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" int(True)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 0\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" int(False)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Class attributes and instance attributes\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class A:\n", " x = 1\n", "\n", "class B(A):\n", " pass\n", "\n", "class C(A):\n", " pass\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(1, 1, 1)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["A.x, B.x, C.x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(1, 2, 1)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["B.x = 2\n", "A.x, B.x, C.x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(3, 2, 3)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["A.x = 3\n", "A.x, B.x, C.x # C.x changed, but B.x didn't\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(3, 3)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = A()\n", "a.x, A.x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(4, 3)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a.x += 1\n", "a.x, A.x\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[5, 420]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_obj = SomeClass(420)\n", "some_obj.some_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[5, 420]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_obj.another_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[5, 111]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_obj = SomeClass(111)\n", "another_obj.some_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[5, 420, 111]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_obj.another_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_obj.another_list is SomeClass.another_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_obj.another_list is some_obj.another_list\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Non-reflexive class method *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class SomeClass:\n", " def instance_method(self):\n", " pass\n", " \n", " @classmethod\n", " def class_method(cls):\n", " pass\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeClass.instance_method is SomeClass.instance_method\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeClass.class_method is SomeClass.class_method\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(SomeClass.class_method) == id(SomeClass.class_method)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- The reason `SomeClass.class_method is SomeClass.class_method` is `False` is due to the `@classmethod` decorator. \n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" \n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" SomeClass.instance_method\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" \n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" SomeClass.class_method\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " A new bound method every time `SomeClass.class_method` is accessed.\n", "\n", "- `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). \n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 yielding None\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_iterable = ('a', 'b')\n", "\n", "def some_func(val):\n", " return \"something\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (<= 3.7.x):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a', 'b']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["[x for x in some_iterable]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" at 0x7f70b0a4ad58>\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["[(yield x) for x in some_iterable]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a', 'b']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list([(yield x) for x in some_iterable])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a', None, 'b', None]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list((yield x) for x in some_iterable)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a', 'something', 'b', 'something']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(some_func((yield x)) for x in some_iterable)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n", "- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n", "- Related bug report: http://bugs.python.org/issue10544\n", "- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Yielding from... return! *\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func(x):\n", " if x == 3:\n", " return [\"wtf\"]\n", " else:\n", " yield from range(x)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (> 3.3):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(some_func(3))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Where did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n", "\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func(x):\n", " if x == 3:\n", " return [\"wtf\"]\n", " else:\n", " for i in range(x):\n", " yield i\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(some_func(3))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "The same result, this didn't work either.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" try:\n", " next(some_func(3))\n", " except StopIteration as e:\n", " some_string = e.value\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [\"wtf\"]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_string\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Nan-reflexivity *\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = float('inf')\n", "b = float('nan')\n", "c = float('-iNf') # These strings are case-insensitive\n", "d = float('nan')\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["inf\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["nan\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["-inf\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["c\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["ValueError: could not convert string to float: some_other_string\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["float('some_other_string')\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a == -c # inf==inf\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["None == None # None == None\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["b == d # but nan!=nan\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0.0\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["50 / a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["nan\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a / a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["nan\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["23 + b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = float('nan')\n", "y = x / x\n", "y is y # identity holds\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["y == y # equality fails of y\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["[y] == [y] # but the equality succeeds for the list containing y\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (False, True)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" x = float('nan')\n", " x == x, [x] == [x]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (False, True)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" y = float('nan')\n", " y == y, [y] == [y]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (False, False)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" x == y, [x] == [y]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Mutating the immutable!\n", "This might seem trivial if you know how references work in Python.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_tuple = (\"A\", \"tuple\", \"with\", \"values\")\n", "another_tuple = ([1, 2], [3, 4], [5, 6])\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["TypeError: 'tuple' object does not support item assignment\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_tuple[2] = \"change this\"\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["([1, 2], [3, 4], [5, 6, 1000])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_tuple[2].append(1000) #This throws no error\n", "another_tuple\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["TypeError: 'tuple' object does not support item assignment\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_tuple[2] += [99, 999]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_tuple\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "But I thought tuples were immutable...\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* Quoting from https://docs.python.org/2/reference/datamodel.html\n", "\n", " > Immutable sequences\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", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The disappearing variable from outer scope\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["e = 7\n", "try:\n", " raise Exception()\n", "except Exception as e:\n", " pass\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.x):**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["# prints nothing\n"]}], "source": ["print(e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["NameError: name 'e' is not defined\n"]}], "source": ["print(e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* Source: https://docs.python.org/3/reference/compound_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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" except E as N:\n", " foo\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " was translated into\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" except E as N:\n", " try:\n", " foo\n", " finally:\n", " del N\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def f(x):\n", " del(x)\n", " print(x)\n", "\n", " x = 5\n", " y = [5, 4, 3]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 5\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" >>>f(x)\n", " UnboundLocalError: local variable 'x' referenced before assignment\n", " >>>f(y)\n", " UnboundLocalError: local variable 'x' referenced before assignment\n", " x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [5, 4, 3]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" y\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" Exception()\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" e\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" # Nothing is printed!\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" print e\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The mysterious key type conversion\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class SomeClass(str):\n", " pass\n", "\n", "some_dict = {'s': 42}\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["str\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["type(list(some_dict.keys())[0])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["{'s': 40}\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["s = SomeClass('s')\n", "some_dict[s] = 40\n", "some_dict # expected: Two different keys-value pairs\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["str\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["type(list(some_dict.keys())[0])\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" {'s': 40, 's': 42}\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" s = SomeClass('s')\n", " some_dict[s] = 40\n", " some_dict\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (__main__.SomeClass, str)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" keys = list(some_dict.keys())\n", " type(keys[0]), type(keys[1])\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Let's see if you can guess this?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = a[b] = {}, 5\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["{5: ({...}, 5)}\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form\n", " ```\n", " (target_list \"=\")+ (expression_list | yield_expression)\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [[...]]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list = some_list[0] = [0]\n", " some_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [[...]]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list[0]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list is some_list[0]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list[0][0][0][0][0][0] == some_list\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" a, b = {}, 5\n", " a[b] = a, b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" a[b][0] is a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Modifying a dictionary while iterating over it\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = {0: None}\n", "\n", "for i in x:\n", " del x[i]\n", " x[i+1] = None\n", " print(i)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.7- Python 3.5):**\n", "\n", "```\n", "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "```\n", "\n", "Yes, it runs for exactly **eight** times and stops.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* Iteration over a dictionary that you edit at the same time is not supported.\n", "* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.\n", "* How deleted keys are handled and when the resize occurs might be different for different Python implementations.\n", "* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread.\n", "* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The out of scope variable\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 1\n", "def some_func():\n", " return a\n", "\n", "def another_func():\n", " a += 1\n", " return a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["UnboundLocalError: local variable 'a' referenced before assignment\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.\n", "* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.\n", "* To modify the outer scope variable `a` in `another_func`, use `global` keyword.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def another_func()\n", " global a\n", " a += 1\n", " return a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Deleting a list item while iterating\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_1 = [1, 2, 3, 4]\n", "list_2 = [1, 2, 3, 4]\n", "list_3 = [1, 2, 3, 4]\n", "list_4 = [1, 2, 3, 4]\n", "\n", "for idx, item in enumerate(list_1):\n", " del item\n", "\n", "for idx, item in enumerate(list_2):\n", " list_2.remove(item)\n", "\n", "for idx, item in enumerate(list_3[:]):\n", " list_3.remove(item)\n", "\n", "for idx, item in enumerate(list_4):\n", " list_4.pop(idx)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_1\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[2, 4]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_2\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_3\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[2, 4]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_4\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Can you guess why the output is `[2, 4]`?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 139798789457608\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list = [1, 2, 3, 4]\n", " id(some_list)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 139798779601192\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" id(some_list[:]) # Notice that python creates new object for sliced list.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Difference between `del`, `remove`, and `pop`:**\n", "* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).\n", "* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.\n", "* `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified.\n", "\n", "**Why the output is `[2, 4]`?**\n", "- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.\n", "\n", "* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example\n", "* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Lossy zip of iterators *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[0, 1, 2, 3, 4, 5, 6]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["numbers = list(range(7))\n", "numbers\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["([0, 1, 2], [3, 4, 5, 6])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["first_three, remaining = numbers[:3], numbers[3:]\n", "first_three, remaining\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[(0, 0), (1, 1), (2, 2)]\n", "# so far so good, let's zip the remaining\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["numbers_iter = iter(numbers)\n", "list(zip(numbers_iter, first_three)) \n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[(4, 3), (5, 4), (6, 5)]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(zip(numbers_iter, remaining))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["Where did element `3` go from the `numbers` list?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def zip(*iterables):\n", " sentinel = object()\n", " iterators = [iter(it) for it in iterables]\n", " while iterators:\n", " result = []\n", " for it in iterators:\n", " elem = next(it, sentinel)\n", " if elem is sentinel: return\n", " result.append(elem)\n", " yield tuple(result)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. \n", "- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.\n", "- The correct way to do the above using `zip` would be,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [(0, 0), (1, 1), (2, 2)]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" numbers = list(range(7))\n", " numbers_iter = iter(numbers)\n", " list(zip(first_three, numbers_iter))\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [(3, 3), (4, 4), (5, 5), (6, 6)]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" list(zip(remaining, numbers_iter))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" The first argument of zip should be the one with fewest elements.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Loop variables leaking out!\n", "1\\.\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["for x in range(7):\n", " if x == 6:\n", " print(x, ': for x inside loop')\n", "print(x, ': x in global')\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["6 : for x inside loop\n", "6 : x in global\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "But `x` was never defined outside the scope of for loop...\n", "\n", "2\\.\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["# This time let's initialize x first\n", "x = -1\n", "for x in range(7):\n", " if x == 6:\n", " print(x, ': for x inside loop')\n", "print(x, ': x in global')\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["6 : for x inside loop\n", "6 : x in global\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n", "**Output (Python 2.x):**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[0, 1, 2, 3, 4]\n"]}], "source": ["x = 1\n", "print([x for x in range(5)])\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["4\n"]}], "source": ["print(x)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[0, 1, 2, 3, 4]\n"]}], "source": ["x = 1\n", "print([x for x in range(5)])\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["1\n"]}], "source": ["print(x)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.\n", "\n", "- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What\u2019s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog:\n", "\n", " > \"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.\"\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Beware of default mutable arguments!\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func(default_arg=[]):\n", " default_arg.append(\"some_string\")\n", " return default_arg\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['some_string']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['some_string', 'some_string']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['some_string']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func([])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['some_string', 'some_string', 'some_string']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def some_func(default_arg=[]):\n", " default_arg.append(\"some_string\")\n", " return default_arg\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ([],)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_func.__defaults__ #This will show the default argument values for the function\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (['some_string'],)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_func()\n", " some_func.__defaults__\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (['some_string', 'some_string'],)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_func()\n", " some_func.__defaults__\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (['some_string', 'some_string'],)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_func([])\n", " some_func.__defaults__\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def some_func(default_arg=None):\n", " if not default_arg:\n", " default_arg = []\n", " default_arg.append(\"some_string\")\n", " return default_arg\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Catching the Exceptions\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_list = [1, 2, 3]\n", "try:\n", " # This should raise an ``IndexError``\n", " print(some_list[4])\n", "except IndexError, ValueError:\n", " print(\"Caught!\")\n", "\n", "try:\n", " # This should raise a ``ValueError``\n", " some_list.remove(4)\n", "except IndexError, ValueError:\n", " print(\"Caught again!\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Caught!\n", "\n", "ValueError: list.remove(x): x not in list\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" File \"\", line 3\n", " except IndexError, ValueError:\n", " ^\n", "SyntaxError: invalid syntax\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list = [1, 2, 3]\n", " try:\n", " # This should raise a ``ValueError``\n", " some_list.remove(4)\n", " except (IndexError, ValueError), e:\n", " print(\"Caught again!\")\n", " print(e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" **Output (Python 2.x):**\n", " ```\n", " Caught again!\n", " list.remove(x): x not in list\n", " ```\n", " **Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" File \"\", line 4\n", " except (IndexError, ValueError), e:\n", " ^\n", " IndentationError: unindent does not match any outer indentation level\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list = [1, 2, 3]\n", " try:\n", " some_list.remove(4)\n", "\n", " except (IndexError, ValueError) as e:\n", " print(\"Caught again!\")\n", " print(e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" **Output:**\n", " ```\n", " Caught again!\n", " list.remove(x): x not in list\n", " ```\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Same operands, different story!\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = [1, 2, 3, 4]\n", "b = a\n", "a = a + [5, 6, 7, 8]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4, 5, 6, 7, 8]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = [1, 2, 3, 4]\n", "b = a\n", "a += [5, 6, 7, 8]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4, 5, 6, 7, 8]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4, 5, 6, 7, 8]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this.\n", "\n", "* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged.\n", "\n", "* The expression `a += [5,6,7,8]` is actually mapped to an \"extend\" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Be careful with chained operations\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["(False == False) in [False] # makes sense\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["False == (False in [False]) # makes sense\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["False == False in [False] # now what?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["True is False == False\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["False is False is False\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["1 > 0 < 1\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["(1 > 0) < 1\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["1 > (0 < 1)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "As per https://docs.python.org/2/reference/expressions.html#not-in\n", "\n", "> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.\n", "\n", "While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 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` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n", "* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`.\n", "* The expression `(1 > 0) < 1` is equivalent to `True < 1` and\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" int(True)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" True + 1 #not relevant for this example, but just for fun\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" So, `1 < 1` evaluates to `False`\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Name resolution ignoring class scope\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = 5\n", "class SomeClass:\n", " x = 17\n", " y = (x for i in range(10))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["5\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(SomeClass.y)[0]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = 5\n", "class SomeClass:\n", " x = 17\n", " y = [x for i in range(10)]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["17\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeClass.y[0]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["5\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeClass.y[0]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "- Scopes nested inside class definition ignore names bound at the class level.\n", "- A generator expression has its own scope.\n", "- Starting from Python 3.X, list comprehensions also have their own scope.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Needles in a Haystack *\n", "I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios,\n", "\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x, y = (0, 1) if True else None, None\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["((0, 1), None)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x, y # expected (0, 1)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n", "\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["t = ('one', 'two')\n", "for i in t:\n", " print(i)\n", "\n", "t = ('one')\n", "for i in t:\n", " print(i)\n", "\n", "t = ()\n", "print(t)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["one\n", "two\n", "o\n", "n\n", "e\n", "tuple()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n", "```\n", "ten_words_list = [\n", " \"some\",\n", " \"very\",\n", " \"big\",\n", " \"list\",\n", " \"that\"\n", " \"consists\",\n", " \"of\",\n", " \"exactly\",\n", " \"ten\",\n", " \"words\"\n", "]\n", "```\n", "\n", "**Output**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["9\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len(ten_words_list)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "4\\. Not asserting strongly enough\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"python\"\n", "b = \"javascript\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["# No AssertionError is raised\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# An assert statement with an assertion failure message.\n", "assert(a == b, \"Both languages are different\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "5\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_list = [1, 2, 3]\n", "some_dict = {\n", " \"key_1\": 1,\n", " \"key_2\": 2,\n", " \"key_3\": 3\n", "}\n", "\n", "some_list = some_list.append(4) \n", "some_dict = some_dict.update({\"key_4\": 4})\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["None\n"]}], "source": ["print(some_list)\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["None\n"]}], "source": ["print(some_dict)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "6\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_recursive_func(a):\n", " if a[0] == 0:\n", " return \n", " a[0] -= 1\n", " some_recursive_func(a)\n", " return a\n", "\n", "def similar_recursive_func(a):\n", " if a == 0:\n", " return a\n", " a -= 1\n", " similar_recursive_func(a)\n", " return a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[0, 0]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_recursive_func([5, 0])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["4\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["similar_recursive_func(5)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`.\n", "\n", "* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character.\n", "\n", "* `()` is a special token and denotes empty `tuple`.\n", "\n", "* In 3, as you might have already figured out, there's a missing comma after 5th element (`\"that\"`) in the list. So by implicit string literal concatenation,\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ten_words_list\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up,\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" Traceback (most recent call last):\n", " File \"\", line 1, in \n", " AssertionError\n", " \n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" a = \"python\"\n", " b = \"javascript\"\n", " assert a == b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" :1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n", " \n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" assert (a == b, \"Values are not equal\")\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" Traceback (most recent call last):\n", " File \"\", line 1, in \n", " AssertionError: Values aren not equal\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" assert a == b, \"Values are not equal\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).\n", "\n", "* Last one should be fairly obvious, passing mutable object (like `list` ) results in a call by reference, whereas an immutable object (like `int`) results in a call by value.\n", "\n", "* Being aware of these nitpicks can save you hours of debugging effort in the long run. \n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Splitsies *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a']\n", "\n", "# is same as\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'a'.split()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a']\n", "\n", "# but\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'a'.split(' ')\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0\n", "\n", "# isn't the same as\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len(''.split())\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len(''.split(' '))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split)\n", " > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.\n", " > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.\n", "- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ['', 'a', '']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ' a '.split(' ')\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ['a']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ' a '.split()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ['']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ''.split(' ')\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 All sorted? *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = 7, 8, 9\n", "sorted(x) == x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["sorted(x) == sorted(x)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["y = reversed(x)\n", "sorted(y) == sorted(y)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. \n", "\n", "- ```py\n", " >>> [] == tuple()\n", " False\n", " >>> x = 7, 8, 9\n", " >>> type(x), type(sorted(x))\n", " (tuple, list)\n", " ```\n", "\n", "- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first.\n", "\n", "- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ([7, 8, 9], [])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" x = 7, 8, 9\n", " y = reversed(x)\n", " sorted(y), sorted(y)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Midnight time doesn't exist?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from datetime import datetime\n", "\n", "midnight = datetime(2018, 1, 1, 0, 0)\n", "midnight_time = midnight.time()\n", "\n", "noon = datetime(2018, 1, 1, 12, 0)\n", "noon_time = noon.time()\n", "\n", "if midnight_time:\n", " print(\"Time at midnight is\", midnight_time)\n", "\n", "if noon_time:\n", " print(\"Time at noon is\", noon_time)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (< 3.5):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["('Time at noon is', datetime.time(12, 0))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["The midnight time is not printed.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of \"empty.\"\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Okay Python, Can you make me fly?\n", "Well, here you go\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["import antigravity\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "Sshh... It's a super-secret.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ `antigravity` module is one of the few easter eggs released by Python developers.\n", "+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python.\n", "+ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 `goto`, but why?\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["from goto import goto, label\n", "for i in range(9):\n", " for j in range(9):\n", " for k in range(9):\n", " print(\"I am trapped, please rescue!\")\n", " if k == 2:\n", " goto .breakout # breaking out from a deeply nested loop\n", "label .breakout\n", "print(\"Freedom!\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.3):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["I am trapped, please rescue!\n", "I am trapped, please rescue!\n", "Freedom!\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004.\n", "- Current versions of Python do not have this module.\n", "- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Brace yourself!\n", "If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing,\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from __future__ import braces\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" File \"some_file.py\", line 1\n", " from __future__ import braces\n", "SyntaxError: not a chance\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ The `__future__` module is normally used to provide features from future versions of Python. The \"future\" in this specific context is however, ironic.\n", "+ This is an easter egg concerned with the community's feelings on this issue.\n", "+ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file.\n", "+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Let's meet Friendly Language Uncle For Life\n", "**Output (Python 3.x)**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"some_file.py\", line 1\n", " \"Ruby\" != \"Python\"\n", " ^\n", "SyntaxError: invalid syntax\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from __future__ import barry_as_FLUFL\n", "\"Ruby\" != \"Python\" # there's no doubt about it\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["\"Ruby\" <> \"Python\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "There we go.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means).\n", "- Quoting from the PEP-401\n", " \n", " > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.\n", "- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/).\n", "- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" from __future__ import barry_as_FLUFL\n", " print(eval('\"Ruby\" <> \"Python\"'))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Even Python understands that love is complicated\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["import this\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Wait, what's **this**? `this` is love :heart:\n", "\n", "**Output:**\n", "```\n", "The Zen of Python, by Tim Peters\n", "\n", "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n", "Complex is better than complicated.\n", "Flat is better than nested.\n", "Sparse is better than dense.\n", "Readability counts.\n", "Special cases aren't special enough to break the rules.\n", "Although practicality beats purity.\n", "Errors should never pass silently.\n", "Unless explicitly silenced.\n", "In the face of ambiguity, refuse the temptation to guess.\n", "There should be one-- and preferably only one --obvious way to do it.\n", "Although that way may not be obvious at first unless you're Dutch.\n", "Now is better than never.\n", "Although never is often better than *right* now.\n", "If the implementation is hard to explain, it's a bad idea.\n", "If the implementation is easy to explain, it may be a good idea.\n", "Namespaces are one honking great idea -- let's do more of those!\n", "```\n", "\n", "It's the Zen of Python!\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love = this\n", "this is love\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love is True\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love is False\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love is not True or False\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love is not True or False; love is love # Love is complicated\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)).\n", "* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens).\n", "* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Yes, it exists!\n", "**The `else` clause for loops.** One typical example might be:\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def does_exists_num(l, to_find):\n", " for num in l:\n", " if num == to_find:\n", " print(\"Exists!\")\n", " break\n", " else:\n", " print(\"Does not exist\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Exists!\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_list = [1, 2, 3, 4, 5]\n", "does_exists_num(some_list, 4)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Does not exist\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["does_exists_num(some_list, -1)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**The `else` clause in exception handling.** An example,\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["try:\n", " pass\n", "except:\n", " print(\"Exception occurred!!!\")\n", "else:\n", " print(\"Try block executed successfully...\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Try block executed successfully...\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a \"nobreak\" clause.\n", "- `else` clause after a try block is also called \"completion clause\" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Ellipsis *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func():\n", " Ellipsis\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["# No output, No Error\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "NameError: name 'SomeRandomString' is not defined\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeRandomString\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Ellipsis\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Ellipsis\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" Ellipsis\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ...\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- Eliipsis can be used for several purposes,\n", " + As a placeholder for code that hasn't been written yet (just like `pass` statement)\n", " + In slicing syntax to represent the full slices in remaining direction\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" array([\n", " [\n", " [0, 1],\n", " [2, 3]\n", " ],\n", "\n", " [\n", " [4, 5],\n", " [6, 7]\n", " ]\n", " ])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" import numpy as np\n", " three_dimensional_array = np.arange(8).reshape(2, 2, 2)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" array([[1, 3],\n", " [5, 7]])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" three_dimensional_array[:,:,1]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" array([[1, 3],\n", " [5, 7]])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" three_dimensional_array[..., 1] # using Ellipsis.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`)\n", " + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`))\n", " + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the \"no argument passed\" and \"None value passed\" scenarios).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Inpinity\n", "The spelling is intended. Please, don't submit a patch for this.\n", "\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["314159\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["infinity = float('infinity')\n", "hash(infinity)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["-314159\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["hash(float('-inf'))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- Hash of infinity is 10\u2075 x \u03c0.\n", "- Interestingly, the hash of `float('-inf')` is \"-10\u2075 x \u03c0\" in Python 3, whereas \"-10\u2075 x e\" in Python 2.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Let's mangle\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class Yo(object):\n", " def __init__(self):\n", " self.__honey = True\n", " self.bro = True\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo().bro\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["AttributeError: 'Yo' object has no attribute '__honey'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo().__honey\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo()._Yo__honey\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class Yo(object):\n", " def __init__(self):\n", " # Let's try something symmetrical this time\n", " self.__honey__ = True\n", " self.bro = True\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo().bro\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "AttributeError: 'Yo' object has no attribute '_Yo__honey__'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo()._Yo__honey__\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Why did `Yo()._Yo__honey` work?\n", "\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["_A__variable = \"Some value\"\n", "\n", "class A(object):\n", " def some_func(self):\n", " return __variable # not initiatlized anywhere yet\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["'Some value'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "AttributeError: 'A' object has no attribute '__variable'\n", "\n", "A().some_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.\n", "* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a \"dunder\") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front.\n", "* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class.\n", "* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores.\n", "* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope.\n", "* Also, if the mangled name is longer than 255 characters, truncation will happen.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Skipping lines?\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["11\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["value = 11\n", "valu\u0435 = 32\n", "value\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Wut?\n", "\n", "**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1077\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["ord('\u0435') # cyrillic 'e' (Ye)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["101\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["ord('e') # latin 'e', as used in English and typed using standard keyboard\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'\u0435' == 'e'\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["42\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["value = 42 # latin e\n", "valu\u0435 = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here\n", "value\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Teleportation\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# `pip install nump` first.\n", "import numpy as np\n", "\n", "def energy_send(x):\n", " # Initializing a numpy array\n", " np.array([float(x)])\n", "\n", "def energy_receive():\n", " # Return an empty numpy array\n", " return np.empty((), dtype=np.float).tolist()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["123.456\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["energy_send(123.456)\n", "energy_receive()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Where's the Nobel Prize?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate.\n", "* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Well, something is fishy...\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def square(x):\n", " \"\"\"\n", " A simple function to calculate the square of a number by addition.\n", " \"\"\"\n", " sum_so_far = 0\n", " for counter in range(x):\n", " sum_so_far = sum_so_far + x\n", " return sum_so_far\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.x):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["square(10)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Shouldn't that be 100?\n", "\n", "**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "* **Don't mix tabs and spaces!** The character just preceding return is a \"tab\", and the code is indented by multiple of \"4 spaces\" elsewhere in the example.\n", "* This is how Python handles tabs:\n", " \n", " > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>\n", "* So the \"tab\" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.\n", "* Python 3 is kind enough to throw an error for such cases automatically.\n", "\n", " **Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" TabError: inconsistent use of tabs and spaces in indentation\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 `+=` is faster\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0.25748300552368164\n", "# using \"+=\", three strings:\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# using \"+\", three strings:\n", "timeit.timeit(\"s1 = s1 + s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0.012188911437988281\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["timeit.timeit(\"s1 += s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Let's make a giant string!\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def add_string_with_plus(iters):\n", " s = \"\"\n", " for i in range(iters):\n", " s += \"xyz\"\n", " assert len(s) == 3*iters\n", "\n", "def add_bytes_with_plus(iters):\n", " s = b\"\"\n", " for i in range(iters):\n", " s += b\"xyz\"\n", " assert len(s) == 3*iters\n", "\n", "def add_string_with_format(iters):\n", " fs = \"{}\"*iters\n", " s = fs.format(*([\"xyz\"]*iters))\n", " assert len(s) == 3*iters\n", "\n", "def add_string_with_join(iters):\n", " l = []\n", " for i in range(iters):\n", " l.append(\"xyz\")\n", " s = \"\".join(l)\n", " assert len(s) == 3*iters\n", "\n", "def convert_list_to_string(l, iters):\n", " s = \"\".join(l)\n", " assert len(s) == 3*iters\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["124 \u00b5s \u00b1 4.73 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# Executed in ipython shell using %timeit for better readablity of results.\n", "# You can also use the timeit module in normal python shell/scriptm=, example usage below\n", "# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())\n", "\n", "NUM_ITERS = 1000\n", "%timeit -n1000 add_string_with_plus(NUM_ITERS)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["211 \u00b5s \u00b1 10.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_bytes_with_plus(NUM_ITERS)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["61 \u00b5s \u00b1 2.18 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_string_with_format(NUM_ITERS)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["117 \u00b5s \u00b1 3.21 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_string_with_join(NUM_ITERS)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10.1 \u00b5s \u00b1 1.06 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["l = [\"xyz\"]*NUM_ITERS\n", "%timeit -n1000 convert_list_to_string(l, NUM_ITERS)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Let's increase the number of iterations by a factor of 10.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1.26 ms \u00b1 76.8 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["NUM_ITERS = 10000\n", "%timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["6.82 ms \u00b1 134 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["645 \u00b5s \u00b1 24.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1.17 ms \u00b1 7.25 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["86.3 \u00b5s \u00b1 2 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["l = [\"xyz\"]*NUM_ITERS\n", "%timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces.\n", "- Don't use `+` for generating long strings \u2014 In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function)\n", "- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings).\n", "- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.\n", "- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + \"x\" + \"y\" + \"z\"` instead of `s += \"xyz\"`, the increase would have been quadratic.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 388 \u00b5s \u00b1 22.4 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def add_string_with_plus(iters):\n", " s = \"\"\n", " for i in range(iters):\n", " s = s + \"x\" + \"y\" + \"z\"\n", " assert len(s) == 3*iters\n", "\n", " %timeit -n100 add_string_with_plus(1000)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 9 ms \u00b1 298 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which,\n", " \n", " > There should be one-- and preferably only one --obvious way to do it.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Minor Ones *\n", "* `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage)\n", "\n", " **\ud83d\udca1 Explanation:** If `join()` is a method on a string, then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API.\n", " \n", "* Few weird looking but semantically correct statements:\n", " + `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`)\n", " + `'a'[0][0][0][0][0]` is also a semantically correct statement as strings are [sequences](https://docs.python.org/3/glossary.html#term-sequence)(iterables supporting element access using integer indices) in Python.\n", " + `3 --0-- 5 == 8` and `--5 == 5` are both semantically correct statements and evaluate to `True`.\n", "\n", "* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java.\n", " ```py\n", " >>> a = 5\n", " >>> a\n", " 5\n", " >>> ++a\n", " 5\n", " >>> --a\n", " 5\n", " ```\n", "\n", " **\ud83d\udca1 Explanation:**\n", " + There is no `++` operator in Python grammar. It is actually two `+` operators.\n", " + `++a` parses as `+(+a)` which translates to `a`. Similarly, the output of the statement `--a` can be justified.\n", " + This StackOverflow [thread](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) discusses the rationale behind the absence of increment and decrement operators in Python.\n", "\n", "* You must be aware of the Walrus operator in Python. But have you ever heard about *the space-invader operator*?\n", " ```py\n", " >>> a = 42\n", " >>> a -=- 1\n", " >>> a\n", " 43\n", " ```\n", " It is used as an alternative incrementation operator, together with another one\n", " ```py\n", " >>> a +=+ 1\n", " >>> a\n", " >>> 44\n", " ```\n", " **\ud83d\udca1 Explanation:** This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case.\n", " \n", "* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. \n", " \n", " ```py\n", " >>> False ** False == True\n", " True\n", " >>> False ** True == False\n", " True\n", " >>> True ** False == True\n", " True\n", " >>> True ** True == True\n", " True\n", " ```\n", "\n", " **\ud83d\udca1 Explanation:** If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to a converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator))\n", " \n", "* Since we are talking operators, there's also `@` operator for matrix multiplication (don't worry, this time it's for real).\n", "\n", " ```py\n", " >>> import numpy as np\n", " >>> np.array([2, 2, 2]) @ np.array([7, 8, 8])\n", " 46\n", " ```\n", "\n", " **\ud83d\udca1 Explanation:** The `@` operator was added in Python 3.5 keeping sthe cientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator.\n", "\n", "* From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example,\n", " ```py\n", " >>> some_string = \"wtfpython\"\n", " >>> f'{some_string=}'\n", " \"string='wtfpython'\"\n", " ``` \n", "\n", "* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!):\n", " \n", " ```py\n", " import dis\n", " exec(\"\"\"\n", " def f():\n", " \"\"\" + \"\"\"\n", " \"\"\".join([\"X\" + str(x) + \"=\" + str(x) for x in range(65539)]))\n", "\n", " f()\n", "\n", " print(dis.dis(f))\n", " ```\n", " \n", "* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module.\n", "\n", "* Sometimes, the `print` method might not print values immediately. For example,\n", "\n", " ```py\n", " # File some_file.py\n", " import time\n", " \n", " print(\"wtfpython\", end=\"_\")\n", " time.sleep(3)\n", " ```\n", "\n", " This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument.\n", "\n", "* List slicing with out of the bounds indices throws no errors\n", " ```py\n", " >>> some_list = [1, 2, 3, 4, 5]\n", " >>> some_list[111:]\n", " []\n", " ```\n", "\n", "* Slicing an iterable not always creates a new object. For example,\n", " ```py\n", " >>> some_str = \"wtfpython\"\n", " >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n']\n", " >>> some_list is some_list[:] # False expected because a new object is created.\n", " False\n", " >>> some_str is some_str[:] # True because strings are immutable, so making a new object is of not much use.\n", " True\n", " ```\n", "\n", "* `int('\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.\n", "\n", "* You can seperate numeric literals with underscores (for better readablity) from Python 3 onwards.\n", "\n", " ```py\n", " >>> six_million = 6_000_000\n", " >>> six_million\n", " 6000000\n", " >>> hex_address = 0xF00D_CAFE\n", " >>> hex_address\n", " 4027435774\n", " ```\n", "\n", "* `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear\n", " ```py\n", " def count(s, sub):\n", " result = 0\n", " for i in range(len(s) + 1 - len(sub)):\n", " result += (s[i:i + len(sub)] == sub)\n", " return result\n", " ```\n", " The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string.\n", "\n", "**That's all folks!**\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 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 \"\", line 1\n", " a := \"wtf_walrus\"\n", " ^\n", "SyntaxError: invalid syntax\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> (a := \"wtf_walrus\") # This works though\n", ">>> a\n", "```\n", "```py\n", "'wtf_walrus'\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2 \\.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "# Python version 3.8+\n", "\n", ">>> a = 6, 9\n", ">>> a\n", "```\n", "```py\n", "(6, 9)\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> (a := 6, 9)\n", ">>> a\n", "```\n", "```py\n", "6\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> a, b = 6, 9 # Typcial unpacking\n", ">>> a, b\n", "```\n", "```py\n", "(6, 9)\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> (a, b = 16, 19) # Oops\n", "```\n", "```py\n", " File \"\", line 1\n", " (a, b = 6, 9)\n", " ^\n", "SyntaxError: invalid syntax\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> (a, b := 16, 19) # This prints out a weird 3-tuple\n", "```\n", "```py\n", "(6, 16, 19)\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> a # a is still unchanged?\n", "```\n", "```py\n", "6\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> b\n", "```\n", "```py\n", "16\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "**Quick walrus operator refresher**\n", "\n", "The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "def some_func():\n", " # Assume some expensive computation here\n", " # time.sleep(1000)\n", " return 5\n", "\n", "# So instead of,\n", "if some_func():\n", " print(some_func()) # Which is bad practice since computation is happening twice\n", "\n", "# or\n", "a = some_func()\n", "if a:\n", " print(a)\n", "\n", "# Now you can concisely write\n", "if a := some_func():\n", " print(a)\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (> 3.8):**\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "5\n", "5\n", "5\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "This 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, hence the `SyntaxError` in the `a := \"wtf_walrus\"` statement of the first snippet. Parenthesizing it worked as expected and assigned `a`. \n", "\n", "- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. \n", "\n", "- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", "\n", " - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6')\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> (a := 6, 9) == ((a := 6), 9)\n", "```\n", "```py\n", " True\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> x = (a := 696, 9)\n", " >>> x\n", "```\n", "```py\n", " (696, 9)\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> x[0] is a # Both reference same memory location\n", "```\n", "```py\n", " True\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. \n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Stubborn `del` operation\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "class SomeClass:\n", " def __del__(self):\n", " print(\"Deleted!\")\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "1\\.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> x = SomeClass()\n", ">>> y = x\n", ">>> del x # this should print \"Deleted!\"\n", ">>> del y\n", "```\n", "```py\n", "Deleted!\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.\n", "\n", "2\\.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> x = SomeClass()\n", ">>> y = x\n", ">>> del x\n", ">>> y # check if y exists\n", "```\n", "```py\n", "<__main__.SomeClass instance at 0x7f98a1a67fc8>\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> del y # Like previously, this should print \"Deleted!\"\n", ">>> globals() # oh, it didn't. Let's check all our global variables and confirm\n", "```\n", "```py\n", "Deleted!\n", "{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None}\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Okay, now it's deleted :confused:\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ `del x` doesn\u2019t directly call `x.__del__()`.\n", "+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x\u2019s reference count reaches zero.\n", "+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.\n", "+ Calling `globals` caused the existing reference to be destroyed, and hence we can see \"Deleted!\" being printed (finally!).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Wild imports *\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "# File: module.py\n", "\n", "def some_weird_name_func_():\n", " print(\"works!\")\n", "\n", "def _another_weird_name_func():\n", " print(\"works!\")\n", "\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output**\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> from module import *\n", ">>> some_weird_name_func_()\n", "```\n", "```py\n", "\"works!\"\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> _another_weird_name_func()\n", "```\n", "```py\n", "Traceback (most recent call last):\n", " File \"\", line 1, in \n", "NameError: name '_another_weird_name_func' is not defined\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime.\n", "- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> from module import some_weird_name_func_, _another_weird_name_func\n", " >>> _another_weird_name_func()\n", "```\n", "```py\n", " works!\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " __all__ = ['_another_weird_name_func']\n", "\n", " def some_weird_name_func_():\n", " print(\"works!\")\n", "\n", " def _another_weird_name_func():\n", " print(\"works!\")\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" **Output**\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> _another_weird_name_func()\n", "```\n", "```py\n", " \"works!\"\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> some_weird_name_func_()\n", "```\n", "```py\n", " Traceback (most recent call last):\n", " File \"\", line 1, in \n", " NameError: name 'some_weird_name_func_' is not defined\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Contributing\n", "\n", "A few ways in which you can contribute to wtfpython,\n", "\n", "- Suggesting new examples\n", "- Helping with translation (See [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation))\n", "- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc.\n", "- Identifying gaps (things like inadequate explanation, redundant examples, etc.)\n", "- Any creative suggestions to make this project more fun and useful\n", "\n", "Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) to discuss things.\n", "\n", "PS: Please don't reach out with backlinking requests, no links will be added unless they're highly relevant to the project.\n", "\n", "# Acknowledgements\n", "\n", "The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by Pythonistas gave it the shape it is in right now.\n", "\n", "#### Some nice Links!\n", "* https://www.youtube.com/watch?v=sH4XF6pKKmk\n", "* https://www.reddit.com/r/Python/comments/3cu6ej/what_are_some_wtf_things_about_python\n", "* https://sopython.com/wiki/Common_Gotchas_In_Python\n", "* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines\n", "* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python\n", "* https://www.python.org/doc/humor/\n", "* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator\n", "* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65\n", "* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues\n", "\n", "# \ud83c\udf93 License\n", "\n", "[![WTFPL 2.0][license-image]][license-url]\n", "\n", "© [Satwik Kansal](https://satwikkansal.xyz)\n", "\n", "[license-url]: http://www.wtfpl.net\n", "[license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square\n", "\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 2} \ No newline at end of file From 734360ff599fdb11f8e22fbe8224e887ac47fadb Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 21 Dec 2019 20:38:18 +0530 Subject: [PATCH 129/221] Add team trees --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index fb48b8eb..f54e3a81 100644 --- a/README.md +++ b/README.md @@ -3514,3 +3514,4 @@ If you like wtfpython, you can use these quick links to share it with your frien ## More content like this? If you're interested in more content like this, you can share your email [here](https://satwikkansal.xyz/content-like-wtfpython/). +PS: On a sidenote, consider [buying me a meal](https://ko-fi.com/satwikkansal) or [planting a tree](https://teamtrees.org/). From d59db75b4cf5ba6f9f19d8c711785f61f17bb808 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 21 Dec 2019 22:11:55 +0530 Subject: [PATCH 130/221] Add link to other modes --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f54e3a81..de8e03a4 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@

Exploring and understanding Python through surprising snippets.

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].) +Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/3.0/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) 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. @@ -3514,4 +3515,4 @@ If you like wtfpython, you can use these quick links to share it with your frien ## More content like this? If you're interested in more content like this, you can share your email [here](https://satwikkansal.xyz/content-like-wtfpython/). -PS: On a sidenote, consider [buying me a meal](https://ko-fi.com/satwikkansal) or [planting a tree](https://teamtrees.org/). +*PS: On a sidenote, consider [buying me a meal](https://ko-fi.com/satwikkansal) or [planting a tree](https://teamtrees.org/).* From 76d98d91385fe3c20ba553106fca496c392cacf6 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sat, 21 Dec 2019 22:12:56 +0530 Subject: [PATCH 131/221] Fix line break --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index de8e03a4..e9923f99 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@

Exploring and understanding Python through surprising snippets.

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].) + Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/3.0/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) 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. From f8aa17c8bac8dd486ec416b1759a8c71bbfa9bed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ramiro=20G=C3=B3mez?= Date: Sun, 22 Dec 2019 21:11:25 +0100 Subject: [PATCH 132/221] Make hashtags in Twitter link work Change URL parameter from `hastags` to `hashtags`. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9923f99..d821d049 100644 --- a/README.md +++ b/README.md @@ -3511,7 +3511,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' If you like wtfpython, you can use these quick links to share it with your friends, -[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&text=If%20you%20really%20think%20you%20know%20Python,%20think%20once%20more!%20Check%20out%20wtfpython&hastags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=If%20you%20really%20thing%20you%20know%20Python,%20think%20once%20more!) | [Facebook](https://www.facebook.com/dialog/share?app_id=536779657179021&display=page&href=https%3A%2F%2Fgithub.com%2Fsatwikkansal%2Fwtfpython"e=If%20you%20really%20think%20you%20know%20Python%2C%20think%20once%20more!) +[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&text=If%20you%20really%20think%20you%20know%20Python,%20think%20once%20more!%20Check%20out%20wtfpython&hashtags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=If%20you%20really%20thing%20you%20know%20Python,%20think%20once%20more!) | [Facebook](https://www.facebook.com/dialog/share?app_id=536779657179021&display=page&href=https%3A%2F%2Fgithub.com%2Fsatwikkansal%2Fwtfpython"e=If%20you%20really%20think%20you%20know%20Python%2C%20think%20once%20more!) ## More content like this? From e35642ed0506401146a707bc626815a74a8a754f Mon Sep 17 00:00:00 2001 From: Saverio Miroddi Date: Mon, 23 Dec 2019 10:31:40 +0100 Subject: [PATCH 133/221] Correct some typos Corrected a handful of typos. --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index e9923f99..11c575b2 100644 --- a/README.md +++ b/README.md @@ -198,7 +198,7 @@ SyntaxError: invalid syntax >>> a 6 ->>> a, b = 6, 9 # Typcial unpacking +>>> a, b = 6, 9 # Typical unpacking >>> a, b (6, 9) >>> (a, b = 16, 19) # Oops @@ -666,7 +666,7 @@ for i, some_dict[i] in enumerate(some_string): 1\. ```py array = [1, 8, 15] -# A typical generator expresion +# A typical generator expression gen = (x for x in array if array.count(x) > 0) array = [2, 8, 22] ``` @@ -3070,7 +3070,7 @@ _A__variable = "Some value" class A(object): def some_func(self): - return __variable # not initiatlized anywhere yet + return __variable # not initialized anywhere yet ``` **Output:** @@ -3263,7 +3263,7 @@ def convert_list_to_string(l, iters): **Output:** ```py -# Executed in ipython shell using %timeit for better readablity of results. +# Executed in ipython shell using %timeit for better readability of results. # You can also use the timeit module in normal python shell/scriptm=, example usage below # timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) @@ -3387,7 +3387,7 @@ Let's increase the number of iterations by a factor of 10. 46 ``` - **💡 Explanation:** The `@` operator was added in Python 3.5 keeping sthe cientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator. + **💡 Explanation:** The `@` operator was added in Python 3.5 keeping the scientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator. * From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example, ```py @@ -3443,7 +3443,7 @@ Let's increase the number of iterations by a factor of 10. * `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python. -* You can seperate numeric literals with underscores (for better readablity) from Python 3 onwards. +* You can separate numeric literals with underscores (for better readability) from Python 3 onwards. ```py >>> six_million = 6_000_000 From b3387c9dc7b7c8c912ca0e6ca9a6350471e4f2ac Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 23 Dec 2019 15:58:25 +0530 Subject: [PATCH 134/221] Add indent to the dump for better diff --- irrelevant/notebook_generator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/irrelevant/notebook_generator.py b/irrelevant/notebook_generator.py index 17551dfa..d2755300 100644 --- a/irrelevant/notebook_generator.py +++ b/irrelevant/notebook_generator.py @@ -296,7 +296,7 @@ def convert_to_notebook(pre_examples_content, parsed_json, post_examples_content #pprint.pprint(result, indent=2) with open(notebook_path, "w") as f: - json.dump(result, f) + json.dump(result, f, indent=2) with open(fpath, 'r+', encoding="utf-8") as f: From 438f52c3e92322314b3d41d9ae82be1b32014c7a Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 23 Dec 2019 15:58:49 +0530 Subject: [PATCH 135/221] Update notebook with recent changes --- irrelevant/wtf.ipynb | 12318 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 12317 insertions(+), 1 deletion(-) diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb index cd824f4f..12c7bb82 100644 --- a/irrelevant/wtf.ipynb +++ b/irrelevant/wtf.ipynb @@ -1 +1,12317 @@ -{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["

\"\"

\n", "

What the f*ck Python! \ud83d\ude31

\n", "

Exploring and understanding Python through surprising snippets.

\n", "\n", "Translations: [Chinese \u4e2d\u6587](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's 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", "# Structure of the Examples\n", "\n", "All the examples are structured like below:\n", "\n", "> ### \u25b6 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", "> #### \ud83d\udca1 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", "# \ud83d\udc40 Examples\n", "\n", "\n\n## Hosted notebook instructions\n\nThis 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\nThe 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\nThat being said, most of the 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": ["### \u25b6 Strings can be tricky sometimes\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140420665652016\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"some_string\"\n", "id(a)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140420665652016\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(\"some\" + \"_\" + \"string\") # Notice that both the ids are same.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"wtf\"\n", "b = \"wtf\"\n", "a is b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"wtf!\"\n", "b = \"wtf!\"\n", "a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = \"wtf!\", \"wtf!\"\n", "a is b # All versions except 3.7.x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"wtf!\"; b = \"wtf!\"\n", "a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["# This time in file some_file.py\n", "a = \"wtf!\"\n", "b = \"wtf!\"\n", "print(a is b)\n", "\n", "# prints True when the module is invoked!\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "4\\.\n", "\n", "**Output (< Python3.7 )**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Makes sense, right?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ The behavior in first and second snippets is due to a CPython optimization (called string interning) 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 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. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", " ![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images//string-intern/string_intern.png)\n", "+ When `a` and `b` are set to `\"wtf!\"` 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 `wtf!` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, 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 [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.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 with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Hash brownies\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict = {}\n", "some_dict[5.5] = \"JavaScript\"\n", "some_dict[5.0] = \"Ruby\"\n", "some_dict[5] = \"Python\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\"JavaScript\"\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict[5.5]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\"Python\"\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\"Python\"\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict[5] \n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["complex\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["complex_five = 5 + 0j\n", "type(complex_five)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\"Python\"\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict[complex_five]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "So, why is Python all over the place?\n", "\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.\n", "* Immutable objects with the same value always have the same hash in Python.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" 5 == 5.0 == 5 + 0j\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" hash(5) == hash(5.0) == hash(5 + 0j)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" **Note:** Objects with different values may also have same hash (known as [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science))).\n", "* When the statement `some_dict[5] = \"Python\"` is executed, the existing value \"Ruby\" is overwritten with \"Python\" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`.\n", "* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains the rationale behind it.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Deep down, we're all the same.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class WTF:\n", " pass\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["WTF() == WTF() # two different instances can't be equal\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["WTF() is WTF() # identities are also different\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(WTF()) == id(WTF())\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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 evaluated to `False`? Let's see with this snippet.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" class WTF(object):\n", " def __init__(self): print(\"I\")\n", " def __del__(self): print(\"D\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" I\n", " I\n", " D\n", " D\n", " False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" WTF() is WTF()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" I\n", " D\n", " I\n", " D\n", " True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" id(WTF()) == id(WTF())\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" As you may observe, the order in which the objects are destroyed is what made all the difference here.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Disorder within order *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from collections import OrderedDict\n", "\n", "dictionary = dict()\n", "dictionary[1] = 'a'; dictionary[2] = 'b';\n", "\n", "ordered_dict = OrderedDict()\n", "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", "\n", "another_ordered_dict = OrderedDict()\n", "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", "\n", "class DictWithHash(dict):\n", " \"\"\"\n", " A dict that also implements __hash__ magic.\n", " \"\"\"\n", " __hash__ = lambda self: 0\n", "\n", "class OrderedDictWithHash(OrderedDict):\n", " \"\"\"\n", " An OrderedDict that also implements __hash__ magic.\n", " \"\"\"\n", " __hash__ = lambda self: 0\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["dictionary == ordered_dict # If a == b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["dictionary == another_ordered_dict # and b == c\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\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"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["ordered_dict == another_ordered_dict # the why isn't c == a ??\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "TypeError: unhashable type: 'dict'\n", "\n", "# Makes sense since dict don't have __hash__ implemented, let's use\n", "# our wrapper classes.\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len({dictionary, ordered_dict, another_ordered_dict})\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["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})\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "What is going on here?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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://docs.python.org/3/library/collections.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", "- The reason for this equality is 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 lenght 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_set = set()\n", " some_set.add(dictionary) # these are the mapping objects from the snippets above\n", " ordered_dict in some_set\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_set.add(ordered_dict)\n", " len(some_set)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_ordered_dict in some_set\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 1\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_set.add(another_ordered_dict)\n", " len(some_set)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_set = set()\n", " another_set.add(ordered_dict)\n", " another_ordered_dict in another_set\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_set.add(another_ordered_dict)\n", " len(another_set)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" dictionary in another_set\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_set.add(another_ordered_dict)\n", " len(another_set)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Keep trying... *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func():\n", " try:\n", " return 'from_try'\n", " finally:\n", " return 'from_finally'\n", "\n", "def another_func(): \n", " for _ in range(3):\n", " try:\n", " continue\n", " finally:\n", " print(\"Finally!\")\n", "\n", "def one_more_func(): # A gotcha!\n", " try:\n", " for i in range(3):\n", " try:\n", " 1 / 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 ocurred\", e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["'from_finally'\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Finally!\n", "Finally!\n", "Finally!\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "ZeroDivisionError: division by zero\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["1 / 0\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Iteration 0\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["one_more_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- When a `return`, `break` or `continue` statement is executed in the `try` suite of a \"try\u2026finally\" 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 For what?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_string = \"wtf\"\n", "some_dict = {}\n", "for i, some_dict[i] in enumerate(some_string):\n", " i = 10\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["{0: 'w', 1: 't', 2: 'f'}\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_dict # An indexed dict appears.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as:\n", " ```\n", " for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" for i in range(4):\n", " print(i)\n", " i = 10\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n", " ```\n", " 0\n", " 1\n", " 2\n", " 3\n", " ```\n", "\n", " Did you expect the loop to run just once?\n", "\n", " **\ud83d\udca1 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)` 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" i, some_dict[i] = (0, 'w')\n", " i, some_dict[i] = (1, 't')\n", " i, some_dict[i] = (2, 'f')\n", " some_dict\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Evaluation time discrepancy\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["array = [1, 8, 15]\n", "# A typical generator expresion\n", "gen = (x for x in array if array.count(x) > 0)\n", "array = [2, 8, 22]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[8]\n"]}], "source": ["print(list(gen)) # Where did the other values go?\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["array_1 = [1,2,3,4]\n", "gen_1 = (x for x in array_1)\n", "array_1 = [1,2,3,4,5]\n", "\n", "array_2 = [1,2,3,4]\n", "gen_2 = (x for x in array_2)\n", "array_2[:] = [1,2,3,4,5]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[1, 2, 3, 4]\n", "\n"]}], "source": ["print(list(gen_1))\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[1, 2, 3, 4, 5]\n"]}], "source": ["print(list(gen_2))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["array_3 = [1, 2, 3]\n", "array_4 = [10, 20, 30]\n", "gen = (i + j for i in array_3 for j in array_4)\n", "\n", "array_3 = [4, 5, 6]\n", "array_4 = [400, 500, 600]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[401, 501, 601, 402, 502, 602, 403, 503, 603]\n"]}], "source": ["print(list(gen))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "- In a [generator](https://wiki.python.org/moin/Generators) 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 binded 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(g)` 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://www.python.org/dev/peps/pep-0289/#the-details)\n", " \n", " > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 How not to use `is` operator\n", "The following is a very famous example present all over the internet.\n", "\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 256\n", "b = 256\n", "a is b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 257\n", "b = 257\n", "a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = []\n", "b = []\n", "a is b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = tuple()\n", "b = tuple()\n", "a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "**Output**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = 257, 257\n", "a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.7.x specifically)**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [">> a is b\n", "False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = 257, 257\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" class A: pass\n", " A() is A() # These are two empty objects at two different memory locations.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**`256` is an existing object but `257` isn't**\n", "\n", "When 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", "\n", "Quoting from https://docs.python.org/3/c-api/long.html\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10922528\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(256)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10922528\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 256\n", "b = 256\n", "id(a)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10922528\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(b)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140084850247312\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(257)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140084850247440\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = 257\n", "y = 257\n", "id(x)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140084850247344\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(y)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Here 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", "\n", "Similar 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140640774013296\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = 257, 257\n", "id(a)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140640774013296\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(b)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140640774013392\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 257\n", "b = 257\n", "id(a)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["140640774013488\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(b)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" a, b = 257.0, 257.0\n", " a is b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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://github.com/satwikkansal/wtfpython/issues/100) for updates.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 `is not ...` is not `is (not ...)`\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'something' is not None\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'something' is (not None)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 A tic-tac-toe where X wins in the first attempt!\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# Let's initialize a row\n", "row = [\"\"] * 3 #row i['', '', '']\n", "# Let's make a board\n", "board = [row] * 3\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[['', '', ''], ['', '', ''], ['', '', '']]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['', '', '']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board[0]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["''\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board[0][0]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[['X', '', ''], ['X', '', ''], ['X', '', '']]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board[0][0] = \"X\"\n", "board\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "We didn't assign three `\"X\"`s, did we?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "When we initialize `row` variable, this visualization explains what happens in the memory\n", "\n", "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images//tic-tac-toe/after_row_initialized.png)\n", "\n", "And 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", "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images//tic-tac-toe/after_board_initialized.png)\n", "\n", "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[['X', '', ''], ['', '', ''], ['', '', '']]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["board = [['']*3 for _ in range(3)]\n", "board[0][0] = \"X\"\n", "board\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The sticky output function\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["funcs = []\n", "results = []\n", "for 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", "\n", "funcs_results = [func() for func in funcs]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[0, 1, 2, 3, 4, 5, 6]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["results\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[6, 6, 6, 6, 6, 6, 6]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["funcs_results\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.\n", "\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["powers_of_x = [lambda x: x**i for i in range(10)]\n", "[f(2) for f in powers_of_x]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.\n", "\n", "- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" funcs = []\n", " for x in range(7):\n", " def some_func(x=x):\n", " return x\n", " funcs.append(some_func)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [0, 1, 2, 3, 4, 5, 6]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" funcs_results = [func() for func in funcs]\n", " funcs_results\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The chicken-egg problem *\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(3, int)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(type, object)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(object, type)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "So which is the \"ultimate\" base class? There's more to the confusion by the way,\n", "\n", "2\\. \n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class A: pass\n", "isinstance(A, A)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(type, type)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["isinstance(object, object)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(int, object)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(type, object)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(object, type)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "- `type` is a [metaclass](https://realpython.com/python-metaclasses/) 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Subclass relationships\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from collections import Hashable\n", "issubclass(list, object)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(object, Hashable)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["issubclass(list, Hashable)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "The 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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://www.naftaliharris.com/blog/python-subclass-intransitivity/).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 All-true-ation *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([True, True, True])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([True, True, False])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([[]])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["all([[[]]])\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Why's this True-False alteration?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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 `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty.\n", "- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The surprising comma\n", "**Output (< 3.6):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"\", line 1\n", " def h(x, **kwargs,):\n", " ^\n", "SyntaxError: invalid syntax\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"\", line 1\n", " def h(*args,):\n", " ^\n", "SyntaxError: invalid syntax\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def h(*args,):\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Strings and the backslashes\n", "**Output:**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["\"\n", "\n"]}], "source": ["print(\"\\\"\")\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["\\\"\n", "\n"]}], "source": ["print(r\"\\\"\")\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["File \"\", line 1\n", " print(r\"\\\")\n", " ^\n", "SyntaxError: EOL while scanning string literal\n", "\n"]}], "source": ["print(r\"\\\")\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["r'\\'' == \"\\\\'\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 'wt\"f'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" 'wt\\\"f'\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" r'wt\\\"f' == 'wt\\\\\"f'\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 'wt\\\\\"f'\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" print(repr(r'wt\\\"f')\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" print(\"\\n\")\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" '\\\\\\\\n'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" print(r\"\\\\n\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 not knot!\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = True\n", "y = False\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["not x == y\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"\", line 1\n", " x == not y\n", " ^\n", "SyntaxError: invalid syntax\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x == not y\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Half triple-quoted strings\n", "**Output:**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["wtfpython\n"]}], "source": ["print('wtfpython''')\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["wtfpython\n"]}], "source": ["print(\"wtfpython\"\"\")\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"\", line 3\n", " print(\"\"\"wtfpython\")\n", " ^\n", "SyntaxError: EOF while scanning triple-quoted string literal\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# The following statements raise `SyntaxError`\n", "# print('''wtfpython')\n", "# print(\"\"\"wtfpython\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ Python supports implicit [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation), Example,\n", " ```\n", " >>> print(\"wtf\" \"python\")\n", " wtfpython\n", " >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n", " wtf\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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 What's wrong with booleans?\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# A simple example to count the number of booleans and\n", "# integers in an iterable of mixed data types.\n", "mixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\n", "integers_found_so_far = 0\n", "booleans_found_so_far = 0\n", "\n", "for 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["4\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["integers_found_so_far\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["booleans_found_so_far\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["'wtf'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_bool = True\n", "\"wtf\" * some_bool\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["''\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_bool = False\n", "\"wtf\" * some_bool\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def tell_truth():\n", " True = False\n", " if True == False:\n", " print(\"I have lost faith in truth!\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (< 3.x):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["I have lost faith in truth!\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["tell_truth()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* `bool` is a subclass of `int` in Python\n", " \n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" issubclass(bool, int)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" issubclass(int, bool)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" \n", "* And thus, `True` and `False` are instances of `int`\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" isinstance(True, int)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" isinstance(False, int)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* The integer value of `True` is `1` and that of `False` is `0`.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" int(True)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 0\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" int(False)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Class attributes and instance attributes\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class A:\n", " x = 1\n", "\n", "class B(A):\n", " pass\n", "\n", "class C(A):\n", " pass\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(1, 1, 1)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["A.x, B.x, C.x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(1, 2, 1)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["B.x = 2\n", "A.x, B.x, C.x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(3, 2, 3)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["A.x = 3\n", "A.x, B.x, C.x # C.x changed, but B.x didn't\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(3, 3)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = A()\n", "a.x, A.x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["(4, 3)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a.x += 1\n", "a.x, A.x\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[5, 420]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_obj = SomeClass(420)\n", "some_obj.some_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[5, 420]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_obj.another_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[5, 111]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_obj = SomeClass(111)\n", "another_obj.some_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[5, 420, 111]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_obj.another_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_obj.another_list is SomeClass.another_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_obj.another_list is some_obj.another_list\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Non-reflexive class method *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class SomeClass:\n", " def instance_method(self):\n", " pass\n", " \n", " @classmethod\n", " def class_method(cls):\n", " pass\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeClass.instance_method is SomeClass.instance_method\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeClass.class_method is SomeClass.class_method\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["id(SomeClass.class_method) == id(SomeClass.class_method)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- The reason `SomeClass.class_method is SomeClass.class_method` is `False` is due to the `@classmethod` decorator. \n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" \n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" SomeClass.instance_method\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" \n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" SomeClass.class_method\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " A new bound method every time `SomeClass.class_method` is accessed.\n", "\n", "- `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). \n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 yielding None\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_iterable = ('a', 'b')\n", "\n", "def some_func(val):\n", " return \"something\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (<= 3.7.x):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a', 'b']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["[x for x in some_iterable]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" at 0x7f70b0a4ad58>\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["[(yield x) for x in some_iterable]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a', 'b']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list([(yield x) for x in some_iterable])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a', None, 'b', None]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list((yield x) for x in some_iterable)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a', 'something', 'b', 'something']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(some_func((yield x)) for x in some_iterable)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n", "- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n", "- Related bug report: http://bugs.python.org/issue10544\n", "- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Yielding from... return! *\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func(x):\n", " if x == 3:\n", " return [\"wtf\"]\n", " else:\n", " yield from range(x)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (> 3.3):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(some_func(3))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Where did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n", "\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func(x):\n", " if x == 3:\n", " return [\"wtf\"]\n", " else:\n", " for i in range(x):\n", " yield i\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(some_func(3))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "The same result, this didn't work either.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" try:\n", " next(some_func(3))\n", " except StopIteration as e:\n", " some_string = e.value\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [\"wtf\"]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_string\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Nan-reflexivity *\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = float('inf')\n", "b = float('nan')\n", "c = float('-iNf') # These strings are case-insensitive\n", "d = float('nan')\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["inf\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["nan\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["-inf\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["c\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["ValueError: could not convert string to float: some_other_string\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["float('some_other_string')\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a == -c # inf==inf\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["None == None # None == None\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["b == d # but nan!=nan\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0.0\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["50 / a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["nan\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a / a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["nan\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["23 + b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = float('nan')\n", "y = x / x\n", "y is y # identity holds\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["y == y # equality fails of y\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["[y] == [y] # but the equality succeeds for the list containing y\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (False, True)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" x = float('nan')\n", " x == x, [x] == [x]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (False, True)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" y = float('nan')\n", " y == y, [y] == [y]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (False, False)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" x == y, [x] == [y]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Mutating the immutable!\n", "This might seem trivial if you know how references work in Python.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_tuple = (\"A\", \"tuple\", \"with\", \"values\")\n", "another_tuple = ([1, 2], [3, 4], [5, 6])\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["TypeError: 'tuple' object does not support item assignment\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_tuple[2] = \"change this\"\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["([1, 2], [3, 4], [5, 6, 1000])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_tuple[2].append(1000) #This throws no error\n", "another_tuple\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["TypeError: 'tuple' object does not support item assignment\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_tuple[2] += [99, 999]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_tuple\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "But I thought tuples were immutable...\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* Quoting from https://docs.python.org/2/reference/datamodel.html\n", "\n", " > Immutable sequences\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", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The disappearing variable from outer scope\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["e = 7\n", "try:\n", " raise Exception()\n", "except Exception as e:\n", " pass\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.x):**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["# prints nothing\n"]}], "source": ["print(e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["NameError: name 'e' is not defined\n"]}], "source": ["print(e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* Source: https://docs.python.org/3/reference/compound_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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" except E as N:\n", " foo\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " was translated into\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" except E as N:\n", " try:\n", " foo\n", " finally:\n", " del N\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def f(x):\n", " del(x)\n", " print(x)\n", "\n", " x = 5\n", " y = [5, 4, 3]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 5\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" >>>f(x)\n", " UnboundLocalError: local variable 'x' referenced before assignment\n", " >>>f(y)\n", " UnboundLocalError: local variable 'x' referenced before assignment\n", " x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [5, 4, 3]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" y\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" Exception()\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" e\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" # Nothing is printed!\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" print e\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The mysterious key type conversion\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class SomeClass(str):\n", " pass\n", "\n", "some_dict = {'s': 42}\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["str\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["type(list(some_dict.keys())[0])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["{'s': 40}\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["s = SomeClass('s')\n", "some_dict[s] = 40\n", "some_dict # expected: Two different keys-value pairs\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["str\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["type(list(some_dict.keys())[0])\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" 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"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" {'s': 40, 's': 42}\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" s = SomeClass('s')\n", " some_dict[s] = 40\n", " some_dict\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (__main__.SomeClass, str)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" keys = list(some_dict.keys())\n", " type(keys[0]), type(keys[1])\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Let's see if you can guess this?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a, b = a[b] = {}, 5\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["{5: ({...}, 5)}\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form\n", " ```\n", " (target_list \"=\")+ (expression_list | yield_expression)\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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [[...]]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list = some_list[0] = [0]\n", " some_list\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [[...]]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list[0]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list is some_list[0]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list[0][0][0][0][0][0] == some_list\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" 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"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" a, b = {}, 5\n", " a[b] = a, b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" a[b][0] is a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Modifying a dictionary while iterating over it\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = {0: None}\n", "\n", "for i in x:\n", " del x[i]\n", " x[i+1] = None\n", " print(i)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.7- Python 3.5):**\n", "\n", "```\n", "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "```\n", "\n", "Yes, it runs for exactly **eight** times and stops.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* Iteration over a dictionary that you edit at the same time is not supported.\n", "* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.\n", "* How deleted keys are handled and when the resize occurs might be different for different Python implementations.\n", "* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread.\n", "* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 The out of scope variable\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = 1\n", "def some_func():\n", " return a\n", "\n", "def another_func():\n", " a += 1\n", " return a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["UnboundLocalError: local variable 'a' referenced before assignment\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["another_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.\n", "* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.\n", "* To modify the outer scope variable `a` in `another_func`, use `global` keyword.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def another_func()\n", " global a\n", " a += 1\n", " return a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" another_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Deleting a list item while iterating\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_1 = [1, 2, 3, 4]\n", "list_2 = [1, 2, 3, 4]\n", "list_3 = [1, 2, 3, 4]\n", "list_4 = [1, 2, 3, 4]\n", "\n", "for idx, item in enumerate(list_1):\n", " del item\n", "\n", "for idx, item in enumerate(list_2):\n", " list_2.remove(item)\n", "\n", "for idx, item in enumerate(list_3[:]):\n", " list_3.remove(item)\n", "\n", "for idx, item in enumerate(list_4):\n", " list_4.pop(idx)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_1\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[2, 4]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_2\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_3\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[2, 4]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list_4\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Can you guess why the output is `[2, 4]`?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 139798789457608\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list = [1, 2, 3, 4]\n", " id(some_list)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 139798779601192\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" id(some_list[:]) # Notice that python creates new object for sliced list.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Difference between `del`, `remove`, and `pop`:**\n", "* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).\n", "* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.\n", "* `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified.\n", "\n", "**Why the output is `[2, 4]`?**\n", "- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.\n", "\n", "* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example\n", "* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Lossy zip of iterators *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[0, 1, 2, 3, 4, 5, 6]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["numbers = list(range(7))\n", "numbers\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["([0, 1, 2], [3, 4, 5, 6])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["first_three, remaining = numbers[:3], numbers[3:]\n", "first_three, remaining\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[(0, 0), (1, 1), (2, 2)]\n", "# so far so good, let's zip the remaining\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["numbers_iter = iter(numbers)\n", "list(zip(numbers_iter, first_three)) \n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[(4, 3), (5, 4), (6, 5)]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(zip(numbers_iter, remaining))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["Where did element `3` go from the `numbers` list?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def zip(*iterables):\n", " sentinel = object()\n", " iterators = [iter(it) for it in iterables]\n", " while iterators:\n", " result = []\n", " for it in iterators:\n", " elem = next(it, sentinel)\n", " if elem is sentinel: return\n", " result.append(elem)\n", " yield tuple(result)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. \n", "- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.\n", "- The correct way to do the above using `zip` would be,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [(0, 0), (1, 1), (2, 2)]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" numbers = list(range(7))\n", " numbers_iter = iter(numbers)\n", " list(zip(first_three, numbers_iter))\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" [(3, 3), (4, 4), (5, 5), (6, 6)]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" list(zip(remaining, numbers_iter))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" The first argument of zip should be the one with fewest elements.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Loop variables leaking out!\n", "1\\.\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["for x in range(7):\n", " if x == 6:\n", " print(x, ': for x inside loop')\n", "print(x, ': x in global')\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["6 : for x inside loop\n", "6 : x in global\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "But `x` was never defined outside the scope of for loop...\n", "\n", "2\\.\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["# This time let's initialize x first\n", "x = -1\n", "for x in range(7):\n", " if x == 6:\n", " print(x, ': for x inside loop')\n", "print(x, ': x in global')\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["6 : for x inside loop\n", "6 : x in global\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n", "**Output (Python 2.x):**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[0, 1, 2, 3, 4]\n"]}], "source": ["x = 1\n", "print([x for x in range(5)])\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["4\n"]}], "source": ["print(x)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["[0, 1, 2, 3, 4]\n"]}], "source": ["x = 1\n", "print([x for x in range(5)])\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["1\n"]}], "source": ["print(x)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.\n", "\n", "- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What\u2019s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog:\n", "\n", " > \"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.\"\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Beware of default mutable arguments!\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func(default_arg=[]):\n", " default_arg.append(\"some_string\")\n", " return default_arg\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['some_string']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['some_string', 'some_string']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['some_string']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func([])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['some_string', 'some_string', 'some_string']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def some_func(default_arg=[]):\n", " default_arg.append(\"some_string\")\n", " return default_arg\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " **Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ([],)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_func.__defaults__ #This will show the default argument values for the function\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (['some_string'],)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_func()\n", " some_func.__defaults__\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (['some_string', 'some_string'],)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_func()\n", " some_func.__defaults__\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" (['some_string', 'some_string'],)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_func([])\n", " some_func.__defaults__\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def some_func(default_arg=None):\n", " if not default_arg:\n", " default_arg = []\n", " default_arg.append(\"some_string\")\n", " return default_arg\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Catching the Exceptions\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_list = [1, 2, 3]\n", "try:\n", " # This should raise an ``IndexError``\n", " print(some_list[4])\n", "except IndexError, ValueError:\n", " print(\"Caught!\")\n", "\n", "try:\n", " # This should raise a ``ValueError``\n", " some_list.remove(4)\n", "except IndexError, ValueError:\n", " print(\"Caught again!\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Caught!\n", "\n", "ValueError: list.remove(x): x not in list\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" File \"\", line 3\n", " except IndexError, ValueError:\n", " ^\n", "SyntaxError: invalid syntax\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list = [1, 2, 3]\n", " try:\n", " # This should raise a ``ValueError``\n", " some_list.remove(4)\n", " except (IndexError, ValueError), e:\n", " print(\"Caught again!\")\n", " print(e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" **Output (Python 2.x):**\n", " ```\n", " Caught again!\n", " list.remove(x): x not in list\n", " ```\n", " **Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" File \"\", line 4\n", " except (IndexError, ValueError), e:\n", " ^\n", " IndentationError: unindent does not match any outer indentation level\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" some_list = [1, 2, 3]\n", " try:\n", " some_list.remove(4)\n", "\n", " except (IndexError, ValueError) as e:\n", " print(\"Caught again!\")\n", " print(e)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" **Output:**\n", " ```\n", " Caught again!\n", " list.remove(x): x not in list\n", " ```\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Same operands, different story!\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = [1, 2, 3, 4]\n", "b = a\n", "a = a + [5, 6, 7, 8]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4, 5, 6, 7, 8]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = [1, 2, 3, 4]\n", "b = a\n", "a += [5, 6, 7, 8]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4, 5, 6, 7, 8]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[1, 2, 3, 4, 5, 6, 7, 8]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["b\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this.\n", "\n", "* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged.\n", "\n", "* The expression `a += [5,6,7,8]` is actually mapped to an \"extend\" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Be careful with chained operations\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["(False == False) in [False] # makes sense\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["False == (False in [False]) # makes sense\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["False == False in [False] # now what?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["True is False == False\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["False is False is False\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["1 > 0 < 1\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["(1 > 0) < 1\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["1 > (0 < 1)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "As per https://docs.python.org/2/reference/expressions.html#not-in\n", "\n", "> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.\n", "\n", "While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 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` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n", "* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`.\n", "* The expression `(1 > 0) < 1` is equivalent to `True < 1` and\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" int(True)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 2\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" True + 1 #not relevant for this example, but just for fun\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" So, `1 < 1` evaluates to `False`\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Name resolution ignoring class scope\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = 5\n", "class SomeClass:\n", " x = 17\n", " y = (x for i in range(10))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["5\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["list(SomeClass.y)[0]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = 5\n", "class SomeClass:\n", " x = 17\n", " y = [x for i in range(10)]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["17\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeClass.y[0]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["5\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeClass.y[0]\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "- Scopes nested inside class definition ignore names bound at the class level.\n", "- A generator expression has its own scope.\n", "- Starting from Python 3.X, list comprehensions also have their own scope.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Needles in a Haystack *\n", "I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios,\n", "\n", "1\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x, y = (0, 1) if True else None, None\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["((0, 1), None)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x, y # expected (0, 1)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n", "\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["t = ('one', 'two')\n", "for i in t:\n", " print(i)\n", "\n", "t = ('one')\n", "for i in t:\n", " print(i)\n", "\n", "t = ()\n", "print(t)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["one\n", "two\n", "o\n", "n\n", "e\n", "tuple()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "3\\.\n", "\n", "```\n", "ten_words_list = [\n", " \"some\",\n", " \"very\",\n", " \"big\",\n", " \"list\",\n", " \"that\"\n", " \"consists\",\n", " \"of\",\n", " \"exactly\",\n", " \"ten\",\n", " \"words\"\n", "]\n", "```\n", "\n", "**Output**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["9\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len(ten_words_list)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "4\\. Not asserting strongly enough\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["a = \"python\"\n", "b = \"javascript\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["# No AssertionError is raised\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# An assert statement with an assertion failure message.\n", "assert(a == b, \"Both languages are different\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "5\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_list = [1, 2, 3]\n", "some_dict = {\n", " \"key_1\": 1,\n", " \"key_2\": 2,\n", " \"key_3\": 3\n", "}\n", "\n", "some_list = some_list.append(4) \n", "some_dict = some_dict.update({\"key_4\": 4})\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["None\n"]}], "source": ["print(some_list)\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["None\n"]}], "source": ["print(some_dict)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "6\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_recursive_func(a):\n", " if a[0] == 0:\n", " return \n", " a[0] -= 1\n", " some_recursive_func(a)\n", " return a\n", "\n", "def similar_recursive_func(a):\n", " if a == 0:\n", " return a\n", " a -= 1\n", " similar_recursive_func(a)\n", " return a\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["[0, 0]\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_recursive_func([5, 0])\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["4\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["similar_recursive_func(5)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`.\n", "\n", "* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character.\n", "\n", "* `()` is a special token and denotes empty `tuple`.\n", "\n", "* In 3, as you might have already figured out, there's a missing comma after 5th element (`\"that\"`) in the list. So by implicit string literal concatenation,\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ten_words_list\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up,\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" Traceback (most recent call last):\n", " File \"\", line 1, in \n", " AssertionError\n", " \n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" a = \"python\"\n", " b = \"javascript\"\n", " assert a == b\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" :1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n", " \n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" assert (a == b, \"Values are not equal\")\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" Traceback (most recent call last):\n", " File \"\", line 1, in \n", " AssertionError: Values aren not equal\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" assert a == b, \"Values are not equal\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).\n", "\n", "* Last one should be fairly obvious, passing mutable object (like `list` ) results in a call by reference, whereas an immutable object (like `int`) results in a call by value.\n", "\n", "* Being aware of these nitpicks can save you hours of debugging effort in the long run. \n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Splitsies *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a']\n", "\n", "# is same as\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'a'.split()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["['a']\n", "\n", "# but\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'a'.split(' ')\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0\n", "\n", "# isn't the same as\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len(''.split())\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["len(''.split(' '))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split)\n", " > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.\n", " > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.\n", "- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ['', 'a', '']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ' a '.split(' ')\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ['a']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ' a '.split()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ['']\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ''.split(' ')\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 All sorted? *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["x = 7, 8, 9\n", "sorted(x) == x\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["sorted(x) == sorted(x)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["y = reversed(x)\n", "sorted(y) == sorted(y)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. \n", "\n", "- ```py\n", " >>> [] == tuple()\n", " False\n", " >>> x = 7, 8, 9\n", " >>> type(x), type(sorted(x))\n", " (tuple, list)\n", " ```\n", "\n", "- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first.\n", "\n", "- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" ([7, 8, 9], [])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" x = 7, 8, 9\n", " y = reversed(x)\n", " sorted(y), sorted(y)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Midnight time doesn't exist?\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from datetime import datetime\n", "\n", "midnight = datetime(2018, 1, 1, 0, 0)\n", "midnight_time = midnight.time()\n", "\n", "noon = datetime(2018, 1, 1, 12, 0)\n", "noon_time = noon.time()\n", "\n", "if midnight_time:\n", " print(\"Time at midnight is\", midnight_time)\n", "\n", "if noon_time:\n", " print(\"Time at noon is\", noon_time)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (< 3.5):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["('Time at noon is', datetime.time(12, 0))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["The midnight time is not printed.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of \"empty.\"\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Okay Python, Can you make me fly?\n", "Well, here you go\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["import antigravity\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "Sshh... It's a super-secret.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ `antigravity` module is one of the few easter eggs released by Python developers.\n", "+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python.\n", "+ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 `goto`, but why?\n"]}, {"cell_type": "code", "metadata": {"collapsed": true}, "execution_count": null, "outputs": [{"name": "stdout", "output_type": "stream", "text": []}], "source": ["from goto import goto, label\n", "for i in range(9):\n", " for j in range(9):\n", " for k in range(9):\n", " print(\"I am trapped, please rescue!\")\n", " if k == 2:\n", " goto .breakout # breaking out from a deeply nested loop\n", "label .breakout\n", "print(\"Freedom!\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.3):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["I am trapped, please rescue!\n", "I am trapped, please rescue!\n", "Freedom!\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004.\n", "- Current versions of Python do not have this module.\n", "- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Brace yourself!\n", "If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing,\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from __future__ import braces\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" File \"some_file.py\", line 1\n", " from __future__ import braces\n", "SyntaxError: not a chance\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ The `__future__` module is normally used to provide features from future versions of Python. The \"future\" in this specific context is however, ironic.\n", "+ This is an easter egg concerned with the community's feelings on this issue.\n", "+ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file.\n", "+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Let's meet Friendly Language Uncle For Life\n", "**Output (Python 3.x)**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" File \"some_file.py\", line 1\n", " \"Ruby\" != \"Python\"\n", " ^\n", "SyntaxError: invalid syntax\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["from __future__ import barry_as_FLUFL\n", "\"Ruby\" != \"Python\" # there's no doubt about it\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["\"Ruby\" <> \"Python\"\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "There we go.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means).\n", "- Quoting from the PEP-401\n", " \n", " > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.\n", "- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/).\n", "- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working,\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" from __future__ import barry_as_FLUFL\n", " print(eval('\"Ruby\" <> \"Python\"'))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Even Python understands that love is complicated\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["import this\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Wait, what's **this**? `this` is love :heart:\n", "\n", "**Output:**\n", "```\n", "The Zen of Python, by Tim Peters\n", "\n", "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n", "Complex is better than complicated.\n", "Flat is better than nested.\n", "Sparse is better than dense.\n", "Readability counts.\n", "Special cases aren't special enough to break the rules.\n", "Although practicality beats purity.\n", "Errors should never pass silently.\n", "Unless explicitly silenced.\n", "In the face of ambiguity, refuse the temptation to guess.\n", "There should be one-- and preferably only one --obvious way to do it.\n", "Although that way may not be obvious at first unless you're Dutch.\n", "Now is better than never.\n", "Although never is often better than *right* now.\n", "If the implementation is hard to explain, it's a bad idea.\n", "If the implementation is easy to explain, it may be a good idea.\n", "Namespaces are one honking great idea -- let's do more of those!\n", "```\n", "\n", "It's the Zen of Python!\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love = this\n", "this is love\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love is True\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love is False\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love is not True or False\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["love is not True or False; love is love # Love is complicated\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)).\n", "* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens).\n", "* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Yes, it exists!\n", "**The `else` clause for loops.** One typical example might be:\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def does_exists_num(l, to_find):\n", " for num in l:\n", " if num == to_find:\n", " print(\"Exists!\")\n", " break\n", " else:\n", " print(\"Does not exist\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Exists!\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_list = [1, 2, 3, 4, 5]\n", "does_exists_num(some_list, 4)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Does not exist\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["does_exists_num(some_list, -1)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**The `else` clause in exception handling.** An example,\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["try:\n", " pass\n", "except:\n", " print(\"Exception occurred!!!\")\n", "else:\n", " print(\"Try block executed successfully...\")\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Try block executed successfully...\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a \"nobreak\" clause.\n", "- `else` clause after a try block is also called \"completion clause\" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Ellipsis *\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def some_func():\n", " Ellipsis\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["# No output, No Error\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["some_func()\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "NameError: name 'SomeRandomString' is not defined\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["SomeRandomString\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Ellipsis\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Ellipsis\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" Ellipsis\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" ...\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- Eliipsis can be used for several purposes,\n", " + As a placeholder for code that hasn't been written yet (just like `pass` statement)\n", " + In slicing syntax to represent the full slices in remaining direction\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" array([\n", " [\n", " [0, 1],\n", " [2, 3]\n", " ],\n", "\n", " [\n", " [4, 5],\n", " [6, 7]\n", " ]\n", " ])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" import numpy as np\n", " three_dimensional_array = np.arange(8).reshape(2, 2, 2)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" array([[1, 3],\n", " [5, 7]])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" three_dimensional_array[:,:,1]\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" array([[1, 3],\n", " [5, 7]])\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" three_dimensional_array[..., 1] # using Ellipsis.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`)\n", " + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`))\n", " + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the \"no argument passed\" and \"None value passed\" scenarios).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Inpinity\n", "The spelling is intended. Please, don't submit a patch for this.\n", "\n", "**Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["314159\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["infinity = float('infinity')\n", "hash(infinity)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["-314159\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["hash(float('-inf'))\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "- Hash of infinity is 10\u2075 x \u03c0.\n", "- Interestingly, the hash of `float('-inf')` is \"-10\u2075 x \u03c0\" in Python 3, whereas \"-10\u2075 x e\" in Python 2.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Let's mangle\n", "1\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class Yo(object):\n", " def __init__(self):\n", " self.__honey = True\n", " self.bro = True\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo().bro\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["AttributeError: 'Yo' object has no attribute '__honey'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo().__honey\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo()._Yo__honey\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2\\.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["class Yo(object):\n", " def __init__(self):\n", " # Let's try something symmetrical this time\n", " self.__honey__ = True\n", " self.bro = True\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["True\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo().bro\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "AttributeError: 'Yo' object has no attribute '_Yo__honey__'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Yo()._Yo__honey__\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Why did `Yo()._Yo__honey` work?\n", "\n", "3\\.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["_A__variable = \"Some value\"\n", "\n", "class A(object):\n", " def some_func(self):\n", " return __variable # not initiatlized anywhere yet\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["'Some value'\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["Traceback (most recent call last):\n", " File \"\", line 1, in \n", "AttributeError: 'A' object has no attribute '__variable'\n", "\n", "A().some_func()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.\n", "* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a \"dunder\") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front.\n", "* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class.\n", "* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores.\n", "* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope.\n", "* Also, if the mangled name is longer than 255 characters, truncation will happen.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Skipping lines?\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["11\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["value = 11\n", "valu\u0435 = 32\n", "value\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Wut?\n", "\n", "**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1077\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["ord('\u0435') # cyrillic 'e' (Ye)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["101\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["ord('e') # latin 'e', as used in English and typed using standard keyboard\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["False\n", "\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["'\u0435' == 'e'\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["42\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["value = 42 # latin e\n", "valu\u0435 = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here\n", "value\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Teleportation\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# `pip install nump` first.\n", "import numpy as np\n", "\n", "def energy_send(x):\n", " # Initializing a numpy array\n", " np.array([float(x)])\n", "\n", "def energy_receive():\n", " # Return an empty numpy array\n", " return np.empty((), dtype=np.float).tolist()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["123.456\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["energy_send(123.456)\n", "energy_receive()\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Where's the Nobel Prize?\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate.\n", "* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Well, something is fishy...\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def square(x):\n", " \"\"\"\n", " A simple function to calculate the square of a number by addition.\n", " \"\"\"\n", " sum_so_far = 0\n", " for counter in range(x):\n", " sum_so_far = sum_so_far + x\n", " return sum_so_far\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (Python 2.x):**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["square(10)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Shouldn't that be 100?\n", "\n", "**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "* **Don't mix tabs and spaces!** The character just preceding return is a \"tab\", and the code is indented by multiple of \"4 spaces\" elsewhere in the example.\n", "* This is how Python handles tabs:\n", " \n", " > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>\n", "* So the \"tab\" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.\n", "* Python 3 is kind enough to throw an error for such cases automatically.\n", "\n", " **Output (Python 3.x):**\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" TabError: inconsistent use of tabs and spaces in indentation\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 `+=` is faster\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0.25748300552368164\n", "# using \"+=\", three strings:\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# using \"+\", three strings:\n", "timeit.timeit(\"s1 = s1 + s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["0.012188911437988281\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["timeit.timeit(\"s1 += s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Let's make a giant string!\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": []}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["def add_string_with_plus(iters):\n", " s = \"\"\n", " for i in range(iters):\n", " s += \"xyz\"\n", " assert len(s) == 3*iters\n", "\n", "def add_bytes_with_plus(iters):\n", " s = b\"\"\n", " for i in range(iters):\n", " s += b\"xyz\"\n", " assert len(s) == 3*iters\n", "\n", "def add_string_with_format(iters):\n", " fs = \"{}\"*iters\n", " s = fs.format(*([\"xyz\"]*iters))\n", " assert len(s) == 3*iters\n", "\n", "def add_string_with_join(iters):\n", " l = []\n", " for i in range(iters):\n", " l.append(\"xyz\")\n", " s = \"\".join(l)\n", " assert len(s) == 3*iters\n", "\n", "def convert_list_to_string(l, iters):\n", " s = \"\".join(l)\n", " assert len(s) == 3*iters\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["124 \u00b5s \u00b1 4.73 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["# Executed in ipython shell using %timeit for better readablity of results.\n", "# You can also use the timeit module in normal python shell/scriptm=, example usage below\n", "# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())\n", "\n", "NUM_ITERS = 1000\n", "%timeit -n1000 add_string_with_plus(NUM_ITERS)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["211 \u00b5s \u00b1 10.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_bytes_with_plus(NUM_ITERS)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["61 \u00b5s \u00b1 2.18 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_string_with_format(NUM_ITERS)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["117 \u00b5s \u00b1 3.21 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_string_with_join(NUM_ITERS)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["10.1 \u00b5s \u00b1 1.06 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["l = [\"xyz\"]*NUM_ITERS\n", "%timeit -n1000 convert_list_to_string(l, NUM_ITERS)\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Let's increase the number of iterations by a factor of 10.\n", "\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1.26 ms \u00b1 76.8 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["NUM_ITERS = 10000\n", "%timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["6.82 ms \u00b1 134 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["645 \u00b5s \u00b1 24.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["1.17 ms \u00b1 7.25 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["%timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": ["86.3 \u00b5s \u00b1 2 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": ["l = [\"xyz\"]*NUM_ITERS\n", "%timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces.\n", "- Don't use `+` for generating long strings \u2014 In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function)\n", "- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings).\n", "- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.\n", "- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + \"x\" + \"y\" + \"z\"` instead of `s += \"xyz\"`, the increase would have been quadratic.\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 388 \u00b5s \u00b1 22.4 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" def add_string_with_plus(iters):\n", " s = \"\"\n", " for i in range(iters):\n", " s = s + \"x\" + \"y\" + \"z\"\n", " assert len(s) == 3*iters\n", "\n", " %timeit -n100 add_string_with_plus(1000)\n"]}, {"cell_type": "code", "execution_count": null, "metadata": {"collapsed": true}, "outputs": [{"data": {"text/plain": [" 9 ms \u00b1 298 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n"]}, "output_type": "execute_result", "metadata": {}, "execution_count": null}], "source": [" %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which,\n", " \n", " > There should be one-- and preferably only one --obvious way to do it.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Minor Ones *\n", "* `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage)\n", "\n", " **\ud83d\udca1 Explanation:** If `join()` is a method on a string, then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API.\n", " \n", "* Few weird looking but semantically correct statements:\n", " + `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`)\n", " + `'a'[0][0][0][0][0]` is also a semantically correct statement as strings are [sequences](https://docs.python.org/3/glossary.html#term-sequence)(iterables supporting element access using integer indices) in Python.\n", " + `3 --0-- 5 == 8` and `--5 == 5` are both semantically correct statements and evaluate to `True`.\n", "\n", "* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java.\n", " ```py\n", " >>> a = 5\n", " >>> a\n", " 5\n", " >>> ++a\n", " 5\n", " >>> --a\n", " 5\n", " ```\n", "\n", " **\ud83d\udca1 Explanation:**\n", " + There is no `++` operator in Python grammar. It is actually two `+` operators.\n", " + `++a` parses as `+(+a)` which translates to `a`. Similarly, the output of the statement `--a` can be justified.\n", " + This StackOverflow [thread](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) discusses the rationale behind the absence of increment and decrement operators in Python.\n", "\n", "* You must be aware of the Walrus operator in Python. But have you ever heard about *the space-invader operator*?\n", " ```py\n", " >>> a = 42\n", " >>> a -=- 1\n", " >>> a\n", " 43\n", " ```\n", " It is used as an alternative incrementation operator, together with another one\n", " ```py\n", " >>> a +=+ 1\n", " >>> a\n", " >>> 44\n", " ```\n", " **\ud83d\udca1 Explanation:** This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case.\n", " \n", "* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. \n", " \n", " ```py\n", " >>> False ** False == True\n", " True\n", " >>> False ** True == False\n", " True\n", " >>> True ** False == True\n", " True\n", " >>> True ** True == True\n", " True\n", " ```\n", "\n", " **\ud83d\udca1 Explanation:** If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to a converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator))\n", " \n", "* Since we are talking operators, there's also `@` operator for matrix multiplication (don't worry, this time it's for real).\n", "\n", " ```py\n", " >>> import numpy as np\n", " >>> np.array([2, 2, 2]) @ np.array([7, 8, 8])\n", " 46\n", " ```\n", "\n", " **\ud83d\udca1 Explanation:** The `@` operator was added in Python 3.5 keeping sthe cientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator.\n", "\n", "* From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example,\n", " ```py\n", " >>> some_string = \"wtfpython\"\n", " >>> f'{some_string=}'\n", " \"string='wtfpython'\"\n", " ``` \n", "\n", "* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!):\n", " \n", " ```py\n", " import dis\n", " exec(\"\"\"\n", " def f():\n", " \"\"\" + \"\"\"\n", " \"\"\".join([\"X\" + str(x) + \"=\" + str(x) for x in range(65539)]))\n", "\n", " f()\n", "\n", " print(dis.dis(f))\n", " ```\n", " \n", "* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module.\n", "\n", "* Sometimes, the `print` method might not print values immediately. For example,\n", "\n", " ```py\n", " # File some_file.py\n", " import time\n", " \n", " print(\"wtfpython\", end=\"_\")\n", " time.sleep(3)\n", " ```\n", "\n", " This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument.\n", "\n", "* List slicing with out of the bounds indices throws no errors\n", " ```py\n", " >>> some_list = [1, 2, 3, 4, 5]\n", " >>> some_list[111:]\n", " []\n", " ```\n", "\n", "* Slicing an iterable not always creates a new object. For example,\n", " ```py\n", " >>> some_str = \"wtfpython\"\n", " >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n']\n", " >>> some_list is some_list[:] # False expected because a new object is created.\n", " False\n", " >>> some_str is some_str[:] # True because strings are immutable, so making a new object is of not much use.\n", " True\n", " ```\n", "\n", "* `int('\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.\n", "\n", "* You can seperate numeric literals with underscores (for better readablity) from Python 3 onwards.\n", "\n", " ```py\n", " >>> six_million = 6_000_000\n", " >>> six_million\n", " 6000000\n", " >>> hex_address = 0xF00D_CAFE\n", " >>> hex_address\n", " 4027435774\n", " ```\n", "\n", "* `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear\n", " ```py\n", " def count(s, sub):\n", " result = 0\n", " for i in range(len(s) + 1 - len(sub)):\n", " result += (s[i:i + len(sub)] == sub)\n", " return result\n", " ```\n", " The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string.\n", "\n", "**That's all folks!**\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 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 \"\", line 1\n", " a := \"wtf_walrus\"\n", " ^\n", "SyntaxError: invalid syntax\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> (a := \"wtf_walrus\") # This works though\n", ">>> a\n", "```\n", "```py\n", "'wtf_walrus'\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "2 \\.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "# Python version 3.8+\n", "\n", ">>> a = 6, 9\n", ">>> a\n", "```\n", "```py\n", "(6, 9)\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> (a := 6, 9)\n", ">>> a\n", "```\n", "```py\n", "6\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> a, b = 6, 9 # Typcial unpacking\n", ">>> a, b\n", "```\n", "```py\n", "(6, 9)\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> (a, b = 16, 19) # Oops\n", "```\n", "```py\n", " File \"\", line 1\n", " (a, b = 6, 9)\n", " ^\n", "SyntaxError: invalid syntax\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> (a, b := 16, 19) # This prints out a weird 3-tuple\n", "```\n", "```py\n", "(6, 16, 19)\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> a # a is still unchanged?\n", "```\n", "```py\n", "6\n", "\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> b\n", "```\n", "```py\n", "16\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation\n", "\n", "**Quick walrus operator refresher**\n", "\n", "The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression.\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "def some_func():\n", " # Assume some expensive computation here\n", " # time.sleep(1000)\n", " return 5\n", "\n", "# So instead of,\n", "if some_func():\n", " print(some_func()) # Which is bad practice since computation is happening twice\n", "\n", "# or\n", "a = some_func()\n", "if a:\n", " print(a)\n", "\n", "# Now you can concisely write\n", "if a := some_func():\n", " print(a)\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output (> 3.8):**\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "5\n", "5\n", "5\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "This 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, hence the `SyntaxError` in the `a := \"wtf_walrus\"` statement of the first snippet. Parenthesizing it worked as expected and assigned `a`. \n", "\n", "- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. \n", "\n", "- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", "\n", " - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6')\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> (a := 6, 9) == ((a := 6), 9)\n", "```\n", "```py\n", " True\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> x = (a := 696, 9)\n", " >>> x\n", "```\n", "```py\n", " (696, 9)\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> x[0] is a # Both reference same memory location\n", "```\n", "```py\n", " True\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", " - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. \n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Stubborn `del` operation\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "class SomeClass:\n", " def __del__(self):\n", " print(\"Deleted!\")\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output:**\n", "1\\.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> x = SomeClass()\n", ">>> y = x\n", ">>> del x # this should print \"Deleted!\"\n", ">>> del y\n", "```\n", "```py\n", "Deleted!\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.\n", "\n", "2\\.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> x = SomeClass()\n", ">>> y = x\n", ">>> del x\n", ">>> y # check if y exists\n", "```\n", "```py\n", "<__main__.SomeClass instance at 0x7f98a1a67fc8>\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> del y # Like previously, this should print \"Deleted!\"\n", ">>> globals() # oh, it didn't. Let's check all our global variables and confirm\n", "```\n", "```py\n", "Deleted!\n", "{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None}\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "Okay, now it's deleted :confused:\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "+ `del x` doesn\u2019t directly call `x.__del__()`.\n", "+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x\u2019s reference count reaches zero.\n", "+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.\n", "+ Calling `globals` caused the existing reference to be destroyed, and hence we can see \"Deleted!\" being printed (finally!).\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### \u25b6 Wild imports *\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", "# File: module.py\n", "\n", "def some_weird_name_func_():\n", " print(\"works!\")\n", "\n", "def _another_weird_name_func():\n", " print(\"works!\")\n", "\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n", "**Output**\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> from module import *\n", ">>> some_weird_name_func_()\n", "```\n", "```py\n", "\"works!\"\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", ">>> _another_weird_name_func()\n", "```\n", "```py\n", "Traceback (most recent call last):\n", " File \"\", line 1, in \n", "NameError: name '_another_weird_name_func' is not defined\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["#### \ud83d\udca1 Explanation:\n", "\n", "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime.\n", "- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> from module import some_weird_name_func_, _another_weird_name_func\n", " >>> _another_weird_name_func()\n", "```\n", "```py\n", " works!\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports.\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " __all__ = ['_another_weird_name_func']\n", "\n", " def some_weird_name_func_():\n", " print(\"works!\")\n", "\n", " def _another_weird_name_func():\n", " print(\"works!\")\n", "```\n", "```py\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": [" **Output**\n", "\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> _another_weird_name_func()\n", "```\n", "```py\n", " \"works!\"\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["```py\n", " >>> some_weird_name_func_()\n", "```\n", "```py\n", " Traceback (most recent call last):\n", " File \"\", line 1, in \n", " NameError: name 'some_weird_name_func_' is not defined\n", "```\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Contributing\n", "\n", "A few ways in which you can contribute to wtfpython,\n", "\n", "- Suggesting new examples\n", "- Helping with translation (See [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation))\n", "- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc.\n", "- Identifying gaps (things like inadequate explanation, redundant examples, etc.)\n", "- Any creative suggestions to make this project more fun and useful\n", "\n", "Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) to discuss things.\n", "\n", "PS: Please don't reach out with backlinking requests, no links will be added unless they're highly relevant to the project.\n", "\n", "# Acknowledgements\n", "\n", "The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by Pythonistas gave it the shape it is in right now.\n", "\n", "#### Some nice Links!\n", "* https://www.youtube.com/watch?v=sH4XF6pKKmk\n", "* https://www.reddit.com/r/Python/comments/3cu6ej/what_are_some_wtf_things_about_python\n", "* https://sopython.com/wiki/Common_Gotchas_In_Python\n", "* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines\n", "* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python\n", "* https://www.python.org/doc/humor/\n", "* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator\n", "* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65\n", "* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues\n", "\n", "# \ud83c\udf93 License\n", "\n", "[![WTFPL 2.0][license-image]][license-url]\n", "\n", "© [Satwik Kansal](https://satwikkansal.xyz)\n", "\n", "[license-url]: http://www.wtfpl.net\n", "[license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square\n", "\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 2} \ No newline at end of file +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

\"\"

\n", + "

What the f*ck Python! \ud83d\ude31

\n", + "

Exploring and understanding Python through surprising snippets.

\n", + "\n", + "Translations: [Chinese \u4e2d\u6587](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", + "Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/3.0/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython)\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's 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", + "\n", + "# Structure of the Examples\n", + "\n", + "All the examples are structured like below:\n", + "\n", + "> ### \u25b6 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", + "> #### \ud83d\udca1 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", + "# \ud83d\udc40 Examples\n", + "\n", + "\n\n## Hosted notebook instructions\n\nThis 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\nThe 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\nThat being said, most of the 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": [ + "### \u25b6 Strings can be tricky sometimes\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140420665652016\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = \"some_string\"\n", + "id(a)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140420665652016\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "id(\"some\" + \"_\" + \"string\") # Notice that both the ids are same.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = \"wtf\"\n", + "b = \"wtf\"\n", + "a is b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = \"wtf!\"\n", + "b = \"wtf!\"\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a, b = \"wtf!\", \"wtf!\"\n", + "a is b # All versions except 3.7.x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = \"wtf!\"; b = \"wtf!\"\n", + "a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "# This time in file some_file.py\n", + "a = \"wtf!\"\n", + "b = \"wtf!\"\n", + "print(a is b)\n", + "\n", + "# prints True when the module is invoked!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "4\\.\n", + "\n", + "**Output (< Python3.7 )**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Makes sense, right?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ The behavior in first and second snippets is due to a CPython optimization (called string interning) 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 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. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", + " ![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images/string-intern/string_intern.png)\n", + "+ When `a` and `b` are set to `\"wtf!\"` 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 `wtf!` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", + "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, 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 [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.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 with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Hash brownies\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_dict = {}\n", + "some_dict[5.5] = \"JavaScript\"\n", + "some_dict[5.0] = \"Ruby\"\n", + "some_dict[5] = \"Python\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"JavaScript\"\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_dict[5.5]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"Python\"\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"Python\"\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_dict[5] \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "complex\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "complex_five = 5 + 0j\n", + "type(complex_five)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\"Python\"\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_dict[complex_five]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "So, why is Python all over the place?\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.\n", + "* Immutable objects with the same value always have the same hash in Python.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " 5 == 5.0 == 5 + 0j\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " hash(5) == hash(5.0) == hash(5 + 0j)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Note:** Objects with different values may also have same hash (known as [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science))).\n", + "* When the statement `some_dict[5] = \"Python\"` is executed, the existing value \"Ruby\" is overwritten with \"Python\" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`.\n", + "* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains the rationale behind it.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Deep down, we're all the same.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class WTF:\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "WTF() == WTF() # two different instances can't be equal\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "WTF() is WTF() # identities are also different\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "id(WTF()) == id(WTF())\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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 evaluated to `False`? Let's see with this snippet.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " class WTF(object):\n", + " def __init__(self): print(\"I\")\n", + " def __del__(self): print(\"D\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " I\n", + " I\n", + " D\n", + " D\n", + " False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " WTF() is WTF()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " I\n", + " D\n", + " I\n", + " D\n", + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " id(WTF()) == id(WTF())\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " As you may observe, the order in which the objects are destroyed is what made all the difference here.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Disorder within order *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "from collections import OrderedDict\n", + "\n", + "dictionary = dict()\n", + "dictionary[1] = 'a'; dictionary[2] = 'b';\n", + "\n", + "ordered_dict = OrderedDict()\n", + "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", + "\n", + "another_ordered_dict = OrderedDict()\n", + "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", + "\n", + "class DictWithHash(dict):\n", + " \"\"\"\n", + " A dict that also implements __hash__ magic.\n", + " \"\"\"\n", + " __hash__ = lambda self: 0\n", + "\n", + "class OrderedDictWithHash(OrderedDict):\n", + " \"\"\"\n", + " An OrderedDict that also implements __hash__ magic.\n", + " \"\"\"\n", + " __hash__ = lambda self: 0\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "dictionary == ordered_dict # If a == b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "dictionary == another_ordered_dict # and b == c\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\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" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "ordered_dict == another_ordered_dict # the why isn't c == a ??\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "TypeError: unhashable type: 'dict'\n", + "\n", + "# Makes sense since dict don't have __hash__ implemented, let's use\n", + "# our wrapper classes.\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len({dictionary, ordered_dict, another_ordered_dict})\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "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})\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "2\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "What is going on here?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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://docs.python.org/3/library/collections.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", + "- The reason for this equality is 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 lenght 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_set = set()\n", + " some_set.add(dictionary) # these are the mapping objects from the snippets above\n", + " ordered_dict in some_set\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 1\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_set.add(ordered_dict)\n", + " len(some_set)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " another_ordered_dict in some_set\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 1\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_set.add(another_ordered_dict)\n", + " len(some_set)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " another_set = set()\n", + " another_set.add(ordered_dict)\n", + " another_ordered_dict in another_set\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 2\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " another_set.add(another_ordered_dict)\n", + " len(another_set)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " dictionary in another_set\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 2\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " another_set.add(another_ordered_dict)\n", + " len(another_set)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Keep trying... *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def some_func():\n", + " try:\n", + " return 'from_try'\n", + " finally:\n", + " return 'from_finally'\n", + "\n", + "def another_func(): \n", + " for _ in range(3):\n", + " try:\n", + " continue\n", + " finally:\n", + " print(\"Finally!\")\n", + "\n", + "def one_more_func(): # A gotcha!\n", + " try:\n", + " for i in range(3):\n", + " try:\n", + " 1 / 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 ocurred\", e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'from_finally'\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Finally!\n", + "Finally!\n", + "Finally!\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "another_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "ZeroDivisionError: division by zero\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "1 / 0\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Iteration 0\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "one_more_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- When a `return`, `break` or `continue` statement is executed in the `try` suite of a \"try\u2026finally\" 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 For what?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_string = \"wtf\"\n", + "some_dict = {}\n", + "for i, some_dict[i] in enumerate(some_string):\n", + " i = 10\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{0: 'w', 1: 't', 2: 'f'}\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_dict # An indexed dict appears.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as:\n", + " ```\n", + " for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " for i in range(4):\n", + " print(i)\n", + " i = 10\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n", + " ```\n", + " 0\n", + " 1\n", + " 2\n", + " 3\n", + " ```\n", + "\n", + " Did you expect the loop to run just once?\n", + "\n", + " **\ud83d\udca1 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)` 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " i, some_dict[i] = (0, 'w')\n", + " i, some_dict[i] = (1, 't')\n", + " i, some_dict[i] = (2, 'f')\n", + " some_dict\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Evaluation time discrepancy\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "array = [1, 8, 15]\n", + "# A typical generator expression\n", + "gen = (x for x in array if array.count(x) > 0)\n", + "array = [2, 8, 22]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[8]\n" + ] + } + ], + "source": [ + "print(list(gen)) # Where did the other values go?\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "array_1 = [1,2,3,4]\n", + "gen_1 = (x for x in array_1)\n", + "array_1 = [1,2,3,4,5]\n", + "\n", + "array_2 = [1,2,3,4]\n", + "gen_2 = (x for x in array_2)\n", + "array_2[:] = [1,2,3,4,5]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4]\n", + "\n" + ] + } + ], + "source": [ + "print(list(gen_1))\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5]\n" + ] + } + ], + "source": [ + "print(list(gen_2))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "array_3 = [1, 2, 3]\n", + "array_4 = [10, 20, 30]\n", + "gen = (i + j for i in array_3 for j in array_4)\n", + "\n", + "array_3 = [4, 5, 6]\n", + "array_4 = [400, 500, 600]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[401, 501, 601, 402, 502, 602, 403, 503, 603]\n" + ] + } + ], + "source": [ + "print(list(gen))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "- In a [generator](https://wiki.python.org/moin/Generators) 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 binded 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(g)` 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://www.python.org/dev/peps/pep-0289/#the-details)\n", + " \n", + " > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 How not to use `is` operator\n", + "The following is a very famous example present all over the internet.\n", + "\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = 256\n", + "b = 256\n", + "a is b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = 257\n", + "b = 257\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = []\n", + "b = []\n", + "a is b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = tuple()\n", + "b = tuple()\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "**Output**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a, b = 257, 257\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.7.x specifically)**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + ">> a is b\n", + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a, b = 257, 257\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " class A: pass\n", + " A() is A() # These are two empty objects at two different memory locations.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**`256` is an existing object but `257` isn't**\n", + "\n", + "When 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", + "\n", + "Quoting from https://docs.python.org/3/c-api/long.html\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10922528\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "id(256)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10922528\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = 256\n", + "b = 256\n", + "id(a)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10922528\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "id(b)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140084850247312\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "id(257)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140084850247440\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 257\n", + "y = 257\n", + "id(x)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140084850247344\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "id(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Here 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", + "\n", + "Similar 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140640774013296\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a, b = 257, 257\n", + "id(a)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140640774013296\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "id(b)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140640774013392\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = 257\n", + "b = 257\n", + "id(a)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "140640774013488\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "id(b)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " a, b = 257.0, 257.0\n", + " a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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://github.com/satwikkansal/wtfpython/issues/100) for updates.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 `is not ...` is not `is (not ...)`\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'something' is not None\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'something' is (not None)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 A tic-tac-toe where X wins in the first attempt!\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "# Let's initialize a row\n", + "row = [\"\"] * 3 #row i['', '', '']\n", + "# Let's make a board\n", + "board = [row] * 3\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[['', '', ''], ['', '', ''], ['', '', '']]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "board\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['', '', '']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "board[0]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "''\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "board[0][0]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[['X', '', ''], ['X', '', ''], ['X', '', '']]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "board[0][0] = \"X\"\n", + "board\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "We didn't assign three `\"X\"`s, did we?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "When we initialize `row` variable, this visualization explains what happens in the memory\n", + "\n", + "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images/tic-tac-toe/after_row_initialized.png)\n", + "\n", + "And 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", + "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images/tic-tac-toe/after_board_initialized.png)\n", + "\n", + "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[['X', '', ''], ['', '', ''], ['', '', '']]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "board = [['']*3 for _ in range(3)]\n", + "board[0][0] = \"X\"\n", + "board\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 The sticky output function\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "funcs = []\n", + "results = []\n", + "for 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", + "\n", + "funcs_results = [func() for func in funcs]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "results\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[6, 6, 6, 6, 6, 6, 6]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "funcs_results\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.\n", + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "powers_of_x = [lambda x: x**i for i in range(10)]\n", + "[f(2) for f in powers_of_x]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.\n", + "\n", + "- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " funcs = []\n", + " for x in range(7):\n", + " def some_func(x=x):\n", + " return x\n", + " funcs.append(some_func)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [0, 1, 2, 3, 4, 5, 6]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " funcs_results = [func() for func in funcs]\n", + " funcs_results\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 The chicken-egg problem *\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "isinstance(3, int)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "isinstance(type, object)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "isinstance(object, type)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "So which is the \"ultimate\" base class? There's more to the confusion by the way,\n", + "\n", + "2\\. \n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class A: pass\n", + "isinstance(A, A)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "isinstance(type, type)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "isinstance(object, object)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "issubclass(int, object)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "issubclass(type, object)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "issubclass(object, type)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "- `type` is a [metaclass](https://realpython.com/python-metaclasses/) 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Subclass relationships\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "from collections import Hashable\n", + "issubclass(list, object)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "issubclass(object, Hashable)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "issubclass(list, Hashable)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "The 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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://www.naftaliharris.com/blog/python-subclass-intransitivity/).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 All-true-ation *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "all([True, True, True])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "all([True, True, False])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "all([])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "all([[]])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "all([[[]]])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Why's this True-False alteration?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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 `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty.\n", + "- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 The surprising comma\n", + "**Output (< 3.6):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"\", line 1\n", + " def h(x, **kwargs,):\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"\", line 1\n", + " def h(*args,):\n", + " ^\n", + "SyntaxError: invalid syntax\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def h(*args,):\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Strings and the backslashes\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\"\n", + "\n" + ] + } + ], + "source": [ + "print(\"\\\"\")\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\\\"\n", + "\n" + ] + } + ], + "source": [ + "print(r\"\\\"\")\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "File \"\", line 1\n", + " print(r\"\\\")\n", + " ^\n", + "SyntaxError: EOL while scanning string literal\n", + "\n" + ] + } + ], + "source": [ + "print(r\"\\\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "r'\\'' == \"\\\\'\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 'wt\"f'\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " 'wt\\\"f'\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " r'wt\\\"f' == 'wt\\\\\"f'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 'wt\\\\\"f'\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " print(repr(r'wt\\\"f')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " print(\"\\n\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " '\\\\\\\\n'\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " print(r\"\\\\n\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 not knot!\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = True\n", + "y = False\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "not x == y\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"\", line 1\n", + " x == not y\n", + " ^\n", + "SyntaxError: invalid syntax\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x == not y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Half triple-quoted strings\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "wtfpython\n" + ] + } + ], + "source": [ + "print('wtfpython''')\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "wtfpython\n" + ] + } + ], + "source": [ + "print(\"wtfpython\"\"\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"\", line 3\n", + " print(\"\"\"wtfpython\")\n", + " ^\n", + "SyntaxError: EOF while scanning triple-quoted string literal\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "# The following statements raise `SyntaxError`\n", + "# print('''wtfpython')\n", + "# print(\"\"\"wtfpython\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ Python supports implicit [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation), Example,\n", + " ```\n", + " >>> print(\"wtf\" \"python\")\n", + " wtfpython\n", + " >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n", + " wtf\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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 What's wrong with booleans?\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "# A simple example to count the number of booleans and\n", + "# integers in an iterable of mixed data types.\n", + "mixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\n", + "integers_found_so_far = 0\n", + "booleans_found_so_far = 0\n", + "\n", + "for 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "integers_found_so_far\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "booleans_found_so_far\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'wtf'\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_bool = True\n", + "\"wtf\" * some_bool\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "''\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_bool = False\n", + "\"wtf\" * some_bool\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def tell_truth():\n", + " True = False\n", + " if True == False:\n", + " print(\"I have lost faith in truth!\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (< 3.x):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "I have lost faith in truth!\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "tell_truth()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* `bool` is a subclass of `int` in Python\n", + " \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " issubclass(bool, int)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " issubclass(int, bool)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " \n", + "* And thus, `True` and `False` are instances of `int`\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " isinstance(True, int)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " isinstance(False, int)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* The integer value of `True` is `1` and that of `False` is `0`.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 1\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " int(True)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 0\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " int(False)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Class attributes and instance attributes\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class A:\n", + " x = 1\n", + "\n", + "class B(A):\n", + " pass\n", + "\n", + "class C(A):\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(1, 1, 1)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "A.x, B.x, C.x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(1, 2, 1)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "B.x = 2\n", + "A.x, B.x, C.x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(3, 2, 3)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "A.x = 3\n", + "A.x, B.x, C.x # C.x changed, but B.x didn't\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(3, 3)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = A()\n", + "a.x, A.x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(4, 3)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a.x += 1\n", + "a.x, A.x\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 420]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_obj = SomeClass(420)\n", + "some_obj.some_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 420]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_obj.another_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 111]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "another_obj = SomeClass(111)\n", + "another_obj.some_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 420, 111]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "another_obj.another_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "another_obj.another_list is SomeClass.another_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "another_obj.another_list is some_obj.another_list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Non-reflexive class method *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class SomeClass:\n", + " def instance_method(self):\n", + " pass\n", + " \n", + " @classmethod\n", + " def class_method(cls):\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "SomeClass.instance_method is SomeClass.instance_method\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "SomeClass.class_method is SomeClass.class_method\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "id(SomeClass.class_method) == id(SomeClass.class_method)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- The reason `SomeClass.class_method is SomeClass.class_method` is `False` is due to the `@classmethod` decorator. \n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " \n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " SomeClass.instance_method\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " \n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " SomeClass.class_method\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " A new bound method every time `SomeClass.class_method` is accessed.\n", + "\n", + "- `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 yielding None\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_iterable = ('a', 'b')\n", + "\n", + "def some_func(val):\n", + " return \"something\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (<= 3.7.x):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "[x for x in some_iterable]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " at 0x7f70b0a4ad58>\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "[(yield x) for x in some_iterable]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list([(yield x) for x in some_iterable])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', None, 'b', None]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list((yield x) for x in some_iterable)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'something', 'b', 'something']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list(some_func((yield x)) for x in some_iterable)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n", + "- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n", + "- Related bug report: http://bugs.python.org/issue10544\n", + "- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Yielding from... return! *\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def some_func(x):\n", + " if x == 3:\n", + " return [\"wtf\"]\n", + " else:\n", + " yield from range(x)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (> 3.3):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list(some_func(3))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Where did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n", + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def some_func(x):\n", + " if x == 3:\n", + " return [\"wtf\"]\n", + " else:\n", + " for i in range(x):\n", + " yield i\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list(some_func(3))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "The same result, this didn't work either.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " try:\n", + " next(some_func(3))\n", + " except StopIteration as e:\n", + " some_string = e.value\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [\"wtf\"]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_string\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Nan-reflexivity *\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = float('inf')\n", + "b = float('nan')\n", + "c = float('-iNf') # These strings are case-insensitive\n", + "d = float('nan')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "inf\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "nan\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "-inf\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "c\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "ValueError: could not convert string to float: some_other_string\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "float('some_other_string')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a == -c # inf==inf\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "None == None # None == None\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "b == d # but nan!=nan\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.0\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "50 / a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "nan\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a / a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "nan\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "23 + b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = float('nan')\n", + "y = x / x\n", + "y is y # identity holds\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "y == y # equality fails of y\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "[y] == [y] # but the equality succeeds for the list containing y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (False, True)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " x = float('nan')\n", + " x == x, [x] == [x]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (False, True)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " y = float('nan')\n", + " y == y, [y] == [y]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (False, False)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " x == y, [x] == [y]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Mutating the immutable!\n", + "This might seem trivial if you know how references work in Python.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_tuple = (\"A\", \"tuple\", \"with\", \"values\")\n", + "another_tuple = ([1, 2], [3, 4], [5, 6])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "TypeError: 'tuple' object does not support item assignment\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_tuple[2] = \"change this\"\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "([1, 2], [3, 4], [5, 6, 1000])\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "another_tuple[2].append(1000) #This throws no error\n", + "another_tuple\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "TypeError: 'tuple' object does not support item assignment\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "another_tuple[2] += [99, 999]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "another_tuple\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "But I thought tuples were immutable...\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* Quoting from https://docs.python.org/2/reference/datamodel.html\n", + "\n", + " > Immutable sequences\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", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 The disappearing variable from outer scope\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "e = 7\n", + "try:\n", + " raise Exception()\n", + "except Exception as e:\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "# prints nothing\n" + ] + } + ], + "source": [ + "print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "NameError: name 'e' is not defined\n" + ] + } + ], + "source": [ + "print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* Source: https://docs.python.org/3/reference/compound_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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " except E as N:\n", + " foo\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " was translated into\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " except E as N:\n", + " try:\n", + " foo\n", + " finally:\n", + " del N\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " def f(x):\n", + " del(x)\n", + " print(x)\n", + "\n", + " x = 5\n", + " y = [5, 4, 3]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 5\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " >>>f(x)\n", + " UnboundLocalError: local variable 'x' referenced before assignment\n", + " >>>f(y)\n", + " UnboundLocalError: local variable 'x' referenced before assignment\n", + " x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [5, 4, 3]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Exception()\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " e\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " # Nothing is printed!\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " print e\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 The mysterious key type conversion\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class SomeClass(str):\n", + " pass\n", + "\n", + "some_dict = {'s': 42}\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "type(list(some_dict.keys())[0])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{'s': 40}\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "s = SomeClass('s')\n", + "some_dict[s] = 40\n", + "some_dict # expected: Two different keys-value pairs\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "str\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "type(list(some_dict.keys())[0])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " {'s': 40, 's': 42}\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " s = SomeClass('s')\n", + " some_dict[s] = 40\n", + " some_dict\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (__main__.SomeClass, str)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " keys = list(some_dict.keys())\n", + " type(keys[0]), type(keys[1])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Let's see if you can guess this?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a, b = a[b] = {}, 5\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "{5: ({...}, 5)}\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form\n", + " ```\n", + " (target_list \"=\")+ (expression_list | yield_expression)\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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [[...]]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_list = some_list[0] = [0]\n", + " some_list\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [[...]]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_list[0]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_list is some_list[0]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_list[0][0][0][0][0][0] == some_list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " a, b = {}, 5\n", + " a[b] = a, b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " a[b][0] is a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Modifying a dictionary while iterating over it\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = {0: None}\n", + "\n", + "for i in x:\n", + " del x[i]\n", + " x[i+1] = None\n", + " print(i)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.7- Python 3.5):**\n", + "\n", + "```\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "```\n", + "\n", + "Yes, it runs for exactly **eight** times and stops.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* Iteration over a dictionary that you edit at the same time is not supported.\n", + "* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.\n", + "* How deleted keys are handled and when the resize occurs might be different for different Python implementations.\n", + "* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread.\n", + "* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 The out of scope variable\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = 1\n", + "def some_func():\n", + " return a\n", + "\n", + "def another_func():\n", + " a += 1\n", + " return a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "UnboundLocalError: local variable 'a' referenced before assignment\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "another_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.\n", + "* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.\n", + "* To modify the outer scope variable `a` in `another_func`, use `global` keyword.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " def another_func()\n", + " global a\n", + " a += 1\n", + " return a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 2\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " another_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Deleting a list item while iterating\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list_1 = [1, 2, 3, 4]\n", + "list_2 = [1, 2, 3, 4]\n", + "list_3 = [1, 2, 3, 4]\n", + "list_4 = [1, 2, 3, 4]\n", + "\n", + "for idx, item in enumerate(list_1):\n", + " del item\n", + "\n", + "for idx, item in enumerate(list_2):\n", + " list_2.remove(item)\n", + "\n", + "for idx, item in enumerate(list_3[:]):\n", + " list_3.remove(item)\n", + "\n", + "for idx, item in enumerate(list_4):\n", + " list_4.pop(idx)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list_1\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 4]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list_2\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list_3\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 4]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list_4\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Can you guess why the output is `[2, 4]`?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 139798789457608\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_list = [1, 2, 3, 4]\n", + " id(some_list)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 139798779601192\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " id(some_list[:]) # Notice that python creates new object for sliced list.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Difference between `del`, `remove`, and `pop`:**\n", + "* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).\n", + "* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.\n", + "* `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified.\n", + "\n", + "**Why the output is `[2, 4]`?**\n", + "- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.\n", + "\n", + "* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example\n", + "* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Lossy zip of iterators *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "numbers = list(range(7))\n", + "numbers\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "([0, 1, 2], [3, 4, 5, 6])\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "first_three, remaining = numbers[:3], numbers[3:]\n", + "first_three, remaining\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[(0, 0), (1, 1), (2, 2)]\n", + "# so far so good, let's zip the remaining\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "numbers_iter = iter(numbers)\n", + "list(zip(numbers_iter, first_three)) \n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[(4, 3), (5, 4), (6, 5)]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list(zip(numbers_iter, remaining))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Where did element `3` go from the `numbers` list?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " def zip(*iterables):\n", + " sentinel = object()\n", + " iterators = [iter(it) for it in iterables]\n", + " while iterators:\n", + " result = []\n", + " for it in iterators:\n", + " elem = next(it, sentinel)\n", + " if elem is sentinel: return\n", + " result.append(elem)\n", + " yield tuple(result)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. \n", + "- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.\n", + "- The correct way to do the above using `zip` would be,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [(0, 0), (1, 1), (2, 2)]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " numbers = list(range(7))\n", + " numbers_iter = iter(numbers)\n", + " list(zip(first_three, numbers_iter))\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " [(3, 3), (4, 4), (5, 5), (6, 6)]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " list(zip(remaining, numbers_iter))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " The first argument of zip should be the one with fewest elements.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Loop variables leaking out!\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "for x in range(7):\n", + " if x == 6:\n", + " print(x, ': for x inside loop')\n", + "print(x, ': x in global')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "6 : for x inside loop\n", + "6 : x in global\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "But `x` was never defined outside the scope of for loop...\n", + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "# This time let's initialize x first\n", + "x = -1\n", + "for x in range(7):\n", + " if x == 6:\n", + " print(x, ': for x inside loop')\n", + "print(x, ': x in global')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "6 : for x inside loop\n", + "6 : x in global\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 2, 3, 4]\n" + ] + } + ], + "source": [ + "x = 1\n", + "print([x for x in range(5)])\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n" + ] + } + ], + "source": [ + "print(x)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 2, 3, 4]\n" + ] + } + ], + "source": [ + "x = 1\n", + "print([x for x in range(5)])\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n" + ] + } + ], + "source": [ + "print(x)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.\n", + "\n", + "- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What\u2019s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog:\n", + "\n", + " > \"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.\"\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Beware of default mutable arguments!\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def some_func(default_arg=[]):\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string', 'some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_func([])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string', 'some_string', 'some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " def some_func(default_arg=[]):\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " **Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ([],)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_func.__defaults__ #This will show the default argument values for the function\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string'],)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_func()\n", + " some_func.__defaults__\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string', 'some_string'],)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_func()\n", + " some_func.__defaults__\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string', 'some_string'],)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_func([])\n", + " some_func.__defaults__\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " def some_func(default_arg=None):\n", + " if not default_arg:\n", + " default_arg = []\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Catching the Exceptions\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_list = [1, 2, 3]\n", + "try:\n", + " # This should raise an ``IndexError``\n", + " print(some_list[4])\n", + "except IndexError, ValueError:\n", + " print(\"Caught!\")\n", + "\n", + "try:\n", + " # This should raise a ``ValueError``\n", + " some_list.remove(4)\n", + "except IndexError, ValueError:\n", + " print(\"Caught again!\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "Caught!\n", + "\n", + "ValueError: list.remove(x): x not in list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " File \"\", line 3\n", + " except IndexError, ValueError:\n", + " ^\n", + "SyntaxError: invalid syntax\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_list = [1, 2, 3]\n", + " try:\n", + " # This should raise a ``ValueError``\n", + " some_list.remove(4)\n", + " except (IndexError, ValueError), e:\n", + " print(\"Caught again!\")\n", + " print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Output (Python 2.x):**\n", + " ```\n", + " Caught again!\n", + " list.remove(x): x not in list\n", + " ```\n", + " **Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " File \"\", line 4\n", + " except (IndexError, ValueError), e:\n", + " ^\n", + " IndentationError: unindent does not match any outer indentation level\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_list = [1, 2, 3]\n", + " try:\n", + " some_list.remove(4)\n", + "\n", + " except (IndexError, ValueError) as e:\n", + " print(\"Caught again!\")\n", + " print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Output:**\n", + " ```\n", + " Caught again!\n", + " list.remove(x): x not in list\n", + " ```\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Same operands, different story!\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = [1, 2, 3, 4]\n", + "b = a\n", + "a = a + [5, 6, 7, 8]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = [1, 2, 3, 4]\n", + "b = a\n", + "a += [5, 6, 7, 8]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this.\n", + "\n", + "* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged.\n", + "\n", + "* The expression `a += [5,6,7,8]` is actually mapped to an \"extend\" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Be careful with chained operations\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "(False == False) in [False] # makes sense\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "False == (False in [False]) # makes sense\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "False == False in [False] # now what?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "True is False == False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "False is False is False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "1 > 0 < 1\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "(1 > 0) < 1\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "1 > (0 < 1)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "As per https://docs.python.org/2/reference/expressions.html#not-in\n", + "\n", + "> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.\n", + "\n", + "While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 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` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n", + "* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`.\n", + "* The expression `(1 > 0) < 1` is equivalent to `True < 1` and\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 1\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " int(True)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 2\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " True + 1 #not relevant for this example, but just for fun\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " So, `1 < 1` evaluates to `False`\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Name resolution ignoring class scope\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 5\n", + "class SomeClass:\n", + " x = 17\n", + " y = (x for i in range(10))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list(SomeClass.y)[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 5\n", + "class SomeClass:\n", + " x = 17\n", + " y = [x for i in range(10)]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "17\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "SomeClass.y[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "SomeClass.y[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "- Scopes nested inside class definition ignore names bound at the class level.\n", + "- A generator expression has its own scope.\n", + "- Starting from Python 3.X, list comprehensions also have their own scope.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Needles in a Haystack *\n", + "I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios,\n", + "\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x, y = (0, 1) if True else None, None\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "((0, 1), None)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x, y # expected (0, 1)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "t = ('one', 'two')\n", + "for i in t:\n", + " print(i)\n", + "\n", + "t = ('one')\n", + "for i in t:\n", + " print(i)\n", + "\n", + "t = ()\n", + "print(t)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "one\n", + "two\n", + "o\n", + "n\n", + "e\n", + "tuple()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n", + "```\n", + "ten_words_list = [\n", + " \"some\",\n", + " \"very\",\n", + " \"big\",\n", + " \"list\",\n", + " \"that\"\n", + " \"consists\",\n", + " \"of\",\n", + " \"exactly\",\n", + " \"ten\",\n", + " \"words\"\n", + "]\n", + "```\n", + "\n", + "**Output**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "9\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len(ten_words_list)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "4\\. Not asserting strongly enough\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = \"python\"\n", + "b = \"javascript\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "# No AssertionError is raised\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "# An assert statement with an assertion failure message.\n", + "assert(a == b, \"Both languages are different\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "5\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_list = [1, 2, 3]\n", + "some_dict = {\n", + " \"key_1\": 1,\n", + " \"key_2\": 2,\n", + " \"key_3\": 3\n", + "}\n", + "\n", + "some_list = some_list.append(4) \n", + "some_dict = some_dict.update({\"key_4\": 4})\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "print(some_list)\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "print(some_dict)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "6\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def some_recursive_func(a):\n", + " if a[0] == 0:\n", + " return \n", + " a[0] -= 1\n", + " some_recursive_func(a)\n", + " return a\n", + "\n", + "def similar_recursive_func(a):\n", + " if a == 0:\n", + " return a\n", + " a -= 1\n", + " similar_recursive_func(a)\n", + " return a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 0]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_recursive_func([5, 0])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "similar_recursive_func(5)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`.\n", + "\n", + "* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character.\n", + "\n", + "* `()` is a special token and denotes empty `tuple`.\n", + "\n", + "* In 3, as you might have already figured out, there's a missing comma after 5th element (`\"that\"`) in the list. So by implicit string literal concatenation,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ten_words_list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " AssertionError\n", + " \n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " a = \"python\"\n", + " b = \"javascript\"\n", + " assert a == b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " :1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n", + " \n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " assert (a == b, \"Values are not equal\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " AssertionError: Values aren not equal\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " assert a == b, \"Values are not equal\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).\n", + "\n", + "* Last one should be fairly obvious, passing mutable object (like `list` ) results in a call by reference, whereas an immutable object (like `int`) results in a call by value.\n", + "\n", + "* Being aware of these nitpicks can save you hours of debugging effort in the long run. \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Splitsies *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a']\n", + "\n", + "# is same as\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'a'.split()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a']\n", + "\n", + "# but\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'a'.split(' ')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0\n", + "\n", + "# isn't the same as\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len(''.split())\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len(''.split(' '))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split)\n", + " > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.\n", + " > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.\n", + "- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['', 'a', '']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ' a '.split(' ')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['a']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ' a '.split()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ''.split(' ')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 All sorted? *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 7, 8, 9\n", + "sorted(x) == x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "sorted(x) == sorted(x)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "y = reversed(x)\n", + "sorted(y) == sorted(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. \n", + "\n", + "- ```py\n", + " >>> [] == tuple()\n", + " False\n", + " >>> x = 7, 8, 9\n", + " >>> type(x), type(sorted(x))\n", + " (tuple, list)\n", + " ```\n", + "\n", + "- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first.\n", + "\n", + "- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ([7, 8, 9], [])\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " x = 7, 8, 9\n", + " y = reversed(x)\n", + " sorted(y), sorted(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Midnight time doesn't exist?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "from datetime import datetime\n", + "\n", + "midnight = datetime(2018, 1, 1, 0, 0)\n", + "midnight_time = midnight.time()\n", + "\n", + "noon = datetime(2018, 1, 1, 12, 0)\n", + "noon_time = noon.time()\n", + "\n", + "if midnight_time:\n", + " print(\"Time at midnight is\", midnight_time)\n", + "\n", + "if noon_time:\n", + " print(\"Time at noon is\", noon_time)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (< 3.5):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "('Time at noon is', datetime.time(12, 0))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The midnight time is not printed.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of \"empty.\"\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Okay Python, Can you make me fly?\n", + "Well, here you go\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "import antigravity\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "Sshh... It's a super-secret.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ `antigravity` module is one of the few easter eggs released by Python developers.\n", + "+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python.\n", + "+ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 `goto`, but why?\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "from goto import goto, label\n", + "for i in range(9):\n", + " for j in range(9):\n", + " for k in range(9):\n", + " print(\"I am trapped, please rescue!\")\n", + " if k == 2:\n", + " goto .breakout # breaking out from a deeply nested loop\n", + "label .breakout\n", + "print(\"Freedom!\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.3):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "I am trapped, please rescue!\n", + "I am trapped, please rescue!\n", + "Freedom!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004.\n", + "- Current versions of Python do not have this module.\n", + "- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Brace yourself!\n", + "If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "from __future__ import braces\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " File \"some_file.py\", line 1\n", + " from __future__ import braces\n", + "SyntaxError: not a chance\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ The `__future__` module is normally used to provide features from future versions of Python. The \"future\" in this specific context is however, ironic.\n", + "+ This is an easter egg concerned with the community's feelings on this issue.\n", + "+ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file.\n", + "+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Let's meet Friendly Language Uncle For Life\n", + "**Output (Python 3.x)**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " File \"some_file.py\", line 1\n", + " \"Ruby\" != \"Python\"\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "from __future__ import barry_as_FLUFL\n", + "\"Ruby\" != \"Python\" # there's no doubt about it\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "\"Ruby\" <> \"Python\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "There we go.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means).\n", + "- Quoting from the PEP-401\n", + " \n", + " > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.\n", + "- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/).\n", + "- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " from __future__ import barry_as_FLUFL\n", + " print(eval('\"Ruby\" <> \"Python\"'))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Even Python understands that love is complicated\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "import this\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Wait, what's **this**? `this` is love :heart:\n", + "\n", + "**Output:**\n", + "```\n", + "The Zen of Python, by Tim Peters\n", + "\n", + "Beautiful is better than ugly.\n", + "Explicit is better than implicit.\n", + "Simple is better than complex.\n", + "Complex is better than complicated.\n", + "Flat is better than nested.\n", + "Sparse is better than dense.\n", + "Readability counts.\n", + "Special cases aren't special enough to break the rules.\n", + "Although practicality beats purity.\n", + "Errors should never pass silently.\n", + "Unless explicitly silenced.\n", + "In the face of ambiguity, refuse the temptation to guess.\n", + "There should be one-- and preferably only one --obvious way to do it.\n", + "Although that way may not be obvious at first unless you're Dutch.\n", + "Now is better than never.\n", + "Although never is often better than *right* now.\n", + "If the implementation is hard to explain, it's a bad idea.\n", + "If the implementation is easy to explain, it may be a good idea.\n", + "Namespaces are one honking great idea -- let's do more of those!\n", + "```\n", + "\n", + "It's the Zen of Python!\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "love = this\n", + "this is love\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "love is True\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "love is False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "love is not True or False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "love is not True or False; love is love # Love is complicated\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)).\n", + "* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens).\n", + "* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Yes, it exists!\n", + "**The `else` clause for loops.** One typical example might be:\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " def does_exists_num(l, to_find):\n", + " for num in l:\n", + " if num == to_find:\n", + " print(\"Exists!\")\n", + " break\n", + " else:\n", + " print(\"Does not exist\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Exists!\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_list = [1, 2, 3, 4, 5]\n", + "does_exists_num(some_list, 4)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Does not exist\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "does_exists_num(some_list, -1)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**The `else` clause in exception handling.** An example,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "try:\n", + " pass\n", + "except:\n", + " print(\"Exception occurred!!!\")\n", + "else:\n", + " print(\"Try block executed successfully...\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "Try block executed successfully...\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a \"nobreak\" clause.\n", + "- `else` clause after a try block is also called \"completion clause\" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Ellipsis *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def some_func():\n", + " Ellipsis\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "# No output, No Error\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "NameError: name 'SomeRandomString' is not defined\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "SomeRandomString\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Ellipsis\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "Ellipsis\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Ellipsis\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ...\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- Eliipsis can be used for several purposes,\n", + " + As a placeholder for code that hasn't been written yet (just like `pass` statement)\n", + " + In slicing syntax to represent the full slices in remaining direction\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " array([\n", + " [\n", + " [0, 1],\n", + " [2, 3]\n", + " ],\n", + "\n", + " [\n", + " [4, 5],\n", + " [6, 7]\n", + " ]\n", + " ])\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " import numpy as np\n", + " three_dimensional_array = np.arange(8).reshape(2, 2, 2)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " array([[1, 3],\n", + " [5, 7]])\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " three_dimensional_array[:,:,1]\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " array([[1, 3],\n", + " [5, 7]])\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " three_dimensional_array[..., 1] # using Ellipsis.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`)\n", + " + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`))\n", + " + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the \"no argument passed\" and \"None value passed\" scenarios).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Inpinity\n", + "The spelling is intended. Please, don't submit a patch for this.\n", + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "314159\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "infinity = float('infinity')\n", + "hash(infinity)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "-314159\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "hash(float('-inf'))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "- Hash of infinity is 10\u2075 x \u03c0.\n", + "- Interestingly, the hash of `float('-inf')` is \"-10\u2075 x \u03c0\" in Python 3, whereas \"-10\u2075 x e\" in Python 2.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Let's mangle\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class Yo(object):\n", + " def __init__(self):\n", + " self.__honey = True\n", + " self.bro = True\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "Yo().bro\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "AttributeError: 'Yo' object has no attribute '__honey'\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "Yo().__honey\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "Yo()._Yo__honey\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class Yo(object):\n", + " def __init__(self):\n", + " # Let's try something symmetrical this time\n", + " self.__honey__ = True\n", + " self.bro = True\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "Yo().bro\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "AttributeError: 'Yo' object has no attribute '_Yo__honey__'\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "Yo()._Yo__honey__\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Why did `Yo()._Yo__honey` work?\n", + "\n", + "3\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "_A__variable = \"Some value\"\n", + "\n", + "class A(object):\n", + " def some_func(self):\n", + " return __variable # not initialized anywhere yet\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "'Some value'\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "AttributeError: 'A' object has no attribute '__variable'\n", + "\n", + "A().some_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.\n", + "* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a \"dunder\") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front.\n", + "* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class.\n", + "* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores.\n", + "* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope.\n", + "* Also, if the mangled name is longer than 255 characters, truncation will happen.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Skipping lines?\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "11\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "value = 11\n", + "valu\u0435 = 32\n", + "value\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Wut?\n", + "\n", + "**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1077\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "ord('\u0435') # cyrillic 'e' (Ye)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "101\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "ord('e') # latin 'e', as used in English and typed using standard keyboard\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'\u0435' == 'e'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "42\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "value = 42 # latin e\n", + "valu\u0435 = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here\n", + "value\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Teleportation\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "# `pip install nump` first.\n", + "import numpy as np\n", + "\n", + "def energy_send(x):\n", + " # Initializing a numpy array\n", + " np.array([float(x)])\n", + "\n", + "def energy_receive():\n", + " # Return an empty numpy array\n", + " return np.empty((), dtype=np.float).tolist()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "123.456\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "energy_send(123.456)\n", + "energy_receive()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Where's the Nobel Prize?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate.\n", + "* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Well, something is fishy...\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def square(x):\n", + " \"\"\"\n", + " A simple function to calculate the square of a number by addition.\n", + " \"\"\"\n", + " sum_so_far = 0\n", + " for counter in range(x):\n", + " sum_so_far = sum_so_far + x\n", + " return sum_so_far\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "square(10)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Shouldn't that be 100?\n", + "\n", + "**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "* **Don't mix tabs and spaces!** The character just preceding return is a \"tab\", and the code is indented by multiple of \"4 spaces\" elsewhere in the example.\n", + "* This is how Python handles tabs:\n", + " \n", + " > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>\n", + "* So the \"tab\" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.\n", + "* Python 3 is kind enough to throw an error for such cases automatically.\n", + "\n", + " **Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " TabError: inconsistent use of tabs and spaces in indentation\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 `+=` is faster\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.25748300552368164\n", + "# using \"+=\", three strings:\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "# using \"+\", three strings:\n", + "timeit.timeit(\"s1 = s1 + s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0.012188911437988281\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "timeit.timeit(\"s1 += s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Let's make a giant string!\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def add_string_with_plus(iters):\n", + " s = \"\"\n", + " for i in range(iters):\n", + " s += \"xyz\"\n", + " assert len(s) == 3*iters\n", + "\n", + "def add_bytes_with_plus(iters):\n", + " s = b\"\"\n", + " for i in range(iters):\n", + " s += b\"xyz\"\n", + " assert len(s) == 3*iters\n", + "\n", + "def add_string_with_format(iters):\n", + " fs = \"{}\"*iters\n", + " s = fs.format(*([\"xyz\"]*iters))\n", + " assert len(s) == 3*iters\n", + "\n", + "def add_string_with_join(iters):\n", + " l = []\n", + " for i in range(iters):\n", + " l.append(\"xyz\")\n", + " s = \"\".join(l)\n", + " assert len(s) == 3*iters\n", + "\n", + "def convert_list_to_string(l, iters):\n", + " s = \"\".join(l)\n", + " assert len(s) == 3*iters\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "124 \u00b5s \u00b1 4.73 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "# Executed in ipython shell using %timeit for better readability of results.\n", + "# You can also use the timeit module in normal python shell/scriptm=, example usage below\n", + "# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())\n", + "\n", + "NUM_ITERS = 1000\n", + "%timeit -n1000 add_string_with_plus(NUM_ITERS)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "211 \u00b5s \u00b1 10.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "%timeit -n1000 add_bytes_with_plus(NUM_ITERS)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "61 \u00b5s \u00b1 2.18 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "%timeit -n1000 add_string_with_format(NUM_ITERS)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "117 \u00b5s \u00b1 3.21 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "%timeit -n1000 add_string_with_join(NUM_ITERS)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10.1 \u00b5s \u00b1 1.06 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "l = [\"xyz\"]*NUM_ITERS\n", + "%timeit -n1000 convert_list_to_string(l, NUM_ITERS)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Let's increase the number of iterations by a factor of 10.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1.26 ms \u00b1 76.8 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "NUM_ITERS = 10000\n", + "%timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "6.82 ms \u00b1 134 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "%timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "645 \u00b5s \u00b1 24.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "%timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1.17 ms \u00b1 7.25 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "%timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "86.3 \u00b5s \u00b1 2 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "l = [\"xyz\"]*NUM_ITERS\n", + "%timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces.\n", + "- Don't use `+` for generating long strings \u2014 In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function)\n", + "- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings).\n", + "- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.\n", + "- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + \"x\" + \"y\" + \"z\"` instead of `s += \"xyz\"`, the increase would have been quadratic.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 388 \u00b5s \u00b1 22.4 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " def add_string_with_plus(iters):\n", + " s = \"\"\n", + " for i in range(iters):\n", + " s = s + \"x\" + \"y\" + \"z\"\n", + " assert len(s) == 3*iters\n", + "\n", + " %timeit -n100 add_string_with_plus(1000)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " 9 ms \u00b1 298 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which,\n", + " \n", + " > There should be one-- and preferably only one --obvious way to do it.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Minor Ones *\n", + "* `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage)\n", + "\n", + " **\ud83d\udca1 Explanation:** If `join()` is a method on a string, then it can operate on any iterable (list, tuple, iterators). If it were a method on a list, it'd have to be implemented separately by every type. Also, it doesn't make much sense to put a string-specific method on a generic `list` object API.\n", + " \n", + "* Few weird looking but semantically correct statements:\n", + " + `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`)\n", + " + `'a'[0][0][0][0][0]` is also a semantically correct statement as strings are [sequences](https://docs.python.org/3/glossary.html#term-sequence)(iterables supporting element access using integer indices) in Python.\n", + " + `3 --0-- 5 == 8` and `--5 == 5` are both semantically correct statements and evaluate to `True`.\n", + "\n", + "* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java.\n", + " ```py\n", + " >>> a = 5\n", + " >>> a\n", + " 5\n", + " >>> ++a\n", + " 5\n", + " >>> --a\n", + " 5\n", + " ```\n", + "\n", + " **\ud83d\udca1 Explanation:**\n", + " + There is no `++` operator in Python grammar. It is actually two `+` operators.\n", + " + `++a` parses as `+(+a)` which translates to `a`. Similarly, the output of the statement `--a` can be justified.\n", + " + This StackOverflow [thread](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) discusses the rationale behind the absence of increment and decrement operators in Python.\n", + "\n", + "* You must be aware of the Walrus operator in Python. But have you ever heard about *the space-invader operator*?\n", + " ```py\n", + " >>> a = 42\n", + " >>> a -=- 1\n", + " >>> a\n", + " 43\n", + " ```\n", + " It is used as an alternative incrementation operator, together with another one\n", + " ```py\n", + " >>> a +=+ 1\n", + " >>> a\n", + " >>> 44\n", + " ```\n", + " **\ud83d\udca1 Explanation:** This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case.\n", + " \n", + "* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. \n", + " \n", + " ```py\n", + " >>> False ** False == True\n", + " True\n", + " >>> False ** True == False\n", + " True\n", + " >>> True ** False == True\n", + " True\n", + " >>> True ** True == True\n", + " True\n", + " ```\n", + "\n", + " **\ud83d\udca1 Explanation:** If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to a converse implication operator. ([Source](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator))\n", + " \n", + "* Since we are talking operators, there's also `@` operator for matrix multiplication (don't worry, this time it's for real).\n", + "\n", + " ```py\n", + " >>> import numpy as np\n", + " >>> np.array([2, 2, 2]) @ np.array([7, 8, 8])\n", + " 46\n", + " ```\n", + "\n", + " **\ud83d\udca1 Explanation:** The `@` operator was added in Python 3.5 keeping the scientific community in mind. Any object can overload `__matmul__` magic method to define behavior for this operator.\n", + "\n", + "* From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example,\n", + " ```py\n", + " >>> some_string = \"wtfpython\"\n", + " >>> f'{some_string=}'\n", + " \"string='wtfpython'\"\n", + " ``` \n", + "\n", + "* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!):\n", + " \n", + " ```py\n", + " import dis\n", + " exec(\"\"\"\n", + " def f():\n", + " \"\"\" + \"\"\"\n", + " \"\"\".join([\"X\" + str(x) + \"=\" + str(x) for x in range(65539)]))\n", + "\n", + " f()\n", + "\n", + " print(dis.dis(f))\n", + " ```\n", + " \n", + "* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module.\n", + "\n", + "* Sometimes, the `print` method might not print values immediately. For example,\n", + "\n", + " ```py\n", + " # File some_file.py\n", + " import time\n", + " \n", + " print(\"wtfpython\", end=\"_\")\n", + " time.sleep(3)\n", + " ```\n", + "\n", + " This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument.\n", + "\n", + "* List slicing with out of the bounds indices throws no errors\n", + " ```py\n", + " >>> some_list = [1, 2, 3, 4, 5]\n", + " >>> some_list[111:]\n", + " []\n", + " ```\n", + "\n", + "* Slicing an iterable not always creates a new object. For example,\n", + " ```py\n", + " >>> some_str = \"wtfpython\"\n", + " >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n']\n", + " >>> some_list is some_list[:] # False expected because a new object is created.\n", + " False\n", + " >>> some_str is some_str[:] # True because strings are immutable, so making a new object is of not much use.\n", + " True\n", + " ```\n", + "\n", + "* `int('\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.\n", + "\n", + "* You can separate numeric literals with underscores (for better readability) from Python 3 onwards.\n", + "\n", + " ```py\n", + " >>> six_million = 6_000_000\n", + " >>> six_million\n", + " 6000000\n", + " >>> hex_address = 0xF00D_CAFE\n", + " >>> hex_address\n", + " 4027435774\n", + " ```\n", + "\n", + "* `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear\n", + " ```py\n", + " def count(s, sub):\n", + " result = 0\n", + " for i in range(len(s) + 1 - len(sub)):\n", + " result += (s[i:i + len(sub)] == sub)\n", + " return result\n", + " ```\n", + " The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string.\n", + "\n", + "**That's all folks!**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 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 \"\", line 1\n", + " a := \"wtf_walrus\"\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a := \"wtf_walrus\") # This works though\n", + ">>> a\n", + "```\n", + "```py\n", + "'wtf_walrus'\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2 \\.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "# Python version 3.8+\n", + "\n", + ">>> a = 6, 9\n", + ">>> a\n", + "```\n", + "```py\n", + "(6, 9)\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a := 6, 9)\n", + ">>> a\n", + "```\n", + "```py\n", + "6\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> a, b = 6, 9 # Typical unpacking\n", + ">>> a, b\n", + "```\n", + "```py\n", + "(6, 9)\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a, b = 16, 19) # Oops\n", + "```\n", + "```py\n", + " File \"\", line 1\n", + " (a, b = 6, 9)\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> (a, b := 16, 19) # This prints out a weird 3-tuple\n", + "```\n", + "```py\n", + "(6, 16, 19)\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> a # a is still unchanged?\n", + "```\n", + "```py\n", + "6\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> b\n", + "```\n", + "```py\n", + "16\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "**Quick walrus operator refresher**\n", + "\n", + "The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "def some_func():\n", + " # Assume some expensive computation here\n", + " # time.sleep(1000)\n", + " return 5\n", + "\n", + "# So instead of,\n", + "if some_func():\n", + " print(some_func()) # Which is bad practice since computation is happening twice\n", + "\n", + "# or\n", + "a = some_func()\n", + "if a:\n", + " print(a)\n", + "\n", + "# Now you can concisely write\n", + "if a := some_func():\n", + " print(a)\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (> 3.8):**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "5\n", + "5\n", + "5\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "This 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, hence the `SyntaxError` in the `a := \"wtf_walrus\"` statement of the first snippet. Parenthesizing it worked as expected and assigned `a`. \n", + "\n", + "- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. \n", + "\n", + "- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", + "\n", + " - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6')\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> (a := 6, 9) == ((a := 6), 9)\n", + "```\n", + "```py\n", + " True\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> x = (a := 696, 9)\n", + " >>> x\n", + "```\n", + "```py\n", + " (696, 9)\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> x[0] is a # Both reference same memory location\n", + "```\n", + "```py\n", + " True\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Stubborn `del` operation\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "class SomeClass:\n", + " def __del__(self):\n", + " print(\"Deleted!\")\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "1\\.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> x = SomeClass()\n", + ">>> y = x\n", + ">>> del x # this should print \"Deleted!\"\n", + ">>> del y\n", + "```\n", + "```py\n", + "Deleted!\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.\n", + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> x = SomeClass()\n", + ">>> y = x\n", + ">>> del x\n", + ">>> y # check if y exists\n", + "```\n", + "```py\n", + "<__main__.SomeClass instance at 0x7f98a1a67fc8>\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> del y # Like previously, this should print \"Deleted!\"\n", + ">>> globals() # oh, it didn't. Let's check all our global variables and confirm\n", + "```\n", + "```py\n", + "Deleted!\n", + "{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None}\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Okay, now it's deleted :confused:\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ `del x` doesn\u2019t directly call `x.__del__()`.\n", + "+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x\u2019s reference count reaches zero.\n", + "+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.\n", + "+ Calling `globals` caused the existing reference to be destroyed, and hence we can see \"Deleted!\" being printed (finally!).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Wild imports *\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + "# File: module.py\n", + "\n", + "def some_weird_name_func_():\n", + " print(\"works!\")\n", + "\n", + "def _another_weird_name_func():\n", + " print(\"works!\")\n", + "\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> from module import *\n", + ">>> some_weird_name_func_()\n", + "```\n", + "```py\n", + "\"works!\"\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + ">>> _another_weird_name_func()\n", + "```\n", + "```py\n", + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "NameError: name '_another_weird_name_func' is not defined\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime.\n", + "- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> from module import some_weird_name_func_, _another_weird_name_func\n", + " >>> _another_weird_name_func()\n", + "```\n", + "```py\n", + " works!\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " __all__ = ['_another_weird_name_func']\n", + "\n", + " def some_weird_name_func_():\n", + " print(\"works!\")\n", + "\n", + " def _another_weird_name_func():\n", + " print(\"works!\")\n", + "```\n", + "```py\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Output**\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> _another_weird_name_func()\n", + "```\n", + "```py\n", + " \"works!\"\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", + " >>> some_weird_name_func_()\n", + "```\n", + "```py\n", + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " NameError: name 'some_weird_name_func_' is not defined\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Contributing\n", + "\n", + "A few ways in which you can contribute to wtfpython,\n", + "\n", + "- Suggesting new examples\n", + "- Helping with translation (See [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation))\n", + "- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc.\n", + "- Identifying gaps (things like inadequate explanation, redundant examples, etc.)\n", + "- Any creative suggestions to make this project more fun and useful\n", + "\n", + "Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) to discuss things.\n", + "\n", + "PS: Please don't reach out with backlinking requests, no links will be added unless they're highly relevant to the project.\n", + "\n", + "# Acknowledgements\n", + "\n", + "The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by Pythonistas gave it the shape it is in right now.\n", + "\n", + "#### Some nice Links!\n", + "* https://www.youtube.com/watch?v=sH4XF6pKKmk\n", + "* https://www.reddit.com/r/Python/comments/3cu6ej/what_are_some_wtf_things_about_python\n", + "* https://sopython.com/wiki/Common_Gotchas_In_Python\n", + "* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines\n", + "* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python\n", + "* https://www.python.org/doc/humor/\n", + "* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator\n", + "* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65\n", + "* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues\n", + "\n", + "# \ud83c\udf93 License\n", + "\n", + "[![WTFPL 2.0][license-image]][license-url]\n", + "\n", + "© [Satwik Kansal](https://satwikkansal.xyz)\n", + "\n", + "[license-url]: http://www.wtfpl.net\n", + "[license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square\n", + "\n" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 2 +} \ No newline at end of file From bd451754058ef11e1487cbb42018ac39e3396fc7 Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 23 Dec 2019 15:59:59 +0530 Subject: [PATCH 136/221] Point colab notebook to the master --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a8af4d82..c9fe71b5 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ 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].) -Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/3.0/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) +Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) 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. From a39792bd4b4c945c1597fccb557b37cb8d1b4281 Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 23 Dec 2019 16:27:27 +0530 Subject: [PATCH 137/221] Remove kofi link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c9fe71b5..8c3f3f07 100644 --- a/README.md +++ b/README.md @@ -3516,4 +3516,4 @@ If you like wtfpython, you can use these quick links to share it with your frien ## More content like this? If you're interested in more content like this, you can share your email [here](https://satwikkansal.xyz/content-like-wtfpython/). -*PS: On a sidenote, consider [buying me a meal](https://ko-fi.com/satwikkansal) or [planting a tree](https://teamtrees.org/).* +*PS: On a sidenote, consider [planting a tree](https://teamtrees.org/).* From 73a1248d04791ddb2483f04913223bb4cb75fd92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?pu=C9=90lo=C9=B9=20=CA=87=C9=B9=C7=9Dq=C6=83=C7=9D?= =?UTF-8?q?=E1=B4=89s?= Date: Mon, 23 Dec 2019 16:31:44 +0100 Subject: [PATCH 138/221] Fix typo in dictionary section --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8c3f3f07..67f1f117 100644 --- a/README.md +++ b/README.md @@ -515,7 +515,7 @@ What is going on here? > 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. - The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. -- Okay, so why did changing the order affect the lenght 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, +- 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, ```py >>> some_set = set() >>> some_set.add(dictionary) # these are the mapping objects from the snippets above From a1b4f8d521b154a767d656a98e8d7a3565f99719 Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 23 Dec 2019 23:13:08 +0530 Subject: [PATCH 139/221] Put the pdf link back on demand --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 67f1f117..eab7656b 100644 --- a/README.md +++ b/README.md @@ -3513,7 +3513,9 @@ If you like wtfpython, you can use these quick links to share it with your frien [Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&text=If%20you%20really%20think%20you%20know%20Python,%20think%20once%20more!%20Check%20out%20wtfpython&hashtags=python,wtfpython) | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=If%20you%20really%20thing%20you%20know%20Python,%20think%20once%20more!) | [Facebook](https://www.facebook.com/dialog/share?app_id=536779657179021&display=page&href=https%3A%2F%2Fgithub.com%2Fsatwikkansal%2Fwtfpython"e=If%20you%20really%20think%20you%20know%20Python%2C%20think%20once%20more!) -## More content like this? +## Need a pdf version? -If you're interested in more content like this, you can share your email [here](https://satwikkansal.xyz/content-like-wtfpython/). -*PS: On a sidenote, consider [planting a tree](https://teamtrees.org/).* +I've received a few requests for the pdf (and epub) version of wtfpython. You can add your details [here](https://satwikkansal.xyz/wtfpython-pdf/) to get them as soon as they are finished. + + +*PS: On a sidenote, consider donating a dollar to [plant a tree](https://teamtrees.org/).* From dcc2e6a3d86ef27ddac6181626847f7c70662187 Mon Sep 17 00:00:00 2001 From: Satwik Date: Tue, 24 Dec 2019 20:09:12 +0530 Subject: [PATCH 140/221] Update links --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index eab7656b..a59a8b8a 100644 --- a/README.md +++ b/README.md @@ -3464,8 +3464,6 @@ Let's increase the number of iterations by a factor of 10. ``` The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string. -**That's all folks!** - --- --- @@ -3518,4 +3516,5 @@ If you like wtfpython, you can use these quick links to share it with your frien I've received a few requests for the pdf (and epub) version of wtfpython. You can add your details [here](https://satwikkansal.xyz/wtfpython-pdf/) to get them as soon as they are finished. +**That's all folks!** For upcoming content like this, you can add your email [here](https://www.satwikkansal.xyz/content-like-wtfpython/). *PS: On a sidenote, consider donating a dollar to [plant a tree](https://teamtrees.org/).* From 6c0ed6e7c5935fdbc5b23e77bba7cae0dee20fd6 Mon Sep 17 00:00:00 2001 From: Satwik Date: Tue, 24 Dec 2019 21:47:59 +0530 Subject: [PATCH 141/221] Add discussion links --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a59a8b8a..d347e40a 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [ Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) +Discussions: [Hacker News](https://news.ycombinator.com/item?id=21862073) | [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/) + 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. Here's a fun project attempting to explain what exactly is happening under the hood for some counter-intuitive snippets and lesser-known features in Python. From e4f340281cfce44f365f3e81385e067d1ea1f74d Mon Sep 17 00:00:00 2001 From: BoppreH Date: Tue, 24 Dec 2019 14:02:22 -0300 Subject: [PATCH 142/221] Update README.md Fix incorrect output for f-string. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d347e40a..014726b7 100644 --- a/README.md +++ b/README.md @@ -3395,7 +3395,7 @@ Let's increase the number of iterations by a factor of 10. ```py >>> some_string = "wtfpython" >>> f'{some_string=}' - "string='wtfpython'" + "some_string='wtfpython'" ``` * Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!): From 7c85a73442281a979494575d5292d1ce7a9804bf Mon Sep 17 00:00:00 2001 From: Satwik Date: Wed, 25 Dec 2019 00:09:55 +0530 Subject: [PATCH 143/221] Move discussion thread links to the links section --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index d347e40a..2ffd07f5 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,6 @@ Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [ Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) -Discussions: [Hacker News](https://news.ycombinator.com/item?id=21862073) | [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/) - 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. Here's a fun project attempting to explain what exactly is happening under the hood for some counter-intuitive snippets and lesser-known features in Python. @@ -3497,6 +3495,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' * https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator * https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 * https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues +* WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). # 🎓 License From 2f2fcf87bc07ffd94b1ad1aa17062f94853ab73e Mon Sep 17 00:00:00 2001 From: Rahul Gopinath Date: Wed, 25 Dec 2019 10:10:53 +0100 Subject: [PATCH 144/221] Make sure that default_arg is not passed rather than checking for falsity ``` if not default_arg: ... ``` fails when `default_arg` can be assigned and still be false (implementing a `__bool__` or `__len__` etc). You dont want to overwrite the passed values. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index de542efe..f2a825a1 100644 --- a/README.md +++ b/README.md @@ -2173,7 +2173,7 @@ def some_func(default_arg=[]): ```py def some_func(default_arg=None): - if not default_arg: + if default_arg is not None: default_arg = [] default_arg.append("some_string") return default_arg From 9a2718ae3a0d2b70af07eb002077fa60207cf490 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 27 Dec 2019 20:00:59 +0530 Subject: [PATCH 145/221] Fix typo Closes https://github.com/satwikkansal/wtfpython/issues/162 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f2a825a1..7d535275 100644 --- a/README.md +++ b/README.md @@ -259,7 +259,7 @@ This saved one line of code, and implicitly prevented invoking `some_func` twice - As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. -- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, +- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6') From 2c910351b7a71208562cc03b47b4ebe1a3bd60e1 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 27 Dec 2019 20:04:34 +0530 Subject: [PATCH 146/221] Fix relevant typos detected by codespell Closes https://github.com/satwikkansal/wtfpython/issues/161 --- CONTRIBUTING.md | 2 +- README.md | 2 +- irrelevant/notebook_instructions.md | 19 ------------------- irrelevant/obsolete/add_categories | 2 +- irrelevant/wtf.ipynb | 4 ++-- 5 files changed, 5 insertions(+), 24 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e89821db..5085b59e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,7 +29,7 @@ Probably unexpected output ```py Setting up examples for clarification (if necessary) ``` - **Outupt:** + **Output:** ```py >>> trigger # some example that makes it easy to unveil the magic # some justified output diff --git a/README.md b/README.md index 7d535275..8ef9d5d7 100644 --- a/README.md +++ b/README.md @@ -575,7 +575,7 @@ def one_more_func(): # A gotcha! print("Iteration", i) break except ZeroDivisionError as e: - print("Zero division error ocurred", e) + print("Zero division error occurred", e) ``` **Output:** diff --git a/irrelevant/notebook_instructions.md b/irrelevant/notebook_instructions.md index 891698ae..bc267eb3 100644 --- a/irrelevant/notebook_instructions.md +++ b/irrelevant/notebook_instructions.md @@ -5,22 +5,3 @@ - Reorder the examples, so that the ones that work are upfront. - Run the `notebook_generator.py`, it will generate a notebook named `wtf.ipynb` - Revert the README.md changes (optional) - - -# Hosted notebook instructions - -This is just an experimental attempt of browsing wtfpython through jupyter notebooks. Some examples are read-only because, -- they either require a version of Python that's not supported in the hosted runtime. -- or they can't be reproduced in the notebook envrinonment. - -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 - -```py ->>> import sys ->>> sys.version -# Prints out Python version here. -``` - -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! - - diff --git a/irrelevant/obsolete/add_categories b/irrelevant/obsolete/add_categories index 7818b2c3..5eed768d 100644 --- a/irrelevant/obsolete/add_categories +++ b/irrelevant/obsolete/add_categories @@ -139,7 +139,7 @@ f* Half triple-quoted strings f -Implicity key type conversion +Implicit key type conversion f* Stubborn `del` operator diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb index 12c7bb82..de1cba2c 100644 --- a/irrelevant/wtf.ipynb +++ b/irrelevant/wtf.ipynb @@ -1044,7 +1044,7 @@ " \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", "- The reason for this equality is 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 lenght 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" + "- 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" ] }, { @@ -1289,7 +1289,7 @@ " print(\"Iteration\", i)\n", " break\n", " except ZeroDivisionError as e:\n", - " print(\"Zero division error ocurred\", e)\n" + " print(\"Zero division error occurred\", e)\n" ] }, { From f98bd4363ff18e07347350061f7d68102c41cbc8 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 30 Dec 2019 13:05:38 +0530 Subject: [PATCH 147/221] Fix typo Closes https://github.com/satwikkansal/wtfpython/issues/164 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ef9d5d7..5afc1f13 100644 --- a/README.md +++ b/README.md @@ -343,7 +343,7 @@ Makes sense, right? + After being "interned," many variables may reference the same string object in memory (saving memory thereby). + In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation-dependent. There are some rules that can be used to guess if a string will be interned or not: * All length 0 and length 1 strings are interned. - * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) + * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) ![image](/images/string-intern/string_intern.png) + When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). From 1b3b2e6c712e7b101036ef67df1a1ed68dbd503f Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 30 Dec 2019 19:20:31 +0530 Subject: [PATCH 148/221] Fix typo Closes https://github.com/satwikkansal/wtfpython/issues/165 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5afc1f13..c88c8e45 100644 --- a/README.md +++ b/README.md @@ -346,7 +346,7 @@ Makes sense, right? * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) ![image](/images/string-intern/string_intern.png) -+ When `a` and `b` are set to `"wtf!"` 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 `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). ++ When `a` and `b` are set to `"wtf!"` 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 `"wtf!"` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). + A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are two statements in a single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` + The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. + Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). From 185d60c1b696e2029f7e6d641afe272ca466feec Mon Sep 17 00:00:00 2001 From: Satwik Date: Tue, 31 Dec 2019 16:09:41 +0530 Subject: [PATCH 149/221] Update hash brownies explanation and the logical order of few examples. Addresses https://github.com/satwikkansal/wtfpython/pull/76 --- README.md | 374 +++++++++++++++++++++++++++++------------------------- 1 file changed, 198 insertions(+), 176 deletions(-) diff --git a/README.md b/README.md index c88c8e45..d1db60cd 100644 --- a/README.md +++ b/README.md @@ -31,13 +31,14 @@ So, here we go... * [Section: Strain your brain!](#section-strain-your-brain) + [▶ First things first! *](#-first-things-first-) + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) + + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + + [▶ How not to use `is` operator](#-how-not-to-use-is-operator) + [▶ Hash brownies](#-hash-brownies) + [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) + [▶ Disorder within order *](#-disorder-within-order-) + [▶ Keep trying... *](#-keep-trying-) + [▶ For what?](#-for-what) + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - + [▶ How not to use `is` operator](#-how-not-to-use-is-operator) + [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) + [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + [▶ The sticky output function](#-the-sticky-output-function) @@ -68,7 +69,6 @@ So, here we go... + [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) + [▶ Catching the Exceptions](#-catching-the-exceptions) + [▶ Same operands, different story!](#-same-operands-different-story) - + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) + [▶ Needles in a Haystack *](#-needles-in-a-haystack-) + [▶ Splitsies *](#-splitsies-) @@ -353,6 +353,177 @@ Makes sense, right? --- + +### ▶ Be careful with chained operations + +```py +>>> (False == False) in [False] # makes sense +False +>>> False == (False in [False]) # makes sense +False +>>> False == False in [False] # now what? +True + +>>> True is False == False +False +>>> False is False is False +True + +>>> 1 > 0 < 1 +True +>>> (1 > 0) < 1 +False +>>> 1 > (0 < 1) +False +``` + +#### 💡 Explanation: + +As per https://docs.python.org/2/reference/expressions.html#not-in + +> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once. + +While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. + +* `False is False is False` is equivalent to `(False is False) and (False is False)` +* `True is False == False` is equivalent to `True is False and False == False` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. +* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`. +* The expression `(1 > 0) < 1` is equivalent to `True < 1` and + ```py + >>> int(True) + 1 + >>> True + 1 #not relevant for this example, but just for fun + 2 + ``` + So, `1 < 1` evaluates to `False` + +--- + +### ▶ How not to use `is` operator + +The following is a very famous example present all over the internet. + +1\. + +```py +>>> a = 256 +>>> b = 256 +>>> a is b +True + +>>> a = 257 +>>> b = 257 +>>> a is b +False +``` + +2\. + +```py +>>> a = [] +>>> b = [] +>>> a is b +False + +>>> a = tuple() +>>> b = tuple() +>>> a is b +True +``` + +3\. +**Output** + +```py +>>> a, b = 257, 257 +>>> a is b +True +``` + +**Output (Python 3.7.x specifically)** + +```py +>>> a, b = 257, 257 +>> a is b +False +``` + +#### 💡 Explanation: + +**The difference between `is` and `==`** + +* `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). +* `==` operator compares the values of both the operands and checks if they are the same. +* So `is` is for reference equality and `==` is for value equality. An example to clear things up, + ```py + >>> class A: pass + >>> A() is A() # These are two empty objects at two different memory locations. + False + ``` + +**`256` is an existing object but `257` isn't** + +When 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. + +Quoting from https://docs.python.org/3/c-api/long.html +> 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. :-) + +```py +>>> id(256) +10922528 +>>> a = 256 +>>> b = 256 +>>> id(a) +10922528 +>>> id(b) +10922528 +>>> id(257) +140084850247312 +>>> x = 257 +>>> y = 257 +>>> id(x) +140084850247440 +>>> id(y) +140084850247344 +``` + +Here 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. + +Similar 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, + +**Both `a` and `b` refer to the same object when initialized with same value in the same line.** + +**Output** + +```py +>>> a, b = 257, 257 +>>> id(a) +140640774013296 +>>> id(b) +140640774013296 +>>> a = 257 +>>> b = 257 +>>> id(a) +140640774013392 +>>> id(b) +140640774013488 +``` + +* 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. + +* 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, + + ```py + >>> a, b = 257.0, 257.0 + >>> a is b + True + ``` + +* 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://github.com/satwikkansal/wtfpython/issues/100) for updates. + +--- + + ### ▶ Hash brownies 1\. @@ -385,17 +556,37 @@ So, why is Python all over the place? #### 💡 Explanation -* Python dictionaries check for equality and compare the hash value to determine if two keys are the same. -* Immutable objects with the same value always have the same hash in Python. +* 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`): + ```py + >>> 5 == 5.0 == 5 + 0j + True + >>> 5 is not 5.0 is not 5 + 0j + True + >>> some_dict = {} + >>> some_dict[5.0] = "Ruby" + >>> 5.0 in some_dict + True + >>> (5 in some_dict) and (5 + 0j in some_dict) + True + ``` +* 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. + ```py + >>> some_dict + {5.0: 'Ruby'} + >>> some_dict[5] = "Python" + >>> some_dict + {5.0: 'Python'} + ``` +* 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. + +* How did Python found `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://docs.python.org/3/reference/datamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value. ```py >>> 5 == 5.0 == 5 + 0j True >>> hash(5) == hash(5.0) == hash(5 + 0j) True ``` - **Note:** Objects with different values may also have same hash (known as [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science))). -* When the statement `some_dict[5] = "Python"` is executed, the existing value "Ruby" is overwritten with "Python" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`. -* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains the rationale behind it. + **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](https://en.wikipedia.org/wiki/Collision_(computer_science)), and degrades the constant-time performance that hashing usually provides.) --- @@ -729,129 +920,6 @@ array_4 = [400, 500, 600] --- -### ▶ How not to use `is` operator - -The following is a very famous example present all over the internet. - -1\. - -```py ->>> a = 256 ->>> b = 256 ->>> a is b -True - ->>> a = 257 ->>> b = 257 ->>> a is b -False -``` - -2\. - -```py ->>> a = [] ->>> b = [] ->>> a is b -False - ->>> a = tuple() ->>> b = tuple() ->>> a is b -True -``` - -3\. -**Output** - -```py ->>> a, b = 257, 257 ->>> a is b -True -``` - -**Output (Python 3.7.x specifically)** - -```py ->>> a, b = 257, 257 ->> a is b -False -``` - -#### 💡 Explanation: - -**The difference between `is` and `==`** - -* `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). -* `==` operator compares the values of both the operands and checks if they are the same. -* So `is` is for reference equality and `==` is for value equality. An example to clear things up, - ```py - >>> class A: pass - >>> A() is A() # These are two empty objects at two different memory locations. - False - ``` - -**`256` is an existing object but `257` isn't** - -When 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. - -Quoting from https://docs.python.org/3/c-api/long.html -> 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. :-) - -```py ->>> id(256) -10922528 ->>> a = 256 ->>> b = 256 ->>> id(a) -10922528 ->>> id(b) -10922528 ->>> id(257) -140084850247312 ->>> x = 257 ->>> y = 257 ->>> id(x) -140084850247440 ->>> id(y) -140084850247344 -``` - -Here 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. - -Similar 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, - -**Both `a` and `b` refer to the same object when initialized with same value in the same line.** - -**Output** - -```py ->>> a, b = 257, 257 ->>> id(a) -140640774013296 ->>> id(b) -140640774013296 ->>> a = 257 ->>> b = 257 ->>> id(a) -140640774013392 ->>> id(b) -140640774013488 -``` - -* 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. - -* 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, - - ```py - >>> a, b = 257.0, 257.0 - >>> a is b - True - ``` - -* 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://github.com/satwikkansal/wtfpython/issues/100) for updates. - ---- ### ▶ `is not ...` is not `is (not ...)` @@ -2298,52 +2366,6 @@ a += [5, 6, 7, 8] --- - -### ▶ Be careful with chained operations - -```py ->>> (False == False) in [False] # makes sense -False ->>> False == (False in [False]) # makes sense -False ->>> False == False in [False] # now what? -True - ->>> True is False == False -False ->>> False is False is False -True - ->>> 1 > 0 < 1 -True ->>> (1 > 0) < 1 -False ->>> 1 > (0 < 1) -False -``` - -#### 💡 Explanation: - -As per https://docs.python.org/2/reference/expressions.html#not-in - -> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once. - -While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. - -* `False is False is False` is equivalent to `(False is False) and (False is False)` -* `True is False == False` is equivalent to `True is False and False == False` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. -* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`. -* The expression `(1 > 0) < 1` is equivalent to `True < 1` and - ```py - >>> int(True) - 1 - >>> True + 1 #not relevant for this example, but just for fun - 2 - ``` - So, `1 < 1` evaluates to `False` - ---- - ### ▶ Name resolution ignoring class scope 1\. From 3d64252310060daabb53a3bd8dd393b205552966 Mon Sep 17 00:00:00 2001 From: Louis Guitton Date: Sat, 4 Jan 2020 17:16:09 +0100 Subject: [PATCH 150/221] Fix typo in 'Strings can be tricky sometimes' --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d1db60cd..7493d22e 100644 --- a/README.md +++ b/README.md @@ -349,7 +349,7 @@ Makes sense, right? + When `a` and `b` are set to `"wtf!"` 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 `"wtf!"` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). + A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are two statements in a single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` + The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. -+ Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). ++ Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the fourth snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). --- From 68f6e0217c684c52953e6ba482570dabaff76f23 Mon Sep 17 00:00:00 2001 From: Nick Muoh Date: Sat, 4 Jan 2020 19:49:32 -0500 Subject: [PATCH 151/221] Fixed mispelling --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d1db60cd..5874fa4f 100644 --- a/README.md +++ b/README.md @@ -3161,7 +3161,7 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ ```py -# `pip install nump` first. +# `pip install numpy` first. import numpy as np def energy_send(x): From 43679ebd1e501c8834138d19612139326fafa4fd Mon Sep 17 00:00:00 2001 From: Chris Guo Date: Wed, 8 Jan 2020 00:09:25 +0800 Subject: [PATCH 152/221] fix: fix example input error --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c130f296..43ebdfae 100644 --- a/README.md +++ b/README.md @@ -3097,11 +3097,12 @@ class A(object): **Output:** ```py +>>> A().__variable Traceback (most recent call last): File "", line 1, in AttributeError: 'A' object has no attribute '__variable' ->>> >>> A().some_func() +>>> A().some_func() 'Some value' ``` From d1a414414334f4ffe555bdf361155356dca5df7f Mon Sep 17 00:00:00 2001 From: Kerollos Magdy Date: Thu, 9 Jan 2020 13:12:14 +0200 Subject: [PATCH 153/221] Fix issue creating link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 43ebdfae..db1fe37f 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ A nice way to get the most out of these examples, in my opinion, is to read them - Read the output snippets and, + Check if the outputs are the same as you'd expect. + Make sure if you know the exact reason behind the output being the way it is. - - 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)). + - 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/issues/new)). - If yes, give a gentle pat on your back, and you may skip to the next example. PS: You can also read WTFPython at the command line using the [pypi package](https://pypi.python.org/pypi/wtfpython), From 30a6623ccd2476196415bf0016eb96f46413268e Mon Sep 17 00:00:00 2001 From: Arthur Pastel Date: Fri, 10 Jan 2020 12:43:16 +0100 Subject: [PATCH 154/221] Wild imports typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db1fe37f..2c36d3f3 100644 --- a/README.md +++ b/README.md @@ -2651,7 +2651,7 @@ NameError: name '_another_weird_name_func' is not defined #### 💡 Explanation: -- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime. +- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore don't get imported. This may lead to errors during runtime. - Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred. ```py >>> from module import some_weird_name_func_, _another_weird_name_func From 5f8067df42e41aaf3ab7c77742e8193a0a62cc2f Mon Sep 17 00:00:00 2001 From: Antoine Rozo Date: Fri, 10 Jan 2020 14:39:29 +0100 Subject: [PATCH 155/221] Fix explanation for 6th example of "Needles in a Haystack" --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db1fe37f..d3c8bde1 100644 --- a/README.md +++ b/README.md @@ -2579,7 +2579,7 @@ def similar_recursive_func(a): * As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). -* Last one should be fairly obvious, passing mutable object (like `list` ) results in a call by reference, whereas an immutable object (like `int`) results in a call by value. +* Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignation of an immutable (`a -= 1`) is not an alteration of the value. * Being aware of these nitpicks can save you hours of debugging effort in the long run. From 00a1228ca39155f27271bbde1feb18b6f9b71ad9 Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 10:04:41 -0500 Subject: [PATCH 156/221] Fix spelling (found -> find) Noticed a minor spelling error while reading through this fantastic document. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..4fae417b 100644 --- a/README.md +++ b/README.md @@ -579,7 +579,7 @@ So, why is Python all over the place? ``` * 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. -* How did Python found `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://docs.python.org/3/reference/datamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value. +* 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://docs.python.org/3/reference/datamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value. ```py >>> 5 == 5.0 == 5 + 0j True From f20be4cfc437475ece4aa745557cb73a54f94a7c Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 10:13:50 -0500 Subject: [PATCH 157/221] Extend the explanation of the "is not ..." section I thought that the explanation for "'something' is (not None)" could be a little more explicit. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..60cead49 100644 --- a/README.md +++ b/README.md @@ -933,7 +933,7 @@ False #### 💡 Explanation - `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. -- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. +- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. In this expression, `(not None)` evaluates to `True`, since `None` is is `False` in a boolean context, so the expression becomes `'something' is True`. --- From 8370f3a3b93432c69746544d3546177f888e050c Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 10:16:47 -0500 Subject: [PATCH 158/221] A minor grammar correction --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..c6220b78 100644 --- a/README.md +++ b/README.md @@ -1023,7 +1023,7 @@ Even when the values of `x` were different in every iteration prior to appending - When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation. -- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope. +- 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 again within the function's scope. ```py funcs = [] From 3e99005ae431ff6dc470c58c90258e371e72230e Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 10:19:17 -0500 Subject: [PATCH 159/221] Clarify for quoting examples The example of the use of backslash to escape a double-quote makes more sense when used inside a double-quoted string. If the string is quoted with single quotes, one could of course just write 'wt"f' withouth requiring any escaping. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..0f1b3bc1 100644 --- a/README.md +++ b/README.md @@ -1210,7 +1210,7 @@ True - 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). ```py - >>> 'wt\"f' + >>> "wt\"f" 'wt"f' ``` - 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. From 16c90f9b2429b3182df44d399339c7d3c540be3e Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 12:03:30 -0500 Subject: [PATCH 160/221] Fixed logic error in "Beware of default mutable arguments!" The example showing how using None as a default argument is used instead of a mutable default argument had reversed logic. It would set default_arg to [] whenever the caller passed a non-None argument. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..f08baa3e 100644 --- a/README.md +++ b/README.md @@ -2241,7 +2241,7 @@ def some_func(default_arg=[]): ```py def some_func(default_arg=None): - if default_arg is not None: + if default_arg is None: default_arg = [] default_arg.append("some_string") return default_arg From 6cebc952c3116d49eced5e41444647b63b214919 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 20 Jan 2020 14:23:20 +0530 Subject: [PATCH 161/221] Fix minor typo in the "is not" example --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index eff94035..ab26e5a0 100644 --- a/README.md +++ b/README.md @@ -933,7 +933,8 @@ False #### 💡 Explanation - `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. -- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. In this expression, `(not None)` evaluates to `True`, since `None` is is `False` in a boolean context, so the expression becomes `'something' is True`. +- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. +- 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`. --- From 50265e91fcf50d00710b91e7e413c76533ab8893 Mon Sep 17 00:00:00 2001 From: Haksell Date: Sat, 15 Feb 2020 09:03:08 +0100 Subject: [PATCH 162/221] Correct six typos --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index ab26e5a0..b037a984 100644 --- a/README.md +++ b/README.md @@ -673,7 +673,7 @@ class OrderedDictWithHash(OrderedDict): True >>> dictionary == another_ordered_dict # and b == c True ->>> ordered_dict == another_ordered_dict # the why isn't c == a ?? +>>> ordered_dict == another_ordered_dict # then why isn't c == a ?? False # We all know that a set consists of only unique elements, @@ -705,7 +705,7 @@ What is going on here? - 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://docs.python.org/3/library/collections.html#ordereddict-objects) > 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. -- The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. +- The reason for this equality in behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. - 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, ```py >>> some_set = set() @@ -840,7 +840,7 @@ for i, some_dict[i] in enumerate(some_string): **💡 Explanation:** - - 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)` this case) is unpacked and assigned the target list variables (`i` in this case). + - 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). * 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: ```py @@ -2113,7 +2113,7 @@ Where did element `3` go from the `numbers` list? result.append(elem) yield tuple(result) ``` -- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. +- So the function takes in arbitrary number of utterable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. - The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`. - The correct way to do the above using `zip` would be, ```py @@ -2575,7 +2575,7 @@ def similar_recursive_func(a): >>> assert a == b, "Values are not equal" Traceback (most recent call last): File "", line 1, in - AssertionError: Values aren not equal + AssertionError: Values are not equal ``` * As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). @@ -3446,7 +3446,7 @@ Let's increase the number of iterations by a factor of 10. time.sleep(3) ``` - This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument. + This will print the `wtfpython` after 3 seconds due to the `end` argument because the output buffer is flushed either after encountering `\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument. * List slicing with out of the bounds indices throws no errors ```py From a4af8a4e0c8f92d197dbddd7bcaec674f7c6ed59 Mon Sep 17 00:00:00 2001 From: Haksell Date: Sat, 15 Feb 2020 09:04:24 +0100 Subject: [PATCH 163/221] Correct six typos --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b037a984..9de76511 100644 --- a/README.md +++ b/README.md @@ -2113,7 +2113,7 @@ Where did element `3` go from the `numbers` list? result.append(elem) yield tuple(result) ``` -- So the function takes in arbitrary number of utterable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. +- So the function takes in arbitrary number of iterable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. - The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`. - The correct way to do the above using `zip` would be, ```py From 184df9f99dcaae4c55db1cf0cf048a7d2e74f51c Mon Sep 17 00:00:00 2001 From: Pradhvan Date: Sat, 15 Feb 2020 14:30:05 +0530 Subject: [PATCH 164/221] README.md: Update Python version in 'Modifying a dictionary while iterating over it' example --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ab26e5a0..27bbce77 100644 --- a/README.md +++ b/README.md @@ -1930,7 +1930,7 @@ Yes, it runs for exactly **eight** times and stops. * It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. * How deleted keys are handled and when the resize occurs might be different for different Python implementations. * So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. -* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. +* Python 3.7.6 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. --- From 78cb5f39f5b2689386b0fa18340a3e8690bf32e2 Mon Sep 17 00:00:00 2001 From: myrmica-habilis Date: Fri, 20 Mar 2020 11:00:29 +0100 Subject: [PATCH 165/221] Update README.md - assignment expressions are evaluated and printed by the REPL --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2702a661..cd9baec6 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ File "", line 1 SyntaxError: invalid syntax >>> (a := "wtf_walrus") # This works though +'wtf_walrus' >>> a 'wtf_walrus' ``` @@ -195,6 +196,7 @@ SyntaxError: invalid syntax (6, 9) >>> (a := 6, 9) +(6, 9) >>> a 6 From 67f743eddd8cbc5e55bda08d604c938ee92a3c42 Mon Sep 17 00:00:00 2001 From: Yonatan Goldschmidt Date: Tue, 24 Mar 2020 22:22:34 +0200 Subject: [PATCH 166/221] Correctify explanation of Stubborn `del` operation --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2702a661..4d76ec23 100644 --- a/README.md +++ b/README.md @@ -1954,7 +1954,7 @@ class SomeClass: Deleted! ``` -Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example. +Phew, deleted at last. You might have guessed what saved `__del__` from being called in our first attempt to delete `x`. Let's add more twists to the example. 2\. ```py @@ -1973,9 +1973,9 @@ Okay, now it's deleted :confused: #### 💡 Explanation: + `del x` doesn’t directly call `x.__del__()`. -+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero. -+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered. -+ Calling `globals` caused the existing reference to be destroyed, and hence we can see "Deleted!" being printed (finally!). ++ When `del x` is encountered, Python deletes the name `x` from current scope and decrements by 1 the reference count of the object `x` referenced. `__del__()` is called only when the object's reference count reaches zero. ++ In the second output snippet, `__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object (specifically, the `_` magic variable which references the result value of the last non `None` expression on the REPL), thus preventing the reference count from reaching zero when `del y` was encountered. ++ Calling `globals` (or really, executing anything that will have a non `None` result) caused `_` to reference the new result, dropping the existing reference. Now the reference count reached 0 and we can see "Deleted!" being printed (finally!). --- From f735fe31163ebe72c7d95468a5ca6496fed5944f Mon Sep 17 00:00:00 2001 From: "zenglifa@msu.edu" Date: Sat, 25 Apr 2020 15:37:50 -0400 Subject: [PATCH 167/221] Replace http link with https --- wtfpython-pypi/content.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wtfpython-pypi/content.md b/wtfpython-pypi/content.md index 9827fc46..0d246693 100644 --- a/wtfpython-pypi/content.md +++ b/wtfpython-pypi/content.md @@ -1732,7 +1732,7 @@ UnboundLocalError: local variable 'a' referenced before assignment #### 💡 Explanation: * When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope which throws an error. -* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. +* Read [this](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. * To modify the outer scope variable `a` in `another_func`, use `global` keyword. ```py def another_func() From 9ff40de544eb50d68f2e9d6ce9059315d5a6a7f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joachim=20Stro=CC=88mbergson?= Date: Sat, 2 May 2020 08:54:24 +0200 Subject: [PATCH 168/221] 'less than 21' is the correct expression. Could slso be 'less or equal to 20'. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d76ec23..12b4274b 100644 --- a/README.md +++ b/README.md @@ -348,7 +348,7 @@ Makes sense, right? ![image](/images/string-intern/string_intern.png) + When `a` and `b` are set to `"wtf!"` 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 `"wtf!"` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). + A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are two statements in a single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` -+ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. ++ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 21. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. + Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the fourth snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). --- From 32f14a7e16d0e28e47762e319794663c9e28c1b3 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sun, 14 Jun 2020 10:40:30 +0530 Subject: [PATCH 169/221] Add Vietnamese translation Closes https://github.com/satwikkansal/wtfpython/issues/195 --- CONTRIBUTORS.md | 9 +++++++++ README.md | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 313c024f..fe779bb5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -22,6 +22,15 @@ Following are the wonderful people (in no specific order) who have contributed t | koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) | | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) | +--- + +**Translations** + +| Translator | Github | Language | +|-------------|--------|--------| +| leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [Chinese](https://github.com/leisurelicht/wtfpython-cn) | +| vuduclyunitn | [vuduclyunitn](https://github.com/vuduclyunitn) | [Vietnamese](https://github.com/vuduclyunitn/wtfptyhon-vi) | + Thank you all for your time and making wtfpython more awesome! :smile: diff --git a/README.md b/README.md index 77387cec..6a6c77c0 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-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].) +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [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].) Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From 3ba87fea65fcfa3ff6330ddca3f40e3e9937ff4e Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 15 Jun 2020 16:03:06 +0530 Subject: [PATCH 170/221] Add link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6a6c77c0..b1e27ce4 100644 --- a/README.md +++ b/README.md @@ -3544,4 +3544,4 @@ I've received a few requests for the pdf (and epub) version of wtfpython. You ca **That's all folks!** For upcoming content like this, you can add your email [here](https://www.satwikkansal.xyz/content-like-wtfpython/). -*PS: On a sidenote, consider donating a dollar to [plant a tree](https://teamtrees.org/).* +*PS: Take help from developers like me on Codementor (for free 10$ credits, you can use [this link](https://www.codementor.io/?partner=satwikkansal)).* From 7457ffb8483eaf40dbb7ec743c31690d179d12ca Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Thu, 25 Jun 2020 16:28:58 +0530 Subject: [PATCH 171/221] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b1e27ce4..0a1009ae 100644 --- a/README.md +++ b/README.md @@ -3544,4 +3544,5 @@ I've received a few requests for the pdf (and epub) version of wtfpython. You ca **That's all folks!** For upcoming content like this, you can add your email [here](https://www.satwikkansal.xyz/content-like-wtfpython/). -*PS: Take help from developers like me on Codementor (for free 10$ credits, you can use [this link](https://www.codementor.io/?partner=satwikkansal)).* + +*PS: For consulting, you can reach out to me via Codementor (use [this link](https://www.codementor.io/satwikkansal?partner=satwikkansal) for free 10$ credits).* From 0b74f9ba5d31c4748ce7fefa237e9649f37fd325 Mon Sep 17 00:00:00 2001 From: Yonatan Goldschmidt Date: Sat, 4 Jul 2020 18:36:27 +0300 Subject: [PATCH 172/221] Add "dict lookup performance" section Closes: #208 --- README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/README.md b/README.md index 0a1009ae..c92935d2 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,7 @@ So, here we go... * [Section: Miscellaneous](#section-miscellaneous) + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + + [▶ `dict` lookup performance](#-dict-lookup-performance) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -3348,6 +3349,37 @@ Let's increase the number of iterations by a factor of 10. --- +### ▶ `dict` lookup performance + +```py +>>> some_dict = {str(i): 1 for i in range(1_000_000)} +>>> %timeit some_dict['5'] +28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +>>> some_dict[1] = 1 +>>> %timeit some_dict['5'] +37.2 ns ± 0.265 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +# why did it become much slower? +``` + +#### 💡 Explanation: ++ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys. ++ The specialized function (named `lookdict_unicode` in CPython's sources) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method. ++ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function. ++ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary - attempting a failed lookup has the same effect: +```py +>>> some_dict = {str(i): 1 for i in range(1_000_000)} +>>> %timeit some_dict['5'] +28.5 ns ± 0.142 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +>>> some_dict[1] +Traceback (most recent call last): + File "", line 1, in +KeyError: 1 +>>> %timeit some_dict['5'] +38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +``` + +--- + ### ▶ Minor Ones * * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) From f97cbdd9193f6e40aded532994339f0e4c5d56df Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 10 Jul 2020 22:28:44 +0530 Subject: [PATCH 173/221] Minor updates to slowinig down dict lookups example --- README.md | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index c92935d2..95fad37d 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ So, here we go... * [Section: Miscellaneous](#section-miscellaneous) + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ `dict` lookup performance](#-dict-lookup-performance) + + [▶ `dict` lookup performance](#-slowing-down-dict-lookups) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -3349,36 +3349,38 @@ Let's increase the number of iterations by a factor of 10. --- -### ▶ `dict` lookup performance +### ▶ Slowing down `dict` lookups ```py ->>> some_dict = {str(i): 1 for i in range(1_000_000)} +some_dict = {str(i): 1 for i in range(1_000_000)} +another_dict = {str(i): 1 for i in range(1_000_000)} +``` + +**Output:** +```py >>> %timeit some_dict['5'] 28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) >>> some_dict[1] = 1 >>> %timeit some_dict['5'] 37.2 ns ± 0.265 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) -# why did it become much slower? -``` -#### 💡 Explanation: -+ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys. -+ The specialized function (named `lookdict_unicode` in CPython's sources) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method. -+ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function. -+ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary - attempting a failed lookup has the same effect: -```py ->>> some_dict = {str(i): 1 for i in range(1_000_000)} ->>> %timeit some_dict['5'] +>>> %timeit another_dict['5'] 28.5 ns ± 0.142 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) ->>> some_dict[1] +>>> another_dict[1] # Trying to access a key that doesn't exist Traceback (most recent call last): File "", line 1, in KeyError: 1 ->>> %timeit some_dict['5'] +>>> %timeit another_dict['5'] 38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) ``` +Why are same lookups becoming slower? + +#### 💡 Explanation: ++ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys. ++ The specialized function (named `lookdict_unicode` in CPython's [source](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method. ++ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function. ++ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary. That's why attempting a failed lookup has the same effect. ---- ### ▶ Minor Ones * From ee70d52fe47745ed6b0d21ef2e3011fd198b15d3 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 10 Jul 2020 22:30:30 +0530 Subject: [PATCH 174/221] Add Jongy to the contributors list --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fe779bb5..5a20cfc0 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -21,7 +21,7 @@ Following are the wonderful people (in no specific order) who have contributed t | Ghost account | N/A | [#96](https://github.com/satwikkansal/wtfpython/issues/96) | koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) | | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) | - +| Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208) | --- **Translations** From f72d7325fa512219c9a8ff9b69a6a7128bf3685f Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 10 Jul 2020 22:34:22 +0530 Subject: [PATCH 175/221] Fix uuid and toc --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 95fad37d..6b74228b 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ So, here we go... * [Section: Miscellaneous](#section-miscellaneous) + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ `dict` lookup performance](#-slowing-down-dict-lookups) + + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -3349,8 +3349,8 @@ Let's increase the number of iterations by a factor of 10. --- -### ▶ Slowing down `dict` lookups - +### ▶ Slowing down `dict` lookups * + ```py some_dict = {str(i): 1 for i in range(1_000_000)} another_dict = {str(i): 1 for i in range(1_000_000)} From ee0696b676298dd70ce944626ff2e4819d70d4d2 Mon Sep 17 00:00:00 2001 From: Yonatan Goldschmidt Date: Fri, 31 Jul 2020 12:05:04 +0300 Subject: [PATCH 176/221] Add "bloating instance dicts" section Closes: #210 --- CONTRIBUTORS.md | 2 +- README.md | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 5a20cfc0..0ae584ed 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -21,7 +21,7 @@ Following are the wonderful people (in no specific order) who have contributed t | Ghost account | N/A | [#96](https://github.com/satwikkansal/wtfpython/issues/96) | koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) | | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) | -| Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208) | +| Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208), [#210](https://github.com/satwikkansal/wtfpython/issues/210) | --- **Translations** diff --git a/README.md b/README.md index 6b74228b..40f065cd 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ So, here we go... + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups) + + [▶ Bloating instance `dict`s *](#-bloating-instance-dicts-) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -3382,6 +3383,68 @@ Why are same lookups becoming slower? + This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary. That's why attempting a failed lookup has the same effect. +### ▶ Bloating instance `dict`s * + +```py +import sys + +class SomeClass: + def __init__(self): + self.some_attr1 = 1 + self.some_attr2 = 2 + self.some_attr3 = 3 + self.some_attr4 = 4 + + +def dict_size(o): + return sys.getsizeof(o.__dict__) + +``` + +**Output:** (Python 3.8, other Python 3 versions may vary a little) +```py +>>> o1 = SomeClass() +>>> o2 = SomeClass() +>>> dict_size(o1) +104 +>>> dict_size(o2) +104 +>>> del o1.some_attr1 +>>> o3 = SomeClass() +>>> dict_size(o3) +232 +>>> dict_size(o1) +232 +``` + +Let's try again... In a new interpreter: + +```py +>>> o1 = SomeClass() +>>> o2 = SomeClass() +>>> dict_size(o1) +104 # as expected +>>> o1.some_attr5 = 5 +>>> o1.some_attr6 = 6 +>>> dict_size(o1) +360 +>>> dict_size(o2) +272 +>>> o3 = SomeClass() +>>> dict_size(o3) +232 +``` + +What makes those dictionaries become bloated? And why are newly created objects bloated as well? + +#### 💡 Explanation: ++ CPython is able to reuse the same "keys" object in multiple dictionaries. This was added in [PEP 412](https://www.python.org/dev/peps/pep-0412/) with the motivation to reduce memory usage, specifically in dictionaries of instances - where keys (instance attributes) tend to be common to all instances. ++ This optimization is entirely seamless for instance dictionaries, but it is disabled if certain assumptions are broken. ++ Key-sharing dictionaries do not support deletion; if an instance attribute is deleted, the dictionary is "unshared", and key-sharing is disabled for all future instances of the same class. ++ Additionaly, if the dictionary keys have be resized (because new keys are inserted), they are kept shared *only* if they are used by a exactly single dictionary (this allows adding many attributes in the `__init__` of the very first created instance, without causing an "unshare"). If multiple instances exist when a resize happens, key-sharing is disabled for all future instances of the same class: CPython can't tell if your instances are using the same set of attributes anymore, and decides to bail out on attempting to share their keys. ++ A small tip, if you aim to lower your program's memory footprint: don't delete instance attributes, and make sure to initialize all attributes in your `__init__`! + + ### ▶ Minor Ones * * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) From 87906b9b2f5666d2ccd67a46b0b522d8ca4d6ffe Mon Sep 17 00:00:00 2001 From: Yonatan Goldschmidt Date: Fri, 31 Jul 2020 12:05:08 +0300 Subject: [PATCH 177/221] Fix anchor name of "slowing down dict lookups" --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 40f065cd..00859a05 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ So, here we go... * [Section: Miscellaneous](#section-miscellaneous) + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups) + + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups-) + [▶ Bloating instance `dict`s *](#-bloating-instance-dicts-) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) From a3baf043bde359d029c719b3b729dade0f18858a Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 24 Aug 2020 20:10:59 +0530 Subject: [PATCH 178/221] Add a note about the asterisks Fixes https://github.com/satwikkansal/wtfpython/issues/219 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 00859a05..b2f05d8b 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ While some of the examples you see below may not be WTFs in the truest sense, bu 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: -PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). +PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) (the examples marked with asterisk are the ones added in the latest major revision). So, here we go... From 7d06e7b5c1cde321c166521e72bca5c37db05818 Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 27 Aug 2020 00:47:08 +0530 Subject: [PATCH 179/221] Add a meme --- images/expanding-brain-meme.jpg | Bin 0 -> 115494 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 images/expanding-brain-meme.jpg diff --git a/images/expanding-brain-meme.jpg b/images/expanding-brain-meme.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9437c2f9c3308f07b1b662d4fe9fc774b83b938e GIT binary patch literal 115494 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

Hcb<6fOC!;)a??oD?u8Ab#&XQFuTEoeOMLd@f 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Ν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

Nrzm20 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%0Dur`(yzifiP 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 Date: Thu, 17 Sep 2020 03:38:41 +0300 Subject: [PATCH 180/221] Add link to Python FAQ to "Mutating the immutable" --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b2f05d8b..9f30a419 100644 --- a/README.md +++ b/README.md @@ -1701,6 +1701,7 @@ But I thought tuples were immutable... 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.) * `+=` 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. +* There's also an explanation in [official Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works). --- From 27b66b4f317f7bc30a65cc84b8e6de2cb99acb7c Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Thu, 17 Sep 2020 17:02:56 +0530 Subject: [PATCH 181/221] Fix typo and minor changes --- CONTRIBUTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5085b59e..27b19618 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,6 +40,6 @@ Probably unexpected output Few things that you can consider while writing an example, -- Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's strictly enforced scheme in the project, but you can take a glance at other examples to get a gist. +- Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's no strictly enforced scheme in the project as such, but you can take a glance at other examples to get a gist. - Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write. -- Also, please don't forget to add your name to the [contributors list](/CONTRIBUTING.md). +- Also, feel free to add your name to the [contributors list](/CONTRIBUTING.md). From 9e28e00123ae2e467641a10c3d3cd4a3c2f5b6d8 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Thu, 1 Oct 2020 16:56:40 +0530 Subject: [PATCH 182/221] Update CONTRIBUTING.md --- CONTRIBUTING.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 27b19618..962a2f9d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,12 +1,8 @@ -All kinds of patches are welcome. Feel free to even suggest some catchy and funny titles for the existing Examples. The goal is to make this collection as interesting to read as possible. +All kinds of patches are welcome. Feel free to even suggest some catchy and funny titles for the existing Examples. The goal is to make this collection as interesting to read as possible. Here are a few ways through which you can contribute, -If you are interested in translating the project to another language (some people have done that in the past), please feel free to open up an issue, and let me know if you need any kind of help. - -If the changes you suggest are significant, filing an issue before submitting the actual patch will be appreciated. If you'd like to work on the issue (highly encouraged), you can mention that you're interested in working on it while creating the issue and get assigned to it. - -If you're adding a new example, please do create an issue to discuss it before submitting a patch. - -You can use the following template for adding a new example: +- If you are interested in translating the project to another language (some people have done that in the past), please feel free to open up an issue, and let me know if you need any kind of help. +- If the changes you suggest are significant, filing an issue before submitting the actual patch will be appreciated. If you'd like to work on the issue (highly encouraged), you can mention that you're interested in working on it while creating the issue and get assigned to it. +- If you're adding a new example, it is highly recommended to create an issue to discuss it before submitting a patch. You can use the following template for adding a new example:
 ### ▶ Some fancy Title *
@@ -40,6 +36,8 @@ Probably unexpected output
 
 Few things that you can consider while writing an example, 
 
+- If you are choosing to submit a new example without creating an issue and discussing, please check the project to make sure there aren't similar examples already.
 - Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's no strictly enforced scheme in the project as such, but you can take a glance at other examples to get a gist.
 - Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write.
 - Also, feel free to add your name to the [contributors list](/CONTRIBUTING.md).
+

From d4ad5a06436fb0cf7b9c307cf9ac9e745e58092f Mon Sep 17 00:00:00 2001
From: AmitShinde <68842692+amitShindeGit@users.noreply.github.com>
Date: Thu, 1 Oct 2020 19:41:25 +0530
Subject: [PATCH 183/221] Update README.md

---
 README.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/README.md b/README.md
index 9f30a419..5ad8af70 100644
--- a/README.md
+++ b/README.md
@@ -1228,7 +1228,7 @@ True
     >>> print("\n")
 
     >>> print(r"\\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.
 

From 7525e800b81115cd72e182702637e3f0b932cd99 Mon Sep 17 00:00:00 2001
From: Diptangsu Goswami 
Date: Mon, 5 Oct 2020 20:35:20 +0530
Subject: [PATCH 184/221] #193 The out of scope variable, nonlocal (#228)

* fixed link to CONTRIBUTORS.md

* The out of scope variable, nonlocal, #193

* added myself to CONTRIBUTORS.md :D

* Update CONTRIBUTORS.md

* added entry in index

* merged nonlocal to `the out of scope variable` example

Also removed the extra entry from the main index.
---
 CONTRIBUTING.md |  3 +--
 CONTRIBUTORS.md |  2 ++
 README.md       | 44 +++++++++++++++++++++++++++++++++++++++++---
 3 files changed, 44 insertions(+), 5 deletions(-)

diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 962a2f9d..f774370a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -39,5 +39,4 @@ Few things that you can consider while writing an example,
 - If you are choosing to submit a new example without creating an issue and discussing, please check the project to make sure there aren't similar examples already.
 - Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's no strictly enforced scheme in the project as such, but you can take a glance at other examples to get a gist.
 - Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write.
-- Also, feel free to add your name to the [contributors list](/CONTRIBUTING.md).
-
+- Also, feel free to add your name to the [contributors list](/CONTRIBUTORS.md).
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 0ae584ed..9dd1d2b9 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -22,6 +22,8 @@ Following are the wonderful people (in no specific order) who have contributed t
 | koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) |
 | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) |
 | Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208), [#210](https://github.com/satwikkansal/wtfpython/issues/210) |
+| Diptangsu Goswami | [diptangsu](https://github.com/diptangsu) | [#193](https://github.com/satwikkansal/wtfpython/issues/193) |
+
 ---
 
 **Translations**
diff --git a/README.md b/README.md
index 5ad8af70..a451e943 100644
--- a/README.md
+++ b/README.md
@@ -1028,7 +1028,8 @@ Even when the values of `x` were different in every iteration prior to appending
 
 - When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.
 
-- 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 again within the function's scope.
+- 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 
+within the function's scope.
 
     ```py
     funcs = []
@@ -1994,6 +1995,20 @@ def some_func():
 def another_func():
     a += 1
     return a
+
+
+def some_closure_func():
+    a = 1
+    def some_inner_func():
+        return a
+    return some_inner_func()
+
+def another_closure_func():
+    a = 1
+    def another_inner_func():
+        a += 1
+        return a
+    return another_inner_func()
 ```
 
 **Output:**
@@ -2002,11 +2017,15 @@ def another_func():
 1
 >>> another_func()
 UnboundLocalError: local variable 'a' referenced before assignment
+
+>>> some_closure_func()
+1
+>>> another_closure_func()
+UnboundLocalError: local variable 'a' referenced before assignment
 ```
 
 #### 💡 Explanation:
-* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`,  but it has not been initialized previously in the same scope, which throws an error.
-* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.
+* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.
 * To modify the outer scope variable `a` in `another_func`, use `global` keyword.
   ```py
   def another_func()
@@ -2020,6 +2039,25 @@ UnboundLocalError: local variable 'a' referenced before assignment
   >>> another_func()
   2
   ```
+* In `another_closure_func`, `a` becomes local to the scope of `another_inner_func`, but it has not been initialized previously in the same scope, which is why it throws an error.
+* To modify the outer scope variable `a` in `another_inner_func`, use the `nonlocal` keyword.
+  ```py
+  def another_func():
+      a = 1
+      def another_inner_func():
+          nonlocal a
+          a += 1
+          return a
+      return another_inner_func()
+  ```
+
+  **Output:**
+  ```py
+  >>> another_func()
+  2
+  ```
+* The keywords `global` and `nonlocal` are ways to simply tell the python interpreter to not delcare new variables, but to just look them up from the corresponding scope.
+* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.
 
 ---
 

From 33bcfa744a4f24eb59702b1c4191365bdaa25676 Mon Sep 17 00:00:00 2001
From: Satwik Kansal 
Date: Mon, 5 Oct 2020 20:42:16 +0530
Subject: [PATCH 185/221] Minor changes to nonlocal explanation

Closes https://github.com/satwikkansal/wtfpython/issues/193
---
 README.md | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/README.md b/README.md
index a451e943..9f53516d 100644
--- a/README.md
+++ b/README.md
@@ -1987,6 +1987,8 @@ Okay, now it's deleted :confused:
 
 ### ▶ The out of scope variable
 
+
+1\.
 ```py
 a = 1
 def some_func():
@@ -1995,8 +1997,10 @@ def some_func():
 def another_func():
     a += 1
     return a
+```
 
-
+2\.
+```py
 def some_closure_func():
     a = 1
     def some_inner_func():
@@ -2026,7 +2030,7 @@ UnboundLocalError: local variable 'a' referenced before assignment
 
 #### 💡 Explanation:
 * When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.
-* To modify the outer scope variable `a` in `another_func`, use `global` keyword.
+* To modify the outer scope variable `a` in `another_func`, we have to use the `global` keyword.
   ```py
   def another_func()
       global a
@@ -2039,8 +2043,8 @@ UnboundLocalError: local variable 'a' referenced before assignment
   >>> another_func()
   2
   ```
-* In `another_closure_func`, `a` becomes local to the scope of `another_inner_func`, but it has not been initialized previously in the same scope, which is why it throws an error.
-* To modify the outer scope variable `a` in `another_inner_func`, use the `nonlocal` keyword.
+* In `another_closure_func`, `a` becomes local to the scope of `another_inner_func`, but it has not been initialized previously in the same scope, which is why it throws an error. 
+* To modify the outer scope variable `a` in `another_inner_func`, use the `nonlocal` keyword. The nonlocal statement is used to refer to variables defined in the nearest outer (excluding the global) scope.
   ```py
   def another_func():
       a = 1
@@ -2056,7 +2060,7 @@ UnboundLocalError: local variable 'a' referenced before assignment
   >>> another_func()
   2
   ```
-* The keywords `global` and `nonlocal` are ways to simply tell the python interpreter to not delcare new variables, but to just look them up from the corresponding scope.
+* The keywords `global` and `nonlocal` tell the python interpreter to not delcare new variables and look them up in the corresponding outer scopes.
 * Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.
 
 ---

From f082e9f22abe5e70bcaf69c1597b723027139597 Mon Sep 17 00:00:00 2001
From: Satwik Kansal 
Date: Sat, 24 Oct 2020 21:57:35 +0530
Subject: [PATCH 186/221] Update README.md

---
 README.md | 2 --
 1 file changed, 2 deletions(-)

diff --git a/README.md b/README.md
index 9f53516d..ecf56236 100644
--- a/README.md
+++ b/README.md
@@ -3684,5 +3684,3 @@ I've received a few requests for the pdf (and epub) version of wtfpython. You ca
 
 
 **That's all folks!** For upcoming content like this, you can add your email [here](https://www.satwikkansal.xyz/content-like-wtfpython/).
-
-*PS: For consulting, you can reach out to me via Codementor (use [this link](https://www.codementor.io/satwikkansal?partner=satwikkansal) for free 10$ credits).*

From 435fd5f49e396a48ee25385edbb0744dfaf68480 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E8=B0=AD=E4=B9=9D=E9=BC=8E?= <109224573@qq.com>
Date: Tue, 27 Oct 2020 11:07:47 +0800
Subject: [PATCH 187/221] Change Py2 docs to 3

---
 README.md | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)

diff --git a/README.md b/README.md
index ecf56236..a2861ee8 100644
--- a/README.md
+++ b/README.md
@@ -383,7 +383,7 @@ False
 
 #### 💡 Explanation:
 
-As per https://docs.python.org/2/reference/expressions.html#not-in
+As per https://docs.python.org/3/reference/expressions.html#membership-test-operations
 
 > Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
 
@@ -1280,7 +1280,7 @@ SyntaxError: EOF while scanning triple-quoted string literal
 ```
 
 #### 💡 Explanation:
-+ Python supports implicit [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation), Example,
++ Python supports implicit [string literal concatenation](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation), Example,
   ```
   >>> print("wtf" "python")
   wtfpython
@@ -1696,7 +1696,7 @@ But I thought tuples were immutable...
 
 #### 💡 Explanation:
 
-* Quoting from https://docs.python.org/2/reference/datamodel.html
+* Quoting from https://docs.python.org/3/reference/datamodel.html
 
     > Immutable sequences
         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.)
@@ -1858,7 +1858,7 @@ a, b = a[b] = {}, 5
 
 #### 💡 Explanation:
 
-* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form
+* According to [Python language reference](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), assignment statements have the form
   ```
   (target_list "=")+ (expression_list | yield_expression)
   ```
@@ -2625,7 +2625,7 @@ def similar_recursive_func(a):
   AssertionError: Values are not equal
   ```
 
-* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).
+* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).
 
 * Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignation of an immutable (`a -= 1`) is not an alteration of the value.
 
@@ -2655,7 +2655,7 @@ def similar_recursive_func(a):
 
 #### 💡 Explanation:
 
-- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split)
+- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/3/library/stdtypes.html#str.split)
     >  If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.
     > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.
 - Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,
@@ -3576,7 +3576,7 @@ What makes those dictionaries become bloated? And why are newly created objects
     print(dis.dis(f))
     ```
      
-* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module.
+* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) module.
 
 * Sometimes, the `print` method might not print values immediately. For example,
 

From e5b519149d7bb34e48cd0c654841c4a508c6546c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E8=B0=AD=E4=B9=9D=E9=BC=8E?= <109224573@qq.com>
Date: Tue, 27 Oct 2020 11:10:03 +0800
Subject: [PATCH 188/221] Use https links

---
 README.md | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/README.md b/README.md
index ecf56236..0391db7b 100644
--- a/README.md
+++ b/README.md
@@ -1521,7 +1521,7 @@ def some_func(val):
 #### 💡 Explanation:
 - This is a bug in CPython's handling of `yield` in generators and comprehensions.
 - Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions
-- Related bug report: http://bugs.python.org/issue10544
+- Related bug report: https://bugs.python.org/issue10544
 - Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.
 
 ---
@@ -2061,7 +2061,7 @@ UnboundLocalError: local variable 'a' referenced before assignment
   2
   ```
 * The keywords `global` and `nonlocal` tell the python interpreter to not delcare new variables and look them up in the corresponding outer scopes.
-* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.
+* Read [this](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.
 
 ---
 
@@ -2821,7 +2821,7 @@ Sshh... It's a super-secret.
 
 #### 💡 Explanation:
 + `antigravity` module is one of the few easter eggs released by Python developers.
-+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python.
++ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](https://xkcd.com/353/) about Python.
 + Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).
 
 ---
@@ -3607,7 +3607,7 @@ What makes those dictionaries become bloated? And why are newly created objects
     True
     ```
 
-* `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.
+* `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.
 
 * You can separate numeric literals with underscores (for better readability) from Python 3 onwards.
 

From c824ed781333cd182fd5897ecc7bbae1f1d367ee Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E8=B0=AD=E4=B9=9D=E9=BC=8E?= <109224573@qq.com>
Date: Tue, 27 Oct 2020 11:10:44 +0800
Subject: [PATCH 189/221] Update README.md

---
 README.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/README.md b/README.md
index a2861ee8..9668814e 100644
--- a/README.md
+++ b/README.md
@@ -2625,7 +2625,7 @@ def similar_recursive_func(a):
   AssertionError: Values are not equal
   ```
 
-* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).
+* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).
 
 * Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignation of an immutable (`a -= 1`) is not an alteration of the value.
 

From ac63a4fb3aebd34ac9e02963ba55b78ff7cb6aaa Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E8=B0=AD=E4=B9=9D=E9=BC=8E?= <109224573@qq.com>
Date: Tue, 27 Oct 2020 12:19:37 +0800
Subject: [PATCH 190/221] fix indentation

---
 README.md | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/README.md b/README.md
index ecf56236..942f6ebe 100644
--- a/README.md
+++ b/README.md
@@ -2569,17 +2569,17 @@ None
 ```py
 def some_recursive_func(a):
     if a[0] == 0:
-        return 
+        return
     a[0] -= 1
     some_recursive_func(a)
     return a
 
 def similar_recursive_func(a):
-        if a == 0:
-                return a
-        a -= 1
-        similar_recursive_func(a)
+    if a == 0:
         return a
+    a -= 1
+    similar_recursive_func(a)
+    return a
 ```
 
 **Output:**

From f13b98e6d56d8eac1225c198bac8c9e713ebeea7 Mon Sep 17 00:00:00 2001
From: Yonatan Goldschmidt 
Date: Tue, 3 Nov 2020 01:55:49 +0200
Subject: [PATCH 191/221] Add section on methods equality and identity

Closes: #233
---
 CONTRIBUTORS.md |  2 +-
 README.md       | 79 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 80 insertions(+), 1 deletion(-)

diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 9dd1d2b9..659a382d 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -21,7 +21,7 @@ Following are the wonderful people (in no specific order) who have contributed t
 | Ghost account | N/A | [#96](https://github.com/satwikkansal/wtfpython/issues/96)
 | koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) |
 | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) |
-| Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208), [#210](https://github.com/satwikkansal/wtfpython/issues/210) |
+| Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208), [#210](https://github.com/satwikkansal/wtfpython/issues/210), [#233](https://github.com/satwikkansal/wtfpython/issues/233) |
 | Diptangsu Goswami | [diptangsu](https://github.com/diptangsu) | [#193](https://github.com/satwikkansal/wtfpython/issues/193) |
 
 ---
diff --git a/README.md b/README.md
index ea954708..f2a8691f 100644
--- a/README.md
+++ b/README.md
@@ -44,6 +44,7 @@ So, here we go...
     + [▶ The sticky output function](#-the-sticky-output-function)
     + [▶ The chicken-egg problem *](#-the-chicken-egg-problem-)
     + [▶ Subclass relationships](#-subclass-relationships)
+    + [▶ Methods equality and identity](#-methods-equality-and-identity)
     + [▶ All-true-ation *](#-all-true-ation-)
     + [▶ The surprising comma](#-the-surprising-comma)
     + [▶ Strings and the backslashes](#-strings-and-the-backslashes)
@@ -1122,6 +1123,84 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A`
 
 ---
 
+### ▶ Methods equality and identity
+
+
+1.
+```py
+class SomeClass:
+    def method(self):
+        pass
+
+    @classmethod
+    def classm(cls):
+        pass
+
+    @staticmethod
+    def staticm():
+        pass
+```
+
+**Output:**
+```py
+>>> print(SomeClass.method is SomeClass.method)
+True
+>>> print(SomeClass.classm is SomeClass.classm)
+False
+>>> print(SomeClass.classm == SomeClass.classm)
+True
+>>> print(SomeClass.staticm is SomeClass.staticm)
+True
+```
+
+Accessing `classm` twice, we get an equal object, but not the *same* one? Let's see what happens
+with instances of `SomeClass`:
+
+2.
+```py
+o1 = SomeClass()
+o2 = SomeClass()
+```
+
+**Output:**
+```py
+>>> print(o1.method == o2.method)
+False
+>>> print(o1.method == o1.method)
+True
+>>> print(o1.method is o1.method)
+False
+>>> print(o1.classm is o1.classm)
+False
+>>> print(o1.classm == o1.classm == o2.classm == SomeClass.classm)
+True
+>>> print(o1.staticm is o1.staticm is o2.staticm is SomeClass.staticm)
+True
+```
+
+Accessing` classm` or `method` twice, creates equal but not *same* objects for the same instance of `SomeClass`.
+
+#### 💡 Explanation
+* Functions are [descriptors](https://docs.python.org/3/howto/descriptor.html). Whenever a function is accessed as an
+attribute, the descriptor is invoked, creating a method object which "binds" the function with the object owning the
+attribute. If called, the method calls the function, implicitly passing the bound object as the first argument
+(this is how we get `self` as the first argument, despite not passing it explicitly).
+* Accessing the attribute multiple times creates multiple method objects! Therefore `o1.method is o2.method` is
+never truthy. Accessing functions as class attributes (as opposed to instance) does not create methods, however; so
+`SomeClass.method is SomeClass.method` is truthy.
+* `classmethod` transforms functions into class methods. Class methods are descriptors that, when accessed, create
+a method object which binds the *class* (type) of the object, instead of the object itself.
+* Unlike functions, `classmethod`s will create a method also when accessed as class attributes (in which case they
+bind the class, not to the type of it). So `SomeClass.classm is SomeClass.classm` is falsy.
+* A method object compares equal when both the functions are equal, and the bound objects are the same. So
+`o1.method == o1.method` is truthy, although not the same object in memory.
+* `staticmethod` transforms functions into a "no-op" descriptor, which returns the function as-is. No method
+objects are ever created, so comparison with `is` is truthy.
+* Having to create new "method" objects every time Python calls instance methods affected performance badly.
+CPython 3.7 [solved it](https://bugs.python.org/issue26110) by introducing new opcodes that deal with calling methods
+without creating the temporary method objects. This is used only when the accessed function is actually called, so the
+snippets here are not affected, and still generate methods :)
+
 ### ▶ All-true-ation *
 
 

From 314de9a30ba31779a1faf0fd79c9030fefdb87d1 Mon Sep 17 00:00:00 2001
From: Yonatan Goldschmidt 
Date: Sun, 8 Nov 2020 01:41:59 +0200
Subject: [PATCH 192/221] Merge "Non-reflexive class method" into new example

---
 README.md | 71 ++++++++++++++++++++-----------------------------------
 1 file changed, 25 insertions(+), 46 deletions(-)

diff --git a/README.md b/README.md
index f2a8691f..7137d079 100644
--- a/README.md
+++ b/README.md
@@ -52,7 +52,6 @@ So, here we go...
     + [▶ Half triple-quoted strings](#-half-triple-quoted-strings)
     + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans)
     + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes)
-    + [▶ Non-reflexive class method *](#-non-reflexive-class-method-)
     + [▶ yielding None](#-yielding-none)
     + [▶ Yielding from... return! *](#-yielding-from-return-)
     + [▶ Nan-reflexivity *](#-nan-reflexivity-)
@@ -1185,18 +1184,41 @@ Accessing` classm` or `method` twice, creates equal but not *same* objects for t
 attribute, the descriptor is invoked, creating a method object which "binds" the function with the object owning the
 attribute. If called, the method calls the function, implicitly passing the bound object as the first argument
 (this is how we get `self` as the first argument, despite not passing it explicitly).
-* Accessing the attribute multiple times creates multiple method objects! Therefore `o1.method is o2.method` is
+```py
+>>> o1.method
+>
+```
+* Accessing the attribute multiple times creates a method object every time! Therefore `o1.method is o1.method` is
 never truthy. Accessing functions as class attributes (as opposed to instance) does not create methods, however; so
 `SomeClass.method is SomeClass.method` is truthy.
+```py
+>>> SomeClass.method
+
+```
 * `classmethod` transforms functions into class methods. Class methods are descriptors that, when accessed, create
 a method object which binds the *class* (type) of the object, instead of the object itself.
+```py
+>>> o1.classm
+>
+```
 * Unlike functions, `classmethod`s will create a method also when accessed as class attributes (in which case they
 bind the class, not to the type of it). So `SomeClass.classm is SomeClass.classm` is falsy.
+```py
+>>> SomeClass.classm
+>
+```
 * A method object compares equal when both the functions are equal, and the bound objects are the same. So
 `o1.method == o1.method` is truthy, although not the same object in memory.
 * `staticmethod` transforms functions into a "no-op" descriptor, which returns the function as-is. No method
 objects are ever created, so comparison with `is` is truthy.
-* Having to create new "method" objects every time Python calls instance methods affected performance badly.
+```py
+>>> o1.staticm
+
+>>> SomeClass.staticm
+
+```
+* Having to create new "method" objects every time Python calls instance methods and having to modify the arguments
+every time in order to insert `self` affected performance badly.
 CPython 3.7 [solved it](https://bugs.python.org/issue26110) by introducing new opcodes that deal with calling methods
 without creating the temporary method objects. This is used only when the accessed function is actually called, so the
 snippets here are not affected, and still generate methods :)
@@ -1530,49 +1552,6 @@ True
 
 ---
 
-### ▶ Non-reflexive class method *
-
-
-
-```py
-class SomeClass:
-        def instance_method(self):
-                pass
-        
-        @classmethod
-        def class_method(cls):
-                pass
-```
-
-**Output:**
-
-```py
->>> SomeClass.instance_method is SomeClass.instance_method
-True
->>> SomeClass.class_method is SomeClass.class_method
-False
->>> id(SomeClass.class_method) == id(SomeClass.class_method)
-True
-```
-
-#### 💡 Explanation:
-
-- The reason `SomeClass.class_method is SomeClass.class_method` is `False` is due to the `@classmethod` decorator. 
-
-  ```py
-  >>> SomeClass.instance_method
-  
-  >>> SomeClass.class_method
-  
-  ```
-
-  A new bound method every time `SomeClass.class_method` is accessed.
-
--  `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). 
-
----
-
-
 ### ▶ yielding None
 
 ```py

From d06fcbff1bd456029bf5e91993cab80bc93abe37 Mon Sep 17 00:00:00 2001
From: Vitor Santa Rosa 
Date: Sat, 28 Nov 2020 23:25:16 -0300
Subject: [PATCH 193/221] Improve string indexing result explanation

---
 README.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/README.md b/README.md
index 7137d079..24597357 100644
--- a/README.md
+++ b/README.md
@@ -3554,7 +3554,7 @@ What makes those dictionaries become bloated? And why are newly created objects
   
 * Few weird looking but semantically correct statements:
   + `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`)
-  + `'a'[0][0][0][0][0]` is also a semantically correct statement as strings are [sequences](https://docs.python.org/3/glossary.html#term-sequence)(iterables supporting element access using integer indices) in Python.
+  + `'a'[0][0][0][0][0]` is also semantically correct, because Python doesn't have a character data type like other languages branched from C. So selecting a single character from a string returns a single-character string.
   + `3 --0-- 5 == 8` and `--5 == 5` are both semantically correct statements and evaluate to `True`.
 
 * Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java.

From 2bc1cd61c11285b19e575dfcbda971b0b90a7477 Mon Sep 17 00:00:00 2001
From: Satwik 
Date: Sun, 17 Jan 2021 13:53:03 +0530
Subject: [PATCH 194/221] Update the sticy output example

Closes https://github.com/satwikkansal/wtfpython/issues/245
---
 CONTRIBUTORS.md |  1 +
 README.md       | 65 +++++++++++++++++++++++++++++++------------------
 2 files changed, 42 insertions(+), 24 deletions(-)

diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 659a382d..28c38901 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -23,6 +23,7 @@ Following are the wonderful people (in no specific order) who have contributed t
 | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) |
 | Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208), [#210](https://github.com/satwikkansal/wtfpython/issues/210), [#233](https://github.com/satwikkansal/wtfpython/issues/233) |
 | Diptangsu Goswami | [diptangsu](https://github.com/diptangsu) | [#193](https://github.com/satwikkansal/wtfpython/issues/193) |
+| Charles | [charles-l](https://github.com/charles-l)  | [#245](https://github.com/satwikkansal/wtfpython/issues/245)
 
 ---
 
diff --git a/README.md b/README.md
index 7137d079..27ed3ab6 100644
--- a/README.md
+++ b/README.md
@@ -41,7 +41,7 @@ So, here we go...
     + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy)
     + [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-)
     + [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt)
-    + [▶ The sticky output function](#-the-sticky-output-function)
+    + [▶ Schrödinger's variable](#-schrödingers-variable-)
     + [▶ The chicken-egg problem *](#-the-chicken-egg-problem-)
     + [▶ Subclass relationships](#-subclass-relationships)
     + [▶ Methods equality and identity](#-methods-equality-and-identity)
@@ -989,10 +989,9 @@ We can avoid this scenario here by not using `row` variable to generate `board`.
 
 ---
 
-### ▶ The sticky output function
+### ▶ Schrödinger's variable *
 
 
-1\.
 
 ```py
 funcs = []
@@ -1006,17 +1005,17 @@ for x in range(7):
 funcs_results = [func() for func in funcs]
 ```
 
-**Output:**
-
+**Output (Python version):**
 ```py
 >>> results
 [0, 1, 2, 3, 4, 5, 6]
 >>> funcs_results
 [6, 6, 6, 6, 6, 6, 6]
 ```
-Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.
 
-2\.
+The 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.
+
+2.
 
 ```py
 >>> powers_of_x = [lambda x: x**i for i in range(10)]
@@ -1024,27 +1023,45 @@ Even when the values of `x` were different in every iteration prior to appending
 [512, 512, 512, 512, 512, 512, 512, 512, 512, 512]
 ```
 
-#### 💡 Explanation
+#### 💡 Explanation:
+* When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the *variable*, not its *value*. The function looks up `x` in the surrounding context, rather than using the value of `x` at the time the function is created. So all of the functions use the latest value assigned to the variable for computation. We can see that it's using the `x` from the surrounding context (i.e. *not* a local variable) with:
+```py
+>>> import inspect
+>>> inspect.getclosurevals(funcs[0])
+ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set())
+```
+Since `x` is a global value, we can change the value that the `funcs` will lookup and return by updating `x`:
 
-- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.
+```py
+>>> x = 42
+>>> [func() for func in funcs]
+[42, 42, 42, 42, 42, 42, 42]
+```
 
-- 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 
-within the function's scope.
+* 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.
 
-    ```py
-    funcs = []
-    for x in range(7):
-        def some_func(x=x):
-            return x
-        funcs.append(some_func)
-    ```
+```py
+funcs = []
+for x in range(7):
+    def some_func(x=x):
+        return x
+    funcs.append(some_func)
+```
 
-    **Output:**
-    ```py
-    >>> funcs_results = [func() for func in funcs]
-    >>> funcs_results
-    [0, 1, 2, 3, 4, 5, 6]
-    ```
+**Output:**
+
+```py
+>>> funcs_results = [func() for func in funcs]
+>>> funcs_results
+[0, 1, 2, 3, 4, 5, 6]
+```
+
+It is not longer using the `x` in the global scope:
+
+```py
+>>> inspect.getclosurevars(funcs[0])
+ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set())
+```
 
 ---
 

From 048a620502d7eb6ccd4ece1fe805ba867da910a2 Mon Sep 17 00:00:00 2001
From: Satwik 
Date: Sun, 17 Jan 2021 13:56:41 +0530
Subject: [PATCH 195/221] Update notebook

---
 irrelevant/wtf.ipynb | 8097 ++++++++++++++++++++++++------------------
 1 file changed, 4629 insertions(+), 3468 deletions(-)

diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb
index de1cba2c..a3147e19 100644
--- a/irrelevant/wtf.ipynb
+++ b/irrelevant/wtf.ipynb
@@ -4,13 +4,13 @@
       "cell_type": "markdown",
       "metadata": {},
       "source": [
-        "

\"\"

\n", + "

\"\"

\n", "

What the f*ck Python! \ud83d\ude31

\n", "

Exploring and understanding Python through surprising snippets.

\n", "\n", - "Translations: [Chinese \u4e2d\u6587](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", + "Translations: [Chinese \u4e2d\u6587](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Ti\u1ebfng Vi\u1ec7t](https://github.com/vuduclyunitn/wtfptyhon-vi) | [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", - "Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/3.0/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython)\n", + "Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython)\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", @@ -20,7 +20,7 @@ "\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", + "PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) (the examples marked with asterisk are the ones added in the latest major revision). \n", "\n", "So, here we go...\n", "\n", @@ -68,7 +68,7 @@ "- 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 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/issues/new)).\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", @@ -353,13 +353,13 @@ "+ 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 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 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. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", - " ![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images/string-intern/string_intern.png)\n", - "+ When `a` and `b` are set to `\"wtf!\"` 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 `wtf!` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", + " ![image](/images/string-intern/string_intern.png)\n", + "+ When `a` and `b` are set to `\"wtf!\"` 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 `\"wtf!\"` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, 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 [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.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 with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", + "+ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 21. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.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 with some change in logic as well, so the fourth snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", "\n" ] }, @@ -367,8 +367,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Hash brownies\n", - "1\\.\n" + "### \u25b6 Be careful with chained operations\n" ] }, { @@ -380,7 +379,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "False\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -388,19 +389,29 @@ } ], "source": [ - "some_dict = {}\n", - "some_dict[5.5] = \"JavaScript\"\n", - "some_dict[5.0] = \"Ruby\"\n", - "some_dict[5] = \"Python\"\n" + "(False == False) in [False] # makes sense\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "**Output:**\n", - "\n" + "False == (False in [False]) # makes sense\n" ] }, { @@ -413,7 +424,8 @@ { "data": { "text/plain": [ - "\"JavaScript\"\n" + "True\n", + "\n" ] }, "output_type": "execute_result", @@ -422,7 +434,7 @@ } ], "source": [ - "some_dict[5.5]\n" + "False == False in [False] # now what?\n" ] }, { @@ -435,7 +447,7 @@ { "data": { "text/plain": [ - "\"Python\"\n" + "False\n" ] }, "output_type": "execute_result", @@ -444,7 +456,7 @@ } ], "source": [ - "some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n" + "True is False == False\n" ] }, { @@ -457,7 +469,7 @@ { "data": { "text/plain": [ - "\"Python\"\n", + "True\n", "\n" ] }, @@ -467,7 +479,7 @@ } ], "source": [ - "some_dict[5] \n" + "False is False is False\n" ] }, { @@ -480,7 +492,7 @@ { "data": { "text/plain": [ - "complex\n" + "True\n" ] }, "output_type": "execute_result", @@ -489,8 +501,7 @@ } ], "source": [ - "complex_five = 5 + 0j\n", - "type(complex_five)\n" + "1 > 0 < 1\n" ] }, { @@ -503,7 +514,7 @@ { "data": { "text/plain": [ - "\"Python\"\n" + "False\n" ] }, "output_type": "execute_result", @@ -512,16 +523,35 @@ } ], "source": [ - "some_dict[complex_five]\n" + "(1 > 0) < 1\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "1 > (0 < 1)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "So, why is Python all over the place?\n", - "\n", "\n" ] }, @@ -529,10 +559,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", + "#### \ud83d\udca1 Explanation:\n", + "\n", + "As per https://docs.python.org/3/reference/expressions.html#membership-test-operations\n", + "\n", + "> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.\n", + "\n", + "While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`.\n", "\n", - "* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.\n", - "* Immutable objects with the same value always have the same hash in Python.\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` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n", + "* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`.\n", + "* The expression `(1 > 0) < 1` is equivalent to `True < 1` and\n" ] }, { @@ -545,7 +583,7 @@ { "data": { "text/plain": [ - " True\n" + " 1\n" ] }, "output_type": "execute_result", @@ -554,7 +592,7 @@ } ], "source": [ - " 5 == 5.0 == 5 + 0j\n" + " int(True)\n" ] }, { @@ -567,7 +605,7 @@ { "data": { "text/plain": [ - " True\n" + " 2\n" ] }, "output_type": "execute_result", @@ -576,16 +614,14 @@ } ], "source": [ - " hash(5) == hash(5.0) == hash(5 + 0j)\n" + " True + 1 #not relevant for this example, but just for fun\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " **Note:** Objects with different values may also have same hash (known as [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science))).\n", - "* When the statement `some_dict[5] = \"Python\"` is executed, the existing value \"Ruby\" is overwritten with \"Python\" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`.\n", - "* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains the rationale behind it.\n", + " So, `1 < 1` evaluates to `False`\n", "\n" ] }, @@ -593,7 +629,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Deep down, we're all the same.\n" + "### \u25b6 How not to use `is` operator\n", + "The following is a very famous example present all over the internet.\n", + "\n", + "1\\.\n", + "\n" ] }, { @@ -605,7 +645,10 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "True\n", + "\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -613,8 +656,33 @@ } ], "source": [ - "class WTF:\n", - " pass\n" + "a = 256\n", + "b = 256\n", + "a is b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = 257\n", + "b = 257\n", + "a is b\n" ] }, { @@ -622,7 +690,8 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + "2\\.\n", + "\n" ] }, { @@ -635,7 +704,8 @@ { "data": { "text/plain": [ - "False\n" + "False\n", + "\n" ] }, "output_type": "execute_result", @@ -644,7 +714,9 @@ } ], "source": [ - "WTF() == WTF() # two different instances can't be equal\n" + "a = []\n", + "b = []\n", + "a is b\n" ] }, { @@ -657,7 +729,7 @@ { "data": { "text/plain": [ - "False\n" + "True\n" ] }, "output_type": "execute_result", @@ -666,7 +738,19 @@ } ], "source": [ - "WTF() is WTF() # identities are also different\n" + "a = tuple()\n", + "b = tuple()\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "**Output**\n", + "\n" ] }, { @@ -688,7 +772,17 @@ } ], "source": [ - "hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\n" + "a, b = 257, 257\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.7.x specifically)**\n", + "\n" ] }, { @@ -701,7 +795,8 @@ { "data": { "text/plain": [ - "True\n" + ">> a is b\n", + "False\n" ] }, "output_type": "execute_result", @@ -710,7 +805,7 @@ } ], "source": [ - "id(WTF()) == id(WTF())\n" + "a, b = 257, 257\n" ] }, { @@ -726,10 +821,11 @@ "source": [ "#### \ud83d\udca1 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 evaluated to `False`? Let's see with this snippet.\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" ] }, { @@ -741,7 +837,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " False\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -749,9 +847,8 @@ } ], "source": [ - " class WTF(object):\n", - " def __init__(self): print(\"I\")\n", - " def __del__(self): print(\"D\")\n" + " class A: pass\n", + " A() is A() # These are two empty objects at two different memory locations.\n" ] }, { @@ -759,7 +856,13 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n" + "**`256` is an existing object but `257` isn't**\n", + "\n", + "When 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", + "\n", + "Quoting from https://docs.python.org/3/c-api/long.html\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" ] }, { @@ -772,11 +875,7 @@ { "data": { "text/plain": [ - " I\n", - " I\n", - " D\n", - " D\n", - " False\n" + "10922528\n" ] }, "output_type": "execute_result", @@ -785,7 +884,7 @@ } ], "source": [ - " WTF() is WTF()\n" + "id(256)\n" ] }, { @@ -798,11 +897,7 @@ { "data": { "text/plain": [ - " I\n", - " D\n", - " I\n", - " D\n", - " True\n" + "10922528\n" ] }, "output_type": "execute_result", @@ -811,22 +906,9 @@ } ], "source": [ - " id(WTF()) == id(WTF())\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " As you may observe, the order in which the objects are destroyed is what made all the difference here.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Disorder within order *\n" + "a = 256\n", + "b = 256\n", + "id(a)\n" ] }, { @@ -838,7 +920,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "10922528\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -846,36 +930,7 @@ } ], "source": [ - "from collections import OrderedDict\n", - "\n", - "dictionary = dict()\n", - "dictionary[1] = 'a'; dictionary[2] = 'b';\n", - "\n", - "ordered_dict = OrderedDict()\n", - "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", - "\n", - "another_ordered_dict = OrderedDict()\n", - "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", - "\n", - "class DictWithHash(dict):\n", - " \"\"\"\n", - " A dict that also implements __hash__ magic.\n", - " \"\"\"\n", - " __hash__ = lambda self: 0\n", - "\n", - "class OrderedDictWithHash(OrderedDict):\n", - " \"\"\"\n", - " An OrderedDict that also implements __hash__ magic.\n", - " \"\"\"\n", - " __hash__ = lambda self: 0\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output**\n" + "id(b)\n" ] }, { @@ -888,7 +943,7 @@ { "data": { "text/plain": [ - "True\n" + "140084850247312\n" ] }, "output_type": "execute_result", @@ -897,7 +952,7 @@ } ], "source": [ - "dictionary == ordered_dict # If a == b\n" + "id(257)\n" ] }, { @@ -910,7 +965,7 @@ { "data": { "text/plain": [ - "True\n" + "140084850247440\n" ] }, "output_type": "execute_result", @@ -919,7 +974,9 @@ } ], "source": [ - "dictionary == another_ordered_dict # and b == c\n" + "x = 257\n", + "y = 257\n", + "id(x)\n" ] }, { @@ -932,11 +989,7 @@ { "data": { "text/plain": [ - "False\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" + "140084850247344\n" ] }, "output_type": "execute_result", @@ -945,7 +998,22 @@ } ], "source": [ - "ordered_dict == another_ordered_dict # the why isn't c == a ??\n" + "id(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Here 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", + "\n", + "Similar 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" ] }, { @@ -958,12 +1026,7 @@ { "data": { "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "TypeError: unhashable type: 'dict'\n", - "\n", - "# Makes sense since dict don't have __hash__ implemented, let's use\n", - "# our wrapper classes.\n" + "140640774013296\n" ] }, "output_type": "execute_result", @@ -972,7 +1035,8 @@ } ], "source": [ - "len({dictionary, ordered_dict, another_ordered_dict})\n" + "a, b = 257, 257\n", + "id(a)\n" ] }, { @@ -985,7 +1049,7 @@ { "data": { "text/plain": [ - "1\n" + "140640774013296\n" ] }, "output_type": "execute_result", @@ -994,13 +1058,7 @@ } ], "source": [ - "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})\n" + "id(b)\n" ] }, { @@ -1013,7 +1071,7 @@ { "data": { "text/plain": [ - "2\n" + "140640774013392\n" ] }, "output_type": "execute_result", @@ -1022,29 +1080,9 @@ } ], "source": [ - "len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "What is going on here?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 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://docs.python.org/3/library/collections.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", - "- The reason for this equality is 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" + "a = 257\n", + "b = 257\n", + "id(a)\n" ] }, { @@ -1057,7 +1095,7 @@ { "data": { "text/plain": [ - " True\n" + "140640774013488\n" ] }, "output_type": "execute_result", @@ -1066,9 +1104,18 @@ } ], "source": [ - " some_set = set()\n", - " some_set.add(dictionary) # these are the mapping objects from the snippets above\n", - " ordered_dict in some_set\n" + "id(b)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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" ] }, { @@ -1081,7 +1128,7 @@ { "data": { "text/plain": [ - " 1\n" + " True\n" ] }, "output_type": "execute_result", @@ -1090,8 +1137,25 @@ } ], "source": [ - " some_set.add(ordered_dict)\n", - " len(some_set)\n" + " a, b = 257.0, 257.0\n", + " a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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://github.com/satwikkansal/wtfpython/issues/100) for updates.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Hash brownies\n", + "1\\.\n" ] }, { @@ -1103,9 +1167,7 @@ "outputs": [ { "data": { - "text/plain": [ - " True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -1113,7 +1175,19 @@ } ], "source": [ - " another_ordered_dict in some_set\n" + "some_dict = {}\n", + "some_dict[5.5] = \"JavaScript\"\n", + "some_dict[5.0] = \"Ruby\"\n", + "some_dict[5] = \"Python\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" ] }, { @@ -1126,8 +1200,7 @@ { "data": { "text/plain": [ - " 1\n", - "\n" + "\"JavaScript\"\n" ] }, "output_type": "execute_result", @@ -1136,8 +1209,7 @@ } ], "source": [ - " some_set.add(another_ordered_dict)\n", - " len(some_set)\n" + "some_dict[5.5]\n" ] }, { @@ -1150,7 +1222,7 @@ { "data": { "text/plain": [ - " False\n" + "\"Python\"\n" ] }, "output_type": "execute_result", @@ -1159,9 +1231,7 @@ } ], "source": [ - " another_set = set()\n", - " another_set.add(ordered_dict)\n", - " another_ordered_dict in another_set\n" + "some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n" ] }, { @@ -1174,7 +1244,8 @@ { "data": { "text/plain": [ - " 2\n" + "\"Python\"\n", + "\n" ] }, "output_type": "execute_result", @@ -1183,8 +1254,7 @@ } ], "source": [ - " another_set.add(another_ordered_dict)\n", - " len(another_set)\n" + "some_dict[5] \n" ] }, { @@ -1197,7 +1267,7 @@ { "data": { "text/plain": [ - " True\n" + "complex\n" ] }, "output_type": "execute_result", @@ -1206,7 +1276,8 @@ } ], "source": [ - " dictionary in another_set\n" + "complex_five = 5 + 0j\n", + "type(complex_five)\n" ] }, { @@ -1219,7 +1290,7 @@ { "data": { "text/plain": [ - " 2\n" + "\"Python\"\n" ] }, "output_type": "execute_result", @@ -1228,15 +1299,16 @@ } ], "source": [ - " another_set.add(another_ordered_dict)\n", - " len(another_set)\n" + "some_dict[complex_five]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " 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", + "So, why is Python all over the place?\n", + "\n", "\n" ] }, @@ -1244,7 +1316,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Keep trying... *\n" + "#### \ud83d\udca1 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" ] }, { @@ -1256,7 +1330,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -1264,41 +1340,7 @@ } ], "source": [ - "def some_func():\n", - " try:\n", - " return 'from_try'\n", - " finally:\n", - " return 'from_finally'\n", - "\n", - "def another_func(): \n", - " for _ in range(3):\n", - " try:\n", - " continue\n", - " finally:\n", - " print(\"Finally!\")\n", - "\n", - "def one_more_func(): # A gotcha!\n", - " try:\n", - " for i in range(3):\n", - " try:\n", - " 1 / 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" + " 5 == 5.0 == 5 + 0j\n" ] }, { @@ -1311,8 +1353,7 @@ { "data": { "text/plain": [ - "'from_finally'\n", - "\n" + " True\n" ] }, "output_type": "execute_result", @@ -1321,7 +1362,7 @@ } ], "source": [ - "some_func()\n" + " 5 is not 5.0 is not 5 + 0j\n" ] }, { @@ -1334,10 +1375,7 @@ { "data": { "text/plain": [ - "Finally!\n", - "Finally!\n", - "Finally!\n", - "\n" + " True\n" ] }, "output_type": "execute_result", @@ -1346,7 +1384,9 @@ } ], "source": [ - "another_func()\n" + " some_dict = {}\n", + " some_dict[5.0] = \"Ruby\"\n", + " 5.0 in some_dict\n" ] }, { @@ -1359,10 +1399,7 @@ { "data": { "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "ZeroDivisionError: division by zero\n", - "\n" + " True\n" ] }, "output_type": "execute_result", @@ -1371,21 +1408,27 @@ } ], "source": [ - "1 / 0\n" + " (5 in some_dict) and (5 + 0j in some_dict)\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* 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" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, "outputs": [ { "data": { "text/plain": [ - "Iteration 0\n", - "\n" + " {5.0: 'Ruby'}\n" ] }, "output_type": "execute_result", @@ -1394,33 +1437,39 @@ } ], "source": [ - "one_more_func()\n" + " some_dict\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " {5.0: 'Python'}\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n" + " some_dict[5] = \"Python\"\n", + " some_dict\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\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", - "- When a `return`, `break` or `continue` statement is executed in the `try` suite of a \"try\u2026finally\" 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 For what?\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://docs.python.org/3/reference/datamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value.\n" ] }, { @@ -1432,7 +1481,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -1440,18 +1491,7 @@ } ], "source": [ - "some_string = \"wtf\"\n", - "some_dict = {}\n", - "for i, some_dict[i] in enumerate(some_string):\n", - " i = 10\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + " 5 == 5.0 == 5 + 0j\n" ] }, { @@ -1464,7 +1504,7 @@ { "data": { "text/plain": [ - "{0: 'w', 1: 't', 2: 'f'}\n" + " True\n" ] }, "output_type": "execute_result", @@ -1473,13 +1513,14 @@ } ], "source": [ - "some_dict # An indexed dict appears.\n" + " hash(5) == hash(5.0) == hash(5 + 0j)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + " **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](https://en.wikipedia.org/wiki/Collision_(computer_science)), and degrades the constant-time performance that hashing usually provides.)\n", "\n" ] }, @@ -1487,14 +1528,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as:\n", - " ```\n", - " for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\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" + "### \u25b6 Deep down, we're all the same.\n" ] }, { @@ -1514,9 +1548,8 @@ } ], "source": [ - " for i in range(4):\n", - " print(i)\n", - " i = 10\n" + "class WTF:\n", + " pass\n" ] }, { @@ -1524,21 +1557,7 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n", - " ```\n", - " 0\n", - " 1\n", - " 2\n", - " 3\n", - " ```\n", - "\n", - " Did you expect the loop to run just once?\n", - "\n", - " **\ud83d\udca1 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)` 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" + "**Output:**\n" ] }, { @@ -1550,7 +1569,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "False\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -1558,25 +1579,7 @@ } ], "source": [ - " i, some_dict[i] = (0, 'w')\n", - " i, some_dict[i] = (1, 't')\n", - " i, some_dict[i] = (2, 'f')\n", - " some_dict\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Evaluation time discrepancy\n", - "1\\.\n" + "WTF() == WTF() # two different instances can't be equal\n" ] }, { @@ -1588,7 +1591,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "False\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -1596,49 +1601,72 @@ } ], "source": [ - "array = [1, 8, 15]\n", - "# A typical generator expression\n", - "gen = (x for x in array if array.count(x) > 0)\n", - "array = [2, 8, 22]\n" + "WTF() is WTF() # identities are also different\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "**Output:**\n", - "\n" + "hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "[8]\n" - ] + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(list(gen)) # Where did the other values go?\n" + "id(WTF()) == id(WTF())\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "2\\.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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 evaluated to `False`? Let's see with this snippet.\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -1656,13 +1684,9 @@ } ], "source": [ - "array_1 = [1,2,3,4]\n", - "gen_1 = (x for x in array_1)\n", - "array_1 = [1,2,3,4,5]\n", - "\n", - "array_2 = [1,2,3,4]\n", - "gen_2 = (x for x in array_2)\n", - "array_2[:] = [1,2,3,4,5]\n" + " class WTF(object):\n", + " def __init__(self): print(\"I\")\n", + " def __del__(self): print(\"D\")\n" ] }, { @@ -1670,57 +1694,76 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + " **Output:**\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, 4]\n", - "\n" - ] + "data": { + "text/plain": [ + " I\n", + " I\n", + " D\n", + " D\n", + " False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(list(gen_1))\n" + " WTF() is WTF()\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, 4, 5]\n" - ] + "data": { + "text/plain": [ + " I\n", + " D\n", + " I\n", + " D\n", + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(list(gen_2))\n" + " id(WTF()) == id(WTF())\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "3\\.\n", + " As you may observe, the order in which the objects are destroyed is what made all the difference here.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Disorder within order *\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -1738,74 +1781,36 @@ } ], "source": [ - "array_3 = [1, 2, 3]\n", - "array_4 = [10, 20, 30]\n", - "gen = (i + j for i in array_3 for j in array_4)\n", + "from collections import OrderedDict\n", "\n", - "array_3 = [4, 5, 6]\n", - "array_4 = [400, 500, 600]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ + "dictionary = dict()\n", + "dictionary[1] = 'a'; dictionary[2] = 'b';\n", "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "metadata": { - "collapsed": true - }, - "execution_count": null, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[401, 501, 601, 402, 502, 602, 403, 503, 603]\n" - ] - } - ], - "source": [ - "print(list(gen))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation\n", + "ordered_dict = OrderedDict()\n", + "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", "\n", - "- In a [generator](https://wiki.python.org/moin/Generators) 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 binded 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(g)` 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://www.python.org/dev/peps/pep-0289/#the-details)\n", - " \n", - " > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n", - "\n" + "another_ordered_dict = OrderedDict()\n", + "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", + "\n", + "class DictWithHash(dict):\n", + " \"\"\"\n", + " A dict that also implements __hash__ magic.\n", + " \"\"\"\n", + " __hash__ = lambda self: 0\n", + "\n", + "class OrderedDictWithHash(OrderedDict):\n", + " \"\"\"\n", + " An OrderedDict that also implements __hash__ magic.\n", + " \"\"\"\n", + " __hash__ = lambda self: 0\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 How not to use `is` operator\n", - "The following is a very famous example present all over the internet.\n", "\n", - "1\\.\n", - "\n" + "**Output**\n" ] }, { @@ -1818,8 +1823,7 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "True\n" ] }, "output_type": "execute_result", @@ -1828,9 +1832,7 @@ } ], "source": [ - "a = 256\n", - "b = 256\n", - "a is b\n" + "dictionary == ordered_dict # If a == b\n" ] }, { @@ -1843,7 +1845,7 @@ { "data": { "text/plain": [ - "False\n" + "True\n" ] }, "output_type": "execute_result", @@ -1852,18 +1854,7 @@ } ], "source": [ - "a = 257\n", - "b = 257\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n", - "\n" + "dictionary == another_ordered_dict # and b == c\n" ] }, { @@ -1877,6 +1868,9 @@ "data": { "text/plain": [ "False\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" ] }, @@ -1886,9 +1880,7 @@ } ], "source": [ - "a = []\n", - "b = []\n", - "a is b\n" + "ordered_dict == another_ordered_dict # then why isn't c == a ??\n" ] }, { @@ -1901,7 +1893,12 @@ { "data": { "text/plain": [ - "True\n" + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "TypeError: unhashable type: 'dict'\n", + "\n", + "# Makes sense since dict don't have __hash__ implemented, let's use\n", + "# our wrapper classes.\n" ] }, "output_type": "execute_result", @@ -1910,19 +1907,7 @@ } ], "source": [ - "a = tuple()\n", - "b = tuple()\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "**Output**\n", - "\n" + "len({dictionary, ordered_dict, another_ordered_dict})\n" ] }, { @@ -1935,7 +1920,7 @@ { "data": { "text/plain": [ - "True\n" + "1\n" ] }, "output_type": "execute_result", @@ -1944,17 +1929,13 @@ } ], "source": [ - "a, b = 257, 257\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 3.7.x specifically)**\n", - "\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})\n" ] }, { @@ -1967,8 +1948,7 @@ { "data": { "text/plain": [ - ">> a is b\n", - "False\n" + "2\n" ] }, "output_type": "execute_result", @@ -1977,13 +1957,15 @@ } ], "source": [ - "a, b = 257, 257\n" + "len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "What is going on here?\n", "\n" ] }, @@ -1993,11 +1975,11 @@ "source": [ "#### \ud83d\udca1 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" + "- 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://docs.python.org/3/library/collections.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", + "- 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" ] }, { @@ -2010,7 +1992,7 @@ { "data": { "text/plain": [ - " False\n" + " True\n" ] }, "output_type": "execute_result", @@ -2019,22 +2001,9 @@ } ], "source": [ - " class A: pass\n", - " A() is A() # These are two empty objects at two different memory locations.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**`256` is an existing object but `257` isn't**\n", - "\n", - "When 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", - "\n", - "Quoting from https://docs.python.org/3/c-api/long.html\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" + " some_set = set()\n", + " some_set.add(dictionary) # these are the mapping objects from the snippets above\n", + " ordered_dict in some_set\n" ] }, { @@ -2047,7 +2016,7 @@ { "data": { "text/plain": [ - "10922528\n" + " 1\n" ] }, "output_type": "execute_result", @@ -2056,7 +2025,8 @@ } ], "source": [ - "id(256)\n" + " some_set.add(ordered_dict)\n", + " len(some_set)\n" ] }, { @@ -2069,7 +2039,7 @@ { "data": { "text/plain": [ - "10922528\n" + " True\n" ] }, "output_type": "execute_result", @@ -2078,9 +2048,7 @@ } ], "source": [ - "a = 256\n", - "b = 256\n", - "id(a)\n" + " another_ordered_dict in some_set\n" ] }, { @@ -2093,7 +2061,8 @@ { "data": { "text/plain": [ - "10922528\n" + " 1\n", + "\n" ] }, "output_type": "execute_result", @@ -2102,7 +2071,8 @@ } ], "source": [ - "id(b)\n" + " some_set.add(another_ordered_dict)\n", + " len(some_set)\n" ] }, { @@ -2115,7 +2085,7 @@ { "data": { "text/plain": [ - "140084850247312\n" + " False\n" ] }, "output_type": "execute_result", @@ -2124,7 +2094,9 @@ } ], "source": [ - "id(257)\n" + " another_set = set()\n", + " another_set.add(ordered_dict)\n", + " another_ordered_dict in another_set\n" ] }, { @@ -2137,7 +2109,7 @@ { "data": { "text/plain": [ - "140084850247440\n" + " 2\n" ] }, "output_type": "execute_result", @@ -2146,9 +2118,8 @@ } ], "source": [ - "x = 257\n", - "y = 257\n", - "id(x)\n" + " another_set.add(another_ordered_dict)\n", + " len(another_set)\n" ] }, { @@ -2161,7 +2132,7 @@ { "data": { "text/plain": [ - "140084850247344\n" + " True\n" ] }, "output_type": "execute_result", @@ -2170,22 +2141,7 @@ } ], "source": [ - "id(y)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Here 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", - "\n", - "Similar 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" + " dictionary in another_set\n" ] }, { @@ -2198,7 +2154,7 @@ { "data": { "text/plain": [ - "140640774013296\n" + " 2\n" ] }, "output_type": "execute_result", @@ -2207,8 +2163,23 @@ } ], "source": [ - "a, b = 257, 257\n", - "id(a)\n" + " another_set.add(another_ordered_dict)\n", + " len(another_set)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Keep trying... *\n" ] }, { @@ -2220,9 +2191,7 @@ "outputs": [ { "data": { - "text/plain": [ - "140640774013296\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2230,31 +2199,41 @@ } ], "source": [ - "id(b)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140640774013392\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "def some_func():\n", + " try:\n", + " return 'from_try'\n", + " finally:\n", + " return 'from_finally'\n", + "\n", + "def another_func(): \n", + " for _ in range(3):\n", + " try:\n", + " continue\n", + " finally:\n", + " print(\"Finally!\")\n", + "\n", + "def one_more_func(): # A gotcha!\n", + " try:\n", + " for i in range(3):\n", + " try:\n", + " 1 / 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, "source": [ - "a = 257\n", - "b = 257\n", - "id(a)\n" + "\n", + "**Output:**\n", + "\n" ] }, { @@ -2267,7 +2246,8 @@ { "data": { "text/plain": [ - "140640774013488\n" + "'from_finally'\n", + "\n" ] }, "output_type": "execute_result", @@ -2276,18 +2256,7 @@ } ], "source": [ - "id(b)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\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" + "some_func()\n" ] }, { @@ -2300,7 +2269,10 @@ { "data": { "text/plain": [ - " True\n" + "Finally!\n", + "Finally!\n", + "Finally!\n", + "\n" ] }, "output_type": "execute_result", @@ -2309,24 +2281,7 @@ } ], "source": [ - " a, b = 257.0, 257.0\n", - " a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\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://github.com/satwikkansal/wtfpython/issues/100) for updates.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 `is not ...` is not `is (not ...)`\n" + "another_func()\n" ] }, { @@ -2339,7 +2294,10 @@ { "data": { "text/plain": [ - "True\n" + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "ZeroDivisionError: division by zero\n", + "\n" ] }, "output_type": "execute_result", @@ -2348,7 +2306,7 @@ } ], "source": [ - "'something' is not None\n" + "1 / 0\n" ] }, { @@ -2361,7 +2319,8 @@ { "data": { "text/plain": [ - "False\n" + "Iteration 0\n", + "\n" ] }, "output_type": "execute_result", @@ -2370,7 +2329,7 @@ } ], "source": [ - "'something' is (not None)\n" + "one_more_func()\n" ] }, { @@ -2384,10 +2343,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", + "#### \ud83d\udca1 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", + "- When a `return`, `break` or `continue` statement is executed in the `try` suite of a \"try\u2026finally\" 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" ] }, @@ -2395,7 +2355,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 A tic-tac-toe where X wins in the first attempt!\n" + "### \u25b6 For what?\n" ] }, { @@ -2415,10 +2375,10 @@ } ], "source": [ - "# Let's initialize a row\n", - "row = [\"\"] * 3 #row i['', '', '']\n", - "# Let's make a board\n", - "board = [row] * 3\n" + "some_string = \"wtf\"\n", + "some_dict = {}\n", + "for i, some_dict[i] in enumerate(some_string):\n", + " i = 10\n" ] }, { @@ -2426,8 +2386,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "**Output:**\n" ] }, { @@ -2440,7 +2399,7 @@ { "data": { "text/plain": [ - "[['', '', ''], ['', '', ''], ['', '', '']]\n" + "{0: 'w', 1: 't', 2: 'f'}\n" ] }, "output_type": "execute_result", @@ -2449,51 +2408,28 @@ } ], "source": [ - "board\n" + "some_dict # An indexed dict appears.\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['', '', '']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "board[0]\n" + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "''\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "board[0][0]\n" + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as:\n", + " ```\n", + " for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\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" ] }, { @@ -2505,9 +2441,7 @@ "outputs": [ { "data": { - "text/plain": [ - "[['X', '', ''], ['X', '', ''], ['X', '', '']]\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2515,35 +2449,31 @@ } ], "source": [ - "board[0][0] = \"X\"\n", - "board\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "We didn't assign three `\"X\"`s, did we?\n", - "\n" + " for i in range(4):\n", + " print(i)\n", + " i = 10\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", "\n", - "When we initialize `row` variable, this visualization explains what happens in the memory\n", + " **Output:**\n", + " ```\n", + " 0\n", + " 1\n", + " 2\n", + " 3\n", + " ```\n", "\n", - "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images/tic-tac-toe/after_row_initialized.png)\n", + " Did you expect the loop to run just once?\n", "\n", - "And 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", + " **\ud83d\udca1 Explanation:**\n", "\n", - "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images/tic-tac-toe/after_board_initialized.png)\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", - "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\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" ] }, { @@ -2555,9 +2485,7 @@ "outputs": [ { "data": { - "text/plain": [ - "[['X', '', ''], ['', '', ''], ['', '', '']]\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2565,9 +2493,10 @@ } ], "source": [ - "board = [['']*3 for _ in range(3)]\n", - "board[0][0] = \"X\"\n", - "board\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" ] }, { @@ -2581,9 +2510,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The sticky output function\n", - "1\\.\n", - "\n" + "### \u25b6 Evaluation time discrepancy\n", + "1\\.\n" ] }, { @@ -2603,15 +2531,10 @@ } ], "source": [ - "funcs = []\n", - "results = []\n", - "for 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", - "\n", - "funcs_results = [func() for func in funcs]\n" + "array = [1, 8, 15]\n", + "# A typical generator expression\n", + "gen = (x for x in array if array.count(x) > 0)\n", + "array = [2, 8, 22]\n" ] }, { @@ -2625,28 +2548,34 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "[0, 1, 2, 3, 4, 5, 6]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "[8]\n" + ] } ], "source": [ - "results\n" + "print(list(gen)) # Where did the other values go?\n" ] }, { - "cell_type": "code", + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true @@ -2654,9 +2583,7 @@ "outputs": [ { "data": { - "text/plain": [ - "[6, 6, 6, 6, 6, 6, 6]\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2664,58 +2591,68 @@ } ], "source": [ - "funcs_results\n" + "array_1 = [1,2,3,4]\n", + "gen_1 = (x for x in array_1)\n", + "array_1 = [1,2,3,4,5]\n", + "\n", + "array_2 = [1,2,3,4]\n", + "gen_2 = (x for x in array_2)\n", + "array_2[:] = [1,2,3,4,5]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.\n", "\n", - "2\\.\n", - "\n" + "**Output:**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4]\n", + "\n" + ] } ], "source": [ - "powers_of_x = [lambda x: x**i for i in range(10)]\n", - "[f(2) for f in powers_of_x]\n" + "print(list(gen_1))\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5]\n" + ] + } + ], "source": [ - "\n" + "print(list(gen_2))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", - "\n", - "- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.\n", "\n", - "- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope.\n", + "3\\.\n", "\n" ] }, @@ -2736,11 +2673,12 @@ } ], "source": [ - " funcs = []\n", - " for x in range(7):\n", - " def some_func(x=x):\n", - " return x\n", - " funcs.append(some_func)\n" + "array_3 = [1, 2, 3]\n", + "array_4 = [10, 20, 30]\n", + "gen = (i + j for i in array_3 for j in array_4)\n", + "\n", + "array_3 = [4, 5, 6]\n", + "array_4 = [400, 500, 600]\n" ] }, { @@ -2748,30 +2686,26 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n" + "**Output:**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - " [0, 1, 2, 3, 4, 5, 6]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "[401, 501, 601, 402, 502, 602, 403, 503, 603]\n" + ] } ], "source": [ - " funcs_results = [func() for func in funcs]\n", - " funcs_results\n" + "print(list(gen))\n" ] }, { @@ -2785,30 +2719,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The chicken-egg problem *\n", - "1\\.\n" + "#### \ud83d\udca1 Explanation\n", + "\n", + "- In a [generator](https://wiki.python.org/moin/Generators) 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 binded 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(g)` 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://www.python.org/dev/peps/pep-0289/#the-details)\n", + " \n", + " > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n", + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "isinstance(3, int)\n" + "### \u25b6 `is not ...` is not `is (not ...)`\n" ] }, { @@ -2830,7 +2758,7 @@ } ], "source": [ - "isinstance(type, object)\n" + "'something' is not None\n" ] }, { @@ -2843,7 +2771,7 @@ { "data": { "text/plain": [ - "True\n" + "False\n" ] }, "output_type": "execute_result", @@ -2852,41 +2780,33 @@ } ], "source": [ - "isinstance(object, type)\n" + "'something' is (not None)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", "\n", - "So which is the \"ultimate\" base class? There's more to the confusion by the way,\n", - "\n", - "2\\. \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" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "class A: pass\n", - "isinstance(A, A)\n" + "### \u25b6 A tic-tac-toe where X wins in the first attempt!\n" ] }, { @@ -2898,9 +2818,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2908,7 +2826,19 @@ } ], "source": [ - "isinstance(type, type)\n" + "# Let's initialize a row\n", + "row = [\"\"] * 3 #row i['', '', '']\n", + "# Let's make a board\n", + "board = [row] * 3\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" ] }, { @@ -2921,7 +2851,7 @@ { "data": { "text/plain": [ - "True\n" + "[['', '', ''], ['', '', ''], ['', '', '']]\n" ] }, "output_type": "execute_result", @@ -2930,16 +2860,7 @@ } ], "source": [ - "isinstance(object, object)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n" + "board\n" ] }, { @@ -2952,7 +2873,7 @@ { "data": { "text/plain": [ - "True\n" + "['', '', '']\n" ] }, "output_type": "execute_result", @@ -2961,7 +2882,7 @@ } ], "source": [ - "issubclass(int, object)\n" + "board[0]\n" ] }, { @@ -2974,7 +2895,7 @@ { "data": { "text/plain": [ - "True\n" + "''\n" ] }, "output_type": "execute_result", @@ -2983,7 +2904,7 @@ } ], "source": [ - "issubclass(type, object)\n" + "board[0][0]\n" ] }, { @@ -2996,7 +2917,7 @@ { "data": { "text/plain": [ - "False\n" + "[['X', '', ''], ['X', '', ''], ['X', '', '']]\n" ] }, "output_type": "execute_result", @@ -3005,7 +2926,8 @@ } ], "source": [ - "issubclass(object, type)\n" + "board[0][0] = \"X\"\n", + "board\n" ] }, { @@ -3013,6 +2935,7 @@ "metadata": {}, "source": [ "\n", + "We didn't assign three `\"X\"`s, did we?\n", "\n" ] }, @@ -3020,26 +2943,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", + "#### \ud83d\udca1 Explanation:\n", "\n", - "- `type` is a [metaclass](https://realpython.com/python-metaclasses/) 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", + "When we initialize `row` variable, this visualization explains what happens in the memory\n", + "\n", + "![image](/images/tic-tac-toe/after_row_initialized.png)\n", + "\n", + "And 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", + "![image](/images/tic-tac-toe/after_board_initialized.png)\n", + "\n", + "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Subclass relationships\n", - "**Output:**\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -3050,7 +2967,7 @@ { "data": { "text/plain": [ - "True\n" + "[['X', '', ''], ['', '', ''], ['', '', '']]\n" ] }, "output_type": "execute_result", @@ -3059,8 +2976,23 @@ } ], "source": [ - "from collections import Hashable\n", - "issubclass(list, object)\n" + "board = [['']*3 for _ in range(3)]\n", + "board[0][0] = \"X\"\n", + "board\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Schr\u00f6dinger's variable *\n" ] }, { @@ -3072,9 +3004,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -3082,58 +3012,23 @@ } ], "source": [ - "issubclass(object, Hashable)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "issubclass(list, Hashable)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ + "funcs = []\n", + "results = []\n", + "for 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", "\n", - "The 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" + "funcs_results = [func() for func in funcs]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 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://www.naftaliharris.com/blog/python-subclass-intransitivity/).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 All-true-ation *\n" + "**Output (Python version):**\n" ] }, { @@ -3146,7 +3041,7 @@ { "data": { "text/plain": [ - "True\n" + "[0, 1, 2, 3, 4, 5, 6]\n" ] }, "output_type": "execute_result", @@ -3155,7 +3050,7 @@ } ], "source": [ - "all([True, True, True])\n" + "results\n" ] }, { @@ -3168,8 +3063,7 @@ { "data": { "text/plain": [ - "False\n", - "\n" + "[6, 6, 6, 6, 6, 6, 6]\n" ] }, "output_type": "execute_result", @@ -3178,7 +3072,18 @@ } ], "source": [ - "all([True, True, False])\n" + "funcs_results\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "The 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", + "\n", + "2.\n", + "\n" ] }, { @@ -3191,7 +3096,7 @@ { "data": { "text/plain": [ - "True\n" + "[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n" ] }, "output_type": "execute_result", @@ -3200,7 +3105,23 @@ } ], "source": [ - "all([])\n" + "powers_of_x = [lambda x: x**i for i in range(10)]\n", + "[f(2) for f in powers_of_x]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "* When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the *variable*, not its *value*. The function looks up `x` in the surrounding context, rather than using the value of `x` at the time the function is created. So all of the functions use the latest value assigned to the variable for computation. We can see that it's using the `x` from the surrounding context (i.e. *not* a local variable) with:\n" ] }, { @@ -3213,7 +3134,7 @@ { "data": { "text/plain": [ - "False\n" + "ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set())\n" ] }, "output_type": "execute_result", @@ -3222,7 +3143,16 @@ } ], "source": [ - "all([[]])\n" + "import inspect\n", + "inspect.getclosurevals(funcs[0])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since `x` is a global value, we can change the value that the `funcs` will lookup and return by updating `x`:\n", + "\n" ] }, { @@ -3235,7 +3165,7 @@ { "data": { "text/plain": [ - "True\n" + "[42, 42, 42, 42, 42, 42, 42]\n" ] }, "output_type": "execute_result", @@ -3244,7 +3174,8 @@ } ], "source": [ - "all([[[]]])\n" + "x = 42\n", + "[func() for func in funcs]\n" ] }, { @@ -3252,38 +3183,40 @@ "metadata": {}, "source": [ "\n", - "Why's this True-False alteration?\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" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "#### \ud83d\udca1 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 `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty.\n", - "- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`.\n", - "\n" + "funcs = []\n", + "for x in range(7):\n", + " def some_func(x=x):\n", + " return x\n", + " funcs.append(some_func)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The surprising comma\n", - "**Output (< 3.6):**\n", + "\n", + "**Output:**\n", "\n" ] }, @@ -3297,11 +3230,7 @@ { "data": { "text/plain": [ - " File \"\", line 1\n", - " def h(x, **kwargs,):\n", - " ^\n", - "SyntaxError: invalid syntax\n", - "\n" + "[0, 1, 2, 3, 4, 5, 6]\n" ] }, "output_type": "execute_result", @@ -3310,13 +3239,17 @@ } ], "source": [ - "def f(x, y,):\n", - " print(x, y)\n", - "\n", - "def g(x=4, y=5,):\n", - " print(x, y)\n", + "funcs_results = [func() for func in funcs]\n", + "funcs_results\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "\n", - "def h(x, **kwargs,):\n" + "It is not longer using the `x` in the global scope:\n", + "\n" ] }, { @@ -3329,10 +3262,7 @@ { "data": { "text/plain": [ - " File \"\", line 1\n", - " def h(*args,):\n", - " ^\n", - "SyntaxError: invalid syntax\n" + "ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set())\n" ] }, "output_type": "execute_result", @@ -3341,25 +3271,13 @@ } ], "source": [ - "def h(*args,):\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "inspect.getclosurevars(funcs[0])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 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://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n", "\n" ] }, @@ -3367,71 +3285,52 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Strings and the backslashes\n", - "**Output:**\n" + "### \u25b6 The chicken-egg problem *\n", + "1\\.\n" ] }, { "cell_type": "code", - "metadata": { - "collapsed": true - }, "execution_count": null, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\"\n", - "\n" - ] - } - ], - "source": [ - "print(\"\\\"\")\n" - ] - }, - { - "cell_type": "code", "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "\\\"\n", - "\n" - ] + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(r\"\\\"\")\n" + "isinstance(3, int)\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "File \"\", line 1\n", - " print(r\"\\\")\n", - " ^\n", - "SyntaxError: EOL while scanning string literal\n", - "\n" - ] + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(r\"\\\")\n" + "isinstance(type, object)\n" ] }, { @@ -3453,23 +3352,18 @@ } ], "source": [ - "r'\\'' == \"\\\\'\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "isinstance(object, type)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 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" + "So which is the \"ultimate\" base class? There's more to the confusion by the way,\n", + "\n", + "2\\. \n", + "\n" ] }, { @@ -3482,7 +3376,7 @@ { "data": { "text/plain": [ - " 'wt\"f'\n" + "False\n" ] }, "output_type": "execute_result", @@ -3491,14 +3385,30 @@ } ], "source": [ - " 'wt\\\"f'\n" - ] + "class A: pass\n", + "isinstance(A, A)\n" + ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "- 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" + "isinstance(type, type)\n" ] }, { @@ -3511,7 +3421,7 @@ { "data": { "text/plain": [ - " True\n" + "True\n" ] }, "output_type": "execute_result", @@ -3520,7 +3430,16 @@ } ], "source": [ - " r'wt\\\"f' == 'wt\\\\\"f'\n" + "isinstance(object, object)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" ] }, { @@ -3533,8 +3452,7 @@ { "data": { "text/plain": [ - " 'wt\\\\\"f'\n", - "\n" + "True\n" ] }, "output_type": "execute_result", @@ -3543,7 +3461,7 @@ } ], "source": [ - " print(repr(r'wt\\\"f')\n" + "issubclass(int, object)\n" ] }, { @@ -3556,7 +3474,7 @@ { "data": { "text/plain": [ - "\n" + "True\n" ] }, "output_type": "execute_result", @@ -3565,7 +3483,7 @@ } ], "source": [ - " print(\"\\n\")\n" + "issubclass(type, object)\n" ] }, { @@ -3578,7 +3496,7 @@ { "data": { "text/plain": [ - " '\\\\\\\\n'\n" + "False\n" ] }, "output_type": "execute_result", @@ -3587,14 +3505,14 @@ } ], "source": [ - " print(r\"\\\\n\")\n" + "issubclass(object, type)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "- 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" ] }, @@ -3602,7 +3520,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 not knot!\n" + "#### \ud83d\udca1 Explanation\n", + "\n", + "- `type` is a [metaclass](https://realpython.com/python-metaclasses/) 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Subclass relationships\n", + "**Output:**\n" ] }, { @@ -3614,7 +3549,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -3622,16 +3559,8 @@ } ], "source": [ - "x = True\n", - "y = False\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "from collections import Hashable\n", + "issubclass(list, object)\n" ] }, { @@ -3653,7 +3582,7 @@ } ], "source": [ - "not x == y\n" + "issubclass(object, Hashable)\n" ] }, { @@ -3666,10 +3595,7 @@ { "data": { "text/plain": [ - " File \"\", line 1\n", - " x == not y\n", - " ^\n", - "SyntaxError: invalid syntax\n" + "False\n" ] }, "output_type": "execute_result", @@ -3678,13 +3604,15 @@ } ], "source": [ - "x == not y\n" + "issubclass(list, Hashable)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "The 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" ] }, @@ -3694,10 +3622,10 @@ "source": [ "#### \ud83d\udca1 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", + "* 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://www.naftaliharris.com/blog/python-subclass-intransitivity/).\n", "\n" ] }, @@ -3705,7 +3633,45 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Half triple-quoted strings\n", + "### \u25b6 Methods equality and identity\n", + "1.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", "**Output:**\n" ] }, @@ -3720,12 +3686,12 @@ "name": "stdout", "output_type": "stream", "text": [ - "wtfpython\n" + "True\n" ] } ], "source": [ - "print('wtfpython''')\n" + "print(SomeClass.method is SomeClass.method)\n" ] }, { @@ -3739,71 +3705,61 @@ "name": "stdout", "output_type": "stream", "text": [ - "wtfpython\n" + "False\n" ] } ], "source": [ - "print(\"wtfpython\"\"\")\n" + "print(SomeClass.classm is SomeClass.classm)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - " File \"\", line 3\n", - " print(\"\"\"wtfpython\")\n", - " ^\n", - "SyntaxError: EOF while scanning triple-quoted string literal\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] } ], "source": [ - "# The following statements raise `SyntaxError`\n", - "# print('''wtfpython')\n", - "# print(\"\"\"wtfpython\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "print(SomeClass.classm == SomeClass.classm)\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], "source": [ - "#### \ud83d\udca1 Explanation:\n", - "+ Python supports implicit [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation), Example,\n", - " ```\n", - " >>> print(\"wtf\" \"python\")\n", - " wtfpython\n", - " >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n", - " wtf\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" + "print(SomeClass.staticm is SomeClass.staticm)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 What's wrong with booleans?\n", - "1\\.\n", - "\n" + "\n", + "Accessing `classm` twice, we get an equal object, but not the *same* one? Let's see what happens\n", + "with instances of `SomeClass`:\n", + "\n", + "2.\n" ] }, { @@ -3823,17 +3779,8 @@ } ], "source": [ - "# A simple example to count the number of booleans and\n", - "# integers in an iterable of mixed data types.\n", - "mixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\n", - "integers_found_so_far = 0\n", - "booleans_found_so_far = 0\n", - "\n", - "for 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" + "o1 = SomeClass()\n", + "o2 = SomeClass()\n" ] }, { @@ -3846,164 +3793,116 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "4\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] } ], "source": [ - "integers_found_so_far\n" + "print(o1.method == o2.method)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "0\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] } ], "source": [ - "booleans_found_so_far\n" + "print(o1.method == o1.method)\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] + } + ], "source": [ - "\n", - "\n", - "2\\.\n" + "print(o1.method is o1.method)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "'wtf'\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] } ], "source": [ - "some_bool = True\n", - "\"wtf\" * some_bool\n" + "print(o1.classm is o1.classm)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, - "outputs": [ - { - "data": { - "text/plain": [ - "''\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "some_bool = False\n", - "\"wtf\" * some_bool\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n" - ] - }, - { - "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": true - }, "outputs": [ { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] } ], "source": [ - "def tell_truth():\n", - " True = False\n", - " if True == False:\n", - " print(\"I have lost faith in truth!\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (< 3.x):**\n", - "\n" + "print(o1.classm == o1.classm == o2.classm == SomeClass.classm)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "I have lost faith in truth!\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] } ], "source": [ - "tell_truth()\n" + "print(o1.staticm is o1.staticm is o2.staticm is SomeClass.staticm)\n" ] }, { @@ -4011,7 +3910,7 @@ "metadata": {}, "source": [ "\n", - "\n", + "Accessing` classm` or `method` twice, creates equal but not *same* objects for the same instance of `SomeClass`.\n", "\n" ] }, @@ -4019,10 +3918,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* `bool` is a subclass of `int` in Python\n", - " \n" + "#### \ud83d\udca1 Explanation\n", + "* Functions are [descriptors](https://docs.python.org/3/howto/descriptor.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" ] }, { @@ -4035,7 +3935,7 @@ { "data": { "text/plain": [ - " True\n" + ">\n" ] }, "output_type": "execute_result", @@ -4044,7 +3944,16 @@ } ], "source": [ - " issubclass(bool, int)\n" + "o1.method\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* 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" ] }, { @@ -4057,7 +3966,7 @@ { "data": { "text/plain": [ - " False\n" + "\n" ] }, "output_type": "execute_result", @@ -4066,15 +3975,15 @@ } ], "source": [ - " issubclass(int, bool)\n" + "SomeClass.method\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " \n", - "* And thus, `True` and `False` are instances of `int`\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" ] }, { @@ -4087,7 +3996,7 @@ { "data": { "text/plain": [ - " True\n" + ">\n" ] }, "output_type": "execute_result", @@ -4096,7 +4005,15 @@ } ], "source": [ - " isinstance(True, int)\n" + "o1.classm\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* 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" ] }, { @@ -4109,7 +4026,7 @@ { "data": { "text/plain": [ - " True\n" + ">\n" ] }, "output_type": "execute_result", @@ -4118,15 +4035,17 @@ } ], "source": [ - " isinstance(False, int)\n" + "SomeClass.classm\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "* The integer value of `True` is `1` and that of `False` is `0`.\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" ] }, { @@ -4139,7 +4058,7 @@ { "data": { "text/plain": [ - " 1\n" + "\n" ] }, "output_type": "execute_result", @@ -4148,7 +4067,7 @@ } ], "source": [ - " int(True)\n" + "o1.staticm\n" ] }, { @@ -4161,7 +4080,7 @@ { "data": { "text/plain": [ - " 0\n" + "\n" ] }, "output_type": "execute_result", @@ -4170,19 +4089,18 @@ } ], "source": [ - " int(False)\n" + "SomeClass.staticm\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) 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", + "* Having to create new \"method\" objects every time Python calls instance methods and having to modify the arguments\n", + "every time in order to insert `self` affected performance badly.\n", + "CPython 3.7 [solved it](https://bugs.python.org/issue26110) by introducing new opcodes that deal with calling methods\n", + "without creating the temporary method objects. This is used only when the accessed function is actually called, so the\n", + "snippets here are not affected, and still generate methods :)\n", "\n" ] }, @@ -4190,43 +4108,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Class attributes and instance attributes\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "class A:\n", - " x = 1\n", - "\n", - "class B(A):\n", - " pass\n", - "\n", - "class C(A):\n", - " pass\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "### \u25b6 All-true-ation *\n" ] }, { @@ -4239,7 +4121,7 @@ { "data": { "text/plain": [ - "(1, 1, 1)\n" + "True\n" ] }, "output_type": "execute_result", @@ -4248,7 +4130,7 @@ } ], "source": [ - "A.x, B.x, C.x\n" + "all([True, True, True])\n" ] }, { @@ -4261,7 +4143,8 @@ { "data": { "text/plain": [ - "(1, 2, 1)\n" + "False\n", + "\n" ] }, "output_type": "execute_result", @@ -4270,8 +4153,7 @@ } ], "source": [ - "B.x = 2\n", - "A.x, B.x, C.x\n" + "all([True, True, False])\n" ] }, { @@ -4284,7 +4166,7 @@ { "data": { "text/plain": [ - "(3, 2, 3)\n" + "True\n" ] }, "output_type": "execute_result", @@ -4293,8 +4175,7 @@ } ], "source": [ - "A.x = 3\n", - "A.x, B.x, C.x # C.x changed, but B.x didn't\n" + "all([])\n" ] }, { @@ -4307,7 +4188,7 @@ { "data": { "text/plain": [ - "(3, 3)\n" + "False\n" ] }, "output_type": "execute_result", @@ -4316,8 +4197,7 @@ } ], "source": [ - "a = A()\n", - "a.x, A.x\n" + "all([[]])\n" ] }, { @@ -4330,7 +4210,7 @@ { "data": { "text/plain": [ - "(4, 3)\n" + "True\n" ] }, "output_type": "execute_result", @@ -4339,8 +4219,7 @@ } ], "source": [ - "a.x += 1\n", - "a.x, A.x\n" + "all([[[]]])\n" ] }, { @@ -4348,42 +4227,38 @@ "metadata": {}, "source": [ "\n", - "2\\.\n" + "Why's this True-False alteration?\n", + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "class 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" + "#### \ud83d\udca1 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 `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty.\n", + "- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`.\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n", + "### \u25b6 The surprising comma\n", + "**Output (< 3.6):**\n", "\n" ] }, @@ -4397,7 +4272,11 @@ { "data": { "text/plain": [ - "[5, 420]\n" + " File \"\", line 1\n", + " def h(x, **kwargs,):\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n" ] }, "output_type": "execute_result", @@ -4406,8 +4285,13 @@ } ], "source": [ - "some_obj = SomeClass(420)\n", - "some_obj.some_list\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" ] }, { @@ -4420,7 +4304,10 @@ { "data": { "text/plain": [ - "[5, 420]\n" + " File \"\", line 1\n", + " def h(*args,):\n", + " ^\n", + "SyntaxError: invalid syntax\n" ] }, "output_type": "execute_result", @@ -4429,74 +4316,97 @@ } ], "source": [ - "some_obj.another_list\n" + "def h(*args,):\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Strings and the backslashes\n", + "**Output:**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "[5, 111]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "\"\n", + "\n" + ] } ], "source": [ - "another_obj = SomeClass(111)\n", - "another_obj.some_list\n" + "print(\"\\\"\")\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "[5, 420, 111]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "\\\"\n", + "\n" + ] } ], "source": [ - "another_obj.another_list\n" + "print(r\"\\\"\")\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "File \"\", line 1\n", + " print(r\"\\\")\n", + " ^\n", + "SyntaxError: EOL while scanning string literal\n", + "\n" + ] } ], "source": [ - "another_obj.another_list is SomeClass.another_list\n" + "print(r\"\\\")\n" ] }, { @@ -4518,7 +4428,7 @@ } ], "source": [ - "another_obj.another_list is some_obj.another_list\n" + "r'\\'' == \"\\\\'\"\n" ] }, { @@ -4532,18 +4442,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", + "#### \ud83d\udca1 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Non-reflexive class method *\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" ] }, { @@ -4555,7 +4456,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " 'wt\"f'\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -4563,44 +4466,14 @@ } ], "source": [ - "class SomeClass:\n", - " def instance_method(self):\n", - " pass\n", - " \n", - " @classmethod\n", - " def class_method(cls):\n", - " pass\n" + " \"wt\\\"f\"\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "SomeClass.instance_method is SomeClass.instance_method\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" ] }, { @@ -4613,7 +4486,7 @@ { "data": { "text/plain": [ - "False\n" + " True\n" ] }, "output_type": "execute_result", @@ -4622,7 +4495,7 @@ } ], "source": [ - "SomeClass.class_method is SomeClass.class_method\n" + " r'wt\\\"f' == 'wt\\\\\"f'\n" ] }, { @@ -4635,7 +4508,8 @@ { "data": { "text/plain": [ - "True\n" + " 'wt\\\\\"f'\n", + "\n" ] }, "output_type": "execute_result", @@ -4644,24 +4518,7 @@ } ], "source": [ - "id(SomeClass.class_method) == id(SomeClass.class_method)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- The reason `SomeClass.class_method is SomeClass.class_method` is `False` is due to the `@classmethod` decorator. \n", - "\n" + " print(repr(r'wt\\\"f')\n" ] }, { @@ -4674,7 +4531,7 @@ { "data": { "text/plain": [ - " \n" + "\n" ] }, "output_type": "execute_result", @@ -4683,7 +4540,7 @@ } ], "source": [ - " SomeClass.instance_method\n" + " print(\"\\n\")\n" ] }, { @@ -4696,7 +4553,7 @@ { "data": { "text/plain": [ - " \n" + " '\\\\n'\n" ] }, "output_type": "execute_result", @@ -4705,17 +4562,14 @@ } ], "source": [ - " SomeClass.class_method\n" + " print(r\"\\\\n\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - " A new bound method every time `SomeClass.class_method` is accessed.\n", - "\n", - "- `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). \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" ] }, @@ -4723,7 +4577,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 yielding None\n" + "### \u25b6 not knot!\n" ] }, { @@ -4743,10 +4597,8 @@ } ], "source": [ - "some_iterable = ('a', 'b')\n", - "\n", - "def some_func(val):\n", - " return \"something\"\n" + "x = True\n", + "y = False\n" ] }, { @@ -4754,8 +4606,7 @@ "metadata": {}, "source": [ "\n", - "**Output (<= 3.7.x):**\n", - "\n" + "**Output:**\n" ] }, { @@ -4768,7 +4619,7 @@ { "data": { "text/plain": [ - "['a', 'b']\n" + "True\n" ] }, "output_type": "execute_result", @@ -4777,7 +4628,7 @@ } ], "source": [ - "[x for x in some_iterable]\n" + "not x == y\n" ] }, { @@ -4790,7 +4641,10 @@ { "data": { "text/plain": [ - " at 0x7f70b0a4ad58>\n" + " File \"\", line 1\n", + " x == not y\n", + " ^\n", + "SyntaxError: invalid syntax\n" ] }, "output_type": "execute_result", @@ -4799,51 +4653,73 @@ } ], "source": [ - "[(yield x) for x in some_iterable]\n" + "x == not y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Half triple-quoted strings\n", + "**Output:**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "['a', 'b']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "wtfpython\n" + ] } ], "source": [ - "list([(yield x) for x in some_iterable])\n" + "print('wtfpython''')\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "['a', None, 'b', None]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "wtfpython\n" + ] } ], "source": [ - "list((yield x) for x in some_iterable)\n" + "print(\"wtfpython\"\"\")\n" ] }, { @@ -4856,7 +4732,10 @@ { "data": { "text/plain": [ - "['a', 'something', 'b', 'something']\n" + " File \"\", line 3\n", + " print(\"\"\"wtfpython\")\n", + " ^\n", + "SyntaxError: EOF while scanning triple-quoted string literal\n" ] }, "output_type": "execute_result", @@ -4865,7 +4744,9 @@ } ], "source": [ - "list(some_func((yield x)) for x in some_iterable)\n" + "# The following statements raise `SyntaxError`\n", + "# print('''wtfpython')\n", + "# print(\"\"\"wtfpython\")\n" ] }, { @@ -4880,18 +4761,22 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n", - "- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n", - "- Related bug report: http://bugs.python.org/issue10544\n", - "- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n", - "\n" + "+ Python supports implicit [string literal concatenation](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation), Example,\n", + " ```\n", + " >>> print(\"wtf\" \"python\")\n", + " wtfpython\n", + " >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n", + " wtf\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" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Yielding from... return! *\n", + "### \u25b6 What's wrong with booleans?\n", "1\\.\n", "\n" ] @@ -4913,11 +4798,17 @@ } ], "source": [ - "def some_func(x):\n", - " if x == 3:\n", - " return [\"wtf\"]\n", - " else:\n", - " yield from range(x)\n" + "# A simple example to count the number of booleans and\n", + "# integers in an iterable of mixed data types.\n", + "mixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\n", + "integers_found_so_far = 0\n", + "booleans_found_so_far = 0\n", + "\n", + "for 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" ] }, { @@ -4925,8 +4816,7 @@ "metadata": {}, "source": [ "\n", - "**Output (> 3.3):**\n", - "\n" + "**Output:**\n" ] }, { @@ -4939,7 +4829,7 @@ { "data": { "text/plain": [ - "[]\n" + "4\n" ] }, "output_type": "execute_result", @@ -4948,18 +4838,7 @@ } ], "source": [ - "list(some_func(3))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Where did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n", - "\n", - "2\\.\n", - "\n" + "integers_found_so_far\n" ] }, { @@ -4971,7 +4850,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "0\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -4979,12 +4860,7 @@ } ], "source": [ - "def some_func(x):\n", - " if x == 3:\n", - " return [\"wtf\"]\n", - " else:\n", - " for i in range(x):\n", - " yield i\n" + "booleans_found_so_far\n" ] }, { @@ -4992,8 +4868,8 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "\n", + "2\\.\n" ] }, { @@ -5006,7 +4882,7 @@ { "data": { "text/plain": [ - "[]\n" + "'wtf'\n" ] }, "output_type": "execute_result", @@ -5015,31 +4891,39 @@ } ], "source": [ - "list(some_func(3))\n" + "some_bool = True\n", + "\"wtf\" * some_bool\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "''\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "The same result, this didn't work either.\n", - "\n" + "some_bool = False\n", + "\"wtf\" * some_bool\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#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", + "3\\.\n", "\n" ] }, @@ -5060,16 +4944,18 @@ } ], "source": [ - " try:\n", - " next(some_func(3))\n", - " except StopIteration as e:\n", - " some_string = e.value\n" + "def tell_truth():\n", + " True = False\n", + " if True == False:\n", + " print(\"I have lost faith in truth!\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "**Output (< 3.x):**\n", "\n" ] }, @@ -5083,7 +4969,7 @@ { "data": { "text/plain": [ - " [\"wtf\"]\n" + "I have lost faith in truth!\n" ] }, "output_type": "execute_result", @@ -5092,13 +4978,15 @@ } ], "source": [ - " some_string\n" + "tell_truth()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "\n" ] }, @@ -5106,9 +4994,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Nan-reflexivity *\n", - "1\\.\n", - "\n" + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* `bool` is a subclass of `int` in Python\n", + " \n" ] }, { @@ -5120,7 +5009,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -5128,19 +5019,37 @@ } ], "source": [ - "a = float('inf')\n", - "b = float('nan')\n", - "c = float('-iNf') # These strings are case-insensitive\n", - "d = float('nan')\n" + " issubclass(bool, int)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " issubclass(int, bool)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n", - "\n" + " \n", + "* And thus, `True` and `False` are instances of `int`\n" ] }, { @@ -5153,7 +5062,7 @@ { "data": { "text/plain": [ - "inf\n" + " True\n" ] }, "output_type": "execute_result", @@ -5162,7 +5071,7 @@ } ], "source": [ - "a\n" + " isinstance(True, int)\n" ] }, { @@ -5175,7 +5084,7 @@ { "data": { "text/plain": [ - "nan\n" + " True\n" ] }, "output_type": "execute_result", @@ -5184,7 +5093,15 @@ } ], "source": [ - "b\n" + " isinstance(False, int)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* The integer value of `True` is `1` and that of `False` is `0`.\n" ] }, { @@ -5197,7 +5114,7 @@ { "data": { "text/plain": [ - "-inf\n" + " 1\n" ] }, "output_type": "execute_result", @@ -5206,7 +5123,7 @@ } ], "source": [ - "c\n" + " int(True)\n" ] }, { @@ -5219,7 +5136,7 @@ { "data": { "text/plain": [ - "ValueError: could not convert string to float: some_other_string\n" + " 0\n" ] }, "output_type": "execute_result", @@ -5228,7 +5145,28 @@ } ], "source": [ - "float('some_other_string')\n" + " int(False)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Class attributes and instance attributes\n", + "1\\.\n" ] }, { @@ -5240,9 +5178,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -5250,7 +5186,22 @@ } ], "source": [ - "a == -c # inf==inf\n" + "class A:\n", + " x = 1\n", + "\n", + "class B(A):\n", + " pass\n", + "\n", + "class C(A):\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -5263,7 +5214,7 @@ { "data": { "text/plain": [ - "True\n" + "(1, 1, 1)\n" ] }, "output_type": "execute_result", @@ -5272,7 +5223,7 @@ } ], "source": [ - "None == None # None == None\n" + "A.x, B.x, C.x\n" ] }, { @@ -5285,7 +5236,7 @@ { "data": { "text/plain": [ - "False\n" + "(1, 2, 1)\n" ] }, "output_type": "execute_result", @@ -5294,7 +5245,8 @@ } ], "source": [ - "b == d # but nan!=nan\n" + "B.x = 2\n", + "A.x, B.x, C.x\n" ] }, { @@ -5307,7 +5259,7 @@ { "data": { "text/plain": [ - "0.0\n" + "(3, 2, 3)\n" ] }, "output_type": "execute_result", @@ -5316,7 +5268,8 @@ } ], "source": [ - "50 / a\n" + "A.x = 3\n", + "A.x, B.x, C.x # C.x changed, but B.x didn't\n" ] }, { @@ -5329,7 +5282,7 @@ { "data": { "text/plain": [ - "nan\n" + "(3, 3)\n" ] }, "output_type": "execute_result", @@ -5338,7 +5291,8 @@ } ], "source": [ - "a / a\n" + "a = A()\n", + "a.x, A.x\n" ] }, { @@ -5351,7 +5305,7 @@ { "data": { "text/plain": [ - "nan\n" + "(4, 3)\n" ] }, "output_type": "execute_result", @@ -5360,7 +5314,8 @@ } ], "source": [ - "23 + b\n" + "a.x += 1\n", + "a.x, A.x\n" ] }, { @@ -5368,8 +5323,7 @@ "metadata": {}, "source": [ "\n", - "2\\.\n", - "\n" + "2\\.\n" ] }, { @@ -5381,9 +5335,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -5391,9 +5343,23 @@ } ], "source": [ - "x = float('nan')\n", - "y = x / x\n", - "y is y # identity holds\n" + "class 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" ] }, { @@ -5406,7 +5372,7 @@ { "data": { "text/plain": [ - "False\n" + "[5, 420]\n" ] }, "output_type": "execute_result", @@ -5415,7 +5381,8 @@ } ], "source": [ - "y == y # equality fails of y\n" + "some_obj = SomeClass(420)\n", + "some_obj.some_list\n" ] }, { @@ -5428,7 +5395,7 @@ { "data": { "text/plain": [ - "True\n" + "[5, 420]\n" ] }, "output_type": "execute_result", @@ -5437,28 +5404,30 @@ } ], "source": [ - "[y] == [y] # but the equality succeeds for the list containing y\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "\n" + "some_obj.another_list\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 111]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "#### \ud83d\udca1 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" + "another_obj = SomeClass(111)\n", + "another_obj.some_list\n" ] }, { @@ -5471,7 +5440,7 @@ { "data": { "text/plain": [ - " (False, True)\n" + "[5, 420, 111]\n" ] }, "output_type": "execute_result", @@ -5480,8 +5449,7 @@ } ], "source": [ - " x = float('nan')\n", - " x == x, [x] == [x]\n" + "another_obj.another_list\n" ] }, { @@ -5494,7 +5462,7 @@ { "data": { "text/plain": [ - " (False, True)\n" + "True\n" ] }, "output_type": "execute_result", @@ -5503,8 +5471,7 @@ } ], "source": [ - " y = float('nan')\n", - " y == y, [y] == [y]\n" + "another_obj.another_list is SomeClass.another_list\n" ] }, { @@ -5517,7 +5484,7 @@ { "data": { "text/plain": [ - " (False, False)\n" + "True\n" ] }, "output_type": "execute_result", @@ -5526,17 +5493,13 @@ } ], "source": [ - " x == y, [x] == [y]\n" + "another_obj.another_list is some_obj.another_list\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\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://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n", "\n" ] }, @@ -5544,11 +5507,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Mutating the immutable!\n", - "This might seem trivial if you know how references work in Python.\n", + "#### \ud83d\udca1 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" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 yielding None\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -5566,8 +5538,10 @@ } ], "source": [ - "some_tuple = (\"A\", \"tuple\", \"with\", \"values\")\n", - "another_tuple = ([1, 2], [3, 4], [5, 6])\n" + "some_iterable = ('a', 'b')\n", + "\n", + "def some_func(val):\n", + " return \"something\"\n" ] }, { @@ -5575,7 +5549,8 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + "**Output (<= 3.7.x):**\n", + "\n" ] }, { @@ -5588,7 +5563,7 @@ { "data": { "text/plain": [ - "TypeError: 'tuple' object does not support item assignment\n" + "['a', 'b']\n" ] }, "output_type": "execute_result", @@ -5597,7 +5572,7 @@ } ], "source": [ - "some_tuple[2] = \"change this\"\n" + "[x for x in some_iterable]\n" ] }, { @@ -5610,7 +5585,7 @@ { "data": { "text/plain": [ - "([1, 2], [3, 4], [5, 6, 1000])\n" + " at 0x7f70b0a4ad58>\n" ] }, "output_type": "execute_result", @@ -5619,8 +5594,7 @@ } ], "source": [ - "another_tuple[2].append(1000) #This throws no error\n", - "another_tuple\n" + "[(yield x) for x in some_iterable]\n" ] }, { @@ -5633,7 +5607,7 @@ { "data": { "text/plain": [ - "TypeError: 'tuple' object does not support item assignment\n" + "['a', 'b']\n" ] }, "output_type": "execute_result", @@ -5642,7 +5616,7 @@ } ], "source": [ - "another_tuple[2] += [99, 999]\n" + "list([(yield x) for x in some_iterable])\n" ] }, { @@ -5655,7 +5629,7 @@ { "data": { "text/plain": [ - "([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n" + "['a', None, 'b', None]\n" ] }, "output_type": "execute_result", @@ -5664,15 +5638,35 @@ } ], "source": [ - "another_tuple\n" + "list((yield x) for x in some_iterable)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'something', 'b', 'something']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list(some_func((yield x)) for x in some_iterable)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "But I thought tuples were immutable...\n", "\n" ] }, @@ -5681,13 +5675,10 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "\n", - "* Quoting from https://docs.python.org/2/reference/datamodel.html\n", - "\n", - " > Immutable sequences\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", + "- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n", + "- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n", + "- Related bug report: https://bugs.python.org/issue10544\n", + "- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n", "\n" ] }, @@ -5695,7 +5686,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The disappearing variable from outer scope\n" + "### \u25b6 Yielding from... return! *\n", + "1\\.\n", + "\n" ] }, { @@ -5715,11 +5708,11 @@ } ], "source": [ - "e = 7\n", - "try:\n", - " raise Exception()\n", - "except Exception as e:\n", - " pass\n" + "def some_func(x):\n", + " if x == 3:\n", + " return [\"wtf\"]\n", + " else:\n", + " yield from range(x)\n" ] }, { @@ -5727,26 +5720,30 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 2.x):**\n" + "**Output (> 3.3):**\n", + "\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "# prints nothing\n" - ] + "data": { + "text/plain": [ + "[]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(e)\n" + "list(some_func(3))\n" ] }, { @@ -5754,44 +5751,43 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 3.x):**\n" + "Where did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n", + "\n", + "2\\.\n", + "\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "NameError: name 'e' is not defined\n" - ] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "def some_func(x):\n", + " if x == 3:\n", + " return [\"wtf\"]\n", + " else:\n", + " for i in range(x):\n", + " yield i\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* Source: https://docs.python.org/3/reference/compound_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", + "**Output:**\n", "\n" ] }, @@ -5804,7 +5800,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "[]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -5812,8 +5810,7 @@ } ], "source": [ - " except E as N:\n", - " foo\n" + "list(some_func(3))\n" ] }, { @@ -5821,7 +5818,23 @@ "metadata": {}, "source": [ "\n", - " was translated into\n", + "The same result, this didn't work either.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#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" ] }, @@ -5842,21 +5855,16 @@ } ], "source": [ - " except E as N:\n", - " try:\n", - " foo\n", - " finally:\n", - " del N\n" - ] - }, - { + " try:\n", + " next(some_func(3))\n", + " except StopIteration as e:\n", + " some_string = e.value\n" + ] + }, + { "cell_type": "markdown", "metadata": {}, "source": [ - "\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" ] }, @@ -5869,7 +5877,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " [\"wtf\"]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -5877,20 +5887,23 @@ } ], "source": [ - " def f(x):\n", - " del(x)\n", - " print(x)\n", - "\n", - " x = 5\n", - " y = [5, 4, 3]\n" + " some_string\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - " **Output:**\n" + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Nan-reflexivity *\n", + "1\\.\n", + "\n" ] }, { @@ -5902,9 +5915,7 @@ "outputs": [ { "data": { - "text/plain": [ - " 5\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -5912,11 +5923,19 @@ } ], "source": [ - " >>>f(x)\n", - " UnboundLocalError: local variable 'x' referenced before assignment\n", - " >>>f(y)\n", - " UnboundLocalError: local variable 'x' referenced before assignment\n", - " x\n" + "a = float('inf')\n", + "b = float('nan')\n", + "c = float('-iNf') # These strings are case-insensitive\n", + "d = float('nan')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" ] }, { @@ -5929,7 +5948,7 @@ { "data": { "text/plain": [ - " [5, 4, 3]\n" + "inf\n" ] }, "output_type": "execute_result", @@ -5938,17 +5957,7 @@ } ], "source": [ - " y\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\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" + "a\n" ] }, { @@ -5961,7 +5970,7 @@ { "data": { "text/plain": [ - " Exception()\n" + "nan\n" ] }, "output_type": "execute_result", @@ -5970,7 +5979,7 @@ } ], "source": [ - " e\n" + "b\n" ] }, { @@ -5983,7 +5992,7 @@ { "data": { "text/plain": [ - " # Nothing is printed!\n" + "-inf\n" ] }, "output_type": "execute_result", @@ -5992,21 +6001,7 @@ } ], "source": [ - " print e\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 The mysterious key type conversion\n" + "c\n" ] }, { @@ -6018,7 +6013,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "ValueError: could not convert string to float: some_other_string\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6026,18 +6023,7 @@ } ], "source": [ - "class SomeClass(str):\n", - " pass\n", - "\n", - "some_dict = {'s': 42}\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "float('some_other_string')\n" ] }, { @@ -6050,7 +6036,7 @@ { "data": { "text/plain": [ - "str\n" + "True\n" ] }, "output_type": "execute_result", @@ -6059,7 +6045,7 @@ } ], "source": [ - "type(list(some_dict.keys())[0])\n" + "a == -c # inf==inf\n" ] }, { @@ -6072,7 +6058,7 @@ { "data": { "text/plain": [ - "{'s': 40}\n" + "True\n" ] }, "output_type": "execute_result", @@ -6081,9 +6067,7 @@ } ], "source": [ - "s = SomeClass('s')\n", - "some_dict[s] = 40\n", - "some_dict # expected: Two different keys-value pairs\n" + "None == None # None == None\n" ] }, { @@ -6096,7 +6080,7 @@ { "data": { "text/plain": [ - "str\n" + "False\n" ] }, "output_type": "execute_result", @@ -6105,26 +6089,7 @@ } ], "source": [ - "type(list(some_dict.keys())[0])\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 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" + "b == d # but nan!=nan\n" ] }, { @@ -6136,7 +6101,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "0.0\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6144,27 +6111,7 @@ } ], "source": [ - " 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " **Output:**\n" + "50 / a\n" ] }, { @@ -6177,7 +6124,7 @@ { "data": { "text/plain": [ - " {'s': 40, 's': 42}\n" + "nan\n" ] }, "output_type": "execute_result", @@ -6186,9 +6133,7 @@ } ], "source": [ - " s = SomeClass('s')\n", - " some_dict[s] = 40\n", - " some_dict\n" + "a / a\n" ] }, { @@ -6201,7 +6146,7 @@ { "data": { "text/plain": [ - " (__main__.SomeClass, str)\n" + "nan\n" ] }, "output_type": "execute_result", @@ -6210,24 +6155,18 @@ } ], "source": [ - " keys = list(some_dict.keys())\n", - " type(keys[0]), type(keys[1])\n" + "23 + b\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "2\\.\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Let's see if you can guess this?\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -6237,7 +6176,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6245,15 +6186,31 @@ } ], "source": [ - "a, b = a[b] = {}, 5\n" + "x = float('nan')\n", + "y = x / x\n", + "y is y # identity holds\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "**Output:**\n" + "y == y # equality fails of y\n" ] }, { @@ -6266,7 +6223,7 @@ { "data": { "text/plain": [ - "{5: ({...}, 5)}\n" + "True\n" ] }, "output_type": "execute_result", @@ -6275,13 +6232,15 @@ } ], "source": [ - "a\n" + "[y] == [y] # but the equality succeeds for the list containing y\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "\n" ] }, @@ -6291,23 +6250,10 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form\n", - " ```\n", - " (target_list \"=\")+ (expression_list | yield_expression)\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", + "- `'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", - "* 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" + "- 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" ] }, { @@ -6320,7 +6266,7 @@ { "data": { "text/plain": [ - " [[...]]\n" + " (False, True)\n" ] }, "output_type": "execute_result", @@ -6329,8 +6275,8 @@ } ], "source": [ - " some_list = some_list[0] = [0]\n", - " some_list\n" + " x = float('nan')\n", + " x == x, [x] == [x]\n" ] }, { @@ -6343,7 +6289,7 @@ { "data": { "text/plain": [ - " [[...]]\n" + " (False, True)\n" ] }, "output_type": "execute_result", @@ -6352,7 +6298,8 @@ } ], "source": [ - " some_list[0]\n" + " y = float('nan')\n", + " y == y, [y] == [y]\n" ] }, { @@ -6365,7 +6312,7 @@ { "data": { "text/plain": [ - " True\n" + " (False, False)\n" ] }, "output_type": "execute_result", @@ -6374,7 +6321,27 @@ } ], "source": [ - " some_list is some_list[0]\n" + " x == y, [x] == [y]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Mutating the immutable!\n", + "This might seem trivial if you know how references work in Python.\n", + "\n" ] }, { @@ -6386,9 +6353,7 @@ "outputs": [ { "data": { - "text/plain": [ - " True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -6396,16 +6361,16 @@ } ], "source": [ - " some_list[0][0][0][0][0][0] == some_list\n" + "some_tuple = (\"A\", \"tuple\", \"with\", \"values\")\n", + "another_tuple = ([1, 2], [3, 4], [5, 6])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " 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" + "**Output:**\n" ] }, { @@ -6417,7 +6382,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "TypeError: 'tuple' object does not support item assignment\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6425,15 +6392,7 @@ } ], "source": [ - " a, b = {}, 5\n", - " a[b] = a, b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n" + "some_tuple[2] = \"change this\"\n" ] }, { @@ -6446,7 +6405,7 @@ { "data": { "text/plain": [ - " True\n" + "([1, 2], [3, 4], [5, 6, 1000])\n" ] }, "output_type": "execute_result", @@ -6455,21 +6414,30 @@ } ], "source": [ - " a[b][0] is a\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "another_tuple[2].append(1000) #This throws no error\n", + "another_tuple\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "TypeError: 'tuple' object does not support item assignment\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "### \u25b6 Modifying a dictionary while iterating over it\n" + "another_tuple[2] += [99, 999]\n" ] }, { @@ -6481,7 +6449,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6489,12 +6459,7 @@ } ], "source": [ - "x = {0: None}\n", - "\n", - "for i in x:\n", - " del x[i]\n", - " x[i+1] = None\n", - " print(i)\n" + "another_tuple\n" ] }, { @@ -6502,20 +6467,7 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 2.7- Python 3.5):**\n", - "\n", - "```\n", - "0\n", - "1\n", - "2\n", - "3\n", - "4\n", - "5\n", - "6\n", - "7\n", - "```\n", - "\n", - "Yes, it runs for exactly **eight** times and stops.\n", + "But I thought tuples were immutable...\n", "\n" ] }, @@ -6525,11 +6477,13 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "* Iteration over a dictionary that you edit at the same time is not supported.\n", - "* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.\n", - "* How deleted keys are handled and when the resize occurs might be different for different Python implementations.\n", - "* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread.\n", - "* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this.\n", + "* Quoting from https://docs.python.org/3/reference/datamodel.html\n", + "\n", + " > Immutable sequences\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://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works).\n", "\n" ] }, @@ -6537,7 +6491,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The out of scope variable\n" + "### \u25b6 The disappearing variable from outer scope\n" ] }, { @@ -6557,13 +6511,11 @@ } ], "source": [ - "a = 1\n", - "def some_func():\n", - " return a\n", - "\n", - "def another_func():\n", - " a += 1\n", - " return a\n" + "e = 7\n", + "try:\n", + " raise Exception()\n", + "except Exception as e:\n", + " pass\n" ] }, { @@ -6571,51 +6523,53 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + "**Output (Python 2.x):**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "1\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "# prints nothing\n" + ] } ], "source": [ - "some_func()\n" + "print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "UnboundLocalError: local variable 'a' referenced before assignment\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "NameError: name 'e' is not defined\n" + ] } ], "source": [ - "another_func()\n" + "print(e)\n" ] }, { @@ -6630,9 +6584,11 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.\n", - "* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.\n", - "* To modify the outer scope variable `a` in `another_func`, use `global` keyword.\n" + "\n", + "* Source: https://docs.python.org/3/reference/compound_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" ] }, { @@ -6652,10 +6608,8 @@ } ], "source": [ - " def another_func()\n", - " global a\n", - " a += 1\n", - " return a\n" + " except E as N:\n", + " foo\n" ] }, { @@ -6663,7 +6617,8 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n" + " was translated into\n", + "\n" ] }, { @@ -6675,9 +6630,7 @@ "outputs": [ { "data": { - "text/plain": [ - " 2\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -6685,23 +6638,24 @@ } ], "source": [ - " another_func()\n" + " except E as N:\n", + " try:\n", + " foo\n", + " finally:\n", + " del N\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\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" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Deleting a list item while iterating\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -6719,22 +6673,12 @@ } ], "source": [ - "list_1 = [1, 2, 3, 4]\n", - "list_2 = [1, 2, 3, 4]\n", - "list_3 = [1, 2, 3, 4]\n", - "list_4 = [1, 2, 3, 4]\n", - "\n", - "for idx, item in enumerate(list_1):\n", - " del item\n", - "\n", - "for idx, item in enumerate(list_2):\n", - " list_2.remove(item)\n", - "\n", - "for idx, item in enumerate(list_3[:]):\n", - " list_3.remove(item)\n", + " def f(x):\n", + " del(x)\n", + " print(x)\n", "\n", - "for idx, item in enumerate(list_4):\n", - " list_4.pop(idx)\n" + " x = 5\n", + " y = [5, 4, 3]\n" ] }, { @@ -6742,7 +6686,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + " **Output:**\n" ] }, { @@ -6755,7 +6699,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4]\n" + " 5\n" ] }, "output_type": "execute_result", @@ -6764,7 +6708,11 @@ } ], "source": [ - "list_1\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" ] }, { @@ -6777,7 +6725,7 @@ { "data": { "text/plain": [ - "[2, 4]\n" + " [5, 4, 3]\n" ] }, "output_type": "execute_result", @@ -6786,7 +6734,17 @@ } ], "source": [ - "list_2\n" + " y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\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" ] }, { @@ -6799,7 +6757,7 @@ { "data": { "text/plain": [ - "[]\n" + " Exception()\n" ] }, "output_type": "execute_result", @@ -6808,7 +6766,7 @@ } ], "source": [ - "list_3\n" + " e\n" ] }, { @@ -6821,7 +6779,7 @@ { "data": { "text/plain": [ - "[2, 4]\n" + " # Nothing is printed!\n" ] }, "output_type": "execute_result", @@ -6830,15 +6788,13 @@ } ], "source": [ - "list_4\n" + " print e\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "Can you guess why the output is `[2, 4]`?\n", "\n" ] }, @@ -6846,33 +6802,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 139798789457608\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - " some_list = [1, 2, 3, 4]\n", - " id(some_list)\n" + "### \u25b6 The mysterious key type conversion\n" ] }, { @@ -6884,9 +6814,7 @@ "outputs": [ { "data": { - "text/plain": [ - " 139798779601192\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -6894,55 +6822,18 @@ } ], "source": [ - " id(some_list[:]) # Notice that python creates new object for sliced list.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Difference between `del`, `remove`, and `pop`:**\n", - "* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).\n", - "* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.\n", - "* `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified.\n", - "\n", - "**Why the output is `[2, 4]`?**\n", - "- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.\n", + "class SomeClass(str):\n", + " pass\n", "\n", - "* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example\n", - "* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.\n", - "\n" + "some_dict = {'s': 42}\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Lossy zip of iterators *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[0, 1, 2, 3, 4, 5, 6]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "numbers = list(range(7))\n", - "numbers\n" + "\n", + "**Output:**\n" ] }, { @@ -6955,7 +6846,7 @@ { "data": { "text/plain": [ - "([0, 1, 2], [3, 4, 5, 6])\n" + "str\n" ] }, "output_type": "execute_result", @@ -6964,8 +6855,7 @@ } ], "source": [ - "first_three, remaining = numbers[:3], numbers[3:]\n", - "first_three, remaining\n" + "type(list(some_dict.keys())[0])\n" ] }, { @@ -6978,8 +6868,7 @@ { "data": { "text/plain": [ - "[(0, 0), (1, 1), (2, 2)]\n", - "# so far so good, let's zip the remaining\n" + "{'s': 40}\n" ] }, "output_type": "execute_result", @@ -6988,8 +6877,9 @@ } ], "source": [ - "numbers_iter = iter(numbers)\n", - "list(zip(numbers_iter, first_three)) \n" + "s = SomeClass('s')\n", + "some_dict[s] = 40\n", + "some_dict # expected: Two different keys-value pairs\n" ] }, { @@ -7002,7 +6892,7 @@ { "data": { "text/plain": [ - "[(4, 3), (5, 4), (6, 5)]\n" + "str\n" ] }, "output_type": "execute_result", @@ -7011,14 +6901,13 @@ } ], "source": [ - "list(zip(numbers_iter, remaining))\n" + "type(list(some_dict.keys())[0])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Where did element `3` go from the `numbers` list?\n", "\n" ] }, @@ -7028,7 +6917,10 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,\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" ] }, { @@ -7048,25 +6940,27 @@ } ], "source": [ - " def zip(*iterables):\n", - " sentinel = object()\n", - " iterators = [iter(it) for it in iterables]\n", - " while iterators:\n", - " result = []\n", - " for it in iterators:\n", - " elem = next(it, sentinel)\n", - " if elem is sentinel: return\n", - " result.append(elem)\n", - " yield tuple(result)\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" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. \n", - "- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.\n", - "- The correct way to do the above using `zip` would be,\n" + "\n", + " **Output:**\n" ] }, { @@ -7079,7 +6973,7 @@ { "data": { "text/plain": [ - " [(0, 0), (1, 1), (2, 2)]\n" + " {'s': 40, 's': 42}\n" ] }, "output_type": "execute_result", @@ -7088,9 +6982,9 @@ } ], "source": [ - " numbers = list(range(7))\n", - " numbers_iter = iter(numbers)\n", - " list(zip(first_three, numbers_iter))\n" + " s = SomeClass('s')\n", + " some_dict[s] = 40\n", + " some_dict\n" ] }, { @@ -7103,7 +6997,7 @@ { "data": { "text/plain": [ - " [(3, 3), (4, 4), (5, 5), (6, 6)]\n" + " (__main__.SomeClass, str)\n" ] }, "output_type": "execute_result", @@ -7112,14 +7006,14 @@ } ], "source": [ - " list(zip(remaining, numbers_iter))\n" + " keys = list(some_dict.keys())\n", + " type(keys[0]), type(keys[1])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " The first argument of zip should be the one with fewest elements.\n", "\n" ] }, @@ -7127,28 +7021,27 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Loop variables leaking out!\n", - "1\\.\n" + "### \u25b6 Let's see if you can guess this?\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "for x in range(7):\n", - " if x == 6:\n", - " print(x, ': for x inside loop')\n", - "print(x, ': x in global')\n" + "a, b = a[b] = {}, 5\n" ] }, { @@ -7168,7 +7061,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "{5: ({...}, 5)}\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7176,48 +7071,39 @@ } ], "source": [ - "6 : for x inside loop\n", - "6 : x in global\n" + "a\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "But `x` was never defined outside the scope of for loop...\n", - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "metadata": { - "collapsed": true - }, - "execution_count": null, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [] - } - ], - "source": [ - "# This time let's initialize x first\n", - "x = -1\n", - "for x in range(7):\n", - " if x == 6:\n", - " print(x, ': for x inside loop')\n", - "print(x, ': x in global')\n" + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation:\n", "\n", - "**Output:**\n" + "* According to [Python language reference](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), assignment statements have the form\n", + " ```\n", + " (target_list \"=\")+ (expression_list | yield_expression)\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" ] }, { @@ -7229,7 +7115,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " [[...]]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7237,132 +7125,83 @@ } ], "source": [ - "6 : for x inside loop\n", - "6 : x in global\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n", - "**Output (Python 2.x):**\n" + " some_list = some_list[0] = [0]\n", + " some_list\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "[0, 1, 2, 3, 4]\n" - ] + "data": { + "text/plain": [ + " [[...]]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "x = 1\n", - "print([x for x in range(5)])\n" + " some_list[0]\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "4\n" - ] + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(x)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 3.x):**\n" + " some_list is some_list[0]\n" ] }, { "cell_type": "code", - "metadata": { - "collapsed": true - }, "execution_count": null, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[0, 1, 2, 3, 4]\n" - ] - } - ], - "source": [ - "x = 1\n", - "print([x for x in range(5)])\n" - ] - }, - { - "cell_type": "code", "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n" - ] + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(x)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + " some_list[0][0][0][0][0][0] == some_list\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.\n", - "\n", - "- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What\u2019s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog:\n", + " Similar is the case in our example (`a[b][0]` is the same object as `a`)\n", "\n", - " > \"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.\"\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Beware of default mutable arguments!\n" + "* So to sum it up, you can break the example down to\n" ] }, { @@ -7382,17 +7221,15 @@ } ], "source": [ - "def some_func(default_arg=[]):\n", - " default_arg.append(\"some_string\")\n", - " return default_arg\n" + " a, b = {}, 5\n", + " a[b] = a, b\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n" + " And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n" ] }, { @@ -7405,7 +7242,7 @@ { "data": { "text/plain": [ - "['some_string']\n" + " True\n" ] }, "output_type": "execute_result", @@ -7414,51 +7251,21 @@ } ], "source": [ - "some_func()\n" + " a[b][0] is a\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['some_string', 'some_string']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "some_func()\n" + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['some_string']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "some_func([])\n" + "### \u25b6 Modifying a dictionary while iterating over it\n" ] }, { @@ -7470,9 +7277,7 @@ "outputs": [ { "data": { - "text/plain": [ - "['some_string', 'some_string', 'some_string']\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -7480,13 +7285,33 @@ } ], "source": [ - "some_func()\n" + "x = {0: None}\n", + "\n", + "for i in x:\n", + " del x[i]\n", + " x[i+1] = None\n", + " print(i)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "**Output (Python 2.7- Python 3.5):**\n", + "\n", + "```\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "```\n", + "\n", + "Yes, it runs for exactly **eight** times and stops.\n", "\n" ] }, @@ -7496,10 +7321,22 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.\n", + "* Iteration over a dictionary that you edit at the same time is not supported.\n", + "* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.\n", + "* How deleted keys are handled and when the resize occurs might be different for different Python implementations.\n", + "* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread.\n", + "* Python 3.7.6 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 The out of scope variable\n", + "1\\.\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -7517,9 +7354,13 @@ } ], "source": [ - " def some_func(default_arg=[]):\n", - " default_arg.append(\"some_string\")\n", - " return default_arg\n" + "a = 1\n", + "def some_func():\n", + " return a\n", + "\n", + "def another_func():\n", + " a += 1\n", + " return a\n" ] }, { @@ -7527,7 +7368,7 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n" + "2\\.\n" ] }, { @@ -7539,9 +7380,7 @@ "outputs": [ { "data": { - "text/plain": [ - " ([],)\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -7549,7 +7388,26 @@ } ], "source": [ - " some_func.__defaults__ #This will show the default argument values for the function\n" + "def some_closure_func():\n", + " a = 1\n", + " def some_inner_func():\n", + " return a\n", + " return some_inner_func()\n", + "\n", + "def another_closure_func():\n", + " a = 1\n", + " def another_inner_func():\n", + " a += 1\n", + " return a\n", + " return another_inner_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -7562,7 +7420,7 @@ { "data": { "text/plain": [ - " (['some_string'],)\n" + "1\n" ] }, "output_type": "execute_result", @@ -7571,8 +7429,7 @@ } ], "source": [ - " some_func()\n", - " some_func.__defaults__\n" + "some_func()\n" ] }, { @@ -7585,7 +7442,8 @@ { "data": { "text/plain": [ - " (['some_string', 'some_string'],)\n" + "UnboundLocalError: local variable 'a' referenced before assignment\n", + "\n" ] }, "output_type": "execute_result", @@ -7594,8 +7452,7 @@ } ], "source": [ - " some_func()\n", - " some_func.__defaults__\n" + "another_func()\n" ] }, { @@ -7608,7 +7465,7 @@ { "data": { "text/plain": [ - " (['some_string', 'some_string'],)\n" + "1\n" ] }, "output_type": "execute_result", @@ -7617,17 +7474,7 @@ } ], "source": [ - " some_func([])\n", - " some_func.__defaults__\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:\n", - "\n" + "some_closure_func()\n" ] }, { @@ -7639,7 +7486,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "UnboundLocalError: local variable 'a' referenced before assignment\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7647,11 +7496,7 @@ } ], "source": [ - " def some_func(default_arg=None):\n", - " if not default_arg:\n", - " default_arg = []\n", - " default_arg.append(\"some_string\")\n", - " return default_arg\n" + "another_closure_func()\n" ] }, { @@ -7665,7 +7510,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Catching the Exceptions\n" + "#### \ud83d\udca1 Explanation:\n", + "* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.\n", + "* To modify the outer scope variable `a` in `another_func`, we have to use the `global` keyword.\n" ] }, { @@ -7685,18 +7532,10 @@ } ], "source": [ - "some_list = [1, 2, 3]\n", - "try:\n", - " # This should raise an ``IndexError``\n", - " print(some_list[4])\n", - "except IndexError, ValueError:\n", - " print(\"Caught!\")\n", - "\n", - "try:\n", - " # This should raise a ``ValueError``\n", - " some_list.remove(4)\n", - "except IndexError, ValueError:\n", - " print(\"Caught again!\")\n" + " def another_func()\n", + " global a\n", + " a += 1\n", + " return a\n" ] }, { @@ -7704,7 +7543,7 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 2.x):**\n" + " **Output:**\n" ] }, { @@ -7716,7 +7555,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " 2\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7724,17 +7565,15 @@ } ], "source": [ - "Caught!\n", - "\n", - "ValueError: list.remove(x): x not in list\n" + " another_func()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output (Python 3.x):**\n" + "* In `another_closure_func`, `a` becomes local to the scope of `another_inner_func`, but it has not been initialized previously in the same scope, which is why it throws an error. \n", + "* To modify the outer scope variable `a` in `another_inner_func`, use the `nonlocal` keyword. The nonlocal statement is used to refer to variables defined in the nearest outer (excluding the global) scope.\n" ] }, { @@ -7754,26 +7593,21 @@ } ], "source": [ - " File \"\", line 3\n", - " except IndexError, ValueError:\n", - " ^\n", - "SyntaxError: invalid syntax\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + " def another_func():\n", + " a = 1\n", + " def another_inner_func():\n", + " nonlocal a\n", + " a += 1\n", + " return a\n", + " return another_inner_func()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", "\n", - "* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example,\n" + " **Output:**\n" ] }, { @@ -7785,7 +7619,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " 2\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7793,25 +7629,23 @@ } ], "source": [ - " some_list = [1, 2, 3]\n", - " try:\n", - " # This should raise a ``ValueError``\n", - " some_list.remove(4)\n", - " except (IndexError, ValueError), e:\n", - " print(\"Caught again!\")\n", - " print(e)\n" + " another_func()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " **Output (Python 2.x):**\n", - " ```\n", - " Caught again!\n", - " list.remove(x): x not in list\n", - " ```\n", - " **Output (Python 3.x):**\n" + "* The keywords `global` and `nonlocal` tell the python interpreter to not delcare new variables and look them up in the corresponding outer scopes.\n", + "* Read [this](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Deleting a list item while iterating\n" ] }, { @@ -7831,10 +7665,22 @@ } ], "source": [ - " File \"\", line 4\n", - " except (IndexError, ValueError), e:\n", - " ^\n", - " IndentationError: unindent does not match any outer indentation level\n" + "list_1 = [1, 2, 3, 4]\n", + "list_2 = [1, 2, 3, 4]\n", + "list_3 = [1, 2, 3, 4]\n", + "list_4 = [1, 2, 3, 4]\n", + "\n", + "for idx, item in enumerate(list_1):\n", + " del item\n", + "\n", + "for idx, item in enumerate(list_2):\n", + " list_2.remove(item)\n", + "\n", + "for idx, item in enumerate(list_3[:]):\n", + " list_3.remove(item)\n", + "\n", + "for idx, item in enumerate(list_4):\n", + " list_4.pop(idx)\n" ] }, { @@ -7842,7 +7688,7 @@ "metadata": {}, "source": [ "\n", - "* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example,\n" + "**Output:**\n" ] }, { @@ -7854,7 +7700,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "[1, 2, 3, 4]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7862,33 +7710,7 @@ } ], "source": [ - " some_list = [1, 2, 3]\n", - " try:\n", - " some_list.remove(4)\n", - "\n", - " except (IndexError, ValueError) as e:\n", - " print(\"Caught again!\")\n", - " print(e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " **Output:**\n", - " ```\n", - " Caught again!\n", - " list.remove(x): x not in list\n", - " ```\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Same operands, different story!\n", - "1\\.\n" + "list_1\n" ] }, { @@ -7900,7 +7722,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "[2, 4]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7908,17 +7732,7 @@ } ], "source": [ - "a = [1, 2, 3, 4]\n", - "b = a\n", - "a = a + [5, 6, 7, 8]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "list_2\n" ] }, { @@ -7931,7 +7745,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4, 5, 6, 7, 8]\n" + "[]\n" ] }, "output_type": "execute_result", @@ -7940,7 +7754,7 @@ } ], "source": [ - "a\n" + "list_3\n" ] }, { @@ -7953,7 +7767,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4]\n" + "[2, 4]\n" ] }, "output_type": "execute_result", @@ -7962,7 +7776,7 @@ } ], "source": [ - "b\n" + "list_4\n" ] }, { @@ -7970,37 +7784,18 @@ "metadata": {}, "source": [ "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "a = [1, 2, 3, 4]\n", - "b = a\n", - "a += [5, 6, 7, 8]\n" + "Can you guess why the output is `[2, 4]`?\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation:\n", "\n", - "**Output:**\n" + "* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.\n", + "\n" ] }, { @@ -8013,7 +7808,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4, 5, 6, 7, 8]\n" + " 139798789457608\n" ] }, "output_type": "execute_result", @@ -8022,7 +7817,8 @@ } ], "source": [ - "a\n" + " some_list = [1, 2, 3, 4]\n", + " id(some_list)\n" ] }, { @@ -8035,7 +7831,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4, 5, 6, 7, 8]\n" + " 139798779601192\n" ] }, "output_type": "execute_result", @@ -8044,27 +7840,24 @@ } ], "source": [ - "b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + " id(some_list[:]) # Notice that python creates new object for sliced list.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", "\n", - "* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this.\n", + "**Difference between `del`, `remove`, and `pop`:**\n", + "* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).\n", + "* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.\n", + "* `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified.\n", "\n", - "* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged.\n", + "**Why the output is `[2, 4]`?**\n", + "- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.\n", "\n", - "* The expression `a += [5,6,7,8]` is actually mapped to an \"extend\" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place.\n", + "* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example\n", + "* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.\n", "\n" ] }, @@ -8072,7 +7865,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Be careful with chained operations\n" + "### \u25b6 Lossy zip of iterators *\n" ] }, { @@ -8085,7 +7878,7 @@ { "data": { "text/plain": [ - "False\n" + "[0, 1, 2, 3, 4, 5, 6]\n" ] }, "output_type": "execute_result", @@ -8094,7 +7887,8 @@ } ], "source": [ - "(False == False) in [False] # makes sense\n" + "numbers = list(range(7))\n", + "numbers\n" ] }, { @@ -8107,7 +7901,7 @@ { "data": { "text/plain": [ - "False\n" + "([0, 1, 2], [3, 4, 5, 6])\n" ] }, "output_type": "execute_result", @@ -8116,7 +7910,8 @@ } ], "source": [ - "False == (False in [False]) # makes sense\n" + "first_three, remaining = numbers[:3], numbers[3:]\n", + "first_three, remaining\n" ] }, { @@ -8129,8 +7924,8 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "[(0, 0), (1, 1), (2, 2)]\n", + "# so far so good, let's zip the remaining\n" ] }, "output_type": "execute_result", @@ -8139,7 +7934,8 @@ } ], "source": [ - "False == False in [False] # now what?\n" + "numbers_iter = iter(numbers)\n", + "list(zip(numbers_iter, first_three)) \n" ] }, { @@ -8152,7 +7948,7 @@ { "data": { "text/plain": [ - "False\n" + "[(4, 3), (5, 4), (6, 5)]\n" ] }, "output_type": "execute_result", @@ -8161,7 +7957,24 @@ } ], "source": [ - "True is False == False\n" + "list(zip(numbers_iter, remaining))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Where did element `3` go from the `numbers` list?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,\n" ] }, { @@ -8173,10 +7986,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n", - "\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8184,7 +7994,25 @@ } ], "source": [ - "False is False is False\n" + " def zip(*iterables):\n", + " sentinel = object()\n", + " iterators = [iter(it) for it in iterables]\n", + " while iterators:\n", + " result = []\n", + " for it in iterators:\n", + " elem = next(it, sentinel)\n", + " if elem is sentinel: return\n", + " result.append(elem)\n", + " yield tuple(result)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- So the function takes in arbitrary number of iterable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. \n", + "- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.\n", + "- The correct way to do the above using `zip` would be,\n" ] }, { @@ -8197,7 +8025,7 @@ { "data": { "text/plain": [ - "True\n" + " [(0, 0), (1, 1), (2, 2)]\n" ] }, "output_type": "execute_result", @@ -8206,7 +8034,9 @@ } ], "source": [ - "1 > 0 < 1\n" + " numbers = list(range(7))\n", + " numbers_iter = iter(numbers)\n", + " list(zip(first_three, numbers_iter))\n" ] }, { @@ -8219,7 +8049,7 @@ { "data": { "text/plain": [ - "False\n" + " [(3, 3), (4, 4), (5, 5), (6, 6)]\n" ] }, "output_type": "execute_result", @@ -8228,35 +8058,14 @@ } ], "source": [ - "(1 > 0) < 1\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "1 > (0 < 1)\n" + " list(zip(remaining, numbers_iter))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + " The first argument of zip should be the one with fewest elements.\n", "\n" ] }, @@ -8264,40 +8073,36 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "As per https://docs.python.org/2/reference/expressions.html#not-in\n", - "\n", - "> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.\n", - "\n", - "While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 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` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n", - "* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`.\n", - "* The expression `(1 > 0) < 1` is equivalent to `True < 1` and\n" + "### \u25b6 Loop variables leaking out!\n", + "1\\.\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - " 1\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [] } ], "source": [ - " int(True)\n" + "for x in range(7):\n", + " if x == 6:\n", + " print(x, ': for x inside loop')\n", + "print(x, ': x in global')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -8309,9 +8114,7 @@ "outputs": [ { "data": { - "text/plain": [ - " 2\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8319,46 +8122,40 @@ } ], "source": [ - " True + 1 #not relevant for this example, but just for fun\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " So, `1 < 1` evaluates to `False`\n", - "\n" + "6 : for x inside loop\n", + "6 : x in global\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Name resolution ignoring class scope\n", - "1\\.\n" + "\n", + "But `x` was never defined outside the scope of for loop...\n", + "\n", + "2\\.\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [] } ], "source": [ - "x = 5\n", - "class SomeClass:\n", - " x = 17\n", - " y = (x for i in range(10))\n" + "# This time let's initialize x first\n", + "x = -1\n", + "for x in range(7):\n", + " if x == 6:\n", + " print(x, ': for x inside loop')\n", + "print(x, ': x in global')\n" ] }, { @@ -8378,9 +8175,7 @@ "outputs": [ { "data": { - "text/plain": [ - "5\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8388,7 +8183,8 @@ } ], "source": [ - "list(SomeClass.y)[0]\n" + "6 : for x inside loop\n", + "6 : x in global\n" ] }, { @@ -8396,60 +8192,48 @@ "metadata": {}, "source": [ "\n", - "2\\.\n" + "3\\.\n", + "\n", + "**Output (Python 2.x):**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 2, 3, 4]\n" + ] } ], "source": [ - "x = 5\n", - "class SomeClass:\n", - " x = 17\n", - " y = [x for i in range(10)]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.x):**\n" + "x = 1\n", + "print([x for x in range(5)])\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "17\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n" + ] } ], "source": [ - "SomeClass.y[0]\n" + "print(x)\n" ] }, { @@ -8462,24 +8246,41 @@ }, { "cell_type": "code", + "metadata": { + "collapsed": true + }, "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 2, 3, 4]\n" + ] + } + ], + "source": [ + "x = 1\n", + "print([x for x in range(5)])\n" + ] + }, + { + "cell_type": "code", "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "5\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n" + ] } ], "source": [ - "SomeClass.y[0]\n" + "print(x)\n" ] }, { @@ -8493,10 +8294,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", - "- Scopes nested inside class definition ignore names bound at the class level.\n", - "- A generator expression has its own scope.\n", - "- Starting from Python 3.X, list comprehensions also have their own scope.\n", + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.\n", + "\n", + "- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What\u2019s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog:\n", + "\n", + " > \"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.\"\n", "\n" ] }, @@ -8504,11 +8308,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Needles in a Haystack *\n", - "I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios,\n", - "\n", - "1\\.\n", - "\n" + "### \u25b6 Beware of default mutable arguments!\n" ] }, { @@ -8528,7 +8328,9 @@ } ], "source": [ - "x, y = (0, 1) if True else None, None\n" + "def some_func(default_arg=[]):\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" ] }, { @@ -8536,8 +8338,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "**Output:**\n" ] }, { @@ -8550,7 +8351,7 @@ { "data": { "text/plain": [ - "((0, 1), None)\n" + "['some_string']\n" ] }, "output_type": "execute_result", @@ -8559,50 +8360,89 @@ } ], "source": [ - "x, y # expected (0, 1)\n" + "some_func()\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string', 'some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "2\\.\n", - "\n" + "some_func()\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [] + "data": { + "text/plain": [ + "['some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "t = ('one', 'two')\n", - "for i in t:\n", - " print(i)\n", - "\n", - "t = ('one')\n", - "for i in t:\n", - " print(i)\n", - "\n", - "t = ()\n", - "print(t)\n" + "some_func([])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string', 'some_string', 'some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation:\n", "\n", - "**Output:**\n", + "- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.\n", "\n" ] }, @@ -8623,12 +8463,9 @@ } ], "source": [ - "one\n", - "two\n", - "o\n", - "n\n", - "e\n", - "tuple()\n" + " def some_func(default_arg=[]):\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" ] }, { @@ -8636,25 +8473,7 @@ "metadata": {}, "source": [ "\n", - "3\\.\n", - "\n", - "```\n", - "ten_words_list = [\n", - " \"some\",\n", - " \"very\",\n", - " \"big\",\n", - " \"list\",\n", - " \"that\"\n", - " \"consists\",\n", - " \"of\",\n", - " \"exactly\",\n", - " \"ten\",\n", - " \"words\"\n", - "]\n", - "```\n", - "\n", - "**Output**\n", - "\n" + " **Output:**\n" ] }, { @@ -8667,7 +8486,7 @@ { "data": { "text/plain": [ - "9\n" + " ([],)\n" ] }, "output_type": "execute_result", @@ -8676,16 +8495,30 @@ } ], "source": [ - "len(ten_words_list)\n" + " some_func.__defaults__ #This will show the default argument values for the function\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string'],)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "4\\. Not asserting strongly enough\n", - "\n" + " some_func()\n", + " some_func.__defaults__\n" ] }, { @@ -8697,7 +8530,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " (['some_string', 'some_string'],)\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -8705,8 +8540,31 @@ } ], "source": [ - "a = \"python\"\n", - "b = \"javascript\"\n" + " some_func()\n", + " some_func.__defaults__\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string', 'some_string'],)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_func([])\n", + " some_func.__defaults__\n" ] }, { @@ -8714,7 +8572,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", + "- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:\n", "\n" ] }, @@ -8727,9 +8585,7 @@ "outputs": [ { "data": { - "text/plain": [ - "# No AssertionError is raised\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8737,19 +8593,27 @@ } ], "source": [ - "# An assert statement with an assertion failure message.\n", - "assert(a == b, \"Both languages are different\")\n" + " def some_func(default_arg=None):\n", + " if default_arg is None:\n", + " default_arg = []\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "5\\.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Catching the Exceptions\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -8768,14 +8632,17 @@ ], "source": [ "some_list = [1, 2, 3]\n", - "some_dict = {\n", - " \"key_1\": 1,\n", - " \"key_2\": 2,\n", - " \"key_3\": 3\n", - "}\n", + "try:\n", + " # This should raise an ``IndexError``\n", + " print(some_list[4])\n", + "except IndexError, ValueError:\n", + " print(\"Caught!\")\n", "\n", - "some_list = some_list.append(4) \n", - "some_dict = some_dict.update({\"key_4\": 4})\n" + "try:\n", + " # This should raise a ``ValueError``\n", + " some_list.remove(4)\n", + "except IndexError, ValueError:\n", + " print(\"Caught again!\")\n" ] }, { @@ -8783,57 +8650,78 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "**Output (Python 2.x):**\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "None\n" - ] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(some_list)\n" + "Caught!\n", + "\n", + "ValueError: list.remove(x): x not in list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "None\n" - ] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(some_dict)\n" + " File \"\", line 3\n", + " except IndexError, ValueError:\n", + " ^\n", + "SyntaxError: invalid syntax\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "6\\.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example,\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -8851,28 +8739,25 @@ } ], "source": [ - "def some_recursive_func(a):\n", - " if a[0] == 0:\n", - " return \n", - " a[0] -= 1\n", - " some_recursive_func(a)\n", - " return a\n", - "\n", - "def similar_recursive_func(a):\n", - " if a == 0:\n", - " return a\n", - " a -= 1\n", - " similar_recursive_func(a)\n", - " return a\n" + " some_list = [1, 2, 3]\n", + " try:\n", + " # This should raise a ``ValueError``\n", + " some_list.remove(4)\n", + " except (IndexError, ValueError), e:\n", + " print(\"Caught again!\")\n", + " print(e)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n", - "\n" + " **Output (Python 2.x):**\n", + " ```\n", + " Caught again!\n", + " list.remove(x): x not in list\n", + " ```\n", + " **Output (Python 3.x):**\n" ] }, { @@ -8884,9 +8769,7 @@ "outputs": [ { "data": { - "text/plain": [ - "[0, 0]\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8894,7 +8777,1395 @@ } ], "source": [ - "some_recursive_func([5, 0])\n" + " File \"\", line 4\n", + " except (IndexError, ValueError), e:\n", + " ^\n", + " IndentationError: unindent does not match any outer indentation level\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_list = [1, 2, 3]\n", + " try:\n", + " some_list.remove(4)\n", + "\n", + " except (IndexError, ValueError) as e:\n", + " print(\"Caught again!\")\n", + " print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Output:**\n", + " ```\n", + " Caught again!\n", + " list.remove(x): x not in list\n", + " ```\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Same operands, different story!\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = [1, 2, 3, 4]\n", + "b = a\n", + "a = a + [5, 6, 7, 8]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = [1, 2, 3, 4]\n", + "b = a\n", + "a += [5, 6, 7, 8]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this.\n", + "\n", + "* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged.\n", + "\n", + "* The expression `a += [5,6,7,8]` is actually mapped to an \"extend\" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Name resolution ignoring class scope\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 5\n", + "class SomeClass:\n", + " x = 17\n", + " y = (x for i in range(10))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list(SomeClass.y)[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 5\n", + "class SomeClass:\n", + " x = 17\n", + " y = [x for i in range(10)]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "17\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "SomeClass.y[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "SomeClass.y[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "- Scopes nested inside class definition ignore names bound at the class level.\n", + "- A generator expression has its own scope.\n", + "- Starting from Python 3.X, list comprehensions also have their own scope.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Needles in a Haystack *\n", + "I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios,\n", + "\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x, y = (0, 1) if True else None, None\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "((0, 1), None)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x, y # expected (0, 1)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "t = ('one', 'two')\n", + "for i in t:\n", + " print(i)\n", + "\n", + "t = ('one')\n", + "for i in t:\n", + " print(i)\n", + "\n", + "t = ()\n", + "print(t)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "one\n", + "two\n", + "o\n", + "n\n", + "e\n", + "tuple()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n", + "```\n", + "ten_words_list = [\n", + " \"some\",\n", + " \"very\",\n", + " \"big\",\n", + " \"list\",\n", + " \"that\"\n", + " \"consists\",\n", + " \"of\",\n", + " \"exactly\",\n", + " \"ten\",\n", + " \"words\"\n", + "]\n", + "```\n", + "\n", + "**Output**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "9\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len(ten_words_list)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "4\\. Not asserting strongly enough\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = \"python\"\n", + "b = \"javascript\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "# No AssertionError is raised\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "# An assert statement with an assertion failure message.\n", + "assert(a == b, \"Both languages are different\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "5\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_list = [1, 2, 3]\n", + "some_dict = {\n", + " \"key_1\": 1,\n", + " \"key_2\": 2,\n", + " \"key_3\": 3\n", + "}\n", + "\n", + "some_list = some_list.append(4) \n", + "some_dict = some_dict.update({\"key_4\": 4})\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "print(some_list)\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "print(some_dict)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "6\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def some_recursive_func(a):\n", + " if a[0] == 0:\n", + " return\n", + " a[0] -= 1\n", + " some_recursive_func(a)\n", + " return a\n", + "\n", + "def similar_recursive_func(a):\n", + " if a == 0:\n", + " return a\n", + " a -= 1\n", + " similar_recursive_func(a)\n", + " return a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 0]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_recursive_func([5, 0])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "similar_recursive_func(5)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`.\n", + "\n", + "* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character.\n", + "\n", + "* `()` is a special token and denotes empty `tuple`.\n", + "\n", + "* In 3, as you might have already figured out, there's a missing comma after 5th element (`\"that\"`) in the list. So by implicit string literal concatenation,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ten_words_list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " AssertionError\n", + " \n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " a = \"python\"\n", + " b = \"javascript\"\n", + " assert a == b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " :1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n", + " \n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " assert (a == b, \"Values are not equal\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " AssertionError: Values are not equal\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " assert a == b, \"Values are not equal\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).\n", + "\n", + "* Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignation of an immutable (`a -= 1`) is not an alteration of the value.\n", + "\n", + "* Being aware of these nitpicks can save you hours of debugging effort in the long run. \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Splitsies *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a']\n", + "\n", + "# is same as\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'a'.split()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a']\n", + "\n", + "# but\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'a'.split(' ')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0\n", + "\n", + "# isn't the same as\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len(''.split())\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len(''.split(' '))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/3/library/stdtypes.html#str.split)\n", + " > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.\n", + " > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.\n", + "- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['', 'a', '']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ' a '.split(' ')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['a']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ' a '.split()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ''.split(' ')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 All sorted? *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 7, 8, 9\n", + "sorted(x) == x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "sorted(x) == sorted(x)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "y = reversed(x)\n", + "sorted(y) == sorted(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. \n", + "\n", + "- ```py\n", + " >>> [] == tuple()\n", + " False\n", + " >>> x = 7, 8, 9\n", + " >>> type(x), type(sorted(x))\n", + " (tuple, list)\n", + " ```\n", + "\n", + "- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first.\n", + "\n", + "- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ([7, 8, 9], [])\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " x = 7, 8, 9\n", + " y = reversed(x)\n", + " sorted(y), sorted(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Midnight time doesn't exist?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "from datetime import datetime\n", + "\n", + "midnight = datetime(2018, 1, 1, 0, 0)\n", + "midnight_time = midnight.time()\n", + "\n", + "noon = datetime(2018, 1, 1, 12, 0)\n", + "noon_time = noon.time()\n", + "\n", + "if midnight_time:\n", + " print(\"Time at midnight is\", midnight_time)\n", + "\n", + "if noon_time:\n", + " print(\"Time at noon is\", noon_time)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (< 3.5):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "('Time at noon is', datetime.time(12, 0))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The midnight time is not printed.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of \"empty.\"\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Okay Python, Can you make me fly?\n", + "Well, here you go\n", + "\n" ] }, { @@ -8906,9 +10177,7 @@ "outputs": [ { "data": { - "text/plain": [ - "4\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8916,13 +10185,16 @@ } ], "source": [ - "similar_recursive_func(5)\n" + "import antigravity\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "**Output:**\n", + "Sshh... It's a super-secret.\n", "\n" ] }, @@ -8931,37 +10203,42 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "\n", - "* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`.\n", - "\n", - "* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character.\n", - "\n", - "* `()` is a special token and denotes empty `tuple`.\n", - "\n", - "* In 3, as you might have already figured out, there's a missing comma after 5th element (`\"that\"`) in the list. So by implicit string literal concatenation,\n", + "+ `antigravity` module is one of the few easter eggs released by Python developers.\n", + "+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](https://xkcd.com/353/) about Python.\n", + "+ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 `goto`, but why?\n" + ] + }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - " ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [] } ], "source": [ - " ten_words_list\n" + "from goto import goto, label\n", + "for i in range(9):\n", + " for j in range(9):\n", + " for k in range(9):\n", + " print(\"I am trapped, please rescue!\")\n", + " if k == 2:\n", + " goto .breakout # breaking out from a deeply nested loop\n", + "label .breakout\n", + "print(\"Freedom!\")\n" ] }, { @@ -8969,8 +10246,7 @@ "metadata": {}, "source": [ "\n", - "* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up,\n", - "\n" + "**Output (Python 2.3):**\n" ] }, { @@ -8982,12 +10258,7 @@ "outputs": [ { "data": { - "text/plain": [ - " Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - " AssertionError\n", - " \n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8995,9 +10266,36 @@ } ], "source": [ - " a = \"python\"\n", - " b = \"javascript\"\n", - " assert a == b\n" + "I am trapped, please rescue!\n", + "I am trapped, please rescue!\n", + "Freedom!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004.\n", + "- Current versions of Python do not have this module.\n", + "- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Brace yourself!\n", + "If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing,\n", + "\n" ] }, { @@ -9009,10 +10307,7 @@ "outputs": [ { "data": { - "text/plain": [ - " :1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n", - " \n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -9020,7 +10315,15 @@ } ], "source": [ - " assert (a == b, \"Values are not equal\")\n" + "from __future__ import braces\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -9032,11 +10335,7 @@ "outputs": [ { "data": { - "text/plain": [ - " Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - " AssertionError: Values aren not equal\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -9044,7 +10343,9 @@ } ], "source": [ - " assert a == b, \"Values are not equal\"\n" + " File \"some_file.py\", line 1\n", + " from __future__ import braces\n", + "SyntaxError: not a chance\n" ] }, { @@ -9052,11 +10353,7 @@ "metadata": {}, "source": [ "\n", - "* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).\n", - "\n", - "* Last one should be fairly obvious, passing mutable object (like `list` ) results in a call by reference, whereas an immutable object (like `int`) results in a call by value.\n", - "\n", - "* Being aware of these nitpicks can save you hours of debugging effort in the long run. \n", + "Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)?\n", "\n" ] }, @@ -9064,31 +10361,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Splitsies *\n" + "#### \ud83d\udca1 Explanation:\n", + "+ The `__future__` module is normally used to provide features from future versions of Python. The \"future\" in this specific context is however, ironic.\n", + "+ This is an easter egg concerned with the community's feelings on this issue.\n", + "+ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file.\n", + "+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement.\n", + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['a']\n", - "\n", - "# is same as\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "'a'.split()\n" + "### \u25b6 Let's meet Friendly Language Uncle For Life\n", + "**Output (Python 3.x)**\n" ] }, { @@ -9101,9 +10387,11 @@ { "data": { "text/plain": [ - "['a']\n", - "\n", - "# but\n" + " File \"some_file.py\", line 1\n", + " \"Ruby\" != \"Python\"\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n" ] }, "output_type": "execute_result", @@ -9112,7 +10400,8 @@ } ], "source": [ - "'a'.split(' ')\n" + "from __future__ import barry_as_FLUFL\n", + "\"Ruby\" != \"Python\" # there's no doubt about it\n" ] }, { @@ -9125,9 +10414,7 @@ { "data": { "text/plain": [ - "0\n", - "\n", - "# isn't the same as\n" + "True\n" ] }, "output_type": "execute_result", @@ -9136,7 +10423,29 @@ } ], "source": [ - "len(''.split())\n" + "\"Ruby\" <> \"Python\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "There we go.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means).\n", + "- Quoting from the PEP-401\n", + " \n", + " > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.\n", + "- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/).\n", + "- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working,\n" ] }, { @@ -9148,9 +10457,7 @@ "outputs": [ { "data": { - "text/plain": [ - "1\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -9158,7 +10465,8 @@ } ], "source": [ - "len(''.split(' '))\n" + " from __future__ import barry_as_FLUFL\n", + " print(eval('\"Ruby\" <> \"Python\"'))\n" ] }, { @@ -9172,12 +10480,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split)\n", - " > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.\n", - " > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.\n", - "- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,\n" + "### \u25b6 Even Python understands that love is complicated\n" ] }, { @@ -9189,9 +10492,7 @@ "outputs": [ { "data": { - "text/plain": [ - " ['', 'a', '']\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -9199,7 +10500,43 @@ } ], "source": [ - " ' a '.split(' ')\n" + "import this\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Wait, what's **this**? `this` is love :heart:\n", + "\n", + "**Output:**\n", + "```\n", + "The Zen of Python, by Tim Peters\n", + "\n", + "Beautiful is better than ugly.\n", + "Explicit is better than implicit.\n", + "Simple is better than complex.\n", + "Complex is better than complicated.\n", + "Flat is better than nested.\n", + "Sparse is better than dense.\n", + "Readability counts.\n", + "Special cases aren't special enough to break the rules.\n", + "Although practicality beats purity.\n", + "Errors should never pass silently.\n", + "Unless explicitly silenced.\n", + "In the face of ambiguity, refuse the temptation to guess.\n", + "There should be one-- and preferably only one --obvious way to do it.\n", + "Although that way may not be obvious at first unless you're Dutch.\n", + "Now is better than never.\n", + "Although never is often better than *right* now.\n", + "If the implementation is hard to explain, it's a bad idea.\n", + "If the implementation is easy to explain, it may be a good idea.\n", + "Namespaces are one honking great idea -- let's do more of those!\n", + "```\n", + "\n", + "It's the Zen of Python!\n", + "\n" ] }, { @@ -9212,7 +10549,7 @@ { "data": { "text/plain": [ - " ['a']\n" + "True\n" ] }, "output_type": "execute_result", @@ -9221,7 +10558,8 @@ } ], "source": [ - " ' a '.split()\n" + "love = this\n", + "this is love\n" ] }, { @@ -9234,7 +10572,7 @@ { "data": { "text/plain": [ - " ['']\n" + "False\n" ] }, "output_type": "execute_result", @@ -9243,21 +10581,7 @@ } ], "source": [ - " ''.split(' ')\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 All sorted? *\n" + "love is True\n" ] }, { @@ -9279,8 +10603,7 @@ } ], "source": [ - "x = 7, 8, 9\n", - "sorted(x) == x\n" + "love is False\n" ] }, { @@ -9293,8 +10616,7 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "True\n" ] }, "output_type": "execute_result", @@ -9303,7 +10625,7 @@ } ], "source": [ - "sorted(x) == sorted(x)\n" + "love is not True or False\n" ] }, { @@ -9316,7 +10638,7 @@ { "data": { "text/plain": [ - "False\n" + "True\n" ] }, "output_type": "execute_result", @@ -9325,8 +10647,7 @@ } ], "source": [ - "y = reversed(x)\n", - "sorted(y) == sorted(y)\n" + "love is not True or False; love is love # Love is complicated\n" ] }, { @@ -9342,60 +10663,21 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. \n", - "\n", - "- ```py\n", - " >>> [] == tuple()\n", - " False\n", - " >>> x = 7, 8, 9\n", - " >>> type(x), type(sorted(x))\n", - " (tuple, list)\n", - " ```\n", - "\n", - "- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first.\n", - "\n", - "- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list.\n", + "* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)).\n", + "* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens).\n", + "* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators).\n", "\n" ] }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " ([7, 8, 9], [])\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - " x = 7, 8, 9\n", - " y = reversed(x)\n", - " sorted(y), sorted(y)\n" - ] - }, { "cell_type": "markdown", "metadata": {}, "source": [ + "### \u25b6 Yes, it exists!\n", + "**The `else` clause for loops.** One typical example might be:\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Midnight time doesn't exist?\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -9413,19 +10695,13 @@ } ], "source": [ - "from datetime import datetime\n", - "\n", - "midnight = datetime(2018, 1, 1, 0, 0)\n", - "midnight_time = midnight.time()\n", - "\n", - "noon = datetime(2018, 1, 1, 12, 0)\n", - "noon_time = noon.time()\n", - "\n", - "if midnight_time:\n", - " print(\"Time at midnight is\", midnight_time)\n", - "\n", - "if noon_time:\n", - " print(\"Time at noon is\", noon_time)\n" + " def does_exists_num(l, to_find):\n", + " for num in l:\n", + " if num == to_find:\n", + " print(\"Exists!\")\n", + " break\n", + " else:\n", + " print(\"Does not exist\")\n" ] }, { @@ -9433,8 +10709,7 @@ "metadata": {}, "source": [ "\n", - "**Output (< 3.5):**\n", - "\n" + "**Output:**\n" ] }, { @@ -9446,7 +10721,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "Exists!\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -9454,34 +10731,8 @@ } ], "source": [ - "('Time at noon is', datetime.time(12, 0))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The midnight time is not printed.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of \"empty.\"\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Okay Python, Can you make me fly?\n", - "Well, here you go\n", - "\n" + "some_list = [1, 2, 3, 4, 5]\n", + "does_exists_num(some_list, 4)\n" ] }, { @@ -9493,7 +10744,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "Does not exist\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -9501,7 +10754,7 @@ } ], "source": [ - "import antigravity\n" + "does_exists_num(some_list, -1)\n" ] }, { @@ -9509,52 +10762,33 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "Sshh... It's a super-secret.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "+ `antigravity` module is one of the few easter eggs released by Python developers.\n", - "+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python.\n", - "+ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).\n", + "**The `else` clause in exception handling.** An example,\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 `goto`, but why?\n" - ] - }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "from goto import goto, label\n", - "for i in range(9):\n", - " for j in range(9):\n", - " for k in range(9):\n", - " print(\"I am trapped, please rescue!\")\n", - " if k == 2:\n", - " goto .breakout # breaking out from a deeply nested loop\n", - "label .breakout\n", - "print(\"Freedom!\")\n" + "try:\n", + " pass\n", + "except:\n", + " print(\"Exception occurred!!!\")\n", + "else:\n", + " print(\"Try block executed successfully...\")\n" ] }, { @@ -9562,7 +10796,7 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 2.3):**\n" + "**Output:**\n" ] }, { @@ -9582,9 +10816,7 @@ } ], "source": [ - "I am trapped, please rescue!\n", - "I am trapped, please rescue!\n", - "Freedom!\n" + "Try block executed successfully...\n" ] }, { @@ -9599,47 +10831,16 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004.\n", - "- Current versions of Python do not have this module.\n", - "- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Brace yourself!\n", - "If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing,\n", + "- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a \"nobreak\" clause.\n", + "- `else` clause after a try block is also called \"completion clause\" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.\n", "\n" ] }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "from __future__ import braces\n" - ] - }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n" + "### \u25b6 Ellipsis *\n" ] }, { @@ -9653,44 +10854,22 @@ "data": { "text/plain": [] }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - " File \"some_file.py\", line 1\n", - " from __future__ import braces\n", - "SyntaxError: not a chance\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "#### \ud83d\udca1 Explanation:\n", - "+ The `__future__` module is normally used to provide features from future versions of Python. The \"future\" in this specific context is however, ironic.\n", - "+ This is an easter egg concerned with the community's feelings on this issue.\n", - "+ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file.\n", - "+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement.\n", - "\n" + "def some_func():\n", + " Ellipsis\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Let's meet Friendly Language Uncle For Life\n", - "**Output (Python 3.x)**\n" + "\n", + "**Output**\n" ] }, { @@ -9703,10 +10882,7 @@ { "data": { "text/plain": [ - " File \"some_file.py\", line 1\n", - " \"Ruby\" != \"Python\"\n", - " ^\n", - "SyntaxError: invalid syntax\n", + "# No output, No Error\n", "\n" ] }, @@ -9716,8 +10892,7 @@ } ], "source": [ - "from __future__ import barry_as_FLUFL\n", - "\"Ruby\" != \"Python\" # there's no doubt about it\n" + "some_func()\n" ] }, { @@ -9730,7 +10905,10 @@ { "data": { "text/plain": [ - "True\n" + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "NameError: name 'SomeRandomString' is not defined\n", + "\n" ] }, "output_type": "execute_result", @@ -9739,29 +10917,7 @@ } ], "source": [ - "\"Ruby\" <> \"Python\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "There we go.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means).\n", - "- Quoting from the PEP-401\n", - " \n", - " > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.\n", - "- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/).\n", - "- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working,\n" + "SomeRandomString\n" ] }, { @@ -9773,7 +10929,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "Ellipsis\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -9781,8 +10939,7 @@ } ], "source": [ - " from __future__ import barry_as_FLUFL\n", - " print(eval('\"Ruby\" <> \"Python\"'))\n" + "Ellipsis\n" ] }, { @@ -9796,7 +10953,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Even Python understands that love is complicated\n" + "#### \ud83d\udca1 Explanation\n", + "- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`.\n" ] }, { @@ -9808,7 +10966,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " Ellipsis\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -9816,43 +10976,16 @@ } ], "source": [ - "import this\n" + " ...\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "Wait, what's **this**? `this` is love :heart:\n", - "\n", - "**Output:**\n", - "```\n", - "The Zen of Python, by Tim Peters\n", - "\n", - "Beautiful is better than ugly.\n", - "Explicit is better than implicit.\n", - "Simple is better than complex.\n", - "Complex is better than complicated.\n", - "Flat is better than nested.\n", - "Sparse is better than dense.\n", - "Readability counts.\n", - "Special cases aren't special enough to break the rules.\n", - "Although practicality beats purity.\n", - "Errors should never pass silently.\n", - "Unless explicitly silenced.\n", - "In the face of ambiguity, refuse the temptation to guess.\n", - "There should be one-- and preferably only one --obvious way to do it.\n", - "Although that way may not be obvious at first unless you're Dutch.\n", - "Now is better than never.\n", - "Although never is often better than *right* now.\n", - "If the implementation is hard to explain, it's a bad idea.\n", - "If the implementation is easy to explain, it may be a good idea.\n", - "Namespaces are one honking great idea -- let's do more of those!\n", - "```\n", - "\n", - "It's the Zen of Python!\n", - "\n" + "- Eliipsis can be used for several purposes,\n", + " + As a placeholder for code that hasn't been written yet (just like `pass` statement)\n", + " + In slicing syntax to represent the full slices in remaining direction\n" ] }, { @@ -9865,7 +10998,17 @@ { "data": { "text/plain": [ - "True\n" + " array([\n", + " [\n", + " [0, 1],\n", + " [2, 3]\n", + " ],\n", + "\n", + " [\n", + " [4, 5],\n", + " [6, 7]\n", + " ]\n", + " ])\n" ] }, "output_type": "execute_result", @@ -9874,8 +11017,15 @@ } ], "source": [ - "love = this\n", - "this is love\n" + " import numpy as np\n", + " three_dimensional_array = np.arange(8).reshape(2, 2, 2)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions\n" ] }, { @@ -9888,7 +11038,8 @@ { "data": { "text/plain": [ - "False\n" + " array([[1, 3],\n", + " [5, 7]])\n" ] }, "output_type": "execute_result", @@ -9897,7 +11048,7 @@ } ], "source": [ - "love is True\n" + " three_dimensional_array[:,:,1]\n" ] }, { @@ -9910,7 +11061,8 @@ { "data": { "text/plain": [ - "False\n" + " array([[1, 3],\n", + " [5, 7]])\n" ] }, "output_type": "execute_result", @@ -9919,7 +11071,27 @@ } ], "source": [ - "love is False\n" + " three_dimensional_array[..., 1] # using Ellipsis.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`)\n", + " + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`))\n", + " + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the \"no argument passed\" and \"None value passed\" scenarios).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Inpinity\n", + "The spelling is intended. Please, don't submit a patch for this.\n", + "\n", + "**Output (Python 3.x):**\n" ] }, { @@ -9932,7 +11104,7 @@ { "data": { "text/plain": [ - "True\n" + "314159\n" ] }, "output_type": "execute_result", @@ -9941,7 +11113,8 @@ } ], "source": [ - "love is not True or False\n" + "infinity = float('infinity')\n", + "hash(infinity)\n" ] }, { @@ -9954,7 +11127,7 @@ { "data": { "text/plain": [ - "True\n" + "-314159\n" ] }, "output_type": "execute_result", @@ -9963,7 +11136,7 @@ } ], "source": [ - "love is not True or False; love is love # Love is complicated\n" + "hash(float('-inf'))\n" ] }, { @@ -9978,10 +11151,8 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "\n", - "* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)).\n", - "* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens).\n", - "* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators).\n", + "- Hash of infinity is 10\u2075 x \u03c0.\n", + "- Interestingly, the hash of `float('-inf')` is \"-10\u2075 x \u03c0\" in Python 3, whereas \"-10\u2075 x e\" in Python 2.\n", "\n" ] }, @@ -9989,9 +11160,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Yes, it exists!\n", - "**The `else` clause for loops.** One typical example might be:\n", - "\n" + "### \u25b6 Let's mangle\n", + "1\\.\n" ] }, { @@ -10011,13 +11181,10 @@ } ], "source": [ - " def does_exists_num(l, to_find):\n", - " for num in l:\n", - " if num == to_find:\n", - " print(\"Exists!\")\n", - " break\n", - " else:\n", - " print(\"Does not exist\")\n" + "class Yo(object):\n", + " def __init__(self):\n", + " self.__honey = True\n", + " self.bro = True\n" ] }, { @@ -10038,7 +11205,7 @@ { "data": { "text/plain": [ - "Exists!\n" + "True\n" ] }, "output_type": "execute_result", @@ -10047,8 +11214,7 @@ } ], "source": [ - "some_list = [1, 2, 3, 4, 5]\n", - "does_exists_num(some_list, 4)\n" + "Yo().bro\n" ] }, { @@ -10061,7 +11227,7 @@ { "data": { "text/plain": [ - "Does not exist\n" + "AttributeError: 'Yo' object has no attribute '__honey'\n" ] }, "output_type": "execute_result", @@ -10070,16 +11236,7 @@ } ], "source": [ - "does_exists_num(some_list, -1)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**The `else` clause in exception handling.** An example,\n", - "\n" + "Yo().__honey\n" ] }, { @@ -10091,7 +11248,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -10099,12 +11258,7 @@ } ], "source": [ - "try:\n", - " pass\n", - "except:\n", - " print(\"Exception occurred!!!\")\n", - "else:\n", - " print(\"Try block executed successfully...\")\n" + "Yo()._Yo__honey\n" ] }, { @@ -10112,7 +11266,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + "2\\.\n" ] }, { @@ -10132,31 +11286,42 @@ } ], "source": [ - "Try block executed successfully...\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "class Yo(object):\n", + " def __init__(self):\n", + " # Let's try something symmetrical this time\n", + " self.__honey__ = True\n", + " self.bro = True\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a \"nobreak\" clause.\n", - "- `else` clause after a try block is also called \"completion clause\" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.\n", - "\n" + "\n", + "**Output:**\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "### \u25b6 Ellipsis *\n" + "Yo().bro\n" ] }, { @@ -10168,7 +11333,11 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "AttributeError: 'Yo' object has no attribute '_Yo__honey__'\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -10176,8 +11345,7 @@ } ], "source": [ - "def some_func():\n", - " Ellipsis\n" + "Yo()._Yo__honey__\n" ] }, { @@ -10185,7 +11353,10 @@ "metadata": {}, "source": [ "\n", - "**Output**\n" + "Why did `Yo()._Yo__honey` work?\n", + "\n", + "3\\.\n", + "\n" ] }, { @@ -10197,10 +11368,7 @@ "outputs": [ { "data": { - "text/plain": [ - "# No output, No Error\n", - "\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -10208,7 +11376,19 @@ } ], "source": [ - "some_func()\n" + "_A__variable = \"Some value\"\n", + "\n", + "class A(object):\n", + " def some_func(self):\n", + " return __variable # not initialized anywhere yet\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -10223,7 +11403,7 @@ "text/plain": [ "Traceback (most recent call last):\n", " File \"\", line 1, in \n", - "NameError: name 'SomeRandomString' is not defined\n", + "AttributeError: 'A' object has no attribute '__variable'\n", "\n" ] }, @@ -10233,7 +11413,7 @@ } ], "source": [ - "SomeRandomString\n" + "A().__variable\n" ] }, { @@ -10246,7 +11426,7 @@ { "data": { "text/plain": [ - "Ellipsis\n" + "'Some value'\n" ] }, "output_type": "execute_result", @@ -10255,13 +11435,14 @@ } ], "source": [ - "Ellipsis\n" + "A().some_func()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", "\n" ] }, @@ -10269,8 +11450,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", - "- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`.\n" + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.\n", + "* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a \"dunder\") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front.\n", + "* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class.\n", + "* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores.\n", + "* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope.\n", + "* Also, if the mangled name is longer than 255 characters, truncation will happen.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Skipping lines?\n", + "**Output:**\n" ] }, { @@ -10283,7 +11479,7 @@ { "data": { "text/plain": [ - " Ellipsis\n" + "11\n" ] }, "output_type": "execute_result", @@ -10292,16 +11488,30 @@ } ], "source": [ - " ...\n" + "value = 11\n", + "valu\u0435 = 32\n", + "value\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "- Eliipsis can be used for several purposes,\n", - " + As a placeholder for code that hasn't been written yet (just like `pass` statement)\n", - " + In slicing syntax to represent the full slices in remaining direction\n" + "\n", + "Wut?\n", + "\n", + "**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter.\n", + "\n" ] }, { @@ -10314,17 +11524,7 @@ { "data": { "text/plain": [ - " array([\n", - " [\n", - " [0, 1],\n", - " [2, 3]\n", - " ],\n", - "\n", - " [\n", - " [4, 5],\n", - " [6, 7]\n", - " ]\n", - " ])\n" + "1077\n" ] }, "output_type": "execute_result", @@ -10333,15 +11533,29 @@ } ], "source": [ - " import numpy as np\n", - " three_dimensional_array = np.arange(8).reshape(2, 2, 2)\n" + "ord('\u0435') # cyrillic 'e' (Ye)\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "101\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - " So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions\n" + "ord('e') # latin 'e', as used in English and typed using standard keyboard\n" ] }, { @@ -10354,8 +11568,8 @@ { "data": { "text/plain": [ - " array([[1, 3],\n", - " [5, 7]])\n" + "False\n", + "\n" ] }, "output_type": "execute_result", @@ -10364,7 +11578,7 @@ } ], "source": [ - " three_dimensional_array[:,:,1]\n" + "'\u0435' == 'e'\n" ] }, { @@ -10377,8 +11591,7 @@ { "data": { "text/plain": [ - " array([[1, 3],\n", - " [5, 7]])\n" + "42\n" ] }, "output_type": "execute_result", @@ -10387,16 +11600,17 @@ } ], "source": [ - " three_dimensional_array[..., 1] # using Ellipsis.\n" + "value = 42 # latin e\n", + "valu\u0435 = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here\n", + "value\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`)\n", - " + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`))\n", - " + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the \"no argument passed\" and \"None value passed\" scenarios).\n", + "\n", + "The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example.\n", "\n" ] }, @@ -10404,10 +11618,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Inpinity\n", - "The spelling is intended. Please, don't submit a patch for this.\n", - "\n", - "**Output (Python 3.x):**\n" + "### \u25b6 Teleportation\n" ] }, { @@ -10419,9 +11630,7 @@ "outputs": [ { "data": { - "text/plain": [ - "314159\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -10429,8 +11638,24 @@ } ], "source": [ - "infinity = float('infinity')\n", - "hash(infinity)\n" + "# `pip install numpy` first.\n", + "import numpy as np\n", + "\n", + "def energy_send(x):\n", + " # Initializing a numpy array\n", + " np.array([float(x)])\n", + "\n", + "def energy_receive():\n", + " # Return an empty numpy array\n", + " return np.empty((), dtype=np.float).tolist()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -10443,7 +11668,7 @@ { "data": { "text/plain": [ - "-314159\n" + "123.456\n" ] }, "output_type": "execute_result", @@ -10452,13 +11677,16 @@ } ], "source": [ - "hash(float('-inf'))\n" + "energy_send(123.456)\n", + "energy_receive()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "Where's the Nobel Prize?\n", "\n" ] }, @@ -10467,8 +11695,9 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "- Hash of infinity is 10\u2075 x \u03c0.\n", - "- Interestingly, the hash of `float('-inf')` is \"-10\u2075 x \u03c0\" in Python 3, whereas \"-10\u2075 x e\" in Python 2.\n", + "\n", + "* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate.\n", + "* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always).\n", "\n" ] }, @@ -10476,8 +11705,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Let's mangle\n", - "1\\.\n" + "### \u25b6 Well, something is fishy...\n" ] }, { @@ -10497,10 +11725,14 @@ } ], "source": [ - "class Yo(object):\n", - " def __init__(self):\n", - " self.__honey = True\n", - " self.bro = True\n" + "def square(x):\n", + " \"\"\"\n", + " A simple function to calculate the square of a number by addition.\n", + " \"\"\"\n", + " sum_so_far = 0\n", + " for counter in range(x):\n", + " sum_so_far = sum_so_far + x\n", + " return sum_so_far\n" ] }, { @@ -10508,29 +11740,8 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "Yo().bro\n" + "**Output (Python 2.x):**\n", + "\n" ] }, { @@ -10543,7 +11754,7 @@ { "data": { "text/plain": [ - "AttributeError: 'Yo' object has no attribute '__honey'\n" + "10\n" ] }, "output_type": "execute_result", @@ -10552,37 +11763,34 @@ } ], "source": [ - "Yo().__honey\n" + "square(10)\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "Yo()._Yo__honey\n" + "\n", + "Shouldn't that be 100?\n", + "\n", + "**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "* **Don't mix tabs and spaces!** The character just preceding return is a \"tab\", and the code is indented by multiple of \"4 spaces\" elsewhere in the example.\n", + "* This is how Python handles tabs:\n", + " \n", + " > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>\n", + "* So the \"tab\" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.\n", + "* Python 3 is kind enough to throw an error for such cases automatically.\n", "\n", - "2\\.\n" + " **Output (Python 3.x):**\n" ] }, { @@ -10602,19 +11810,21 @@ } ], "source": [ - "class Yo(object):\n", - " def __init__(self):\n", - " # Let's try something symmetrical this time\n", - " self.__honey__ = True\n", - " self.bro = True\n" + " TabError: inconsistent use of tabs and spaces in indentation\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n" + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 `+=` is faster\n" ] }, { @@ -10627,8 +11837,8 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "0.25748300552368164\n", + "# using \"+=\", three strings:\n" ] }, "output_type": "execute_result", @@ -10637,7 +11847,8 @@ } ], "source": [ - "Yo().bro\n" + "# using \"+\", three strings:\n", + "timeit.timeit(\"s1 = s1 + s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" ] }, { @@ -10650,9 +11861,7 @@ { "data": { "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "AttributeError: 'Yo' object has no attribute '_Yo__honey__'\n" + "0.012188911437988281\n" ] }, "output_type": "execute_result", @@ -10661,50 +11870,30 @@ } ], "source": [ - "Yo()._Yo__honey__\n" + "timeit.timeit(\"s1 += s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "Why did `Yo()._Yo__honey` work?\n", - "\n", - "3\\.\n", "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "_A__variable = \"Some value\"\n", - "\n", - "class A(object):\n", - " def some_func(self):\n", - " return __variable # not initialized anywhere yet\n" + "#### \ud83d\udca1 Explanation:\n", + "+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n" + "### \u25b6 Let's make a giant string!\n" ] }, { @@ -10716,9 +11905,7 @@ "outputs": [ { "data": { - "text/plain": [ - "'Some value'\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -10726,44 +11913,44 @@ } ], "source": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "AttributeError: 'A' object has no attribute '__variable'\n", + "def add_string_with_plus(iters):\n", + " s = \"\"\n", + " for i in range(iters):\n", + " s += \"xyz\"\n", + " assert len(s) == 3*iters\n", "\n", - "A().some_func()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ + "def add_bytes_with_plus(iters):\n", + " s = b\"\"\n", + " for i in range(iters):\n", + " s += b\"xyz\"\n", + " assert len(s) == 3*iters\n", "\n", - "\n" + "def add_string_with_format(iters):\n", + " fs = \"{}\"*iters\n", + " s = fs.format(*([\"xyz\"]*iters))\n", + " assert len(s) == 3*iters\n", + "\n", + "def add_string_with_join(iters):\n", + " l = []\n", + " for i in range(iters):\n", + " l.append(\"xyz\")\n", + " s = \"\".join(l)\n", + " assert len(s) == 3*iters\n", + "\n", + "def convert_list_to_string(l, iters):\n", + " s = \"\".join(l)\n", + " assert len(s) == 3*iters\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", "\n", - "* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.\n", - "* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a \"dunder\") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front.\n", - "* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class.\n", - "* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores.\n", - "* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope.\n", - "* Also, if the mangled name is longer than 255 characters, truncation will happen.\n", + "**Output:**\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Skipping lines?\n", - "**Output:**\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -10774,7 +11961,7 @@ { "data": { "text/plain": [ - "11\n" + "124 \u00b5s \u00b1 4.73 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" ] }, "output_type": "execute_result", @@ -10783,30 +11970,12 @@ } ], "source": [ - "value = 11\n", - "valu\u0435 = 32\n", - "value\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Wut?\n", - "\n", - "**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation\n", + "# Executed in ipython shell using %timeit for better readability of results.\n", + "# You can also use the timeit module in normal python shell/scriptm=, example usage below\n", + "# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())\n", "\n", - "Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter.\n", - "\n" + "NUM_ITERS = 1000\n", + "%timeit -n1000 add_string_with_plus(NUM_ITERS)\n" ] }, { @@ -10819,7 +11988,7 @@ { "data": { "text/plain": [ - "1077\n" + "211 \u00b5s \u00b1 10.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10828,7 +11997,7 @@ } ], "source": [ - "ord('\u0435') # cyrillic 'e' (Ye)\n" + "%timeit -n1000 add_bytes_with_plus(NUM_ITERS)\n" ] }, { @@ -10841,7 +12010,7 @@ { "data": { "text/plain": [ - "101\n" + "61 \u00b5s \u00b1 2.18 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10850,7 +12019,7 @@ } ], "source": [ - "ord('e') # latin 'e', as used in English and typed using standard keyboard\n" + "%timeit -n1000 add_string_with_format(NUM_ITERS)\n" ] }, { @@ -10863,8 +12032,7 @@ { "data": { "text/plain": [ - "False\n", - "\n" + "117 \u00b5s \u00b1 3.21 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10873,7 +12041,7 @@ } ], "source": [ - "'\u0435' == 'e'\n" + "%timeit -n1000 add_string_with_join(NUM_ITERS)\n" ] }, { @@ -10886,7 +12054,7 @@ { "data": { "text/plain": [ - "42\n" + "10.1 \u00b5s \u00b1 1.06 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10895,9 +12063,8 @@ } ], "source": [ - "value = 42 # latin e\n", - "valu\u0435 = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here\n", - "value\n" + "l = [\"xyz\"]*NUM_ITERS\n", + "%timeit -n1000 convert_list_to_string(l, NUM_ITERS)\n" ] }, { @@ -10905,17 +12072,10 @@ "metadata": {}, "source": [ "\n", - "The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example.\n", + "Let's increase the number of iterations by a factor of 10.\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Teleportation\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -10925,7 +12085,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "1.26 ms \u00b1 76.8 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -10933,24 +12095,8 @@ } ], "source": [ - "# `pip install nump` first.\n", - "import numpy as np\n", - "\n", - "def energy_send(x):\n", - " # Initializing a numpy array\n", - " np.array([float(x)])\n", - "\n", - "def energy_receive():\n", - " # Return an empty numpy array\n", - " return np.empty((), dtype=np.float).tolist()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "NUM_ITERS = 10000\n", + "%timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time\n" ] }, { @@ -10963,7 +12109,7 @@ { "data": { "text/plain": [ - "123.456\n" + "6.82 ms \u00b1 134 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10972,35 +12118,7 @@ } ], "source": [ - "energy_send(123.456)\n", - "energy_receive()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Where's the Nobel Prize?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate.\n", - "* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Well, something is fishy...\n" + "%timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase\n" ] }, { @@ -11012,7 +12130,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "645 \u00b5s \u00b1 24.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -11020,23 +12140,7 @@ } ], "source": [ - "def square(x):\n", - " \"\"\"\n", - " A simple function to calculate the square of a number by addition.\n", - " \"\"\"\n", - " sum_so_far = 0\n", - " for counter in range(x):\n", - " sum_so_far = sum_so_far + x\n", - " return sum_so_far\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.x):**\n", - "\n" + "%timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase\n" ] }, { @@ -11049,7 +12153,7 @@ { "data": { "text/plain": [ - "10\n" + "1.17 ms \u00b1 7.25 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -11058,34 +12162,7 @@ } ], "source": [ - "square(10)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Shouldn't that be 100?\n", - "\n", - "**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation\n", - "\n", - "* **Don't mix tabs and spaces!** The character just preceding return is a \"tab\", and the code is indented by multiple of \"4 spaces\" elsewhere in the example.\n", - "* This is how Python handles tabs:\n", - " \n", - " > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>\n", - "* So the \"tab\" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.\n", - "* Python 3 is kind enough to throw an error for such cases automatically.\n", - "\n", - " **Output (Python 3.x):**\n" + "%timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase\n" ] }, { @@ -11097,7 +12174,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "86.3 \u00b5s \u00b1 2 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -11105,7 +12184,8 @@ } ], "source": [ - " TabError: inconsistent use of tabs and spaces in indentation\n" + "l = [\"xyz\"]*NUM_ITERS\n", + "%timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase\n" ] }, { @@ -11119,7 +12199,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 `+=` is faster\n" + "#### \ud83d\udca1 Explanation\n", + "- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces.\n", + "- Don't use `+` for generating long strings \u2014 In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function)\n", + "- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings).\n", + "- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.\n", + "- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + \"x\" + \"y\" + \"z\"` instead of `s += \"xyz\"`, the increase would have been quadratic.\n" ] }, { @@ -11132,8 +12217,7 @@ { "data": { "text/plain": [ - "0.25748300552368164\n", - "# using \"+=\", three strings:\n" + " 388 \u00b5s \u00b1 22.4 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -11142,8 +12226,13 @@ } ], "source": [ - "# using \"+\", three strings:\n", - "timeit.timeit(\"s1 = s1 + s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" + " def add_string_with_plus(iters):\n", + " s = \"\"\n", + " for i in range(iters):\n", + " s = s + \"x\" + \"y\" + \"z\"\n", + " assert len(s) == 3*iters\n", + "\n", + " %timeit -n100 add_string_with_plus(1000)\n" ] }, { @@ -11156,7 +12245,7 @@ { "data": { "text/plain": [ - "0.012188911437988281\n" + " 9 ms \u00b1 298 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" ] }, "output_type": "execute_result", @@ -11165,22 +12254,16 @@ } ], "source": [ - "timeit.timeit(\"s1 += s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + " %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.\n", + "- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which,\n", + " \n", + " > There should be one-- and preferably only one --obvious way to do it.\n", "\n" ] }, @@ -11188,7 +12271,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Let's make a giant string!\n" + "### \u25b6 Slowing down `dict` lookups *\n" ] }, { @@ -11208,33 +12291,8 @@ } ], "source": [ - "def add_string_with_plus(iters):\n", - " s = \"\"\n", - " for i in range(iters):\n", - " s += \"xyz\"\n", - " assert len(s) == 3*iters\n", - "\n", - "def add_bytes_with_plus(iters):\n", - " s = b\"\"\n", - " for i in range(iters):\n", - " s += b\"xyz\"\n", - " assert len(s) == 3*iters\n", - "\n", - "def add_string_with_format(iters):\n", - " fs = \"{}\"*iters\n", - " s = fs.format(*([\"xyz\"]*iters))\n", - " assert len(s) == 3*iters\n", - "\n", - "def add_string_with_join(iters):\n", - " l = []\n", - " for i in range(iters):\n", - " l.append(\"xyz\")\n", - " s = \"\".join(l)\n", - " assert len(s) == 3*iters\n", - "\n", - "def convert_list_to_string(l, iters):\n", - " s = \"\".join(l)\n", - " assert len(s) == 3*iters\n" + "some_dict = {str(i): 1 for i in range(1_000_000)}\n", + "another_dict = {str(i): 1 for i in range(1_000_000)}\n" ] }, { @@ -11242,8 +12300,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "**Output:**\n" ] }, { @@ -11256,7 +12313,7 @@ { "data": { "text/plain": [ - "124 \u00b5s \u00b1 4.73 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" + "28.6 ns \u00b1 0.115 ns per loop (mean \u00b1 std. dev. of 7 runs, 10000000 loops each)\n" ] }, "output_type": "execute_result", @@ -11265,12 +12322,7 @@ } ], "source": [ - "# Executed in ipython shell using %timeit for better readability of results.\n", - "# You can also use the timeit module in normal python shell/scriptm=, example usage below\n", - "# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())\n", - "\n", - "NUM_ITERS = 1000\n", - "%timeit -n1000 add_string_with_plus(NUM_ITERS)\n" + "%timeit some_dict['5']\n" ] }, { @@ -11283,7 +12335,8 @@ { "data": { "text/plain": [ - "211 \u00b5s \u00b1 10.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "37.2 ns \u00b1 0.265 ns per loop (mean \u00b1 std. dev. of 7 runs, 10000000 loops each)\n", + "\n" ] }, "output_type": "execute_result", @@ -11292,7 +12345,8 @@ } ], "source": [ - "%timeit -n1000 add_bytes_with_plus(NUM_ITERS)\n" + "some_dict[1] = 1\n", + "%timeit some_dict['5']\n" ] }, { @@ -11305,7 +12359,7 @@ { "data": { "text/plain": [ - "61 \u00b5s \u00b1 2.18 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "28.5 ns \u00b1 0.142 ns per loop (mean \u00b1 std. dev. of 7 runs, 10000000 loops each)\n" ] }, "output_type": "execute_result", @@ -11314,7 +12368,7 @@ } ], "source": [ - "%timeit -n1000 add_string_with_format(NUM_ITERS)\n" + "%timeit another_dict['5']\n" ] }, { @@ -11327,7 +12381,9 @@ { "data": { "text/plain": [ - "117 \u00b5s \u00b1 3.21 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "KeyError: 1\n" ] }, "output_type": "execute_result", @@ -11336,7 +12392,7 @@ } ], "source": [ - "%timeit -n1000 add_string_with_join(NUM_ITERS)\n" + "another_dict[1] # Trying to access a key that doesn't exist\n" ] }, { @@ -11349,7 +12405,7 @@ { "data": { "text/plain": [ - "10.1 \u00b5s \u00b1 1.06 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "38.5 ns \u00b1 0.0913 ns per loop (mean \u00b1 std. dev. of 7 runs, 10000000 loops each)\n" ] }, "output_type": "execute_result", @@ -11358,19 +12414,37 @@ } ], "source": [ - "l = [\"xyz\"]*NUM_ITERS\n", - "%timeit -n1000 convert_list_to_string(l, NUM_ITERS)\n" + "%timeit another_dict['5']\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Why are same lookups becoming slower?\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys.\n", + "+ The specialized function (named `lookdict_unicode` in CPython's [source](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method.\n", + "+ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function.\n", + "+ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary. That's why attempting a failed lookup has the same effect.\n", "\n", - "Let's increase the number of iterations by a factor of 10.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Bloating instance `dict`s *\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -11380,9 +12454,7 @@ "outputs": [ { "data": { - "text/plain": [ - "1.26 ms \u00b1 76.8 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -11390,8 +12462,27 @@ } ], "source": [ - "NUM_ITERS = 10000\n", - "%timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time\n" + "import sys\n", + "\n", + "class SomeClass:\n", + " def __init__(self):\n", + " self.some_attr1 = 1\n", + " self.some_attr2 = 2\n", + " self.some_attr3 = 3\n", + " self.some_attr4 = 4\n", + "\n", + "\n", + "def dict_size(o):\n", + " return sys.getsizeof(o.__dict__)\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:** (Python 3.8, other Python 3 versions may vary a little)\n" ] }, { @@ -11404,7 +12495,7 @@ { "data": { "text/plain": [ - "6.82 ms \u00b1 134 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "104\n" ] }, "output_type": "execute_result", @@ -11413,7 +12504,9 @@ } ], "source": [ - "%timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase\n" + "o1 = SomeClass()\n", + "o2 = SomeClass()\n", + "dict_size(o1)\n" ] }, { @@ -11426,7 +12519,7 @@ { "data": { "text/plain": [ - "645 \u00b5s \u00b1 24.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "104\n" ] }, "output_type": "execute_result", @@ -11435,7 +12528,7 @@ } ], "source": [ - "%timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase\n" + "dict_size(o2)\n" ] }, { @@ -11448,7 +12541,7 @@ { "data": { "text/plain": [ - "1.17 ms \u00b1 7.25 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "232\n" ] }, "output_type": "execute_result", @@ -11457,7 +12550,9 @@ } ], "source": [ - "%timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase\n" + "del o1.some_attr1\n", + "o3 = SomeClass()\n", + "dict_size(o3)\n" ] }, { @@ -11470,7 +12565,7 @@ { "data": { "text/plain": [ - "86.3 \u00b5s \u00b1 2 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "232\n" ] }, "output_type": "execute_result", @@ -11479,27 +12574,40 @@ } ], "source": [ - "l = [\"xyz\"]*NUM_ITERS\n", - "%timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase\n" + "dict_size(o1)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "Let's try again... In a new interpreter:\n", "\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "104 # as expected\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "#### \ud83d\udca1 Explanation\n", - "- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces.\n", - "- Don't use `+` for generating long strings \u2014 In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function)\n", - "- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings).\n", - "- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.\n", - "- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + \"x\" + \"y\" + \"z\"` instead of `s += \"xyz\"`, the increase would have been quadratic.\n" + "o1 = SomeClass()\n", + "o2 = SomeClass()\n", + "dict_size(o1)\n" ] }, { @@ -11512,7 +12620,7 @@ { "data": { "text/plain": [ - " 388 \u00b5s \u00b1 22.4 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "360\n" ] }, "output_type": "execute_result", @@ -11521,13 +12629,9 @@ } ], "source": [ - " def add_string_with_plus(iters):\n", - " s = \"\"\n", - " for i in range(iters):\n", - " s = s + \"x\" + \"y\" + \"z\"\n", - " assert len(s) == 3*iters\n", - "\n", - " %timeit -n100 add_string_with_plus(1000)\n" + "o1.some_attr5 = 5\n", + "o1.some_attr6 = 6\n", + "dict_size(o1)\n" ] }, { @@ -11540,7 +12644,7 @@ { "data": { "text/plain": [ - " 9 ms \u00b1 298 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" + "272\n" ] }, "output_type": "execute_result", @@ -11549,16 +12653,52 @@ } ], "source": [ - " %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time\n" + "dict_size(o2)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "232\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "o3 = SomeClass()\n", + "dict_size(o3)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which,\n", - " \n", - " > There should be one-- and preferably only one --obvious way to do it.\n", + "\n", + "What makes those dictionaries become bloated? And why are newly created objects bloated as well?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ CPython is able to reuse the same \"keys\" object in multiple dictionaries. This was added in [PEP 412](https://www.python.org/dev/peps/pep-0412/) with the motivation to reduce memory usage, specifically in dictionaries of instances - where keys (instance attributes) tend to be common to all instances.\n", + "+ This optimization is entirely seamless for instance dictionaries, but it is disabled if certain assumptions are broken.\n", + "+ Key-sharing dictionaries do not support deletion; if an instance attribute is deleted, the dictionary is \"unshared\", and key-sharing is disabled for all future instances of the same class.\n", + "+ Additionaly, if the dictionary keys have be resized (because new keys are inserted), they are kept shared *only* if they are used by a exactly single dictionary (this allows adding many attributes in the `__init__` of the very first created instance, without causing an \"unshare\"). If multiple instances exist when a resize happens, key-sharing is disabled for all future instances of the same class: CPython can't tell if your instances are using the same set of attributes anymore, and decides to bail out on attempting to share their keys.\n", + "+ A small tip, if you aim to lower your program's memory footprint: don't delete instance attributes, and make sure to initialize all attributes in your `__init__`!\n", + "\n", "\n" ] }, @@ -11636,7 +12776,7 @@ " ```py\n", " >>> some_string = \"wtfpython\"\n", " >>> f'{some_string=}'\n", - " \"string='wtfpython'\"\n", + " \"some_string='wtfpython'\"\n", " ``` \n", "\n", "* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!):\n", @@ -11653,7 +12793,7 @@ " print(dis.dis(f))\n", " ```\n", " \n", - "* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module.\n", + "* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) module.\n", "\n", "* Sometimes, the `print` method might not print values immediately. For example,\n", "\n", @@ -11665,7 +12805,7 @@ " time.sleep(3)\n", " ```\n", "\n", - " This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument.\n", + " This will print the `wtfpython` after 3 seconds due to the `end` argument because the output buffer is flushed either after encountering `\\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument.\n", "\n", "* List slicing with out of the bounds indices throws no errors\n", " ```py\n", @@ -11684,7 +12824,7 @@ " True\n", " ```\n", "\n", - "* `int('\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.\n", + "* `int('\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.\n", "\n", "* You can separate numeric literals with underscores (for better readability) from Python 3 onwards.\n", "\n", @@ -11706,8 +12846,6 @@ " return result\n", " ```\n", " The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string.\n", - "\n", - "**That's all folks!**\n", "\n" ] }, @@ -11760,6 +12898,17 @@ "source": [ "```py\n", ">>> (a := \"wtf_walrus\") # This works though\n", + "```\n", + "```py\n", + "'wtf_walrus'\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", ">>> a\n", "```\n", "```py\n", @@ -11798,6 +12947,17 @@ "source": [ "```py\n", ">>> (a := 6, 9)\n", + "```\n", + "```py\n", + "(6, 9)\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", ">>> a\n", "```\n", "```py\n", @@ -11954,7 +13114,7 @@ "\n", "- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. \n", "\n", - "- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", + "- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", "\n", " - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6')\n", "\n" @@ -12055,7 +13215,7 @@ "metadata": {}, "source": [ "\n", - "Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.\n", + "Phew, deleted at last. You might have guessed what saved `__del__` from being called in our first attempt to delete `x`. Let's add more twists to the example.\n", "\n", "2\\.\n" ] @@ -12104,9 +13264,9 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "+ `del x` doesn\u2019t directly call `x.__del__()`.\n", - "+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x\u2019s reference count reaches zero.\n", - "+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.\n", - "+ Calling `globals` caused the existing reference to be destroyed, and hence we can see \"Deleted!\" being printed (finally!).\n", + "+ When `del x` is encountered, Python deletes the name `x` from current scope and decrements by 1 the reference count of the object `x` referenced. `__del__()` is called only when the object's reference count reaches zero.\n", + "+ In the second output snippet, `__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object (specifically, the `_` magic variable which references the result value of the last non `None` expression on the REPL), thus preventing the reference count from reaching zero when `del y` was encountered.\n", + "+ Calling `globals` (or really, executing anything that will have a non `None` result) caused `_` to reference the new result, dropping the existing reference. Now the reference count reached 0 and we can see \"Deleted!\" being printed (finally!).\n", "\n" ] }, @@ -12184,7 +13344,7 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime.\n", + "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore don't get imported. This may lead to errors during runtime.\n", "- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred.\n" ] }, @@ -12298,6 +13458,7 @@ "* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator\n", "* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65\n", "* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues\n", + "* WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/).\n", "\n", "# \ud83c\udf93 License\n", "\n", From de4b851c72f97d58303a3a09d3a519dc261aa850 Mon Sep 17 00:00:00 2001 From: abdo Date: Wed, 3 Feb 2021 02:01:07 +0300 Subject: [PATCH 196/221] Fix typo getclosurevals -> getclosurevars --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 27ed3ab6..9cadd2af 100644 --- a/README.md +++ b/README.md @@ -1027,7 +1027,7 @@ The values of `x` were different in every iteration prior to appending `some_fun * When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the *variable*, not its *value*. The function looks up `x` in the surrounding context, rather than using the value of `x` at the time the function is created. So all of the functions use the latest value assigned to the variable for computation. We can see that it's using the `x` from the surrounding context (i.e. *not* a local variable) with: ```py >>> import inspect ->>> inspect.getclosurevals(funcs[0]) +>>> inspect.getclosurevars(funcs[0]) ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) ``` Since `x` is a global value, we can change the value that the `funcs` will lookup and return by updating `x`: From 9d0ad9ed98f372f2ad7ae74f4d8e6c50386a5398 Mon Sep 17 00:00:00 2001 From: Umutambyi Gad Date: Sun, 14 Feb 2021 00:55:41 +0100 Subject: [PATCH 197/221] =?UTF-8?q?=F0=9F=93=9D=20Fixed=20simple=20typos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9cadd2af..c6d80b69 100644 --- a/README.md +++ b/README.md @@ -2135,7 +2135,7 @@ UnboundLocalError: local variable 'a' referenced before assignment >>> another_func() 2 ``` -* The keywords `global` and `nonlocal` tell the python interpreter to not delcare new variables and look them up in the corresponding outer scopes. +* The keywords `global` and `nonlocal` tell the python interpreter to not declare new variables and look them up in the corresponding outer scopes. * Read [this](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. --- @@ -3114,7 +3114,7 @@ Ellipsis >>> ... Ellipsis ``` -- Eliipsis can be used for several purposes, +- Ellipsis can be used for several purposes, + As a placeholder for code that hasn't been written yet (just like `pass` statement) + In slicing syntax to represent the full slices in remaining direction ```py From f0bd1cb481947a81a5ea164aa333d5224f194702 Mon Sep 17 00:00:00 2001 From: Chris Milson Date: Thu, 18 Feb 2021 19:05:40 +0900 Subject: [PATCH 198/221] Update explanation for All-true-ation #255 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c6d80b69..7f48185c 100644 --- a/README.md +++ b/README.md @@ -1273,8 +1273,8 @@ Why's this True-False alteration? ``` - `all([])` returns `True` since the iterable is empty. -- `all([[]])` returns `False` because `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty. -- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`. +- `all([[]])` returns `False` because the passed array has one element, `[]`, and in python, an empty list is falsy. +- `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. --- From 6e187cf84b3c23c4fc872b0d99b648d3b3d229ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20De=20Freitas?= <37962411+JoseDeFreitas@users.noreply.github.com> Date: Wed, 24 Feb 2021 19:49:05 -0500 Subject: [PATCH 199/221] Add Spanish translation reference --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f48185c..9a74ca37 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [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].) +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://github.com/JoseDeFreitas/wtfpython-es) | [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].) Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From 95a87484c5bb3108f2682cdc425892998d5b83d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20De=20Freitas?= <37962411+JoseDeFreitas@users.noreply.github.com> Date: Wed, 24 Feb 2021 19:50:43 -0500 Subject: [PATCH 200/221] Add myself as contributors --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 28c38901..3048c51a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -33,6 +33,7 @@ Following are the wonderful people (in no specific order) who have contributed t |-------------|--------|--------| | leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [Chinese](https://github.com/leisurelicht/wtfpython-cn) | | vuduclyunitn | [vuduclyunitn](https://github.com/vuduclyunitn) | [Vietnamese](https://github.com/vuduclyunitn/wtfptyhon-vi) | +| José De Freitas | [JoseDeFreitas](https://github.com/JoseDeFreitas) | [Spanish](https://github.com/JoseDeFreitas/wtfpython-es) | Thank you all for your time and making wtfpython more awesome! :smile: From 552559160155eedca639ccbf30e7edfbe05f51f5 Mon Sep 17 00:00:00 2001 From: Sam Benner Date: Wed, 7 Apr 2021 18:46:23 -0500 Subject: [PATCH 201/221] Fix small typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9a74ca37..a22136ef 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,7 @@ SyntaxError: invalid syntax (6, 9) >>> (a, b = 16, 19) # Oops File "", line 1 - (a, b = 6, 9) + (a, b = 16, 19) ^ SyntaxError: invalid syntax From aaa74c46a717ffe2b375b9838f29edd3281a9bd9 Mon Sep 17 00:00:00 2001 From: sonlhcsuit Date: Wed, 28 Apr 2021 16:10:51 +0700 Subject: [PATCH 202/221] fixthings up --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a22136ef..f6182118 100644 --- a/README.md +++ b/README.md @@ -918,7 +918,7 @@ array_4 = [400, 500, 600] - 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. - In the first case, `array_1` is binded 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). - 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]`). -- Okay, going by the logic discussed so far, shouldn't be the value of `list(g)` 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://www.python.org/dev/peps/pep-0289/#the-details) +- 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://www.python.org/dev/peps/pep-0289/#the-details) > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run. From 6642876c640d5d4b06c1397d52f2074ef8dc0288 Mon Sep 17 00:00:00 2001 From: LiquidFun Date: Mon, 10 May 2021 00:20:29 +0200 Subject: [PATCH 203/221] Add new snippet: banker's rounding Closes #267 --- CONTRIBUTORS.md | 1 + README.md | 53 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 3048c51a..ca0e88a2 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -24,6 +24,7 @@ Following are the wonderful people (in no specific order) who have contributed t | Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208), [#210](https://github.com/satwikkansal/wtfpython/issues/210), [#233](https://github.com/satwikkansal/wtfpython/issues/233) | | Diptangsu Goswami | [diptangsu](https://github.com/diptangsu) | [#193](https://github.com/satwikkansal/wtfpython/issues/193) | | Charles | [charles-l](https://github.com/charles-l) | [#245](https://github.com/satwikkansal/wtfpython/issues/245) +| LiquidFun | [LiquidFun](https://github.com/LiquidFun) | [#267](https://github.com/satwikkansal/wtfpython/issues/267) --- diff --git a/README.md b/README.md index f6182118..f015a13b 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,7 @@ So, here we go... + [▶ Catching the Exceptions](#-catching-the-exceptions) + [▶ Same operands, different story!](#-same-operands-different-story) + [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) + + [▶ Rounding like a banker *](#-rounding-like-a-banker-) + [▶ Needles in a Haystack *](#-needles-in-a-haystack-) + [▶ Splitsies *](#-splitsies-) + [▶ Wild imports *](#-wild-imports-) @@ -2532,6 +2533,58 @@ class SomeClass: --- +### ▶ Rounding like a banker * + +Let's implement a naive function to get the middle element of a list: +```py +def get_middle(some_list): + mid_index = round(len(some_list) / 2) + return some_list[mid_index - 1] +``` + +**Python 3.x:** +```py +>>> get_middle([1]) # looks good +1 +>>> get_middle([1,2,3]) # looks good +2 +>>> get_middle([1,2,3,4,5]) # huh? +2 +>>> len([1,2,3,4,5]) / 2 # good +2.5 +>>> round(len([1,2,3,4,5]) / 2) # why? +2 +``` +It seems as though Python rounded 2.5 to 2. + +#### 💡 Explanation: + +This is not a float precision error, in fact, this behavior is intentional. Since Python 3.0, `round()` uses [banker's rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even) where .5 fractions are rounded to the nearest **even** number: + +```py +>>> round(0.5) +0 +>>> round(1.5) +2 +>>> round(2.5) +2 +>>> import numpy # numpy does the same +>>> numpy.round(0.5) +0.0 +>>> numpy.round(1.5) +2.0 +>>> numpy.round(2.5) +2.0 +``` + +This is the recommended way to round .5 fractions as described in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules). However, the other way (round away from zero) is taught in school most of the time, so banker's rounding is likely not that well known. Furthermore, some of the most popular programming languages (for example: JavaScript, Java, C/C++, Ruby, Rust) do not use banker's rounding either. Therefore, this is still quite special to Python and may result in confusion when rounding fractions. + +See the [round() docs](https://docs.python.org/3/library/functions.html#round) or [this stackoverflow thread](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) for more information. + +Note that `get_middle([1])` only returned 1 because the index was `round(0.5) - 1 = 0 - 1 = -1`, returning the last element in the list. + +--- + ### ▶ Needles in a Haystack * From 9fc6db6215cd2773b4fed4fcf1a69fbe172a4b4c Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Tue, 11 May 2021 02:04:55 +0530 Subject: [PATCH 204/221] Minor formatting fix --- README.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f015a13b..955aab8b 100644 --- a/README.md +++ b/README.md @@ -2559,7 +2559,7 @@ It seems as though Python rounded 2.5 to 2. #### 💡 Explanation: -This is not a float precision error, in fact, this behavior is intentional. Since Python 3.0, `round()` uses [banker's rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even) where .5 fractions are rounded to the nearest **even** number: +- This is not a float precision error, in fact, this behavior is intentional. Since Python 3.0, `round()` uses [banker's rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even) where .5 fractions are rounded to the nearest **even** number: ```py >>> round(0.5) @@ -2577,11 +2577,9 @@ This is not a float precision error, in fact, this behavior is intentional. Sinc 2.0 ``` -This is the recommended way to round .5 fractions as described in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules). However, the other way (round away from zero) is taught in school most of the time, so banker's rounding is likely not that well known. Furthermore, some of the most popular programming languages (for example: JavaScript, Java, C/C++, Ruby, Rust) do not use banker's rounding either. Therefore, this is still quite special to Python and may result in confusion when rounding fractions. - -See the [round() docs](https://docs.python.org/3/library/functions.html#round) or [this stackoverflow thread](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) for more information. - -Note that `get_middle([1])` only returned 1 because the index was `round(0.5) - 1 = 0 - 1 = -1`, returning the last element in the list. +- This is the recommended way to round .5 fractions as described in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules). However, the other way (round away from zero) is taught in school most of the time, so banker's rounding is likely not that well known. Furthermore, some of the most popular programming languages (for example: JavaScript, Java, C/C++, Ruby, Rust) do not use banker's rounding either. Therefore, this is still quite special to Python and may result in confusion when rounding fractions. +- See the [round() docs](https://docs.python.org/3/library/functions.html#round) or [this stackoverflow thread](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) for more information. +- Note that `get_middle([1])` only returned 1 because the index was `round(0.5) - 1 = 0 - 1 = -1`, returning the last element in the list. --- From 086be4ed19cad2782f8a2e5ff84423821225fa61 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Wed, 12 May 2021 00:19:21 +0530 Subject: [PATCH 205/221] Update CONTRIBUTING.md --- CONTRIBUTING.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f774370a..dd9049d4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,3 +40,24 @@ Few things that you can consider while writing an example, - Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's no strictly enforced scheme in the project as such, but you can take a glance at other examples to get a gist. - Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write. - Also, feel free to add your name to the [contributors list](/CONTRIBUTORS.md). + +**Some FAQs** + + What is is this after every snippet title (###) in the README: ? Should it be added manually or can it be ignored when creating new snippets? + +That's a random UUID, it is used to keep identify the examples across multiple translations of the project. As a contributor, you don't have to worry about behind the scenes of how it is used, you just have to add a new random UUID to new examples in that format. + + Where should new snippets be added? Top/bottom of the section, doesn't ? + +There are multiple things that are considered to decide the order (the dependency on the other examples, difficulty level, category, etc). I'd suggest simply adding the new example at the bottom of a section you find more fitting (or just add it to the Miscellaneous section). Its order will be taken care of in future revisions. + + What's the difference between the sections (the first two feel very similar)? + +The section "Strain your brain" contains more contrived examples that you may not really encounter in real life, whereas the section "Slippery Slopes" contains examples that have the potential to be encountered more frequently while programming. + + Before the table of contents it says that markdown-toc -i README.md --maxdepth 3 was used to create it. The pip package markdown-toc does not contain either -i or --maxdepth flags. Which package is meant, or what version of that package? + Should the new table of contents entry for the snippet be created with the above command or created manually (in case the above command does more than only add the entry)? + +We use the [markdown-toc](https://www.npmjs.com/package/markdown-toc) npm package to generate ToC. It has some issues with special characters though (I'm not sure if it's fixed yet). More often than not, I just end up inserting the toc link manually at the right place. The tool is handy when I have to big reordering, otherwise just updating toc manually is more convenient imo. + +If you have any questions feel free to ask on [this issue](https://github.com/satwikkansal/wtfpython/issues/269) (thanks to [@LiquidFun](https://github.com/LiquidFun) for starting it). From 2e2d65a9ec63906fbc3b0b10b8c8892c090adc0d Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 9 Aug 2021 18:13:25 +0530 Subject: [PATCH 206/221] Add reference to Korean translation and fix a typo Closes https://github.com/satwikkansal/wtfpython/issues/271 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 955aab8b..cb9c6842 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://github.com/JoseDeFreitas/wtfpython-es) | [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].) +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [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].) Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) @@ -3610,7 +3610,7 @@ What makes those dictionaries become bloated? And why are newly created objects + CPython is able to reuse the same "keys" object in multiple dictionaries. This was added in [PEP 412](https://www.python.org/dev/peps/pep-0412/) with the motivation to reduce memory usage, specifically in dictionaries of instances - where keys (instance attributes) tend to be common to all instances. + This optimization is entirely seamless for instance dictionaries, but it is disabled if certain assumptions are broken. + Key-sharing dictionaries do not support deletion; if an instance attribute is deleted, the dictionary is "unshared", and key-sharing is disabled for all future instances of the same class. -+ Additionaly, if the dictionary keys have be resized (because new keys are inserted), they are kept shared *only* if they are used by a exactly single dictionary (this allows adding many attributes in the `__init__` of the very first created instance, without causing an "unshare"). If multiple instances exist when a resize happens, key-sharing is disabled for all future instances of the same class: CPython can't tell if your instances are using the same set of attributes anymore, and decides to bail out on attempting to share their keys. ++ Additionaly, if the dictionary keys have been resized (because new keys are inserted), they are kept shared *only* if they are used by a exactly single dictionary (this allows adding many attributes in the `__init__` of the very first created instance, without causing an "unshare"). If multiple instances exist when a resize happens, key-sharing is disabled for all future instances of the same class: CPython can't tell if your instances are using the same set of attributes anymore, and decides to bail out on attempting to share their keys. + A small tip, if you aim to lower your program's memory footprint: don't delete instance attributes, and make sure to initialize all attributes in your `__init__`! From 043b83a7223d64728292c5de3cd05cc22e5fab58 Mon Sep 17 00:00:00 2001 From: bwduncan Date: Fri, 29 Oct 2021 20:52:07 +0100 Subject: [PATCH 207/221] Minor README fixups --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index cb9c6842..e9f33c61 100644 --- a/README.md +++ b/README.md @@ -449,7 +449,7 @@ True ```py >>> a, b = 257, 257 ->> a is b +>>> a is b False ``` @@ -917,7 +917,7 @@ array_4 = [400, 500, 600] - In a [generator](https://wiki.python.org/moin/Generators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at runtime. - 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`. - 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. -- In the first case, `array_1` is binded 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). +- 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). - 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]`). - 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://www.python.org/dev/peps/pep-0289/#the-details) @@ -1841,9 +1841,9 @@ NameError: name 'e' is not defined **Output:** ```py - >>>f(x) + >>> f(x) UnboundLocalError: local variable 'x' referenced before assignment - >>>f(y) + >>> f(y) UnboundLocalError: local variable 'x' referenced before assignment >>> x 5 @@ -2753,7 +2753,7 @@ def similar_recursive_func(a): * As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). -* Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignation of an immutable (`a -= 1`) is not an alteration of the value. +* Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignment of an immutable (`a -= 1`) is not an alteration of the value. * Being aware of these nitpicks can save you hours of debugging effort in the long run. From 205c9ede019b0ed8194aee533c3e8ab72917be02 Mon Sep 17 00:00:00 2001 From: flencydoc Date: Thu, 23 Dec 2021 03:53:28 +0000 Subject: [PATCH 208/221] Added docstrings to several undocumented functions. --- irrelevant/notebook_generator.py | 43 +++++++++++++++++++++++++++++++ wtfpython-pypi/wtf_python/main.py | 4 +++ 2 files changed, 47 insertions(+) diff --git a/irrelevant/notebook_generator.py b/irrelevant/notebook_generator.py index d2755300..50e86d2e 100644 --- a/irrelevant/notebook_generator.py +++ b/irrelevant/notebook_generator.py @@ -55,6 +55,12 @@ def generate_code_block(statements, output): + """ + Generates a code block that executes the given statements. + + :param statements: The list of statements to execute. + :type statements: list(str) + """ global sequence_num result = { "type": "code", @@ -67,6 +73,9 @@ def generate_code_block(statements, output): def generate_markdown_block(lines): + """ + Generates a markdown block from a list of lines. + """ global sequence_num result = { "type": "markdown", @@ -85,6 +94,12 @@ def is_interactive_statement(line): def parse_example_parts(lines, title, current_line): + """ + Parse the given lines and return a dictionary with two keys: + build_up, which contains all the text before an H4 (explanation) is encountered, + and + explanation, which contains all the text after build_up until --- or another H3 is encountered. + """ parts = { "build_up": [], "explanation": [] @@ -191,6 +206,14 @@ def remove_from_beginning(tokens, line): def inspect_and_sanitize_code_lines(lines): + """ + Remove lines from the beginning of a code block that are not statements. + + :param lines: A list of strings, each representing a line in the code block. + :returns is_print_present, sanitized_lines: A boolean indicating whether print was present in the original code and a list of strings representing + sanitized lines. The latter may be an empty list if all input lines were removed as comments or whitespace (and thus did not contain any statements). + This function does not remove blank lines at the end of `lines`. + """ tokens_to_remove = STATEMENT_PREFIXES result = [] is_print_present = False @@ -203,6 +226,23 @@ def inspect_and_sanitize_code_lines(lines): def convert_to_cells(cell_contents, read_only): + """ + Converts a list of dictionaries containing markdown and code cells into a Jupyter notebook. + + :param cell_contents: A list of dictionaries, each + dictionary representing either a markdown or code cell. Each dictionary should have the following keys: "type", which is either "markdown" or "code", + and "value". The value for type = 'markdown' is the content as string, whereas the value for type = 'code' is another dictionary with two keys, + statements and output. The statements key contains all lines in between ```py\n``` (including) until ```\n```, while output contains all lines after + ```.output py\n```. + :type cell_contents: List[Dict] + + :param read_only (optional): If True then only print outputs are included in converted + cells. Default False + :type read_only (optional): bool + + :returns A Jupyter notebook containing all cells from input parameter `cell_contents`. + Each converted cell has metadata attribute collapsed set to true if it's code-cell otherwise None if it's markdow-cell. + """ cells = [] for stuff in cell_contents: if stuff["type"] == "markdown": @@ -269,6 +309,9 @@ def convert_to_cells(cell_contents, read_only): def convert_to_notebook(pre_examples_content, parsed_json, post_examples_content): + """ + Convert a JSON file containing the examples to a Jupyter Notebook. + """ result = { "cells": [], "metadata": {}, diff --git a/wtfpython-pypi/wtf_python/main.py b/wtfpython-pypi/wtf_python/main.py index bf768154..0c41d0cc 100644 --- a/wtfpython-pypi/wtf_python/main.py +++ b/wtfpython-pypi/wtf_python/main.py @@ -13,6 +13,10 @@ def fetch_updated_doc(): + """ + Fetch the latest version of the file at `url` and save it to `file_path`. + If anything goes wrong, do nothing. + """ try: print("Fetching the latest version...") urlretrieve(url, file_path) From cd4d7c0e340789bd001e5e9eae0e3c5bb7c7f7f1 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Tue, 18 Jan 2022 00:00:02 +0530 Subject: [PATCH 209/221] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9f33c61..ed45577a 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ All the examples are structured like below: # Usage -A nice way to get the most out of these examples, in my opinion, is to read them chronologically, and for every example: +A nice way to get the most out of these examples, in my opinion, is to read them in sequential order, and for every example: - 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. - Read the output snippets and, + Check if the outputs are the same as you'd expect. From 00c550371292ca481117d836a9565be14dc4b203 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 4 Apr 2022 16:02:41 +0530 Subject: [PATCH 210/221] Update link to Chinese translation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ed45577a..6c5ba669 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [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].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [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].) Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From fe9ed47217714e38e527c7b205f458e23c8b3b87 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Wed, 11 May 2022 22:27:47 +0530 Subject: [PATCH 211/221] Update Spanish translation link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6c5ba669..7f6d9ec8 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [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].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [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].) Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From be377779b69e45c2174e11142d01d55f4a0e6690 Mon Sep 17 00:00:00 2001 From: Matt Kohl <95224098+mattkohl-flex@users.noreply.github.com> Date: Tue, 31 May 2022 15:36:12 +0100 Subject: [PATCH 212/221] Update README.md Grammatical fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f6d9ec8..b5ee9d74 100644 --- a/README.md +++ b/README.md @@ -619,7 +619,7 @@ True * 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. * 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. * 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. -* But why did the `is` operator evaluated to `False`? Let's see with this snippet. +* But why did the `is` operator evaluate to `False`? Let's see with this snippet. ```py class WTF(object): def __init__(self): print("I") From d3a25fa14ea0d484aa556053ea0ce2cfcff7a8c0 Mon Sep 17 00:00:00 2001 From: jeffreykennethli Date: Fri, 3 Jun 2022 10:15:21 -0400 Subject: [PATCH 213/221] Update link and add parenthesis to chained operators section --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b5ee9d74..5de07cc6 100644 --- a/README.md +++ b/README.md @@ -384,15 +384,15 @@ False #### 💡 Explanation: -As per https://docs.python.org/3/reference/expressions.html#membership-test-operations +As per https://docs.python.org/3/reference/expressions.html#comparisons > Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once. While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. * `False is False is False` is equivalent to `(False is False) and (False is False)` -* `True is False == False` is equivalent to `True is False and False == False` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. -* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`. +* `True is False == False` is equivalent to `(True is False) and (False == False)` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. +* `1 > 0 < 1` is equivalent to `(1 > 0) and (0 < 1)` which evaluates to `True`. * The expression `(1 > 0) < 1` is equivalent to `True < 1` and ```py >>> int(True) From feeb410009774e9fac21ea76cd9f78964a9e0328 Mon Sep 17 00:00:00 2001 From: Alexander Mayorov Date: Sat, 17 Sep 2022 21:13:35 +0400 Subject: [PATCH 214/221] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5de07cc6..6a13c0fa 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [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].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [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].) Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From d8258dbc9602450635267957ad2b4a24131f439a Mon Sep 17 00:00:00 2001 From: Alexander Mayorov Date: Sat, 22 Oct 2022 00:00:55 +0400 Subject: [PATCH 215/221] Update README.md Add new feature: Exceeds the limit for integer string conversion --- README.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/README.md b/README.md index 6a13c0fa..002529f8 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ So, here we go... + [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) + [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + + [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) * [Section: Slippery Slopes](#section-slippery-slopes) + [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + [▶ Stubborn `del` operation](#-stubborn-del-operation) @@ -1975,9 +1976,45 @@ a, b = a[b] = {}, 5 True ``` + --- + +### ▶ Exceeds the limit for integer string conversion +```py +>>> # Python 3.10.6 +>>> int("2" * 5432) + +>>> # Python 3.10.8 +>>> int("2" * 5432) +``` + +**Output:** +```py +>>> # Python 3.10.6 +222222222222222222222222222222222222222222222222222222222222222... + +>>> # Python 3.10.8 +Traceback (most recent call last): + ... +ValueError: Exceeds the limit (4300) for integer string conversion: + value has 5432 digits; use sys.set_int_max_str_digits() + to increase the limit. +``` + +#### 💡 Explanation: +This 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. + +Fortunately, 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: +- The -X int_max_str_digits command-line flag +- The set_int_max_str_digits() function from the sys module +- The PYTHONINTMAXSTRDIGITS environment variable + +[Check the documentation](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) for more details on changing the default limit if you expect your code to exceed this value. + + --- + ## Section: Slippery Slopes ### ▶ Modifying a dictionary while iterating over it From a50839656c7b61869d503ed9f0888be9fbb46a46 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Sun, 26 Feb 2023 12:14:52 +0530 Subject: [PATCH 216/221] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 29a96ef2..55d393a4 100644 --- a/README.md +++ b/README.md @@ -3843,7 +3843,7 @@ If you like wtfpython, you can use these quick links to share it with your frien ## Need a pdf version? -I've received a few requests for the pdf (and epub) version of wtfpython. You can add your details [here](https://satwikkansal.xyz/wtfpython-pdf/) to get them as soon as they are finished. +I've received a few requests for the pdf (and epub) version of wtfpython. You can add your details [here](https://form.jotform.com/221593245656057) to get them as soon as they are finished. -**That's all folks!** For upcoming content like this, you can add your email [here](https://www.satwikkansal.xyz/content-like-wtfpython/). +**That's all folks!** For upcoming content like this, you can add your email [here](https://form.jotform.com/221593598380062). From ccf5be1a6f24f5ebbf92e584413f74c97a68a2ae Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Fri, 28 Apr 2023 12:34:28 +0530 Subject: [PATCH 217/221] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 55d393a4..e7a73ed9 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [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].) -Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) +Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) 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. From acfcfa8808713aec9ec5d72e50a1f4fd8a6329b0 Mon Sep 17 00:00:00 2001 From: Francisco Couzo Date: Sun, 27 Aug 2023 14:32:48 +0000 Subject: [PATCH 218/221] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e7a73ed9..30e1f87a 100644 --- a/README.md +++ b/README.md @@ -1196,7 +1196,7 @@ True True ``` -Accessing` classm` or `method` twice, creates equal but not *same* objects for the same instance of `SomeClass`. +Accessing `classm` or `method` twice, creates equal but not *same* objects for the same instance of `SomeClass`. #### 💡 Explanation * Functions are [descriptors](https://docs.python.org/3/howto/descriptor.html). Whenever a function is accessed as an From 6010b97d90fcb9af95746ebc9b44a9040a4a62b1 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 28 Aug 2023 01:24:20 +0530 Subject: [PATCH 219/221] Add link to Germany translation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e7a73ed9..c46a4757 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [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].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [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].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From ab82f9647cc966a776776a9a6c2cdddf5ec925a3 Mon Sep 17 00:00:00 2001 From: Raigorx Hellscream <10247765+raigorx@users.noreply.github.com> Date: Thu, 31 Aug 2023 17:49:04 -0400 Subject: [PATCH 220/221] Update README.md https://docs.python.org/3/library/collections.abc.html#collections.abc.Hashable --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b3915124..1d5dca79 100644 --- a/README.md +++ b/README.md @@ -1121,7 +1121,7 @@ False **Output:** ```py ->>> from collections import Hashable +>>> from collections.abc import Hashable >>> issubclass(list, object) True >>> issubclass(object, Hashable) From 1b1b9d4b7015f71e45cfaa7268e539cef00d499b Mon Sep 17 00:00:00 2001 From: Sean Date: Thu, 5 Oct 2023 16:20:26 +0800 Subject: [PATCH 221/221] Invert logo color for dark theme --- README.md | 2 +- images/logo-dark.png | Bin 0 -> 13052 bytes 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 images/logo-dark.png diff --git a/README.md b/README.md index 1d5dca79..bb3100fc 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

+

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

diff --git a/images/logo-dark.png b/images/logo-dark.png new file mode 100644 index 0000000000000000000000000000000000000000..9d7791f3a30ae76158b3f33d84cdf0f31de2e3c2 GIT binary patch literal 13052 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