### Python Package Installation Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Provides commands for installing the 'wtfpython' package via npm for command-line usage and via pip for Python environments. ```sh # Install npm package $ npm install -g wtfpython ``` ```sh # Install pypi package $ pip install wtfpython -U ``` -------------------------------- ### Add New Python Example Template Source: https://github.com/satwikkansal/wtfpython/blob/master/CONTRIBUTING.md Template for submitting new Python code examples to the wtfpython project. It includes sections for a title, setup code, expected output, and a detailed explanation. ```Python # Setting up the code. # Preparation for the magic... ``` ```Python >>> triggering_statement Probably unexpected output ``` ```Python Setting up examples for clarification (if necessary) ``` ```Python >>> trigger # some example that makes it easy to unveil the magic # some justified output ``` -------------------------------- ### Python 'goto' Implementation Example Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Presents a code snippet using a hypothetical 'goto' and 'label' implementation in Python, simulating control flow jumps. This was originally an April Fool's joke and is not a standard Python feature. ```python 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!") if k == 2: goto .breakout # breaking out from a deeply nested loop label .breakout print("Freedom!") ``` -------------------------------- ### Python 'this' Module - Zen of Python Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Shows how to import the 'this' module, which prints 'The Zen of Python' to the console. It also includes interactive examples demonstrating boolean logic and object identity related to the 'this' module. ```python import this ``` ```python >>> love = this >>> this is love True >>> love is True False >>> love is False False >>> love is not True or False True >>> love is not True or False; love is love # Love is complicated True ``` -------------------------------- ### Python: Accessing The Zen of Python (`import this`) Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Shows how to import the `this` module in Python to display 'The Zen of Python' by Tim Peters. It also includes interactive examples demonstrating the truthiness and logical operations related to the `this` module. ```Python import this ``` ```Python >>> love = this >>> this is love True >>> love is True False >>> love is False False >>> love is not True or False True >>> love is not True or False; love is love # Love is complicated True ``` -------------------------------- ### Python Enumerate and Dictionary Assignment Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Illustrates the assignment process when using `enumerate` with dictionary updates in a loop. The example simplifies the loop's unrolling to show how variables are assigned in each step. ```python some_dict = {} for i, char in enumerate('wtf'): some_dict[i] = char print(some_dict) ``` -------------------------------- ### Python Chained Comparisons Evaluation Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates how chained comparison expressions like 'a op1 b op2 c' are evaluated in Python, equivalent to 'a op1 b and b op2 c'. Includes examples with boolean identities and numeric ranges, highlighting the evaluation order and potential type coercion. ```python False is False is False # Equivalent to: (False is False) and (False is False) True is False == False # Equivalent to: (True is False) and (False == False) 1 > 0 < 1 # Equivalent to: (1 > 0) and (0 < 1) # Example showing type coercion for chained comparisons: # (1 > 0) < 1 is equivalent to True < 1 # Since int(True) is 1, this becomes 1 < 1, which is False. print(int(True)) # Output: 1 ``` -------------------------------- ### Python Dictionary Key Hashing and Equality Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates how objects that hash to the same value and are considered equal (inheriting `__hash__` and `__eq__` from `str`) are treated as the same key in a dictionary. Redefining `__eq__` and `__hash__` is necessary for distinct behavior. ```python class SomeClass(str): pass some_dict = {'s':42} >>> type(list(some_dict.keys())[0]) str >>> s = SomeClass('s') >>> some_dict[s] = 40 >>> some_dict # expected: Two different keys-value pairs {'s': 40} >>> type(list(some_dict.keys())[0]) str ``` ```python class SomeClass(str): def __eq__(self, other): return ( type(self) is SomeClass and type(other) is SomeClass and super().__eq__(other) ) __hash__ = str.__hash__ # Inherit hash from str some_dict = {'s':42} >>> s = SomeClass('s') >>> some_dict[s] = 40 >>> some_dict {'s': 40} >>> keys = list(some_dict.keys()) >>> type(keys[0]), type(keys[1]) (__main__.SomeClass, str) ``` -------------------------------- ### Python: Tuple Assignment and String Repetition Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Illustrates common Python behaviors: tuple unpacking with conditional assignment and the difference between a single-element tuple and a string when iterated over. It also shows string multiplication with booleans. ```python x, y = (0, 1) if True else None, None ``` ```python t = ('one', 'two') for i in t: print(i) t = ('one') # Missing comma makes it a string for i in t: print(i) t = () print(t) ``` -------------------------------- ### Python Name Mangling Example Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates Python's name mangling mechanism where double underscores prefix class member names are modified to prevent naming collisions. Accessing such members requires prepending the class name. ```python class WTF: pass ``` -------------------------------- ### Python Object Identity and Hashing Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Illustrates that distinct instances of a simple class are not equal, not the same object, and have different memory addresses (IDs), but their hash values are also different, reflecting their unique identities. ```python >>> 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 ``` -------------------------------- ### Python: Boolean and Integer Type Coercion Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Explains how booleans in Python are subclasses of integers, where `True` is equivalent to `1` and `False` to `0`. This behavior affects type checking and dictionary key assignments, as demonstrated in the examples. ```python # A simple example to count the number of boolean and # integers in an iterable of mixed data types. mixed_list = [False, 1.0, "some_string", 3, True, [], False] integers_found_so_far = 0 booleans_found_so_far = 0 for item in mixed_list: if isinstance(item, int): integers_found_so_far += 1 elif isinstance(item, bool): booleans_found_so_far += 1 ``` ```python another_dict = {} another_dict[True] = "JavaScript" another_dict[1] = "Ruby" another_dict[1.0] = "Python" ``` ```python some_bool = True print("wtf"*some_bool) some_bool = False print("wtf"*some_bool) ``` -------------------------------- ### In-place List Modification vs. Assignment Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Illustrates the difference between in-place modification of a list using `+=` (which maps to `extend`) and reassignment using `+` (which creates a new list). ```Python a = [1, 2, 3] b = a a = a + [5, 6, 7, 8] # Creates a new list, 'a' points to it print(f"a after a = a + [5,6,7,8]: {a}") print(f"b after a = a + [5,6,7,8]: {b}") # 'b' still points to the original list a = [1, 2, 3] b = a a += [5, 6, 7, 8] # Modifies the list in-place, 'a' and 'b' still point to the same list print(f"a after a += [5,6,7,8]: {a}") print(f"b after a += [5,6,7,8]: {b}") ``` -------------------------------- ### Python String Interning: Assignment and Identity Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Illustrates string interning based on assignment and creation context. Strings created identically in the same line may share an ID, while those created separately might not if not implicitly interned by CPython. ```python >>> a = "wtf" >>> b = "wtf" >>> a is b True >>> a = "wtf!" >>> b = "wtf!" >>> a is b False >>> a, b = "wtf!", "wtf!" >>> a is b True ``` -------------------------------- ### Python Infinity Hash Calculation Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates how Python calculates the hash for float('infinity') and float('-inf'). It highlights the specific values used in Python 3, noting the difference from Python 2 for negative infinity. ```python >>> infinity = float('infinity') >>> hash(infinity) 314159 >>> hash(float('-inf')) -314159 ``` -------------------------------- ### Python zip usage example Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb Demonstrates the usage of the zip function with iterables. It highlights that zip stops as soon as the shortest iterable is exhausted, and elements from longer iterables are truncated. ```Python numbers = list(range(7)) numbers_iter = iter(numbers) list(zip(first_three, numbers_iter)) ``` ```Python list(zip(remaining, numbers_iter)) ``` -------------------------------- ### Python Chained Comparisons and Operator Precedence Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates how Python evaluates chained comparison operators like `a < b < c` and how they differ from explicit grouping with parentheses. It also shows the behavior of `is` in chained comparisons. ```python >>> False == False in [False] # Evaluates as (False == False) and (False in [False]) True ``` ```python >>> False == (False in [False]) # Explicit grouping False ``` ```python >>> True is False == False # Evaluates as (True is False) and (False == False) False ``` ```python >>> False is False is False # Evaluates as (False is False) and (False is False) True ``` ```python >>> 1 > 0 < 1 # Evaluates as (1 > 0) and (0 < 1) True ``` ```python >>> (1 > 0) < 1 # Evaluates as True < 1, which is False False ``` ```python >>> 1 > (0 < 1) # Evaluates as 1 > True, which is False False ``` -------------------------------- ### Banker's Rounding in Python 3 Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Explains Python 3's `round()` function uses banker's rounding (round half to even) for .5 fractions, which differs from the common 'round half up' taught in schools. Includes examples of its behavior. ```Python def get_middle(some_list): mid_index = round(len(some_list) / 2) return some_list[mid_index - 1] print(get_middle([1,2,3,4,5])) print(round(2.5)) ``` -------------------------------- ### Python goto Statement Example Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb Demonstrates the use of the goto and label statements for non-local jumps within Python code, illustrating how to break out of deeply nested loops. This functionality is not part of standard Python. ```python from goto import goto, label for i in range(9): for j in range(9): for k in range(9): print("I am trapped, please rescue!") if k == 2: goto .breakout # breaking out from a deeply nested loop label .breakout print("Freedom!") ``` -------------------------------- ### Python Exception Handling: Multiple Exceptions and Variable Binding Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Illustrates the syntax for catching multiple exceptions and assigning an exception instance to a variable. It highlights the differences between Python 2.x and Python 3.x syntax. ```python # Python 2.x syntax for catching multiple exceptions some_list = [1, 2, 3] try: print(some_list[4]) except IndexError, ValueError: print("Caught!") try: some_list.remove(4) except IndexError, ValueError: print("Caught again!") ``` ```python # Python 2.x syntax with exception variable some_list = [1, 2, 3] try: some_list.remove(4) except (IndexError, ValueError), e: print("Caught again!") print(e) ``` ```python # Python 3.x syntax for catching multiple exceptions and variable binding some_list = [1, 2, 3] try: print(some_list[4]) except (IndexError, ValueError) as e: print("Caught!") print(e) try: some_list.remove(4) except (IndexError, ValueError) as e: print("Caught again!") print(e) ``` -------------------------------- ### All sorted? Python Comparison Quirks Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Demonstrates how comparing tuples and lists, and the behavior of the `reversed()` iterator, can lead to unexpected comparison results in Python. ```python >>> x = 7, 8, 9 >>> sorted(x) == x False >>> sorted(x) == sorted(x) True >>> y = reversed(x) >>> sorted(y) == sorted(y) False ``` -------------------------------- ### Python Local Variable Storage Limit Example Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Illustrates Python's handling of local variable storage limits. While theoretically limited by 2 bytes per variable (65536), Python can manage more. This code defines a function with over 65536 variables to observe its behavior and prints the disassembly. ```Python import dis exec("\ndef f():" + "\n ".join(["X"+str(x)+"=" + str(x) for x in range(65539)])) f() print(dis.dis(f)) ``` -------------------------------- ### Python 'antigravity' Module Easter Egg Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates the 'antigravity' module, a Python easter egg that opens a web browser to a specific XKCD comic. The module also contains a hidden function related to geohashing. ```python import antigravity ``` -------------------------------- ### String Iteration vs. Tuple Iteration Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Shows how assigning a single string to a variable intended for a tuple leads to character-by-character iteration, as Python treats a single string as an iterable of characters. ```Python t = ('one', 'two') for i in t: print(i) t = ('one') # This is just the string 'one', not a tuple for i in t: print(i) t = () print(t) ``` -------------------------------- ### Python 'is' vs '==' Operator Comparison Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Explains the difference between the 'is' operator (identity comparison) and the '==' operator (value comparison). Demonstrates that two distinct empty lists are equal in value but not identical in memory location. ```python >>> [] == [] True >>> [] is [] # These are two empty lists at two different memory locations. False ``` -------------------------------- ### Python Chained Comparison Example Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb Demonstrates how chained comparison operators in Python are evaluated sequentially. The expression `1 > 0 < 1` is equivalent to `(1 > 0) and (0 < 1)`, resulting in True. ```python 1 > 0 < 1 ``` -------------------------------- ### Python Type and Object Relationships Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Explores the fundamental relationships between types and objects in Python, demonstrating that types are objects themselves and can be instances of other types, including `type` and `object`. ```python >>> isinstance(3, int) True >>> isinstance(type, object) True >>> isinstance(object, type) True ``` ```python class A: pass >>> isinstance(A, A) False >>> isinstance(type, type) True >>> isinstance(object, object) True ``` ```python >>> issubclass(int, object) True >>> issubclass(type, object) True >>> issubclass(object, type) False ``` -------------------------------- ### Cyrillic vs Latin 'e' Character Difference Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates how using a Cyrillic 'е' instead of a Latin 'e' can lead to unexpected variable assignments in Python, as they are treated as distinct characters by the interpreter. ```python >>> value = 11 >>> valuе = 32 >>> value 11 ``` ```python # Explanation: >>> 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 ``` -------------------------------- ### Python 'from __future__ import braces' Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Illustrates an attempt to import a non-existent future feature, 'braces', which is a Python easter egg. This import results in a SyntaxError, highlighting Python's design philosophy against C-style braces for scope. ```python from __future__ import braces ``` -------------------------------- ### Python Chained Comparisons Explained Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Demonstrates how chained comparison expressions in Python are evaluated. Each comparison is evaluated sequentially, and the expression is equivalent to a series of 'and' operations, with each sub-expression evaluated at most once. ```python >>> False is False is False True >>> True is False == False False >>> 1 > 0 < 1 True >>> (1 > 0) < 1 False ``` -------------------------------- ### Python String Interning: Multiplication Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Examines string interning with string multiplication. Short strings resulting from multiplication are often interned, leading to identity checks returning True, but this can be implementation-dependent for longer strings. ```python >>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' True >>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' False ``` -------------------------------- ### Python Goto Statement (April Fool's Joke) Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Demonstrates the `goto` module, originally released as an April Fool's joke, which allows for non-sequential execution flow. It is not part of standard Python. ```python from goto import goto, label for i in range(9): for j in range(9): for k in range(9): print("I am trapped, please rescue!") if k == 2: goto .breakout # breaking out from a deeply nested loop label .breakout print("Freedom!") ``` -------------------------------- ### Python Antigravity Easter Egg Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Introduces the `antigravity` module, a Python easter egg that opens a web browser to a specific XKCD comic and contains a hidden geohashing algorithm implementation. ```python import antigravity ``` -------------------------------- ### Python Brace Syntax Future Import (Easter Egg) Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Shows the `from __future__ import braces` statement, an easter egg that results in a `SyntaxError`, humorously referencing the desire for C-style braces in Python. ```python from __future__ import braces ``` -------------------------------- ### Python 'from __future__ import barry_as_FLUFL' Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Illustrates the 'barry_as_FLUFL' future import, another April Fool's joke related to PEP 401. It aimed to reinstate the '<>' operator as the sole inequality operator, causing a SyntaxError with '!='. ```python from __future__ import barry_as_FLUFL "Ruby" != "Python" # there's no doubt about it ``` ```python "Ruby" <> "Python" ``` -------------------------------- ### Float Representation of Infinity and NaN Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates the use of float('inf'), float('-inf'), and float('nan') for representing mathematical infinity and 'Not a Number' in Python. Shows case-insensitivity for 'inf'/'nan' strings and highlights that NaN values are not equal to themselves. ```python a = float('inf') b = float('nan') c = float('-iNf') # Case-insensitive d = float('nan') # Output: # >>> a # inf # >>> b # nan # >>> c # -inf # Attempting to convert invalid strings raises ValueError # >>> float('some_other_string') # ValueError: could not convert string to float: some_other_string # Comparisons: # >>> a == -c # inf == inf # True # >>> None == None # True # >>> b == d # nan != nan # False # Operations with inf/nan: # >>> 50/a # 0.0 # >>> a/a # nan # >>> 23 + b # nan ``` -------------------------------- ### Python: Generator Expressions with `yield` Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Shows the behavior of `yield` within list comprehensions and generator expressions. It highlights how `yield` returns a generator object and how `list()` consumes it, potentially yielding `None` when the generator expression is exhausted. ```python some_iterable = ('a', 'b') def some_func(val): return "something" print([x for x in some_iterable]) print([(yield x) for x in some_iterable]) print(list([(yield x) for x in some_iterable])) print(list((yield x) for x in some_iterable)) print(list(some_func((yield x)) for x in some_iterable)) ``` -------------------------------- ### Python Unicode Decimal Digit Conversion Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates Python 3's ability to convert Unicode decimal characters, such as Arabic-Indic digits, directly into integers. This behavior is due to Python's broad definition of decimal characters. ```Python int('١٢٣٤٥٦٧٨٩') ``` -------------------------------- ### Python Name Mangling: Private Attribute Access Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Demonstrates Python's name mangling for attributes starting with double underscores (`__`). It shows how `__attribute` is mangled to `_ClassName__attribute` for access, but names ending in double underscores (`__attribute__`) are not mangled, preventing accidental name clashes. ```Python class Yo(object): def __init__(self): self.__honey = True self.bro = True >>> Yo().bro True >>> Yo().__honey AttributeError: 'Yo' object has no attribute '__honey' >>> Yo()._Yo__honey True ``` ```Python class Yo(object): def __init__(self): self.__honey__ = True self.bro = True >>> Yo().bro True >>> Yo()._Yo__honey__ Traceback (most recent call last): File "", line 1, in AttributeError: 'Yo' object has no attribute '_Yo__honey__' ``` ```Python _A__variable = "Some value" class A(object): def some_func(self): return __variable # not initialized anywhere yet >>> A().__variable Traceback (most recent call last): File "", line 1, in AttributeError: 'A' object has no attribute '__variable' >>> A().some_func() 'Some value' ``` -------------------------------- ### Python Wildcard Imports and Name Visibility Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Explains how Python's wildcard imports (`from module import *`) affect name visibility. Names starting with an underscore are not imported by default, leading to `NameError` unless explicitly imported or included in the `__all__` list within the module. Using `__all__` allows control over which names are exported during wildcard imports. ```python # File: module.py def some_weird_name_func_(): print("works!") def _another_weird_name_func(): print("works!") ``` ```python >>> 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 ``` ```python >>> from module import some_weird_name_func_, _another_weird_name_func >>> _another_weird_name_func() works! ``` ```python # File: module.py (with __all__) __all__ = ['_another_weird_name_func'] def some_weird_name_func_(): print("works!") def _another_weird_name_func(): print("works!") ``` ```python >>> from module import * >>> _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 ``` -------------------------------- ### Python String Building Performance Comparison Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Evaluates the performance of different methods for building large strings, including repeated concatenation with '+', byte string concatenation, string formatting, and using ''.join(). It highlights that ''.join() on a pre-built list is generally the most efficient. ```python def add_string_with_plus(iters): s = "" for i in range(iters): s += "xyz" assert len(s) == 3*iters def add_bytes_with_plus(iters): s = b"" for i in range(iters): s += b"xyz" assert len(s) == 3*iters def add_string_with_format(iters): fs = "{}"*iters s = fs.format(*(["xyz"]*iters)) assert len(s) == 3*iters def add_string_with_join(iters): l = [] for i in range(iters): l.append("xyz") s = "".join(l) assert len(s) == 3*iters def convert_list_to_string(l, iters): s = "".join(l) assert len(s) == 3*iters ``` ```python >>> 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 ``` ```python >>> 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 ``` -------------------------------- ### Python: Circular Reference Example with Lists Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Provides an illustrative example of creating a circular reference using list assignments in Python. The statement `some_list = some_list[0] = [0]` assigns the list `[0]` to both `some_list` and `some_list[0]`, creating a self-referential structure. The output demonstrates how `is` confirms object identity and how deep nesting can be achieved through such references. ```python some_list = some_list[0] = [0] >>> some_list [[...]] >>> some_list[0] [[...]] >>> some_list is some_list[0] True >>> some_list[0][0][0][0][0][0] == some_list True ``` -------------------------------- ### Demonstrate Initial Instance Dictionary Size Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb Shows the initial memory size of instance dictionaries for newly created objects. It uses a helper function `dict_size` to measure the size of the `__dict__` attribute. ```python 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__) o1 = SomeClass() o2 = SomeClass() dict_size(o1) ``` ```python dict_size(o2) ``` -------------------------------- ### Python Simultaneous Assignment Optimization Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates how Python's interpreter optimizes simultaneous assignments (e.g., `a, b = 257, 257`) by creating a single object and referencing it twice. Contrasts this with separate line assignments which may create distinct objects. ```python >>> a, b = 257, 257 >>> id(a) 140640774013296 >>> id(b) 140640774013296 >>> a = 257 >>> b = 257 >>> id(a) 140640774013392 >>> id(b) 140640774013488 ``` -------------------------------- ### Demonstrate Dictionary Size in a New Interpreter Session Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb Resets the interpreter state to show the behavior of instance dictionary sizes again, focusing on the effects of adding new attributes. ```python o1 = SomeClass() o2 = SomeClass() dict_size(o1) ``` ```python o1.some_attr5 = 5 o1.some_attr6 = 6 dict_size(o1) ``` ```python dict_size(o2) ``` ```python o3 = SomeClass() dict_size(o3) ``` -------------------------------- ### Run notebook_generator.py to create notebook Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/notebook_instructions.md Execute the `notebook_generator.py` script to automatically generate a Jupyter notebook (`wtf.ipynb`). This process typically involves preparing the README.md file by expanding relative links, removing the table of contents, and reordering examples before running the script. ```python python notebook_generator.py ``` -------------------------------- ### Python `print()` Buffering Behavior Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Illustrates that `print()` output might not appear immediately due to buffering, especially when not ending with a newline. The `time.sleep(3)` in the example prevents the output from being flushed until after the sleep period, demonstrating the potential delay. ```python # File some_file.py import time print("wtfpython", end="_") time.sleep(3) ``` -------------------------------- ### Exception Variable Scope in Python `except` Clauses Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Details how Python 3.x clears exception variables assigned with `as` at the end of an `except` block, preventing access to the exception object afterward. This behavior differs from Python 2.x and is designed to prevent reference cycles. The example also contrasts this with function scope. ```python e = 7 try: raise Exception() except Exception as e: pass # In Python 3.x, 'e' is undefined after the except block # print(e) # NameError: name 'e' is not defined # In Python 2.x, 'e' would retain the exception instance # print e # Prints nothing, but 'e' holds the exception object def f(x): del(x) # Deletes the local reference # print(x) # UnboundLocalError: local variable 'x' referenced before assignment x = 5 f(x) # print(x) # Still prints 5, as the function's 'del' only affected its local scope ``` -------------------------------- ### Python Operator Precedence: '==' vs 'not' Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Illustrates how operator precedence affects expression evaluation in Python. The '==' operator has higher precedence than 'not', leading to unexpected results or SyntaxErrors if not parenthesized correctly. For example, 'not x == y' is evaluated as 'not (x == y)', whereas 'x == not y' can be misinterpreted by the parser. ```python x = True y = False >>> not x == y True >>> x == not y File "", line 1 x == not y ^ SyntaxError: invalid syntax ``` -------------------------------- ### List Concatenation and Length Source: https://github.com/satwikkansal/wtfpython/blob/master/README.md Demonstrates how missing commas in list literals can lead to unexpected concatenation, resulting in a shorter list than intended. ```Python ten_words_list = [ "some", "very", "big", "list", "that" "consists", "of", "exactly", "ten", "words" ] print(len(ten_words_list)) ``` -------------------------------- ### Python: Handle Multiple Exceptions with Tuple Source: https://github.com/satwikkansal/wtfpython/blob/master/irrelevant/obsolete/initial.md Demonstrates how to catch multiple exceptions in a single except clause by passing them as a parenthesized tuple. It highlights the deprecated comma-separated syntax (Python 2) and the modern `as` syntax (Python 3) for assigning the exception instance to a variable. ```python some_list = [1, 2, 3] try: # This should raise a ``ValueError`` some_list.remove(4) except (IndexError, ValueError), e: print("Caught again!") print(e) ``` ```python some_list = [1, 2, 3] try: some_list.remove(4) except (IndexError, ValueError) as e: print("Caught again!") print(e) ```