From 55e5ae206a1b66049226dc8948e601f36da91d9e Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Tue, 29 Apr 2025 16:11:30 +0200 Subject: [PATCH] Fix liniting issues --- README.md | 755 +++++++++++++++++++------------- translations/fa-farsi/README.md | 686 +++++++++++++++++------------ 2 files changed, 844 insertions(+), 597 deletions(-) diff --git a/README.md b/README.md index a82e11e..e1114cc 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ +

@@ -35,23 +36,23 @@ 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) - [▶ 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-) + - [▶ Disorder within order \*](#-disorder-within-order-) + - [▶ Keep trying... \*](#-keep-trying-) - [▶ For what?](#-for-what) - [▶ 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) - [▶ Schrödinger's variable](#-schrödingers-variable-) - - [▶ The chicken-egg problem *](#-the-chicken-egg-problem-) + - [▶ 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-) + - [▶ All-true-ation \*](#-all-true-ation-) - [▶ The surprising comma](#-the-surprising-comma) - [▶ Strings and the backslashes](#-strings-and-the-backslashes) - [▶ not knot!](#-not-knot) @@ -59,8 +60,8 @@ So, here we go... - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - [▶ yielding None](#-yielding-none) - - [▶ Yielding from... return! *](#-yielding-from-return-) - - [▶ 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) - [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) @@ -71,17 +72,17 @@ So, here we go... - [▶ 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-) + - [▶ 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) - [▶ 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-) - - [▶ All sorted? *](#-all-sorted-) + - [▶ Rounding like a banker \*](#-rounding-like-a-banker-) + - [▶ 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) @@ -90,7 +91,7 @@ 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) @@ -100,9 +101,9 @@ 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-) - - [▶ Bloating instance `dict`s *](#-bloating-instance-dicts-) - - [▶ Minor Ones *](#-minor-ones-) + - [▶ Slowing down `dict` lookups \*](#-slowing-down-dict-lookups-) + - [▶ Bloating instance `dict`s \*](#-bloating-instance-dicts-) + - [▶ Minor Ones \*](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) - [🎓 License](#-license) @@ -131,7 +132,6 @@ All the examples are structured like below: > > (Optional): One line describing the unexpected output. > -> > #### 💡 Explanation: > > - Brief explanation of what's happening and why is it happening. @@ -167,7 +167,7 @@ A nice way to get the most out of these examples, in my opinion, is to read them ## Section: Strain your brain! -### ▶ First things first! * +### ▶ First things first! \* @@ -264,7 +264,7 @@ if a := some_func(): This saved one line of code, and implicitly prevented invoking `some_func` twice. -- 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`. +- 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 an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. @@ -319,7 +319,7 @@ a = "wtf!"; b = "wtf!" assert a is b ``` -4\. __Disclaimer - snippet is not relavant in modern Python versions__ +4\. **Disclaimer - snippet is not relavant in modern Python versions** **Output (< Python3.7 )** @@ -333,6 +333,7 @@ False 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: @@ -350,13 +351,15 @@ 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 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. +- 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). --- ### ▶ Be careful with chained operations + + ```py >>> (False == False) in [False] # makes sense False @@ -403,7 +406,9 @@ While such behavior might seem silly to you in the above examples, it's fantasti --- ### ▶ How not to use `is` operator + + The following is a very famous example present all over the internet. 1\. @@ -470,6 +475,7 @@ False 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 @@ -528,7 +534,9 @@ Similar optimization applies to other **immutable** objects like empty tuples as --- ### ▶ Hash brownies + + 1\. ```py @@ -545,7 +553,7 @@ some_dict[5] = "Python" "JavaScript" >>> some_dict[5.0] # "Python" destroyed the existence of "Ruby"? "Python" ->>> some_dict[5] +>>> some_dict[5] "Python" >>> complex_five = 5 + 0j @@ -559,7 +567,7 @@ So, why is Python all over the place? #### 💡 Explanation -- 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`): +- 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 @@ -573,6 +581,7 @@ So, why is Python all over the place? >>> (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 @@ -582,6 +591,7 @@ So, why is Python all over the place? >>> 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 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. @@ -593,12 +603,14 @@ So, why is Python all over the place? True ``` - **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.) + **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](), and degrades the constant-time performance that hashing usually provides.) --- ### ▶ Deep down, we're all the same. + + ```py class WTF: pass @@ -651,8 +663,10 @@ True --- -### ▶ Disorder within order * +### ▶ Disorder within order \* + + ```py from collections import OrderedDict @@ -715,45 +729,48 @@ 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. + + > 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 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() - >>> 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 + ```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 - ``` + >>> 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`. + 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(): try: @@ -761,7 +778,7 @@ def some_func(): finally: return 'from_finally' -def another_func(): +def another_func(): for _ in range(3): try: continue @@ -813,7 +830,9 @@ Iteration 0 --- ### ▶ For what? + + ```py some_string = "wtf" some_dict = {} @@ -872,7 +891,9 @@ for i, some_dict[i] in enumerate(some_string): --- ### ▶ Evaluation time discrepancy + + 1\. ```py @@ -937,13 +958,15 @@ array_4 = [400, 500, 600] - 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) - - > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run. + + > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run. --- ### ▶ `is not ...` is not `is (not ...)` + + ```py >>> 'something' is not None True @@ -960,6 +983,7 @@ False --- ### ▶ A tic-tac-toe where X wins in the first attempt! + ```py @@ -1018,7 +1042,8 @@ We can avoid this scenario here by not using `row` variable to generate `board`. --- -### ▶ Schrödinger's variable * +### ▶ Schrödinger's variable \* + ```py @@ -1053,7 +1078,8 @@ The values of `x` were different in every iteration prior to appending `some_fun ``` #### 💡 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: + +- 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 @@ -1069,7 +1095,7 @@ Since `x` is a global value, we can change the value that the `funcs` will looku [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 *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. +- 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 = [] @@ -1096,8 +1122,10 @@ ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) --- -### ▶ The chicken-egg problem * +### ▶ The chicken-egg problem \* + + 1\. ```py @@ -1147,7 +1175,9 @@ False --- ### ▶ Subclass relationships + + **Output:** ```py @@ -1160,7 +1190,7 @@ True 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`) +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: @@ -1172,6 +1202,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` --- ### ▶ Methods equality and identity + 1. @@ -1203,7 +1234,7 @@ True True ``` -Accessing `classm` twice, we get an equal object, but not the *same* one? Let's see what happens +Accessing `classm` twice, we get an equal object, but not the _same_ one? Let's see what happens with instances of `SomeClass`: 2. @@ -1230,44 +1261,49 @@ 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 -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). + 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). ```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. + 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. + 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. + 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. + `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. + objects are ever created, so comparison with `is` is truthy. ```py >>> o1.staticm @@ -1275,13 +1311,14 @@ objects are ever created, so comparison with `is` is truthy. >>> 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 :) -### ▶ All-true-ation * +- 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 :) + +### ▶ All-true-ation \* @@ -1320,7 +1357,9 @@ Why's this True-False alteration? --- ### ▶ The surprising comma + + **Output (< 3.6):** ```py @@ -1352,7 +1391,9 @@ SyntaxError: invalid syntax --- ### ▶ Strings and the backslashes + + **Output:** ```py @@ -1376,31 +1417,33 @@ 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' - ``` + ```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. +- 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' + ```py + >>> r'wt\"f' == 'wt\\"f' + True + >>> print(repr(r'wt\"f')) + 'wt\\"f' - >>> print("\n") + >>> print("\n") - >>> print(r"\\n") - '\\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. --- ### ▶ not knot! + + ```py x = True y = False @@ -1428,7 +1471,9 @@ SyntaxError: invalid syntax --- ### ▶ Half triple-quoted strings + + **Output:** ```py @@ -1446,6 +1491,7 @@ SyntaxError: EOF while scanning triple-quoted string literal ``` #### 💡 Explanation: + - Python supports implicit [string literal concatenation](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation), Example, ``` @@ -1454,12 +1500,15 @@ SyntaxError: EOF while scanning triple-quoted string literal >>> print("wtf" "") # or "wtf""" wtf ``` + - `'''` 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. --- ### ▶ What's wrong with booleans? + + 1\. ```py @@ -1516,12 +1565,12 @@ I have lost faith in truth! - `bool` is a subclass of `int` in Python - ```py - >>> issubclass(bool, int) - True - >>> issubclass(int, bool) - False - ``` + ```py + >>> issubclass(bool, int) + True + >>> issubclass(int, bool) + False + ``` - And thus, `True` and `False` are instances of `int` @@ -1543,14 +1592,16 @@ I have lost faith in truth! - 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 +- 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 + + 1\. ```py @@ -1623,7 +1674,9 @@ True --- ### ▶ yielding None + + ```py some_iterable = ('a', 'b') @@ -1655,8 +1708,10 @@ def some_func(val): --- -### ▶ Yielding from... return! * +### ▶ Yielding from... return! \* + + 1\. ```py @@ -1720,7 +1775,7 @@ The same result, this didn't work either. --- -### ▶ Nan-reflexivity * +### ▶ Nan-reflexivity \* @@ -1775,7 +1830,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 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, +- 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') @@ -1825,7 +1880,8 @@ But I thought tuples were immutable... - Quoting from https://docs.python.org/3/reference/datamodel.html - > Immutable sequences + > 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.) - `+=` 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. @@ -1834,6 +1890,7 @@ But I thought tuples were immutable... --- ### ▶ The disappearing variable from outer scope + ```py @@ -1883,43 +1940,45 @@ NameError: name 'e' is not defined - 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): - del(x) - print(x) + ```py + def f(x): + del(x) + print(x) - x = 5 - y = [5, 4, 3] - ``` + x = 5 + y = [5, 4, 3] + ``` - **Output:** + **Output:** - ```py - >>> f(x) - UnboundLocalError: local variable 'x' referenced before assignment - >>> f(y) - UnboundLocalError: local variable 'x' referenced before assignment - >>> x - 5 - >>> y - [5, 4, 3] - ``` + ```py + >>> f(x) + UnboundLocalError: local variable 'x' referenced before assignment + >>> f(y) + UnboundLocalError: local variable 'x' referenced before assignment + >>> x + 5 + >>> y + [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. - **Output (Python 2.x):** + **Output (Python 2.x):** - ```py - >>> e - Exception() - >>> print e - # Nothing is printed! - ``` + ```py + >>> e + Exception() + >>> print e + # Nothing is printed! + ``` --- ### ▶ The mysterious key type conversion + + ```py class SomeClass(str): pass @@ -1978,7 +2037,9 @@ str --- ### ▶ Let's see if you can guess this? + + ```py a, b = a[b] = {}, 5 ``` @@ -1999,7 +2060,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`). @@ -2083,7 +2144,9 @@ Fortunately, you can increase the limit for the allowed number of digits when yo ## Section: Slippery Slopes ### ▶ Modifying a dictionary while iterating over it + + ```py x = {0: None} @@ -2119,6 +2182,7 @@ Yes, it runs for exactly **eight** times and stops. --- ### ▶ Stubborn `del` operation + @@ -2158,6 +2222,7 @@ Deleted! Okay, now it's deleted :confused: #### 💡 Explanation: + - `del x` doesn’t directly call `x.__del__()`. - 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. @@ -2166,6 +2231,7 @@ Okay, now it's deleted :confused: --- ### ▶ The out of scope variable + 1\. @@ -2212,6 +2278,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`, we have to use the `global` keyword. @@ -2228,6 +2295,7 @@ 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. The nonlocal statement is used to refer to variables defined in the nearest outer (excluding the global) scope. @@ -2247,13 +2315,16 @@ UnboundLocalError: local variable 'a' referenced before assignment >>> another_func() 2 ``` + - 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. --- ### ▶ Deleting a list item while iterating + + ```py list_1 = [1, 2, 3, 4] list_2 = [1, 2, 3, 4] @@ -2292,15 +2363,16 @@ Can you guess why the output is `[2, 4]`? - 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. - ```py - >>> some_list = [1, 2, 3, 4] - >>> id(some_list) - 139798789457608 - >>> id(some_list[:]) # Notice that python creates new object for sliced list. - 139798779601192 - ``` + ```py + >>> some_list = [1, 2, 3, 4] + >>> id(some_list) + 139798789457608 + >>> id(some_list[:]) # Notice that python creates new object for sliced list. + 139798779601192 + ``` **Difference between `del`, `remove`, and `pop`:** + - `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). - `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found. - `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified. @@ -2314,7 +2386,8 @@ Can you guess why the output is `[2, 4]`? --- -### ▶ Lossy zip of iterators * +### ▶ Lossy zip of iterators \* + ```py @@ -2325,7 +2398,7 @@ Can you guess why the output is `[2, 4]`? >>> first_three, remaining ([0, 1, 2], [3, 4, 5, 6]) >>> numbers_iter = iter(numbers) ->>> list(zip(numbers_iter, first_three)) +>>> 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)) @@ -2338,38 +2411,40 @@ Where did element `3` go from the `numbers` list? - 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) - ``` + ```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 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 - >>> 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)] - ``` + ```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. + The first argument of zip should be the one with fewest elements. --- ### ▶ Loop variables leaking out! + + 1\. ```py @@ -2434,11 +2509,12 @@ print(x, ': x in global') - 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." --- ### ▶ Beware of default mutable arguments! + ```py @@ -2464,42 +2540,44 @@ def some_func(default_arg=[]): - 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. - ```py - def some_func(default_arg=[]): - default_arg.append("some_string") - return default_arg - ``` + ```py + def some_func(default_arg=[]): + default_arg.append("some_string") + return default_arg + ``` - **Output:** + **Output:** - ```py - >>> some_func.__defaults__ #This will show the default argument values for the function - ([],) - >>> some_func() - >>> some_func.__defaults__ - (['some_string'],) - >>> some_func() - >>> some_func.__defaults__ - (['some_string', 'some_string'],) - >>> some_func([]) - >>> some_func.__defaults__ - (['some_string', 'some_string'],) - ``` + ```py + >>> some_func.__defaults__ #This will show the default argument values for the function + ([],) + >>> some_func() + >>> some_func.__defaults__ + (['some_string'],) + >>> some_func() + >>> some_func.__defaults__ + (['some_string', 'some_string'],) + >>> some_func([]) + >>> some_func.__defaults__ + (['some_string', 'some_string'],) + ``` - 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: - ```py - def some_func(default_arg=None): - if default_arg is None: - default_arg = [] - default_arg.append("some_string") - return default_arg - ``` + ```py + def some_func(default_arg=None): + if default_arg is None: + default_arg = [] + default_arg.append("some_string") + return default_arg + ``` --- ### ▶ Catching the Exceptions + + ```py some_list = [1, 2, 3] try: @@ -2584,7 +2662,9 @@ SyntaxError: invalid syntax --- ### ▶ Same operands, different story! + + 1\. ```py @@ -2621,7 +2701,7 @@ a += [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. +- `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. @@ -2630,7 +2710,9 @@ a += [5, 6, 7, 8] --- ### ▶ Name resolution ignoring class scope + + 1\. ```py @@ -2678,7 +2760,7 @@ class SomeClass: --- -### ▶ Rounding like a banker * +### ▶ Rounding like a banker \* Let's implement a naive function to get the middle element of a list: @@ -2731,7 +2813,7 @@ It seems as though Python rounded 2.5 to 2. --- -### ▶ Needles in a Haystack * +### ▶ Needles in a Haystack \* @@ -2825,7 +2907,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}) ``` @@ -2889,10 +2971,10 @@ def similar_recursive_func(a): 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 @@ -2907,8 +2989,10 @@ def similar_recursive_func(a): --- -### ▶ Splitsies * +### ▶ Splitsies \* + + ```py >>> 'a'.split() ['a'] @@ -2929,22 +3013,23 @@ 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/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 `['']`. + > 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(' ') - [''] - ``` + ```py + >>> ' a '.split(' ') + ['', 'a', ''] + >>> ' a '.split() + ['a'] + >>> ''.split(' ') + [''] + ``` --- -### ▶ Wild imports * +### ▶ Wild imports \* + @@ -2976,38 +3061,38 @@ NameError: name '_another_weird_name_func' is not defined - 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 - >>> _another_weird_name_func() - works! - ``` + ```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'] + ```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!") - ``` + def _another_weird_name_func(): + print("works!") + ``` - **Output** + **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 + ``` --- -### ▶ All sorted? * +### ▶ All sorted? \* @@ -3049,7 +3134,9 @@ False --- ### ▶ Midnight time doesn't exist? + + ```py from datetime import datetime @@ -3079,6 +3166,7 @@ The midnight time is not printed. 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." --- + --- ## Section: The Hidden treasures! @@ -3086,7 +3174,9 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t 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? + + Well, here you go ```py @@ -3097,6 +3187,7 @@ import antigravity 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](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/). @@ -3104,6 +3195,7 @@ Sshh... It's a super-secret. --- ### ▶ `goto`, but why? + ```py @@ -3135,7 +3227,9 @@ 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 @@ -3153,6 +3247,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. - 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. @@ -3161,7 +3256,9 @@ 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 @@ -3182,20 +3279,23 @@ 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. + - 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 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"')) - ``` + ```py + from __future__ import barry_as_FLUFL + print(eval('"Ruby" <> "Python"')) + ``` --- ### ▶ Even Python understands that love is complicated + + ```py import this ``` @@ -3253,7 +3353,9 @@ True --- ### ▶ Yes, it exists! + + **The `else` clause for loops.** One typical example might be: ```py @@ -3300,8 +3402,10 @@ Try block executed successfully... --- -### ▶ Ellipsis * +### ▶ Ellipsis \* + + ```py def some_func(): Ellipsis @@ -3326,12 +3430,13 @@ Ellipsis - In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`. - ```py - >>> ... - Ellipsis - ``` + ```py + >>> ... + Ellipsis + ``` - 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 @@ -3363,13 +3468,16 @@ Ellipsis ``` 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 + + The spelling is intended. Please, don't submit a patch for this. **Output (Python 3.x):** @@ -3390,7 +3498,9 @@ The spelling is intended. Please, don't submit a patch for this. --- ### ▶ Let's mangle + + 1\. ```py @@ -3467,12 +3577,15 @@ 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 @@ -3543,7 +3656,9 @@ Where's the Nobel Prize? --- ### ▶ Well, something is fishy... + + ```py def square(x): """ @@ -3568,25 +3683,28 @@ Shouldn't that be 100? #### 💡 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. +- **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):** + **Output (Python 3.x):** - ```py - TabError: inconsistent use of tabs and spaces in indentation - ``` + ```py + TabError: inconsistent use of tabs and spaces in indentation + ``` --- + --- ## Section: Miscellaneous ### ▶ `+=` is faster + ```py @@ -3599,12 +3717,15 @@ Shouldn't that be 100? ``` #### 💡 Explanation: + - `+=` 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. --- ### ▶ Let's make a giant string! + + ```py def add_string_with_plus(iters): s = "" @@ -3695,13 +3816,15 @@ Let's increase the number of iterations by a factor of 10. ``` - 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. + + > There should be one-- and preferably only one --obvious way to do it. --- -### ▶ 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)} @@ -3729,13 +3852,16 @@ KeyError: 1 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. -### ▶ Bloating instance `dict`s * +### ▶ Bloating instance `dict`s \* + + ```py import sys @@ -3790,19 +3916,23 @@ Let's try again... In a new interpreter: 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. -- Additionally, 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. +- Additionally, 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__`! -### ▶ Minor Ones * +### ▶ 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. - + - 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 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`. @@ -3820,11 +3950,12 @@ What makes those dictionaries become bloated? And why are newly created objects ``` **💡 Explanation:** + - There is no `++` operator in Python grammar. It is actually two `+` operators. - `++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 @@ -3842,67 +3973,67 @@ What makes those dictionaries become bloated? And why are newly created objects ``` **💡 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 - ``` + ```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 a 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). - ```py - >>> import numpy as np - >>> np.array([2, 2, 2]) @ np.array([7, 8, 8]) - 46 - ``` + ```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 the 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 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 - >>> some_string = "wtfpython" - >>> f'{some_string=}' - "some_string='wtfpython'" - ``` + ```py + >>> some_string = "wtfpython" + >>> f'{some_string=}' + "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!): - ```py - import dis - exec(""" - def f(): - """ + """ - """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) + ```py + import dis + exec(""" + def f(): + """ + """ + """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) - f() + f() - print(dis.dis(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/3/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, - ```py - # File some_file.py - import time - - print("wtfpython", end="_") - time.sleep(3) - ``` + ```py + # File some_file.py + import time - 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. + print("wtfpython", end="_") + time.sleep(3) + ``` + + 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 @@ -3914,27 +4045,27 @@ What makes those dictionaries become bloated? And why are newly created objects - 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 - ``` + ```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](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. - ```py - >>> six_million = 6_000_000 - >>> six_million - 6000000 - >>> hex_address = 0xF00D_CAFE - >>> hex_address - 4027435774 - ``` + ```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 @@ -3949,6 +4080,7 @@ What makes those dictionaries become bloated? And why are newly created objects The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string. --- + --- # Contributing @@ -3970,6 +4102,7 @@ PS: Please don't reach out with backlinking requests, no links will be added unl 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 - https://www.reddit.com/r/Python/comments/3cu6ej/what_are_some_wtf_things_about_python - https://sopython.com/wiki/Common_Gotchas_In_Python @@ -3993,7 +4126,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&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!) +[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!) ## Need a pdf version? diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 22e7eb2..cddeb0b 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -1,3 +1,6 @@ + + +

@@ -148,7 +151,7 @@ - [💡 توضیح:](#-توضیح-50) - [◀ بله، این واقعاً وجود دارد!](#-بله-این-واقعاً-وجود-دارد) - [💡 توضیح:](#-توضیح-51) - - [◀ عملگر Ellipsis \*](#-عملگر-ellipsis--) + - [◀ عملگر Ellipsis \*](#-عملگر-ellipsis-) - [💡توضیح](#توضیح) - [◀ بی‌نهایت (`Inpinity`)](#-بینهایت-inpinity) - [💡 توضیح:](#-توضیح-52) @@ -166,14 +169,13 @@ - [💡 توضیح:](#-توضیح-57) - [◀ بیایید یک رشته‌ی بزرگ بسازیم!](#-بیایید-یک-رشتهی-بزرگ-بسازیم) - [💡 توضیح](#-توضیح-58) - - [◀ کُند کردن جستجوها در `dict` \*](#--کُند-کردن-جستجوها-در-dict-) + - [◀ کُند کردن جستجوها در `dict` \*](#-کُند-کردن-جستجوها-در-dict-) - [💡 توضیح:](#-توضیح-59) - [◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#-حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) - [💡 توضیح:](#-توضیح-60) - [◀ موارد جزئی \*](#-موارد-جزئی-) - [مشارکت](#مشارکت) -- [تقدیر و تشکر](#تقدیر-و-تشکر) - - [چند لینک جالب!](#چند-لینک-جالب) +- [تقدیر و تشکر](#تقدیر-و-تشکر) - [چند لینک جالب!](#چند-لینک-جالب) - [🎓 مجوز](#-مجوز) - [دوستانتان را هم شگفت‌زده کنید!](#دوستانتان-را-هم-شگفتزده-کنید) - [آیا به یک نسخه pdf نیاز دارید؟](#آیا-به-یک-نسخه-pdf-نیاز-دارید) @@ -200,7 +202,6 @@ > > (دلخواه): توضیح یک‌خطی خروجی غیرمنتظره > -> > #### 💡 توضیح: > > - توضیح کوتاه درمورد این‌که چی داره اتفاق میافته و چرا. @@ -239,7 +240,7 @@ ## بخش: ذهن خود را به چالش بکشید! -### ◀ اول از همه! * +### ◀ اول از همه! \* @@ -363,6 +364,7 @@ if a := some_func(): ### ◀ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند + 1\. ```py @@ -447,7 +449,9 @@ False --- ### ◀ مراقب عملیات‌های زنجیره‌ای باشید + + ```py >>> (False == False) in [False] # منطقیه False @@ -472,7 +476,8 @@ False #### 💡 توضیح: طبق https://docs.python.org/3/reference/expressions.html#comparisons -> اگر a، b، c، ...، y، z عبارت‌های عملیات و op1، op2، ...، opN عملگرهای عملیات باشند، آنگاه عملیات a op1 b op2 c ... y opN z معادل عملیات a op1 b and b op2 c and ... y opN z است. فقط دقت کنید که هر عبارت یک بار ارزیابی می‌شود. + +> اگر a، b، c، ...، y، z عبارت‌های عملیات و op1، op2، ...، opN عملگرهای عملیات باشند، آنگاه عملیات a op1 b op2 c ... y opN z معادل عملیات a op1 b and b op2 c and ... y opN z است. فقط دقت کنید که هر عبارت یک بار ارزیابی می‌شود. شاید چنین رفتاری برای شما احمقانه به نظر بیاد ولی برای عملیات‌هایی مثل `a == b == c` و `0 <= x <= 100` عالی عمل می‌کنه. @@ -493,7 +498,9 @@ False --- ### ◀ چطور از عملگر `is` استفاده نکنیم + + عبارت پایین خیلی معروفه و تو کل اینترنت موجوده. 1\. @@ -543,7 +550,7 @@ False #### 💡 توضیح: -**فرض بین عملگرهای `is` و `==`** +**فرض بین عملگرهای `is` و `==`** - عملگر `is` بررسی میکنه که دو متغیر در حافظه دستگاه به یک شیء اشاره میکنند یا نه (یعنی شناسه متغیرها رو با هم تطبیق میده). - عملگر `==` مقدار متغیرها رو با هم مقایسه میکنه و یکسان بودنشون رو بررسی میکنه. @@ -560,6 +567,7 @@ False وقتی پایتون رو اجرا می‌کنید اعداد از `-5` تا `256` در حافظه ذخیره میشن. چون این اعداد خیلی پرکاربرد هستند پس منطقیه که اون‌ها رو در حافظه دستگاه، آماده داشته باشیم. نقل قول از https://docs.python.org/3/c-api/long.html + > در پیاده سازی فعلی یک آرایه از اشیاء عددی صحیح برای تمام اعداد صحیح بین `-5` تا `256` نگه‌داری می‌شود. وقتی شما یک عدد صحیح در این بازه به مقداردهی می‌کنید، فقط یک ارجاع به آن عدد که از قبل در حافظه ذخیره شده است دریافت می‌کنید. پس تغییر مقدار عدد 1 باید ممکن باشد. که در این مورد من به رفتار پایتون شک دارم تعریف‌نشده است. :-) ```py @@ -618,7 +626,9 @@ False --- ### ◀ کلیدهای هش + + 1\. ```py @@ -635,7 +645,7 @@ some_dict[5] = "Python" "JavaScript" >>> some_dict[5.0] # رشته ("Python")، رشته ("Ruby") رو از بین برد؟ "Python" ->>> some_dict[5] +>>> some_dict[5] "Python" >>> complex_five = 5 + 0j @@ -685,12 +695,14 @@ complex True ``` - **توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیده‌ای معروف [تصادف هش](https://en.wikipedia.org/wiki/Collision_(disambiguation)#Other_uses) میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند. + **توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیده‌ای معروف [تصادف هش]() میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند. --- ### ◀ در عمق وجود همه ما یکسان هستیم + + ```py class WTF: pass @@ -743,8 +755,10 @@ True --- -### ◀ بی‌نظمی در خود نظم * +### ◀ بی‌نظمی در خود نظم \* + + ```py from collections import OrderedDict @@ -807,7 +821,7 @@ TypeError: unhashable type: 'dict' #### 💡 توضیح: - دلیل اینکه این مقایسه بین متغیرهای `dictionary`، `ordered_dict` و `another_ordered_dict` به درستی اجرا نمیشه به خاطر نحوه پیاده‌سازی تابع `__eq__` در کلاس `OrderedDict` هست. طبق [مستندات](https://docs.python.org/3/library/collections.html#ordereddict-objects) - > مقایسه برابری بین شیءهایی از نوع OrderedDict به ترتیب اعضای آن‌ها هم بستگی دارد و به صورت `list(od1.items())==list(od2.items())` پیاده سازی شده است. مقایسه برابری بین شیءهای `OrderedDict` و شیءهای قابل نگاشت دیگر به ترتیب اعضای آن‌ها بستگی ندارد و مقایسه همانند دیکشنری‌های عادی انجام می‌شود. + > مقایسه برابری بین شیءهایی از نوع OrderedDict به ترتیب اعضای آن‌ها هم بستگی دارد و به صورت `list(od1.items())==list(od2.items())` پیاده سازی شده است. مقایسه برابری بین شیءهای `OrderedDict` و شیءهای قابل نگاشت دیگر به ترتیب اعضای آن‌ها بستگی ندارد و مقایسه همانند دیکشنری‌های عادی انجام می‌شود. - این رفتار باعث میشه که بتونیم `OrderedDict` ها رو هرجایی که یک دیکشنری عادی کاربرد داره، جایگزین کنیم و استفاده کنیم. - خب، حالا چرا تغییر ترتیب روی طول مجموعه‌ای که از دیکشنری‌ها ساختیم، تاثیر گذاشت؟ جوابش همین رفتار مقایسه‌ای غیرانتقالی بین این شیءهاست. از اونجایی که `set` ها مجموعه‌ای از عناصر غیرتکراری و بدون نظم هستند، ترتیبی که عناصر تو این مجموعه‌ها درج میشن نباید مهم باشه. ولی در این مورد، مهم هست. بیاید کمی تجزیه و تحلیلش کنیم. @@ -837,14 +851,16 @@ TypeError: unhashable type: 'dict' >>> another_set.add(another_ordered_dict) >>> len(another_set) 2 - ``` + ``` - پس بی‌ثباتی تو این رفتار به خاطر اینه که مقدار `another_ordered_dict in another_set` برابر با `False` هست چون `ordered_dict` از قبل داخل `another_set` هست و همونطور که قبلا مشاهده کردید، مقدار `ordered_dict == another_ordered_dict` برابر با `False` هست. + پس بی‌ثباتی تو این رفتار به خاطر اینه که مقدار `another_ordered_dict in another_set` برابر با `False` هست چون `ordered_dict` از قبل داخل `another_set` هست و همونطور که قبلا مشاهده کردید، مقدار `ordered_dict == another_ordered_dict` برابر با `False` هست. --- -### ◀ تلاش کن... * +### ◀ تلاش کن... \* + + ```py def some_func(): try: @@ -852,7 +868,7 @@ def some_func(): finally: return 'from_finally' -def another_func(): +def another_func(): for _ in range(3): try: continue @@ -905,7 +921,9 @@ Iteration 0 --- ### ◀ برای چی؟ + + ```py some_string = "wtf" some_dict = {} @@ -924,7 +942,7 @@ for i, some_dict[i] in enumerate(some_string): - یک حلقه `for` در [گرامر پایتون](https://docs.python.org/3/reference/grammar.html) این طور تعریف میشه: - ``` + ```bash for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] ``` @@ -939,7 +957,7 @@ for i, some_dict[i] in enumerate(some_string): **خروجی:** - ``` + ```bash 0 1 2 @@ -964,7 +982,9 @@ for i, some_dict[i] in enumerate(some_string): --- ### ◀ اختلاف زمانی در محاسبه + + 1\. ```py @@ -1030,12 +1050,14 @@ array_4 = [400, 500, 600] - در مورد دوم، مقداردهی برشی به `array_2` باعث به‌روز شدن شیء قدیمی این متغیر از `[1,2,3,4]` به `[1,2,3,4,5]` میشه و هر دو متغیر `gen_2` و `array_2` به یک شیء اشاره میکنند که حالا به‌روز شده. - خیلی‌خب، حالا طبق منطقی که تا الان گفتیم، نباید مقدار `list(gen)` در قطعه‌کد سوم، `[11, 21, 31, 12, 22, 32, 13, 23, 33]` باشه؟ (چون `array_3` و `array_4` قراره درست مثل `array_1` رفتار کنن). دلیل این که چرا (فقط) مقادیر `array_4` به‌روز شدن، توی [PEP-289](https://www.python.org/dev/peps/pep-0289/#the-details) توضیح داده شده. - > فقط بیرونی‌ترین عبارت حلقه `for` بلافاصله محاسبه میشه و باقی عبارت‌ها به تعویق انداخته میشن تا زمانی که تولیدکننده اجرا بشه. + > فقط بیرونی‌ترین عبارت حلقه `for` بلافاصله محاسبه میشه و باقی عبارت‌ها به تعویق انداخته میشن تا زمانی که تولیدکننده اجرا بشه. --- ### ◀ هر گردی، گردو نیست + + ```py >>> 'something' is not None True @@ -1052,6 +1074,7 @@ False --- ### ◀ یک بازی دوز که توش X همون اول برنده میشه! + ```py @@ -1115,9 +1138,12 @@ board = [row] * 3 --- -### ◀ متغیر شرودینگر * +### ◀ متغیر شرودینگر \* + +مثال اول: + ```py funcs = [] results = [] @@ -1141,7 +1167,7 @@ funcs_results = [func() for func in funcs] مقدار `x` در هر تکرار حلقه قبل از اضافه کردن `some_func` به لیست `funcs` متفاوت بود، ولی همه توابع در خارج از حلقه مقدار `6` رو برمیگردونند. -2. +مثال دوم: ```py >>> powers_of_x = [lambda x: x**i for i in range(10)] @@ -1151,7 +1177,7 @@ funcs_results = [func() for func in funcs] #### 💡 توضیح: -- وقتی یک تابع رو در داخل یک حلقه تعریف می‌کنیم که در بدنه‌اش از متغیر اون حلقه استفاده شده، بست این تابع به *متغیر* وصله، نه *مقدار* اون. تابع به جای اینکه از مقدار `x` در زمان تعریف تابع استفاده کنه، در زمینه اطرافش دنبال `x` می‌گرده. پس همه این توابع از آخرین مقداری که به متغیر `x` مقداردهی شده برای محاسباتشون استفاده می‌کنند. ما می‌تونیم ببینیم که این توابع از متغیر `x` که در زمینه اطرافشون (*نه* از متغیر محلی) هست، استفاده می‌کنند، به این صورت: +- وقتی یک تابع رو در داخل یک حلقه تعریف می‌کنیم که در بدنه‌اش از متغیر اون حلقه استفاده شده، بست این تابع به _متغیر_ وصله، نه _مقدار_ اون. تابع به جای اینکه از مقدار `x` در زمان تعریف تابع استفاده کنه، در زمینه اطرافش دنبال `x` می‌گرده. پس همه این توابع از آخرین مقداری که به متغیر `x` مقداردهی شده برای محاسباتشون استفاده می‌کنند. ما می‌تونیم ببینیم که این توابع از متغیر `x` که در زمینه اطرافشون (_نه_ از متغیر محلی) هست، استفاده می‌کنند، به این صورت: ```py >>> import inspect @@ -1194,8 +1220,10 @@ ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) --- -### ◀ اول مرغ بوده یا تخم مرغ؟ * +### ◀ اول مرغ بوده یا تخم مرغ؟ \* + + 1\. ```py @@ -1245,7 +1273,9 @@ False --- ### ◀ روابط بین زیرمجموعه کلاس‌ها + + **خروجی:** ```py @@ -1270,9 +1300,10 @@ False --- ### ◀ برابری و هویت متدها + -1. +مثال اول ```py class SomeClass: @@ -1301,10 +1332,10 @@ True True ``` -با دوبار دسترسی به `classm`، یک شیء برابر دریافت می‌کنیم، اما *همان* شیء نیست؟ بیایید ببینیم +با دوبار دسترسی به `classm`، یک شیء برابر دریافت می‌کنیم، اما _همان_ شیء نیست؟ بیایید ببینیم چه اتفاقی برای نمونه‌های `SomeClass` می‌افتد: -2. +مثال دوم ```py o1 = SomeClass() @@ -1328,7 +1359,7 @@ True True ``` -دسترسی به `classm` یا `method` دو بار، اشیایی برابر اما نه *یکسان* را برای همان نمونه از `SomeClass` ایجاد می‌کند. +دسترسی به `classm` یا `method` دو بار، اشیایی برابر اما نه _یکسان_ را برای همان نمونه از `SomeClass` ایجاد می‌کند. #### 💡 توضیح @@ -1346,7 +1377,7 @@ True ``` -- `classmethod` توابع را به متدهای کلاس تبدیل می‌کند. متدهای کلاس وصاف‌هایی هستند که هنگام دسترسی، یک شیء متد ایجاد می‌کنند که به *کلاس* (نوع) شیء متصل می‌شود، نه خود شیء. +- `classmethod` توابع را به متدهای کلاس تبدیل می‌کند. متدهای کلاس وصاف‌هایی هستند که هنگام دسترسی، یک شیء متد ایجاد می‌کنند که به _کلاس_ (نوع) شیء متصل می‌شود، نه خود شیء. ```py >>> o1.classm @@ -1371,9 +1402,9 @@ True ``` - ایجاد شیءهای "متد" جدید در هر بار فراخوانی متدهای نمونه و نیاز به اصلاح آرگومان‌ها برای درج `self`، عملکرد را به شدت تحت تأثیر قرار می‌داد. -CPython 3.7 [این مشکل را حل کرد](https://bugs.python.org/issue26110) با معرفی opcodeهای جدیدی که فراخوانی متدها را بدون ایجاد شیء متد موقتی مدیریت می‌کنند. این به شرطی است که تابع دسترسی‌یافته واقعاً فراخوانی شود، بنابراین قطعه‌کدهای اینجا تحت تأثیر قرار نمی‌گیرند و همچنان متد ایجاد می‌کنند :) + CPython 3.7 [این مشکل را حل کرد](https://bugs.python.org/issue26110) با معرفی opcodeهای جدیدی که فراخوانی متدها را بدون ایجاد شیء متد موقتی مدیریت می‌کنند. این به شرطی است که تابع دسترسی‌یافته واقعاً فراخوانی شود، بنابراین قطعه‌کدهای اینجا تحت تأثیر قرار نمی‌گیرند و همچنان متد ایجاد می‌کنند :) -### ◀ آل-ترو-یشن * +### ◀ آل-ترو-یشن \* @@ -1405,14 +1436,16 @@ True return True ``` -- `all([])` مقدار `True` را برمی‌گرداند چون iterable خالی است. -- `all([[]])` مقدار `False` را برمی‌گرداند چون آرایه‌ی داده‌شده یک عنصر دارد، یعنی `[]`، و در پایتون، لیست خالی مقدار falsy دارد. +- `all([])` مقدار `True` را برمی‌گرداند چون iterable خالی است. +- `all([[]])` مقدار `False` را برمی‌گرداند چون آرایه‌ی داده‌شده یک عنصر دارد، یعنی `[]`، و در پایتون، لیست خالی مقدار falsy دارد. - `all([[[]]])` و نسخه‌های بازگشتی بالاتر همیشه `True` هستند. دلیلش این است که عنصر واحد آرایه‌ی داده‌شده (`[[...]]`) دیگر خالی نیست، و لیست‌هایی که دارای مقدار باشند، truthy در نظر گرفته می‌شوند. --- ### ◀ کاما‌ی شگفت‌انگیز + + **خروجی (< 3.6):** ```py @@ -1444,7 +1477,9 @@ SyntaxError: invalid syntax --- ### ◀ رشته‌ها و بک‌اسلش‌ها + + **خروجی:** ```py @@ -1468,31 +1503,33 @@ True - در یک رشته‌ی معمولی در پایتون، بک‌اسلش برای فرار دادن (escape) نویسه‌هایی استفاده می‌شود که ممکن است معنای خاصی داشته باشند (مانند تک‌نقل‌قول، دوتا‌نقل‌قول، و خودِ بک‌اسلش). - ```py - >>> "wt\"f" - 'wt"f' - ``` + ```py + >>> "wt\"f" + 'wt"f' + ``` - در یک رشته‌ی خام (raw string literal) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان شکل منتقل می‌شوند، به‌همراه رفتار فرار دادن نویسه‌ی بعدی. - ```py - >>> r'wt\"f' == 'wt\\"f' - True - >>> print(repr(r'wt\"f')) - 'wt\\"f' + ```py + >>> r'wt\"f' == 'wt\\"f' + True + >>> print(repr(r'wt\"f')) + 'wt\\"f' - >>> print("\n") + >>> print("\n") - >>> print(r"\\n") - '\\n' - ``` + >>> print(r"\\n") + '\\n' + ``` - در یک رشته‌ی خام (raw string) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان صورت منتقل می‌شوند، همراه با رفتاری که کاراکتر بعدی را فرار می‌دهد (escape می‌کند). --- ### ◀ گره نیست، نَه! + + ```py x = True y = False @@ -1520,7 +1557,9 @@ SyntaxError: invalid syntax --- ### ◀ رشته‌های نیمه سه‌نقل‌قولی + + **خروجی:** ```py @@ -1541,7 +1580,7 @@ SyntaxError: EOF while scanning triple-quoted string literal - پایتون از الحاق ضمنی [رشته‌های متنی](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation) پشتیبانی می‌کند. برای مثال، - ``` + ```python >>> print("wtf" "python") wtfpython >>> print("wtf" "") # or "wtf""" @@ -1553,7 +1592,9 @@ SyntaxError: EOF while scanning triple-quoted string literal --- ### ◀ مشکل بولین ها چیست؟ + + 1\. ‫ یک مثال ساده برای شمردن تعداد مقادیر بولی # اعداد صحیح در یک iterable با انواع داده‌ی مخلوط. @@ -1611,12 +1652,12 @@ I have lost faith in truth! - در پایتون، `bool` زیرکلاسی از `int` است - ```py - >>> issubclass(bool, int) - True - >>> issubclass(int, bool) - False - ``` + ```py + >>> issubclass(bool, int) + True + >>> issubclass(int, bool) + False + ``` - و بنابراین، `True` و `False` نمونه‌هایی از `int` هستند @@ -1645,7 +1686,9 @@ I have lost faith in truth! --- ### ◀ متغیرهای کلاس و متغیرهای نمونه + + 1\. ```py @@ -1718,7 +1761,9 @@ True --- ### ◀ واگذار کردن None + + ```py some_iterable = ('a', 'b') @@ -1751,7 +1796,9 @@ def some_func(val): --- ### ◀ بازگرداندن با استفاده از `yield from`! + + 1\. ```py @@ -1815,7 +1862,7 @@ def some_func(x): --- -### ◀ بازتاب‌ناپذیری * +### ◀ بازتاب‌ناپذیری \* @@ -1920,8 +1967,11 @@ TypeError: 'tuple' object does not support item assignment - نقل‌قول از https://docs.python.org/3/reference/datamodel.html - > دنباله‌های تغییرناپذیر - شیئی از نوع دنباله‌ی تغییرناپذیر، پس از ایجاد دیگر قابل تغییر نیست. (اگر شیء شامل ارجاع‌هایی به اشیای دیگر باشد، این اشیای دیگر ممکن است قابل تغییر باشند و تغییر کنند؛ اما مجموعه‌ی اشیایی که مستقیماً توسط یک شیء تغییرناپذیر ارجاع داده می‌شوند، نمی‌تواند تغییر کند.) + > دنباله‌های تغییرناپذیر + + ```text + شیئی از نوع دنباله‌ی تغییرناپذیر، پس از ایجاد دیگر قابل تغییر نیست. (اگر شیء شامل ارجاع‌هایی به اشیای دیگر باشد، این اشیای دیگر ممکن است قابل تغییر باشند و تغییر کنند؛ اما مجموعه‌ی اشیایی که مستقیماً توسط یک شیء تغییرناپذیر ارجاع داده می‌شوند، نمی‌تواند تغییر کند.) + ``` - عملگر `+=` لیست را به‌صورت درجا (in-place) تغییر می‌دهد. تخصیص به یک عضو کار نمی‌کند، اما زمانی که استثنا ایجاد می‌شود، عضو موردنظر پیش از آن به‌صورت درجا تغییر کرده است. - همچنین توضیحی در [پرسش‌های متداول رسمی پایتون](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works) وجود دارد. @@ -1929,6 +1979,7 @@ TypeError: 'tuple' object does not support item assignment --- ### ◀ متغیری که از اسکوپ بیرونی ناپدید می‌شود + ```py @@ -1959,62 +2010,64 @@ NameError: name 'e' is not defined هنگامی که یک استثنا (Exception) با استفاده از کلمه‌ی کلیدی `as` به متغیری تخصیص داده شود، این متغیر در انتهای بلاکِ `except` پاک می‌شود. این رفتار مشابه کد زیر است: - ```py - except E as N: - foo - ``` +```py +except E as N: + foo +``` - به این شکل ترجمه شده باشد: +به این شکل ترجمه شده باشد: - ```py - except E as N: - try: - foo - finally: - del N - ``` +```py +except E as N: + try: + foo + finally: + del N +``` این بدان معناست که استثنا باید به نام دیگری انتساب داده شود تا بتوان پس از پایان بند `except` به آن ارجاع داد. استثناها پاک می‌شوند چون با داشتن «ردیابی» (traceback) ضمیمه‌شده، یک چرخه‌ی مرجع (reference cycle) با قاب پشته (stack frame) تشکیل می‌دهند که باعث می‌شود تمام متغیرهای محلی (locals) در آن قاب تا زمان پاکسازی حافظه (garbage collection) باقی بمانند. - در پایتون، بندها (`clauses`) حوزه‌ی مستقل ندارند. در مثال بالا، همه‌چیز در یک حوزه‌ی واحد قرار دارد، و متغیر `e` در اثر اجرای بند `except` حذف می‌شود. این موضوع در مورد توابع صادق نیست، زیرا توابع حوزه‌های داخلی جداگانه‌ای دارند. مثال زیر این نکته را نشان می‌دهد: - ```py - def f(x): - del(x) - print(x) + ```py + def f(x): + del(x) + print(x) - x = 5 - y = [5, 4, 3] - ``` + x = 5 + y = [5, 4, 3] + ``` - **خروجی:** + **خروجی:** - ```py - >>> f(x) - UnboundLocalError: local variable 'x' referenced before assignment - >>> f(y) - UnboundLocalError: local variable 'x' referenced before assignment - >>> x - 5 - >>> y - [5, 4, 3] - ``` + ```py + >>> f(x) + UnboundLocalError: local variable 'x' referenced before assignment + >>> f(y) + UnboundLocalError: local variable 'x' referenced before assignment + >>> x + 5 + >>> y + [5, 4, 3] + ``` - در پایتون نسخه‌ی ۲.x، نام متغیر `e` به یک نمونه از `Exception()` انتساب داده می‌شود، بنابراین وقتی سعی کنید آن را چاپ کنید، چیزی نمایش داده نمی‌شود. - **خروجی (Python 2.x):** + **خروجی (Python 2.x):** - ```py - >>> e - Exception() - >>> print e - # چیزی چاپ نمی شود. - ``` + ```py + >>> e + Exception() + >>> print e + # چیزی چاپ نمی شود. + ``` --- ### ◀ تبدیل اسرارآمیز نوع کلید + + ```py class SomeClass(str): pass @@ -2073,7 +2126,9 @@ str --- ### ◀ ببینیم می‌توانید این را حدس بزنید؟ + + ```py a, b = a[b] = {}, 5 ``` @@ -2089,12 +2144,12 @@ a, b = a[b] = {}, 5 - طبق [مرجع زبان پایتون](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)، دستورات انتساب فرم زیر را دارند: - ``` + ```text (target_list "=")+ (expression_list | yield_expression) ``` و - + > یک دستور انتساب ابتدا فهرست عبارت‌ها (expression list) را ارزیابی می‌کند (توجه کنید این عبارت می‌تواند یک عبارت تکی یا فهرستی از عبارت‌ها جداشده با ویرگول باشد که دومی به یک تاپل منجر می‌شود)، سپس شیء حاصل را به هریک از اهداف انتساب از **چپ به راست** تخصیص می‌دهد. - علامت `+` در `(target_list "=")+` به این معناست که می‌توان **یک یا چند** هدف انتساب داشت. در این حالت، اهداف انتساب ما `a, b` و `a[b]` هستند (توجه کنید که عبارت ارزیابی‌شده دقیقاً یکی است، که در اینجا `{}` و `5` است). @@ -2178,7 +2233,9 @@ ValueError: Exceeds the limit (4300) for integer string conversion: ## بخش: شیب‌های لغزنده ### ◀ تغییر یک دیکشنری هنگام پیمایش روی آن + + ```py x = {0: None} @@ -2190,7 +2247,7 @@ for i in x: **خروجی (پایتون 2.7تا پایتون 3.5):** -``` +```text 0 1 2 @@ -2214,6 +2271,7 @@ for i in x: --- ### ◀ عملیات سرسختانه‌ی `del` + @@ -2262,6 +2320,7 @@ Deleted! --- ### ◀ متغیری که از حوزه خارج است + 1\. @@ -2352,7 +2411,9 @@ UnboundLocalError: local variable 'a' referenced before assignment --- ### ◀ حذف المان‌های لیست در حین پیمایش + + ```py list_1 = [1, 2, 3, 4] list_2 = [1, 2, 3, 4] @@ -2391,13 +2452,13 @@ for idx, item in enumerate(list_4): - هیچ‌وقت ایده‌ی خوبی نیست که شیئی را که روی آن پیمایش می‌کنید تغییر دهید. روش درست این است که روی یک کپی از آن شیء پیمایش کنید؛ در این‌جا `list_3[:]` دقیقاً همین کار را می‌کند. - ```py - >>> some_list = [1, 2, 3, 4] - >>> id(some_list) - 139798789457608 - >>> id(some_list[:]) # دقت کنید که پایتون برای اسلایس کردن، یک شی جدید میسازد - 139798779601192 - ``` + ```py + >>> some_list = [1, 2, 3, 4] + >>> id(some_list) + 139798789457608 + >>> id(some_list[:]) # دقت کنید که پایتون برای اسلایس کردن، یک شی جدید میسازد + 139798779601192 + ``` **تفاوت بین `del`، `remove` و `pop`:** @@ -2414,7 +2475,8 @@ for idx, item in enumerate(list_4): --- -### ◀ زیپِ دارای اتلاف برای پیمایشگرها * +### ◀ زیپِ دارای اتلاف برای پیمایشگرها \* + ```py @@ -2425,7 +2487,7 @@ for idx, item in enumerate(list_4): >>> first_three, remaining ([0, 1, 2], [3, 4, 5, 6]) >>> numbers_iter = iter(numbers) ->>> list(zip(numbers_iter, first_three)) +>>> list(zip(numbers_iter, first_three)) [(0, 0), (1, 1), (2, 2)] # تاحالا که خوب بوده، حالا روی باقی مانده های زیپ رو امتحان می کنیم. >>> list(zip(numbers_iter, remaining)) @@ -2438,38 +2500,40 @@ for idx, item in enumerate(list_4): - بر اساس [مستندات](https://docs.python.org/3.3/library/functions.html#zip) پایتون، پیاده‌سازی تقریبی تابع `zip` به شکل زیر است: - ```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) - ``` + ```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) + ``` -- بنابراین این تابع تعداد دلخواهی از اشیای قابل پیمایش (*iterable*) را دریافت می‌کند، و با فراخوانی تابع `next` روی آن‌ها، هر یک از عناصرشان را به لیست `result` اضافه می‌کند. این فرایند زمانی متوقف می‌شود که اولین پیمایشگر به انتها برسد. +- بنابراین این تابع تعداد دلخواهی از اشیای قابل پیمایش (_iterable_) را دریافت می‌کند، و با فراخوانی تابع `next` روی آن‌ها، هر یک از عناصرشان را به لیست `result` اضافه می‌کند. این فرایند زمانی متوقف می‌شود که اولین پیمایشگر به انتها برسد. - نکته مهم اینجاست که هر زمان یکی از پیمایشگرها به پایان برسد، عناصر موجود در لیست `result` نیز دور ریخته می‌شوند. این دقیقاً همان اتفاقی است که برای عدد `3` در `numbers_iter` رخ داد. - روش صحیح برای انجام عملیات بالا با استفاده از تابع `zip` چنین است: - - ```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)] - ``` - اولین آرگومانِ تابع `zip` باید پیمایشگری باشد که کمترین تعداد عنصر را دارد. + ```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)] + ``` + + اولین آرگومانِ تابع `zip` باید پیمایشگری باشد که کمترین تعداد عنصر را دارد. --- ### ◀ نشت کردن متغیرهای حلقه! + + 1\. ```py @@ -2530,15 +2594,16 @@ print(x, ': x in global') #### 💡 توضیح: -- در پایتون، حلقه‌های `for` از حوزه (*scope*) فعلی که در آن قرار دارند استفاده می‌کنند و متغیرهای تعریف‌شده در حلقه حتی بعد از اتمام حلقه نیز باقی می‌مانند. این قاعده حتی در مواردی که متغیر حلقه پیش‌تر در فضای نام سراسری (*global namespace*) تعریف شده باشد نیز صدق می‌کند؛ در چنین حالتی، متغیر موجود مجدداً به مقدار جدید متصل می‌شود. +- در پایتون، حلقه‌های `for` از حوزه (_scope_) فعلی که در آن قرار دارند استفاده می‌کنند و متغیرهای تعریف‌شده در حلقه حتی بعد از اتمام حلقه نیز باقی می‌مانند. این قاعده حتی در مواردی که متغیر حلقه پیش‌تر در فضای نام سراسری (_global namespace_) تعریف شده باشد نیز صدق می‌کند؛ در چنین حالتی، متغیر موجود مجدداً به مقدار جدید متصل می‌شود. -- تفاوت‌های موجود در خروجی مفسرهای Python 2.x و Python 3.x در مثال مربوط به «لیست‌های ادراکی» (*list comprehension*) به دلیل تغییراتی است که در مستند [«تغییرات جدید در Python 3.0»](https://docs.python.org/3/whatsnew/3.0.html) آمده است: +- تفاوت‌های موجود در خروجی مفسرهای Python 2.x و Python 3.x در مثال مربوط به «لیست‌های ادراکی» (_list comprehension_) به دلیل تغییراتی است که در مستند [«تغییرات جدید در Python 3.0»](https://docs.python.org/3/whatsnew/3.0.html) آمده است: - > «لیست‌های ادراکی دیگر فرم نحوی `[... for var in item1, item2, ...]` را پشتیبانی نمی‌کنند و به جای آن باید از `[... for var in (item1, item2, ...)]` استفاده شود. همچنین توجه داشته باشید که لیست‌های ادراکی در Python 3.x معنای متفاوتی دارند: آن‌ها از لحاظ معنایی به بیان ساده‌تر، مشابه یک عبارت تولیدکننده (*generator expression*) درون تابع `list()` هستند و در نتیجه، متغیرهای کنترل حلقه دیگر به فضای نام بیرونی نشت نمی‌کنند.» + > «لیست‌های ادراکی دیگر فرم نحوی `[... for var in item1, item2, ...]` را پشتیبانی نمی‌کنند و به جای آن باید از `[... for var in (item1, item2, ...)]` استفاده شود. همچنین توجه داشته باشید که لیست‌های ادراکی در Python 3.x معنای متفاوتی دارند: آن‌ها از لحاظ معنایی به بیان ساده‌تر، مشابه یک عبارت تولیدکننده (_generator expression_) درون تابع `list()` هستند و در نتیجه، متغیرهای کنترل حلقه دیگر به فضای نام بیرونی نشت نمی‌کنند.» --- ### ◀ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید! + ```py @@ -2564,42 +2629,44 @@ def some_func(default_arg=[]): - آرگومان‌های تغییرپذیر پیش‌فرض در توابع پایتون، هر بار که تابع فراخوانی می‌شود مقداردهی نمی‌شوند؛ بلکه مقداردهی آنها تنها یک بار در زمان تعریف تابع انجام می‌شود و مقدار اختصاص‌یافته به آن‌ها به عنوان مقدار پیش‌فرض برای فراخوانی‌های بعدی استفاده خواهد شد. هنگامی که به صراحت مقدار `[]` را به عنوان آرگومان به `some_func` ارسال کردیم، مقدار پیش‌فرض برای متغیر `default_arg` مورد استفاده قرار نگرفت، بنابراین تابع همان‌طور که انتظار داشتیم عمل کرد. - ```py - def some_func(default_arg=[]): - default_arg.append("some_string") - return default_arg - ``` + ```py + def some_func(default_arg=[]): + default_arg.append("some_string") + return default_arg + ``` - **خروجی:** + **خروجی:** - ```py - >>> some_func.__defaults__ # مقادیر پیشفرض این تابع را نمایش می دهد. - ([],) - >>> some_func() - >>> some_func.__defaults__ - (['some_string'],) - >>> some_func() - >>> some_func.__defaults__ - (['some_string', 'some_string'],) - >>> some_func([]) - >>> some_func.__defaults__ - (['some_string', 'some_string'],) - ``` + ```py + >>> some_func.__defaults__ # مقادیر پیشفرض این تابع را نمایش می دهد. + ([],) + >>> some_func() + >>> some_func.__defaults__ + (['some_string'],) + >>> some_func() + >>> some_func.__defaults__ + (['some_string', 'some_string'],) + >>> some_func([]) + >>> some_func.__defaults__ + (['some_string', 'some_string'],) + ``` - یک روش رایج برای جلوگیری از باگ‌هایی که به دلیل آرگومان‌های تغییرپذیر رخ می‌دهند، این است که مقدار پیش‌فرض را `None` قرار داده و سپس درون تابع بررسی کنیم که آیا مقداری به آن آرگومان ارسال شده است یا خیر. مثال: - ```py - def some_func(default_arg=None): - if default_arg is None: - default_arg = [] - default_arg.append("some_string") - return default_arg - ``` + ```py + def some_func(default_arg=None): + if default_arg is None: + default_arg = [] + default_arg.append("some_string") + return default_arg + ``` --- ### ◀ گرفتن استثناها (Exceptions) + + ```py some_list = [1, 2, 3] try: @@ -2648,7 +2715,7 @@ SyntaxError: invalid syntax **خروجی (Python 2.x):** - ``` + ```text Caught again! list.remove(x): x not in list ``` @@ -2676,7 +2743,7 @@ SyntaxError: invalid syntax **خروجی:** - ``` + ```text Caught again! list.remove(x): x not in list ``` @@ -2684,7 +2751,9 @@ SyntaxError: invalid syntax --- ### ◀ عملوندهای یکسان، داستانی متفاوت! + + 1\. ```py @@ -2721,7 +2790,7 @@ a += [5, 6, 7, 8] #### 💡 توضیح: -- عملگر `a += b` همیشه همانند `a = a + b` رفتار نمی‌کند. کلاس‌ها *ممکن است* عملگرهای *`op=`* را به گونه‌ای متفاوت پیاده‌سازی کنند، و لیست‌ها نیز چنین می‌کنند. +- عملگر `a += b` همیشه همانند `a = a + b` رفتار نمی‌کند. کلاس‌ها _ممکن است_ عملگرهای _`op=`_ را به گونه‌ای متفاوت پیاده‌سازی کنند، و لیست‌ها نیز چنین می‌کنند. - عبارت `a = a + [5,6,7,8]` یک لیست جدید ایجاد می‌کند و مرجع `a` را به این لیست جدید اختصاص می‌دهد، بدون آنکه `b` را تغییر دهد. @@ -2730,7 +2799,9 @@ a += [5, 6, 7, 8] --- ### ◀ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس + + 1\. ```py @@ -2778,7 +2849,7 @@ class SomeClass: --- -### ◀ گرد کردن به روش بانکدار * +### ◀ گرد کردن به روش بانکدار \* بیایید یک تابع ساده برای به‌دست‌آوردن عنصر میانی یک لیست پیاده‌سازی کنیم: @@ -2831,7 +2902,7 @@ def get_middle(some_list): --- -### ◀ سوزن‌هایی در انبار کاه * +### ◀ سوزن‌هایی در انبار کاه \* @@ -2878,7 +2949,7 @@ tuple() 3\. -``` +```python ten_words_list = [ "some", "very", @@ -2925,7 +2996,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}) ``` @@ -2968,10 +3039,10 @@ def similar_recursive_func(a): #### 💡 توضیح: - برای مورد ۱، عبارت صحیح برای رفتار مورد انتظار این است: -`x, y = (0, 1) if True else (None, None)` + `x, y = (0, 1) if True else (None, None)` - برای مورد ۲، عبارت صحیح برای رفتار مورد انتظار این است: -اینجا، `t = ('one',)` یا `t = 'one',` (ویرگول از قلم افتاده است). در غیر این صورت مفسر `t` را به عنوان یک `str` در نظر گرفته و به صورت کاراکتر به کاراکتر روی آن پیمایش می‌کند. + اینجا، `t = ('one',)` یا `t = 'one',` (ویرگول از قلم افتاده است). در غیر این صورت مفسر `t` را به عنوان یک `str` در نظر گرفته و به صورت کاراکتر به کاراکتر روی آن پیمایش می‌کند. - علامت `()` یک توکن خاص است و نشان‌دهنده‌ی یک `tuple` خالی است. @@ -2991,10 +3062,10 @@ def similar_recursive_func(a): 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 @@ -3009,8 +3080,10 @@ def similar_recursive_func(a): --- -### ◀ تقسیم‌ها * +### ◀ تقسیم‌ها \* + + ```py >>> 'a'.split() ['a'] @@ -3031,22 +3104,23 @@ def similar_recursive_func(a): #### 💡 توضیح: - در نگاه اول ممکن است به نظر برسد جداکننده‌ی پیش‌فرض متد `split` یک فاصله‌ی تکی (`' '`) است؛ اما مطابق با [مستندات رسمی](https://docs.python.org/3/library/stdtypes.html#str.split): - > اگر `sep` مشخص نشده یا برابر با `None` باشد، یک الگوریتم متفاوت برای جدا کردن اعمال می‌شود: رشته‌هایی از فاصله‌های متوالی به عنوان یک جداکننده‌ی واحد در نظر گرفته شده و در نتیجه، هیچ رشته‌ی خالی‌ای در ابتدا یا انتهای لیست خروجی قرار نمی‌گیرد، حتی اگر رشته‌ی اولیه دارای فاصله‌های اضافی در ابتدا یا انتها باشد. به همین دلیل، تقسیم یک رشته‌ی خالی یا رشته‌ای که فقط شامل فضای خالی است با جداکننده‌ی `None` باعث بازگشت یک لیست خالی `[]` می‌شود. - > اگر `sep` مشخص شود، جداکننده‌های متوالی در کنار هم قرار نمی‌گیرند و هر جداکننده، یک رشته‌ی خالی جدید ایجاد می‌کند. (مثلاً `'1,,2'.split(',')` مقدار `['1', '', '2']` را برمی‌گرداند.) تقسیم یک رشته‌ی خالی با یک جداکننده‌ی مشخص‌شده نیز باعث بازگشت `['']` می‌شود. + > اگر `sep` مشخص نشده یا برابر با `None` باشد، یک الگوریتم متفاوت برای جدا کردن اعمال می‌شود: رشته‌هایی از فاصله‌های متوالی به عنوان یک جداکننده‌ی واحد در نظر گرفته شده و در نتیجه، هیچ رشته‌ی خالی‌ای در ابتدا یا انتهای لیست خروجی قرار نمی‌گیرد، حتی اگر رشته‌ی اولیه دارای فاصله‌های اضافی در ابتدا یا انتها باشد. به همین دلیل، تقسیم یک رشته‌ی خالی یا رشته‌ای که فقط شامل فضای خالی است با جداکننده‌ی `None` باعث بازگشت یک لیست خالی `[]` می‌شود. + > اگر `sep` مشخص شود، جداکننده‌های متوالی در کنار هم قرار نمی‌گیرند و هر جداکننده، یک رشته‌ی خالی جدید ایجاد می‌کند. (مثلاً `'1,,2'.split(',')` مقدار `['1', '', '2']` را برمی‌گرداند.) تقسیم یک رشته‌ی خالی با یک جداکننده‌ی مشخص‌شده نیز باعث بازگشت `['']` می‌شود. - توجه به اینکه چگونه فضای خالی در ابتدا و انتهای رشته در قطعه‌ی کد زیر مدیریت شده است، این مفهوم را روشن‌تر می‌کند: - ```py - >>> ' a '.split(' ') - ['', 'a', ''] - >>> ' a '.split() - ['a'] - >>> ''.split(' ') - [''] - ``` + ```py + >>> ' a '.split(' ') + ['', 'a', ''] + >>> ' a '.split() + ['a'] + >>> ''.split(' ') + [''] + ``` --- -### ◀ واردسازی‌های عمومی * +### ◀ واردسازی‌های عمومی \* + @@ -3078,38 +3152,38 @@ NameError: name '_another_weird_name_func' is not defined - اغلب توصیه می‌شود از واردسازی عمومی (wildcard imports) استفاده نکنید. اولین دلیل واضح آن این است که در این نوع واردسازی‌ها، اسامی که با زیرخط (`_`) شروع شوند، وارد نمی‌شوند. این مسئله ممکن است در زمان اجرا به خطا منجر شود. - اگر از ساختار `from ... import a, b, c` استفاده کنیم، خطای `NameError` فوق اتفاق نمی‌افتاد. - ```py - >>> from module import some_weird_name_func_, _another_weird_name_func - >>> _another_weird_name_func() - works! - ``` + ```py + >>> from module import some_weird_name_func_, _another_weird_name_func + >>> _another_weird_name_func() + works! + ``` - اگر واقعاً تمایل دارید از واردسازی عمومی استفاده کنید، لازم است فهرستی به نام `__all__` را در ماژول خود تعریف کنید که شامل نام اشیاء عمومی (public) قابل‌دسترس هنگام واردسازی عمومی است. - ```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!") - ``` + def _another_weird_name_func(): + print("works!") + ``` - **خروجی** + **خروجی** - ```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 + ``` --- -### ◀ همه چیز مرتب شده؟ * +### ◀ همه چیز مرتب شده؟ \* @@ -3151,7 +3225,9 @@ False --- ### ◀ زمان نیمه‌شب وجود ندارد؟ + + ```py from datetime import datetime @@ -3181,6 +3257,7 @@ if noon_time: پیش از پایتون 3.5، مقدار بولی برای شیء `datetime.time` اگر نشان‌دهندهٔ نیمه‌شب به وقت UTC بود، برابر با `False` در نظر گرفته می‌شد. این رفتار در استفاده از دستور `if obj:` برای بررسی تهی بودن شیء یا برابر بودن آن با مقدار "خالی"، ممکن است باعث بروز خطا شود. --- + --- ## بخش: گنجینه‌های پنهان! @@ -3188,7 +3265,9 @@ if noon_time: این بخش شامل چند مورد جالب و کمتر شناخته‌شده درباره‌ی پایتون است که بیشتر مبتدی‌هایی مثل من از آن بی‌خبرند (البته دیگر اینطور نیست). ### ◀ خب پایتون، می‌توانی کاری کنی پرواز کنم؟ + + خب، بفرمایید ```py @@ -3207,6 +3286,7 @@ Sshh... It's a super-secret. --- ### ◀ `goto`، ولی چرا؟ + ```py @@ -3238,7 +3318,9 @@ Freedom! --- ### ◀ خودتان را آماده کنید! + + اگر جزو افرادی هستید که دوست ندارند در پایتون برای مشخص کردن محدوده‌ها از فضای خالی (whitespace) استفاده کنند، می‌توانید با ایمپورت کردن ماژول زیر از آکولاد `{}` به سبک زبان C استفاده کنید: ```py @@ -3265,7 +3347,9 @@ SyntaxError: not a chance --- ### ◀ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم + + **خروجی (Python 3.x)** ```py @@ -3288,19 +3372,21 @@ True - نقل قولی از PEP-401: > با توجه به اینکه عملگر نابرابری `!=` در پایتون ۳.۰ یک اشتباه وحشتناک و انگشت‌سوز (!) بوده است، عمو زبان مهربان برای همیشه (FLUFL) عملگر الماسی‌شکل `<>` را مجدداً به‌عنوان تنها روش درست برای این منظور بازگردانده است. - + - البته «عمو بَری» چیزهای بیشتری برای گفتن در این PEP داشت؛ می‌توانید آن‌ها را [اینجا](https://www.python.org/dev/peps/pep-0401/) مطالعه کنید. - این قابلیت در محیط تعاملی به خوبی عمل می‌کند، اما در زمان اجرای کد از طریق فایل پایتون، با خطای `SyntaxError` روبرو خواهید شد (برای اطلاعات بیشتر به این [issue](https://github.com/satwikkansal/wtfpython/issues/94) مراجعه کنید). با این حال، می‌توانید کد خود را درون یک `eval` یا `compile` قرار دهید تا این قابلیت فعال شود. - ```py - from __future__ import barry_as_FLUFL - print(eval('"Ruby" <> "Python"')) - ``` + ```py + from __future__ import barry_as_FLUFL + print(eval('"Ruby" <> "Python"')) + ``` --- ### ◀ حتی پایتون هم می‌داند که عشق پیچیده است + + ```py import this ``` @@ -3309,7 +3395,7 @@ import this **خروجی:** -``` +```text The Zen of Python, by Tim Peters Beautiful is better than ugly. @@ -3358,7 +3444,9 @@ True --- ### ◀ بله، این واقعاً وجود دارد! + + **عبارت `else` برای حلقه‌ها.** یک مثال معمول آن می‌تواند چنین باشد: ```py @@ -3405,8 +3493,10 @@ Try block executed successfully... --- -### ◀ عملگر Ellipsis * +### ◀ عملگر Ellipsis \* + + ```py def some_func(): Ellipsis @@ -3431,12 +3521,13 @@ Ellipsis - در پایتون، `Ellipsis` یک شیء درونی (`built-in`) است که به صورت سراسری (`global`) در دسترس است و معادل `...` است. - ```py - >>> ... - Ellipsis - ``` + ```py + >>> ... + Ellipsis + ``` - عملگر `Ellipsis` می‌تواند برای چندین منظور استفاده شود: + - به عنوان یک نگه‌دارنده برای کدی که هنوز نوشته نشده است (مانند دستور `pass`) - در سینتکس برش (`slicing`) برای نمایش برش کامل در ابعاد باقی‌مانده @@ -3468,13 +3559,16 @@ Ellipsis ``` نکته: این روش برای آرایه‌هایی با هر تعداد بُعد کار می‌کند. حتی می‌توانید از برش (`slice`) در بُعد اول و آخر استفاده کرده و ابعاد میانی را نادیده بگیرید (به صورت `n_dimensional_array[first_dim_slice, ..., last_dim_slice]`). + - در [نوع‌دهی (`type hinting`)](https://docs.python.org/3/library/typing.html) برای اشاره به بخشی از نوع (مانند `Callable[..., int]` یا `Tuple[str, ...]`) استفاده می‌شود. - همچنین می‌توانید از `Ellipsis` به عنوان آرگومان پیش‌فرض تابع استفاده کنید (برای مواردی که می‌خواهید میان «آرگومانی ارسال نشده است» و «مقدار `None` ارسال شده است» تمایز قائل شوید). --- ### ◀ بی‌نهایت (`Inpinity`) + + این املای کلمه تعمداً به همین شکل نوشته شده است. لطفاً برای اصلاح آن درخواست (`patch`) ارسال نکنید. **خروجی (پایتون 3.x):** @@ -3495,7 +3589,9 @@ Ellipsis --- ### ◀ بیایید خرابکاری کنیم + + 1\. ```py @@ -3572,12 +3668,15 @@ AttributeError: 'A' object has no attribute '__variable' - همچنین، اگر نام تغییر یافته بیش از ۲۵۵ کاراکتر باشد، برش داده می‌شود. --- + --- ## بخش: ظاهرها فریبنده‌اند! ### ◀ خطوط را رد می‌کند؟ + + **خروجی:** ```py @@ -3648,7 +3747,9 @@ def energy_receive(): --- ### ◀ خب، یک جای کار مشکوک است... + + ```py def square(x): """ @@ -3677,21 +3778,24 @@ def square(x): - نحوۀ برخورد پایتون با تب‌ها به این صورت است: > ابتدا تب‌ها (از چپ به راست) با یک تا هشت فاصله جایگزین می‌شوند به‌طوری که تعداد کل کاراکترها تا انتهای آن جایگزینی، مضربی از هشت باشد <...> + - بنابراین «تب» در آخرین خط تابع `square` با هشت فاصله جایگزین شده و به همین دلیل داخل حلقه قرار می‌گیرد. - پایتون ۳ آنقدر هوشمند هست که چنین مواردی را به‌صورت خودکار با خطا اعلام کند. - **خروجی (Python 3.x):** + **خروجی (Python 3.x):** - ```py - TabError: inconsistent use of tabs and spaces in indentation - ``` + ```py + TabError: inconsistent use of tabs and spaces in indentation + ``` --- + --- ## بخش: متفرقه ### ◀ `+=` سریع‌تر است + ```py @@ -3710,7 +3814,9 @@ def square(x): --- ### ◀ بیایید یک رشته‌ی بزرگ بسازیم! + + ```py def add_string_with_plus(iters): s = "" @@ -3805,12 +3911,14 @@ timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) - وجود راه‌های متعدد برای قالب‌بندی و ایجاد رشته‌های بزرگ تا حدودی در تضاد با [ذِن پایتون](https://www.python.org/dev/peps/pep-0020/) است که می‌گوید: - > «باید یک راه — و ترجیحاً فقط یک راه — واضح برای انجام آن وجود داشته باشد.» + > «باید یک راه — و ترجیحاً فقط یک راه — واضح برای انجام آن وجود داشته باشد.» --- -### ◀ کُند کردن جستجوها در `dict` * +### ◀ کُند کردن جستجوها در `dict` \* + + ```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)} @@ -3844,8 +3952,10 @@ KeyError: 1 - اولین باری که یک دیکشنری (`dict`) با کلیدی غیر از `str` فراخوانی شود، این حالت تغییر می‌کند و جستجوهای بعدی از تابع عمومی استفاده خواهند کرد. - این فرایند برای آن نمونه‌ی خاص از دیکشنری غیرقابل بازگشت است و حتی لازم نیست کلید موردنظر در دیکشنری موجود باشد. به همین دلیل است که حتی تلاش ناموفق برای دسترسی به کلیدی ناموجود نیز باعث ایجاد همین تأثیر (کند شدن جستجو) می‌شود. -### ◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) * +### ◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \* + + ```py import sys @@ -3907,13 +4017,16 @@ def dict_size(o): - همچنین اگر اندازه‌ی دیکشنری به‌علت اضافه‌شدن کلیدهای جدید تغییر کند (`resize` شود)، اشتراک‌گذاری کلیدها تنها زمانی ادامه می‌یابد که فقط یک دیکشنری در حال استفاده از آن‌ها باشد (این اجازه می‌دهد در متد `__init__` برای اولین نمونه‌ی ساخته‌شده، صفات متعددی تعریف کنید بدون آن‌که اشتراک‌گذاری کلیدها از بین برود). اما اگر چند نمونه همزمان وجود داشته باشند و تغییر اندازه‌ی دیکشنری رخ دهد، قابلیت اشتراک‌گذاری کلیدها برای نمونه‌های بعدی همان کلاس غیرفعال خواهد شد. زیرا CPython دیگر نمی‌تواند مطمئن باشد که آیا نمونه‌های بعدی دقیقاً از مجموعه‌ی یکسانی از صفات استفاده خواهند کرد یا خیر. - نکته‌ای کوچک برای کاهش مصرف حافظه‌ی برنامه: هرگز صفات نمونه‌ها را حذف نکنید و حتماً تمام صفات را در متد `__init__` تعریف و مقداردهی اولیه کنید! -### ◀ موارد جزئی * +### ◀ موارد جزئی \* + + - متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) - **توضیح:** اگر `join()` به‌عنوان متدی روی رشته پیاده‌سازی شود، می‌تواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشونده‌ی دیگر کار کند. اگر به‌جای آن روی لیست تعریف می‌شد، باید به‌طور جداگانه برای هر نوع دیگری نیز پیاده‌سازی می‌شد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. + **توضیح:** اگر `join()` به‌عنوان متدی روی رشته پیاده‌سازی شود، می‌تواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشونده‌ی دیگر کار کند. اگر به‌جای آن روی لیست تعریف می‌شد، باید به‌طور جداگانه برای هر نوع دیگری نیز پیاده‌سازی می‌شد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. - تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح: + - عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی). - عبارت `'a'[0][0][0][0][0]` نیز از نظر معنایی صحیح است، زیرا پایتون برخلاف زبان‌هایی که از C منشعب شده‌اند، نوع داده‌ای جداگانه‌ای برای کاراکتر ندارد. بنابراین انتخاب یک کاراکتر از یک رشته، منجر به بازگشت یک رشته‌ی تک‌کاراکتری می‌شود. - عبارات `3 --0-- 5 == 8` و `--5 == 5` هر دو از لحاظ معنایی درست بوده و مقدارشان برابر `True` است. @@ -3936,7 +4049,7 @@ def dict_size(o): - عبارت `++a` به‌شکل `+(+a)` تفسیر می‌شود که معادل `a` است. به‌همین ترتیب، خروجی عبارت `--a` نیز قابل توجیه است. - این [تاپیک در StackOverflow](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) دلایل نبودن عملگرهای افزایش (`++`) و کاهش (`--`) در پایتون را بررسی می‌کند. -- احتمالاً با عملگر Walrus (گراز دریایی) در پایتون آشنا هستید؛ اما تا به حال در مورد *عملگر Space-invader (مهاجم فضایی)* شنیده‌اید؟ +- احتمالاً با عملگر Walrus (گراز دریایی) در پایتون آشنا هستید؛ اما تا به حال در مورد _عملگر Space-invader (مهاجم فضایی)_ شنیده‌اید؟ ```py >>> a = 42 @@ -3947,74 +4060,74 @@ def dict_size(o): از آن به‌عنوان جایگزینی برای عملگر افزایش (increment)، در ترکیب با یک عملگر دیگر استفاده می‌شود. - ```py - >>> a +=+ 1 - >>> a - >>> 44 - ``` +```py +>>> a +=+ 1 +>>> a +>>> 44 +``` - **💡 توضیح:** این شوخی از [توییت Raymond Hettinger](https://twitter.com/raymondh/status/1131103570856632321?lang=en) برگرفته شده است. عملگر «مهاجم فضایی» در واقع همان عبارت بدفرمت‌شده‌ی `a -= (-1)` است که معادل با `a = a - (- 1)` می‌باشد. حالت مشابهی برای عبارت `a += (+ 1)` نیز وجود دارد. +**💡 توضیح:** این شوخی از [توییت Raymond Hettinger](https://twitter.com/raymondh/status/1131103570856632321?lang=en) برگرفته شده است. عملگر «مهاجم فضایی» در واقع همان عبارت بدفرمت‌شده‌ی `a -= (-1)` است که معادل با `a = a - (- 1)` می‌باشد. حالت مشابهی برای عبارت `a += (+ 1)` نیز وجود دارد. - پایتون یک عملگر مستندنشده برای [استلزام معکوس (converse implication)](https://en.wikipedia.org/wiki/Converse_implication) دارد. - ```py - >>> False ** False == True - True - >>> False ** True == False - True - >>> True ** False == True - True - >>> True ** True == True - True - ``` + ```py + >>> False ** False == True + True + >>> False ** True == False + True + >>> True ** False == True + True + >>> True ** True == True + True + ``` - **💡 توضیح:** اگر مقادیر `False` و `True` را به‌ترتیب با اعداد ۰ و ۱ جایگزین کرده و محاسبات را انجام دهید، جدول درستی حاصل، معادل یک عملگر استلزام معکوس خواهد بود. ([منبع](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator)) + **💡 توضیح:** اگر مقادیر `False` و `True` را به‌ترتیب با اعداد ۰ و ۱ جایگزین کرده و محاسبات را انجام دهید، جدول درستی حاصل، معادل یک عملگر استلزام معکوس خواهد بود. ([منبع](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator)) - حالا که صحبت از عملگرها شد، عملگر `@` نیز برای ضرب ماتریسی در پایتون وجود دارد (نگران نباشید، این بار واقعی است). - ```py - >>> import numpy as np - >>> np.array([2, 2, 2]) @ np.array([7, 8, 8]) - 46 - ``` + ```py + >>> import numpy as np + >>> np.array([2, 2, 2]) @ np.array([7, 8, 8]) + 46 + ``` - **💡 توضیح:** عملگر `@` در پایتون ۳٫۵ با در نظر گرفتن نیازهای جامعه علمی اضافه شد. هر شی‌ای می‌تواند متد جادویی `__matmul__` را بازنویسی کند تا رفتار این عملگر را مشخص نماید. + **💡 توضیح:** عملگر `@` در پایتون ۳٫۵ با در نظر گرفتن نیازهای جامعه علمی اضافه شد. هر شی‌ای می‌تواند متد جادویی `__matmul__` را بازنویسی کند تا رفتار این عملگر را مشخص نماید. - از پایتون ۳٫۸ به بعد می‌توانید از نحو متداول f-string مانند `f'{some_var=}'` برای اشکال‌زدایی سریع استفاده کنید. مثال, - ```py - >>> some_string = "wtfpython" - >>> f'{some_string=}' - "some_string='wtfpython'" - ``` + ```py + >>> some_string = "wtfpython" + >>> f'{some_string=}' + "some_string='wtfpython'" + ``` - پایتون برای ذخیره‌سازی متغیرهای محلی در توابع از ۲ بایت استفاده می‌کند. از نظر تئوری، این به معنای امکان تعریف حداکثر ۶۵۵۳۶ متغیر در یک تابع است. با این حال، پایتون راهکار مفیدی ارائه می‌کند که می‌توان با استفاده از آن بیش از ۲^۱۶ نام متغیر را ذخیره کرد. کد زیر نشان می‌دهد وقتی بیش از ۶۵۵۳۶ متغیر محلی تعریف شود، در پشته (stack) چه اتفاقی رخ می‌دهد (هشدار: این کد تقریباً ۲^۱۸ خط متن چاپ می‌کند، بنابراین آماده باشید!): - ```py - import dis - exec(""" - def f(): - """ + """ - """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) + ```py + import dis + exec(""" + def f(): + """ + """ + """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) - f() + f() - print(dis.dis(f)) - ``` + print(dis.dis(f)) + ``` -- چندین رشته (Thread) در پایتون، کدِ *پایتونی* شما را به‌صورت همزمان اجرا نمی‌کنند (بله، درست شنیدید!). شاید به نظر برسد که ایجاد چندین رشته و اجرای همزمان آن‌ها منطقی است، اما به دلیل وجود [قفل مفسر سراسری (GIL)](https://wiki.python.org/moin/GlobalInterpreterLock) در پایتون، تمام کاری که انجام می‌دهید این است که رشته‌هایتان به‌نوبت روی یک هسته اجرا می‌شوند. رشته‌ها در پایتون برای وظایفی مناسب هستند که عملیات I/O دارند، اما برای رسیدن به موازی‌سازی واقعی در وظایف پردازشی سنگین (CPU-bound)، بهتر است از ماژول [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) در پایتون استفاده کنید. +- چندین رشته (Thread) در پایتون، کدِ _پایتونی_ شما را به‌صورت همزمان اجرا نمی‌کنند (بله، درست شنیدید!). شاید به نظر برسد که ایجاد چندین رشته و اجرای همزمان آن‌ها منطقی است، اما به دلیل وجود [قفل مفسر سراسری (GIL)](https://wiki.python.org/moin/GlobalInterpreterLock) در پایتون، تمام کاری که انجام می‌دهید این است که رشته‌هایتان به‌نوبت روی یک هسته اجرا می‌شوند. رشته‌ها در پایتون برای وظایفی مناسب هستند که عملیات I/O دارند، اما برای رسیدن به موازی‌سازی واقعی در وظایف پردازشی سنگین (CPU-bound)، بهتر است از ماژول [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) در پایتون استفاده کنید. - گاهی اوقات، متد `print` ممکن است مقادیر را فوراً چاپ نکند. برای مثال، - ```py - # File some_file.py - import time - - print("wtfpython", end="_") - time.sleep(3) - ``` + ```py + # File some_file.py + import time - این کد عبارت `wtfpython` را به دلیل آرگومان `end` پس از ۳ ثانیه چاپ می‌کند؛ چرا که بافر خروجی تنها پس از رسیدن به کاراکتر `\n` یا در زمان اتمام اجرای برنامه تخلیه می‌شود. برای تخلیه‌ی اجباری بافر می‌توانید از آرگومان `flush=True` استفاده کنید. + print("wtfpython", end="_") + time.sleep(3) + ``` + + این کد عبارت `wtfpython` را به دلیل آرگومان `end` پس از ۳ ثانیه چاپ می‌کند؛ چرا که بافر خروجی تنها پس از رسیدن به کاراکتر `\n` یا در زمان اتمام اجرای برنامه تخلیه می‌شود. برای تخلیه‌ی اجباری بافر می‌توانید از آرگومان `flush=True` استفاده کنید. - برش لیست‌ها (List slicing) با اندیس‌های خارج از محدوده، خطایی ایجاد نمی‌کند. @@ -4026,27 +4139,27 @@ def dict_size(o): - برش زدن (slicing) یک شئ قابل پیمایش (iterable) همیشه یک شئ جدید ایجاد نمی‌کند. به‌عنوان مثال، - ```py - >>> some_str = "wtfpython" - >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n'] - >>> some_list is some_list[:] # انتظار می‌رود False باشد چون یک شیء جدید ایجاد شده است. - False - >>> some_str is some_str[:] # True چون رشته‌ها تغییرناپذیر هستند، بنابراین ساختن یک شیء جدید فایده‌ای ندارد. - True - ``` + ```py + >>> some_str = "wtfpython" + >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n'] + >>> some_list is some_list[:] # انتظار می‌رود False باشد چون یک شیء جدید ایجاد شده است. + False + >>> some_str is some_str[:] # True چون رشته‌ها تغییرناپذیر هستند، بنابراین ساختن یک شیء جدید فایده‌ای ندارد. + True + ``` - در پایتون ۳، فراخوانی `int('١٢٣٤٥٦٧٨٩')` مقدار `123456789` را برمی‌گرداند. در پایتون، نویسه‌های ده‌دهی (Decimal characters) شامل تمام ارقامی هستند که می‌توانند برای تشکیل اعداد در مبنای ده استفاده شوند؛ به‌عنوان مثال نویسه‌ی U+0660 که همان رقم صفر عربی-هندی است. [اینجا](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) داستان جالبی درباره این رفتار پایتون آمده است. - از پایتون ۳ به بعد، می‌توانید برای افزایش خوانایی، اعداد را با استفاده از زیرخط (`_`) جدا کنید. - ```py - >>> six_million = 6_000_000 - >>> six_million - 6000000 - >>> hex_address = 0xF00D_CAFE - >>> hex_address - 4027435774 - ``` + ```py + >>> six_million = 6_000_000 + >>> six_million + 6000000 + >>> hex_address = 0xF00D_CAFE + >>> hex_address + 4027435774 + ``` - عبارت `'abc'.count('') == 4` مقدار `True` برمی‌گرداند. در اینجا یک پیاده‌سازی تقریبی از متد `count` آورده شده که این موضوع را شفاف‌تر می‌کند: @@ -4058,9 +4171,10 @@ def dict_size(o): return result ``` - این رفتار به این دلیل است که زیررشته‌ی خالی (`''`) با برش‌هایی (slices) به طول صفر در رشته‌ی اصلی مطابقت پیدا می‌کند. +این رفتار به این دلیل است که زیررشته‌ی خالی (`''`) با برش‌هایی (slices) به طول صفر در رشته‌ی اصلی مطابقت پیدا می‌کند. --- + --- # مشارکت @@ -4112,4 +4226,4 @@ def dict_size(o): من چند درخواست برای نسخه PDF (و epub) کتاب wtfpython دریافت کرده‌ام. برای دریافت این نسخه‌ها به محض آماده شدن، می‌توانید اطلاعات خود را [اینجا](https://form.jotform.com/221593245656057) وارد کنید. -**همین بود دوستان!** برای دریافت مطالب آینده مشابه این، می‌توانید ایمیل خود را [اینجا](https://form.jotform.com/221593598380062) اضافه کنید. +**همین بود دوستان!** برای دریافت مطالب آینده مشابه این، می‌توانید ایمیل خود را [اینجا](https://form.jotform.com/221593598380062) اضافه کنید.