From 00a1228ca39155f27271bbde1feb18b6f9b71ad9 Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 10:04:41 -0500 Subject: [PATCH 001/210] Fix spelling (found -> find) Noticed a minor spelling error while reading through this fantastic document. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..4fae417b 100644 --- a/README.md +++ b/README.md @@ -579,7 +579,7 @@ So, why is Python all over the place? ``` * So how can we update the key to `5` (instead of `5.0`)? We can't actually do this update in place, but what we can do is first delete the key (`del some_dict[5.0]`), and then set it (`some_dict[5]`) to get the integer `5` as the key instead of floating `5.0`, though this should be needed in rare cases. -* How did Python found `5` in a dictionary containing `5.0`? Python does this in constant time without having to scan through every item by using hash functions. When Python looks up a key `foo` in a dict, it first computes `hash(foo)` (which runs in constant-time). Since in Python it is required that objects that compare equal also have the same hash value ([docs](https://docs.python.org/3/reference/datamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value. +* How did Python find `5` in a dictionary containing `5.0`? Python does this in constant time without having to scan through every item by using hash functions. When Python looks up a key `foo` in a dict, it first computes `hash(foo)` (which runs in constant-time). Since in Python it is required that objects that compare equal also have the same hash value ([docs](https://docs.python.org/3/reference/datamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value. ```py >>> 5 == 5.0 == 5 + 0j True From f20be4cfc437475ece4aa745557cb73a54f94a7c Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 10:13:50 -0500 Subject: [PATCH 002/210] Extend the explanation of the "is not ..." section I thought that the explanation for "'something' is (not None)" could be a little more explicit. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..60cead49 100644 --- a/README.md +++ b/README.md @@ -933,7 +933,7 @@ False #### 💡 Explanation - `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. -- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. +- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. In this expression, `(not None)` evaluates to `True`, since `None` is is `False` in a boolean context, so the expression becomes `'something' is True`. --- From 8370f3a3b93432c69746544d3546177f888e050c Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 10:16:47 -0500 Subject: [PATCH 003/210] A minor grammar correction --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..c6220b78 100644 --- a/README.md +++ b/README.md @@ -1023,7 +1023,7 @@ Even when the values of `x` were different in every iteration prior to appending - When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation. -- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope. +- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why does this work?** Because this will define the variable again within the function's scope. ```py funcs = [] From 3e99005ae431ff6dc470c58c90258e371e72230e Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 10:19:17 -0500 Subject: [PATCH 004/210] Clarify for quoting examples The example of the use of backslash to escape a double-quote makes more sense when used inside a double-quoted string. If the string is quoted with single quotes, one could of course just write 'wt"f' withouth requiring any escaping. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..0f1b3bc1 100644 --- a/README.md +++ b/README.md @@ -1210,7 +1210,7 @@ True - In a usual python string, the backslash is used to escape characters that may have a special meaning (like single-quote, double-quote, and the backslash itself). ```py - >>> 'wt\"f' + >>> "wt\"f" 'wt"f' ``` - In a raw string literal (as indicated by the prefix `r`), the backslashes pass themselves as is along with the behavior of escaping the following character. From 16c90f9b2429b3182df44d399339c7d3c540be3e Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Sun, 19 Jan 2020 12:03:30 -0500 Subject: [PATCH 005/210] Fixed logic error in "Beware of default mutable arguments!" The example showing how using None as a default argument is used instead of a mutable default argument had reversed logic. It would set default_arg to [] whenever the caller passed a non-None argument. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7b5c96f9..f08baa3e 100644 --- a/README.md +++ b/README.md @@ -2241,7 +2241,7 @@ def some_func(default_arg=[]): ```py def some_func(default_arg=None): - if default_arg is not None: + if default_arg is None: default_arg = [] default_arg.append("some_string") return default_arg From 6cebc952c3116d49eced5e41444647b63b214919 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 20 Jan 2020 14:23:20 +0530 Subject: [PATCH 006/210] Fix minor typo in the "is not" example --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index eff94035..ab26e5a0 100644 --- a/README.md +++ b/README.md @@ -933,7 +933,8 @@ False #### 💡 Explanation - `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. -- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. In this expression, `(not None)` evaluates to `True`, since `None` is is `False` in a boolean context, so the expression becomes `'something' is True`. +- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. +- In the example, `(not None)` evaluates to `True` since the value `None` is `False` in a boolean context, so the expression becomes `'something' is True`. --- From 50265e91fcf50d00710b91e7e413c76533ab8893 Mon Sep 17 00:00:00 2001 From: Haksell Date: Sat, 15 Feb 2020 09:03:08 +0100 Subject: [PATCH 007/210] Correct six typos --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index ab26e5a0..b037a984 100644 --- a/README.md +++ b/README.md @@ -673,7 +673,7 @@ class OrderedDictWithHash(OrderedDict): True >>> dictionary == another_ordered_dict # and b == c True ->>> ordered_dict == another_ordered_dict # the why isn't c == a ?? +>>> ordered_dict == another_ordered_dict # then why isn't c == a ?? False # We all know that a set consists of only unique elements, @@ -705,7 +705,7 @@ What is going on here? - The reason why intransitive equality didn't hold among `dictionary`, `ordered_dict` and `another_ordered_dict` is because of the way `__eq__` method is implemented in `OrderedDict` class. From the [docs](https://docs.python.org/3/library/collections.html#ordereddict-objects) > Equality tests between OrderedDict objects are order-sensitive and are implemented as `list(od1.items())==list(od2.items())`. Equality tests between `OrderedDict` objects and other Mapping objects are order-insensitive like regular dictionaries. -- The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. +- The reason for this equality in behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used. - Okay, so why did changing the order affect the length of the generated `set` object? The answer is the lack of intransitive equality only. Since sets are "unordered" collections of unique elements, the order in which elements are inserted shouldn't matter. But in this case, it does matter. Let's break it down a bit, ```py >>> some_set = set() @@ -840,7 +840,7 @@ for i, some_dict[i] in enumerate(some_string): **💡 Explanation:** - - The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(4)` this case) is unpacked and assigned the target list variables (`i` in this case). + - The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(4)` in this case) is unpacked and assigned the target list variables (`i` in this case). * The `enumerate(some_string)` function yields a new value `i` (a counter going up) and a character from the `some_string` in each iteration. It then sets the (just assigned) `i` key of the dictionary `some_dict` to that character. The unrolling of the loop can be simplified as: ```py @@ -2113,7 +2113,7 @@ Where did element `3` go from the `numbers` list? result.append(elem) yield tuple(result) ``` -- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. +- So the function takes in arbitrary number of utterable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. - The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`. - The correct way to do the above using `zip` would be, ```py @@ -2575,7 +2575,7 @@ def similar_recursive_func(a): >>> assert a == b, "Values are not equal" Traceback (most recent call last): File "", line 1, in - AssertionError: Values aren not equal + AssertionError: Values are not equal ``` * As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). @@ -3446,7 +3446,7 @@ Let's increase the number of iterations by a factor of 10. time.sleep(3) ``` - This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument. + This will print the `wtfpython` after 3 seconds due to the `end` argument because the output buffer is flushed either after encountering `\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument. * List slicing with out of the bounds indices throws no errors ```py From a4af8a4e0c8f92d197dbddd7bcaec674f7c6ed59 Mon Sep 17 00:00:00 2001 From: Haksell Date: Sat, 15 Feb 2020 09:04:24 +0100 Subject: [PATCH 008/210] Correct six typos --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b037a984..9de76511 100644 --- a/README.md +++ b/README.md @@ -2113,7 +2113,7 @@ Where did element `3` go from the `numbers` list? result.append(elem) yield tuple(result) ``` -- So the function takes in arbitrary number of utterable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. +- So the function takes in arbitrary number of iterable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. - The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`. - The correct way to do the above using `zip` would be, ```py From 184df9f99dcaae4c55db1cf0cf048a7d2e74f51c Mon Sep 17 00:00:00 2001 From: Pradhvan Date: Sat, 15 Feb 2020 14:30:05 +0530 Subject: [PATCH 009/210] README.md: Update Python version in 'Modifying a dictionary while iterating over it' example --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ab26e5a0..27bbce77 100644 --- a/README.md +++ b/README.md @@ -1930,7 +1930,7 @@ Yes, it runs for exactly **eight** times and stops. * It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. * How deleted keys are handled and when the resize occurs might be different for different Python implementations. * So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. -* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. +* Python 3.7.6 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. --- From 78cb5f39f5b2689386b0fa18340a3e8690bf32e2 Mon Sep 17 00:00:00 2001 From: myrmica-habilis Date: Fri, 20 Mar 2020 11:00:29 +0100 Subject: [PATCH 010/210] Update README.md - assignment expressions are evaluated and printed by the REPL --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2702a661..cd9baec6 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ File "", line 1 SyntaxError: invalid syntax >>> (a := "wtf_walrus") # This works though +'wtf_walrus' >>> a 'wtf_walrus' ``` @@ -195,6 +196,7 @@ SyntaxError: invalid syntax (6, 9) >>> (a := 6, 9) +(6, 9) >>> a 6 From 67f743eddd8cbc5e55bda08d604c938ee92a3c42 Mon Sep 17 00:00:00 2001 From: Yonatan Goldschmidt Date: Tue, 24 Mar 2020 22:22:34 +0200 Subject: [PATCH 011/210] Correctify explanation of Stubborn `del` operation --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2702a661..4d76ec23 100644 --- a/README.md +++ b/README.md @@ -1954,7 +1954,7 @@ class SomeClass: Deleted! ``` -Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example. +Phew, deleted at last. You might have guessed what saved `__del__` from being called in our first attempt to delete `x`. Let's add more twists to the example. 2\. ```py @@ -1973,9 +1973,9 @@ Okay, now it's deleted :confused: #### 💡 Explanation: + `del x` doesn’t directly call `x.__del__()`. -+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero. -+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered. -+ Calling `globals` caused the existing reference to be destroyed, and hence we can see "Deleted!" being printed (finally!). ++ When `del x` is encountered, Python deletes the name `x` from current scope and decrements by 1 the reference count of the object `x` referenced. `__del__()` is called only when the object's reference count reaches zero. ++ In the second output snippet, `__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object (specifically, the `_` magic variable which references the result value of the last non `None` expression on the REPL), thus preventing the reference count from reaching zero when `del y` was encountered. ++ Calling `globals` (or really, executing anything that will have a non `None` result) caused `_` to reference the new result, dropping the existing reference. Now the reference count reached 0 and we can see "Deleted!" being printed (finally!). --- From f735fe31163ebe72c7d95468a5ca6496fed5944f Mon Sep 17 00:00:00 2001 From: "zenglifa@msu.edu" Date: Sat, 25 Apr 2020 15:37:50 -0400 Subject: [PATCH 012/210] Replace http link with https --- wtfpython-pypi/content.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wtfpython-pypi/content.md b/wtfpython-pypi/content.md index 9827fc46..0d246693 100644 --- a/wtfpython-pypi/content.md +++ b/wtfpython-pypi/content.md @@ -1732,7 +1732,7 @@ UnboundLocalError: local variable 'a' referenced before assignment #### 💡 Explanation: * When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope which throws an error. -* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. +* Read [this](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. * To modify the outer scope variable `a` in `another_func`, use `global` keyword. ```py def another_func() From 9ff40de544eb50d68f2e9d6ce9059315d5a6a7f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joachim=20Stro=CC=88mbergson?= Date: Sat, 2 May 2020 08:54:24 +0200 Subject: [PATCH 013/210] 'less than 21' is the correct expression. Could slso be 'less or equal to 20'. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d76ec23..12b4274b 100644 --- a/README.md +++ b/README.md @@ -348,7 +348,7 @@ Makes sense, right? ![image](/images/string-intern/string_intern.png) + When `a` and `b` are set to `"wtf!"` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already `"wtf!"` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion). + A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = "wtf!", "wtf!"` is single statement, whereas `a = "wtf!"; b = "wtf!"` are two statements in a single line. This explains why the identities are different in `a = "wtf!"; b = "wtf!"`, and also explain why they are same when invoked in `some_file.py` -+ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. ++ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 21. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. + Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the fourth snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). --- From 32f14a7e16d0e28e47762e319794663c9e28c1b3 Mon Sep 17 00:00:00 2001 From: Satwik Date: Sun, 14 Jun 2020 10:40:30 +0530 Subject: [PATCH 014/210] Add Vietnamese translation Closes https://github.com/satwikkansal/wtfpython/issues/195 --- CONTRIBUTORS.md | 9 +++++++++ README.md | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 313c024f..fe779bb5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -22,6 +22,15 @@ Following are the wonderful people (in no specific order) who have contributed t | koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) | | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) | +--- + +**Translations** + +| Translator | Github | Language | +|-------------|--------|--------| +| leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [Chinese](https://github.com/leisurelicht/wtfpython-cn) | +| vuduclyunitn | [vuduclyunitn](https://github.com/vuduclyunitn) | [Vietnamese](https://github.com/vuduclyunitn/wtfptyhon-vi) | + Thank you all for your time and making wtfpython more awesome! :smile: diff --git a/README.md b/README.md index 77387cec..6a6c77c0 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From 3ba87fea65fcfa3ff6330ddca3f40e3e9937ff4e Mon Sep 17 00:00:00 2001 From: Satwik Date: Mon, 15 Jun 2020 16:03:06 +0530 Subject: [PATCH 015/210] Add link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6a6c77c0..b1e27ce4 100644 --- a/README.md +++ b/README.md @@ -3544,4 +3544,4 @@ I've received a few requests for the pdf (and epub) version of wtfpython. You ca **That's all folks!** For upcoming content like this, you can add your email [here](https://www.satwikkansal.xyz/content-like-wtfpython/). -*PS: On a sidenote, consider donating a dollar to [plant a tree](https://teamtrees.org/).* +*PS: Take help from developers like me on Codementor (for free 10$ credits, you can use [this link](https://www.codementor.io/?partner=satwikkansal)).* From 7457ffb8483eaf40dbb7ec743c31690d179d12ca Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Thu, 25 Jun 2020 16:28:58 +0530 Subject: [PATCH 016/210] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b1e27ce4..0a1009ae 100644 --- a/README.md +++ b/README.md @@ -3544,4 +3544,5 @@ I've received a few requests for the pdf (and epub) version of wtfpython. You ca **That's all folks!** For upcoming content like this, you can add your email [here](https://www.satwikkansal.xyz/content-like-wtfpython/). -*PS: Take help from developers like me on Codementor (for free 10$ credits, you can use [this link](https://www.codementor.io/?partner=satwikkansal)).* + +*PS: For consulting, you can reach out to me via Codementor (use [this link](https://www.codementor.io/satwikkansal?partner=satwikkansal) for free 10$ credits).* From 0b74f9ba5d31c4748ce7fefa237e9649f37fd325 Mon Sep 17 00:00:00 2001 From: Yonatan Goldschmidt Date: Sat, 4 Jul 2020 18:36:27 +0300 Subject: [PATCH 017/210] Add "dict lookup performance" section Closes: #208 --- README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/README.md b/README.md index 0a1009ae..c92935d2 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,7 @@ So, here we go... * [Section: Miscellaneous](#section-miscellaneous) + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + + [▶ `dict` lookup performance](#-dict-lookup-performance) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -3348,6 +3349,37 @@ Let's increase the number of iterations by a factor of 10. --- +### ▶ `dict` lookup performance + +```py +>>> some_dict = {str(i): 1 for i in range(1_000_000)} +>>> %timeit some_dict['5'] +28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +>>> some_dict[1] = 1 +>>> %timeit some_dict['5'] +37.2 ns ± 0.265 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +# why did it become much slower? +``` + +#### 💡 Explanation: ++ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys. ++ The specialized function (named `lookdict_unicode` in CPython's sources) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method. ++ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function. ++ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary - attempting a failed lookup has the same effect: +```py +>>> some_dict = {str(i): 1 for i in range(1_000_000)} +>>> %timeit some_dict['5'] +28.5 ns ± 0.142 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +>>> some_dict[1] +Traceback (most recent call last): + File "", line 1, in +KeyError: 1 +>>> %timeit some_dict['5'] +38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +``` + +--- + ### ▶ Minor Ones * * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) From f97cbdd9193f6e40aded532994339f0e4c5d56df Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 10 Jul 2020 22:28:44 +0530 Subject: [PATCH 018/210] Minor updates to slowinig down dict lookups example --- README.md | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index c92935d2..95fad37d 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ So, here we go... * [Section: Miscellaneous](#section-miscellaneous) + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ `dict` lookup performance](#-dict-lookup-performance) + + [▶ `dict` lookup performance](#-slowing-down-dict-lookups) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -3349,36 +3349,38 @@ Let's increase the number of iterations by a factor of 10. --- -### ▶ `dict` lookup performance +### ▶ Slowing down `dict` lookups ```py ->>> some_dict = {str(i): 1 for i in range(1_000_000)} +some_dict = {str(i): 1 for i in range(1_000_000)} +another_dict = {str(i): 1 for i in range(1_000_000)} +``` + +**Output:** +```py >>> %timeit some_dict['5'] 28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) >>> some_dict[1] = 1 >>> %timeit some_dict['5'] 37.2 ns ± 0.265 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) -# why did it become much slower? -``` -#### 💡 Explanation: -+ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys. -+ The specialized function (named `lookdict_unicode` in CPython's sources) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method. -+ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function. -+ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary - attempting a failed lookup has the same effect: -```py ->>> some_dict = {str(i): 1 for i in range(1_000_000)} ->>> %timeit some_dict['5'] +>>> %timeit another_dict['5'] 28.5 ns ± 0.142 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) ->>> some_dict[1] +>>> another_dict[1] # Trying to access a key that doesn't exist Traceback (most recent call last): File "", line 1, in KeyError: 1 ->>> %timeit some_dict['5'] +>>> %timeit another_dict['5'] 38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) ``` +Why are same lookups becoming slower? + +#### 💡 Explanation: ++ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys. ++ The specialized function (named `lookdict_unicode` in CPython's [source](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method. ++ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function. ++ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary. That's why attempting a failed lookup has the same effect. ---- ### ▶ Minor Ones * From ee70d52fe47745ed6b0d21ef2e3011fd198b15d3 Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 10 Jul 2020 22:30:30 +0530 Subject: [PATCH 019/210] Add Jongy to the contributors list --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fe779bb5..5a20cfc0 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -21,7 +21,7 @@ Following are the wonderful people (in no specific order) who have contributed t | Ghost account | N/A | [#96](https://github.com/satwikkansal/wtfpython/issues/96) | koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) | | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) | - +| Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208) | --- **Translations** From f72d7325fa512219c9a8ff9b69a6a7128bf3685f Mon Sep 17 00:00:00 2001 From: Satwik Date: Fri, 10 Jul 2020 22:34:22 +0530 Subject: [PATCH 020/210] Fix uuid and toc --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 95fad37d..6b74228b 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ So, here we go... * [Section: Miscellaneous](#section-miscellaneous) + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ `dict` lookup performance](#-slowing-down-dict-lookups) + + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -3349,8 +3349,8 @@ Let's increase the number of iterations by a factor of 10. --- -### ▶ Slowing down `dict` lookups - +### ▶ Slowing down `dict` lookups * + ```py some_dict = {str(i): 1 for i in range(1_000_000)} another_dict = {str(i): 1 for i in range(1_000_000)} From ee0696b676298dd70ce944626ff2e4819d70d4d2 Mon Sep 17 00:00:00 2001 From: Yonatan Goldschmidt Date: Fri, 31 Jul 2020 12:05:04 +0300 Subject: [PATCH 021/210] Add "bloating instance dicts" section Closes: #210 --- CONTRIBUTORS.md | 2 +- README.md | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 5a20cfc0..0ae584ed 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -21,7 +21,7 @@ Following are the wonderful people (in no specific order) who have contributed t | Ghost account | N/A | [#96](https://github.com/satwikkansal/wtfpython/issues/96) | koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) | | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) | -| Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208) | +| Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208), [#210](https://github.com/satwikkansal/wtfpython/issues/210) | --- **Translations** diff --git a/README.md b/README.md index 6b74228b..40f065cd 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ So, here we go... + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups) + + [▶ Bloating instance `dict`s *](#-bloating-instance-dicts-) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) @@ -3382,6 +3383,68 @@ Why are same lookups becoming slower? + This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary. That's why attempting a failed lookup has the same effect. +### ▶ Bloating instance `dict`s * + +```py +import sys + +class SomeClass: + def __init__(self): + self.some_attr1 = 1 + self.some_attr2 = 2 + self.some_attr3 = 3 + self.some_attr4 = 4 + + +def dict_size(o): + return sys.getsizeof(o.__dict__) + +``` + +**Output:** (Python 3.8, other Python 3 versions may vary a little) +```py +>>> o1 = SomeClass() +>>> o2 = SomeClass() +>>> dict_size(o1) +104 +>>> dict_size(o2) +104 +>>> del o1.some_attr1 +>>> o3 = SomeClass() +>>> dict_size(o3) +232 +>>> dict_size(o1) +232 +``` + +Let's try again... In a new interpreter: + +```py +>>> o1 = SomeClass() +>>> o2 = SomeClass() +>>> dict_size(o1) +104 # as expected +>>> o1.some_attr5 = 5 +>>> o1.some_attr6 = 6 +>>> dict_size(o1) +360 +>>> dict_size(o2) +272 +>>> o3 = SomeClass() +>>> dict_size(o3) +232 +``` + +What makes those dictionaries become bloated? And why are newly created objects bloated as well? + +#### 💡 Explanation: ++ CPython is able to reuse the same "keys" object in multiple dictionaries. This was added in [PEP 412](https://www.python.org/dev/peps/pep-0412/) with the motivation to reduce memory usage, specifically in dictionaries of instances - where keys (instance attributes) tend to be common to all instances. ++ This optimization is entirely seamless for instance dictionaries, but it is disabled if certain assumptions are broken. ++ Key-sharing dictionaries do not support deletion; if an instance attribute is deleted, the dictionary is "unshared", and key-sharing is disabled for all future instances of the same class. ++ Additionaly, if the dictionary keys have be resized (because new keys are inserted), they are kept shared *only* if they are used by a exactly single dictionary (this allows adding many attributes in the `__init__` of the very first created instance, without causing an "unshare"). If multiple instances exist when a resize happens, key-sharing is disabled for all future instances of the same class: CPython can't tell if your instances are using the same set of attributes anymore, and decides to bail out on attempting to share their keys. ++ A small tip, if you aim to lower your program's memory footprint: don't delete instance attributes, and make sure to initialize all attributes in your `__init__`! + + ### ▶ Minor Ones * * `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) From 87906b9b2f5666d2ccd67a46b0b522d8ca4d6ffe Mon Sep 17 00:00:00 2001 From: Yonatan Goldschmidt Date: Fri, 31 Jul 2020 12:05:08 +0300 Subject: [PATCH 022/210] Fix anchor name of "slowing down dict lookups" --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 40f065cd..00859a05 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ So, here we go... * [Section: Miscellaneous](#section-miscellaneous) + [▶ `+=` is faster](#--is-faster) + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups) + + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups-) + [▶ Bloating instance `dict`s *](#-bloating-instance-dicts-) + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) From a3baf043bde359d029c719b3b729dade0f18858a Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Mon, 24 Aug 2020 20:10:59 +0530 Subject: [PATCH 023/210] Add a note about the asterisks Fixes https://github.com/satwikkansal/wtfpython/issues/219 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 00859a05..b2f05d8b 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ While some of the examples you see below may not be WTFs in the truest sense, bu If you're an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt. You may have already experienced some of them before, and I might be able to revive sweet old memories of yours! :sweat_smile: -PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). +PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) (the examples marked with asterisk are the ones added in the latest major revision). So, here we go... From 7d06e7b5c1cde321c166521e72bca5c37db05818 Mon Sep 17 00:00:00 2001 From: Satwik Date: Thu, 27 Aug 2020 00:47:08 +0530 Subject: [PATCH 024/210] Add a meme --- images/expanding-brain-meme.jpg | Bin 0 -> 115494 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 images/expanding-brain-meme.jpg diff --git a/images/expanding-brain-meme.jpg b/images/expanding-brain-meme.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9437c2f9c3308f07b1b662d4fe9fc774b83b938e GIT binary patch literal 115494 zcmb@tbyOV9w=O({;O-FI-Q9yb1b26r!7U-UyIXK~f=h58Jjfuy-7RSD6AtNH8A|W84V4$F)p`&AnDS1iAWu8UFMGFyP;HL)}6{VF2D?KtW?b{TT!hL(2Ic`fqXnJG_U1g?k4L z4}}0pCWNFwQvWmk9rSxB$Q^%H0m#r$fOqK7=n#nGg#XU|PlQqibbg8IH4nN>(mztG zvSfGAwha#m7us!re_-kEjB=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HvpD{&5mC zz1{?HSusQn<4&Tiv%1K3A&EF%HXkOi5fh;-$Y?E%`CMym4T7yK2%7hHLq*E2nt%Wi zbOViO!FJV<$~wRc(DFH<%waV(bC50aL@^xk1!y7&CkXj(7qE?>1r%uDKjcr-=5WUN zaAut1jxS4aL^{YIcZaOy?+Qqd7=pcA>6@fPXLAHR2!YEO^j&?iD%G%4v0dYdCv9UU zu}$j;h14&1*I01eZKc06eB7$}k)ZVb9?uxJ4Qflth$`r7ARqy4R{;?g0m}3^zOi>n zG2$>paSo96k`?~|Yd;!I z&j7N^3*+cDs;!A;#kwJ*!J6(iiDD+r@*nc{EZ%sdmR?`qIiutKbCj=N>v_ii0B_D| zKd0-5jlb7;L$B@k&DZ*Valoa#@8_6QRK`M8NP0Yg_|%Jv(%4;P=*U z#t$K Date: Thu, 17 Sep 2020 03:38:41 +0300 Subject: [PATCH 025/210] Add link to Python FAQ to "Mutating the immutable" --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b2f05d8b..9f30a419 100644 --- a/README.md +++ b/README.md @@ -1701,6 +1701,7 @@ But I thought tuples were immutable... An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.) * `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place. +* There's also an explanation in [official Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works). --- From 27b66b4f317f7bc30a65cc84b8e6de2cb99acb7c Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Thu, 17 Sep 2020 17:02:56 +0530 Subject: [PATCH 026/210] Fix typo and minor changes --- CONTRIBUTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5085b59e..27b19618 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,6 +40,6 @@ Probably unexpected output Few things that you can consider while writing an example, -- Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's strictly enforced scheme in the project, but you can take a glance at other examples to get a gist. +- Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's no strictly enforced scheme in the project as such, but you can take a glance at other examples to get a gist. - Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write. -- Also, please don't forget to add your name to the [contributors list](/CONTRIBUTING.md). +- Also, feel free to add your name to the [contributors list](/CONTRIBUTING.md). From 9e28e00123ae2e467641a10c3d3cd4a3c2f5b6d8 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Thu, 1 Oct 2020 16:56:40 +0530 Subject: [PATCH 027/210] Update CONTRIBUTING.md --- CONTRIBUTING.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 27b19618..962a2f9d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,12 +1,8 @@ -All kinds of patches are welcome. Feel free to even suggest some catchy and funny titles for the existing Examples. The goal is to make this collection as interesting to read as possible. +All kinds of patches are welcome. Feel free to even suggest some catchy and funny titles for the existing Examples. The goal is to make this collection as interesting to read as possible. Here are a few ways through which you can contribute, -If you are interested in translating the project to another language (some people have done that in the past), please feel free to open up an issue, and let me know if you need any kind of help. - -If the changes you suggest are significant, filing an issue before submitting the actual patch will be appreciated. If you'd like to work on the issue (highly encouraged), you can mention that you're interested in working on it while creating the issue and get assigned to it. - -If you're adding a new example, please do create an issue to discuss it before submitting a patch. - -You can use the following template for adding a new example: +- If you are interested in translating the project to another language (some people have done that in the past), please feel free to open up an issue, and let me know if you need any kind of help. +- If the changes you suggest are significant, filing an issue before submitting the actual patch will be appreciated. If you'd like to work on the issue (highly encouraged), you can mention that you're interested in working on it while creating the issue and get assigned to it. +- If you're adding a new example, it is highly recommended to create an issue to discuss it before submitting a patch. You can use the following template for adding a new example:
 ### ▶ Some fancy Title *
@@ -40,6 +36,8 @@ Probably unexpected output
 
 Few things that you can consider while writing an example, 
 
+- If you are choosing to submit a new example without creating an issue and discussing, please check the project to make sure there aren't similar examples already.
 - Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's no strictly enforced scheme in the project as such, but you can take a glance at other examples to get a gist.
 - Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write.
 - Also, feel free to add your name to the [contributors list](/CONTRIBUTING.md).
+

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

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

diff --git a/README.md b/README.md
index 9f30a419..5ad8af70 100644
--- a/README.md
+++ b/README.md
@@ -1228,7 +1228,7 @@ True
     >>> print("\n")
 
     >>> print(r"\\n")
-    '\\\\n'
+    '\\n'
     ```
 - This means when a parser encounters a backslash in a raw string, it expects another character following it. And in our case (`print(r"\")`), the backslash escaped the trailing quote, leaving the parser without a terminating quote (hence the `SyntaxError`). That's why backslashes don't work at the end of a raw string.
 

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

* fixed link to CONTRIBUTORS.md

* The out of scope variable, nonlocal, #193

* added myself to CONTRIBUTORS.md :D

* Update CONTRIBUTORS.md

* added entry in index

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

\"\"

\n", + "

\"\"

\n", "

What the f*ck Python! \ud83d\ude31

\n", "

Exploring and understanding Python through surprising snippets.

\n", "\n", - "Translations: [Chinese \u4e2d\u6587](https://github.com/leisurelicht/wtfpython-cn) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].)\n", + "Translations: [Chinese \u4e2d\u6587](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Ti\u1ebfng Vi\u1ec7t](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].)\n", "\n", - "Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/3.0/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython)\n", + "Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython)\n", "\n", "Python, being a beautifully designed high-level and interpreter-based programming language, provides us with many features for the programmer's comfort. But sometimes, the outcomes of a Python snippet may not seem obvious at first sight.\n", "\n", @@ -20,7 +20,7 @@ "\n", "If you're an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt. You may have already experienced some of them before, and I might be able to revive sweet old memories of yours! :sweat_smile:\n", "\n", - "PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/).\n", + "PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) (the examples marked with asterisk are the ones added in the latest major revision). \n", "\n", "So, here we go...\n", "\n", @@ -68,7 +68,7 @@ "- Read the output snippets and,\n", " + Check if the outputs are the same as you'd expect.\n", " + Make sure if you know the exact reason behind the output being the way it is.\n", - " - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfPython)).\n", + " - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfpython/issues/new)).\n", " - If yes, give a gentle pat on your back, and you may skip to the next example.\n", "\n", "PS: You can also read WTFPython at the command line using the [pypi package](https://pypi.python.org/pypi/wtfpython),\n", @@ -353,13 +353,13 @@ "+ After being \"interned,\" many variables may reference the same string object in memory (saving memory thereby).\n", "+ In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation-dependent. There are some rules that can be used to guess if a string will be interned or not:\n", " * All length 0 and length 1 strings are interned.\n", - " * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned)\n", + " * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned)\n", " * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", - " ![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images/string-intern/string_intern.png)\n", - "+ When `a` and `b` are set to `\"wtf!\"` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't \"know\" that there's already `wtf!` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", + " ![image](/images/string-intern/string_intern.png)\n", + "+ When `a` and `b` are set to `\"wtf!\"` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't \"know\" that there's already `\"wtf!\"` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, and also explain why they are same when invoked in `some_file.py`\n", - "+ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same.\n", - "+ Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the third snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", + "+ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 21. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same.\n", + "+ Note: In Python 3.7, Constant folding was moved out from peephole optimizer to the new AST optimizer with some change in logic as well, so the fourth snippet doesn't work for Python 3.7. You can read more about the change [here](https://bugs.python.org/issue11549). \n", "\n" ] }, @@ -367,8 +367,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Hash brownies\n", - "1\\.\n" + "### \u25b6 Be careful with chained operations\n" ] }, { @@ -380,7 +379,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "False\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -388,19 +389,29 @@ } ], "source": [ - "some_dict = {}\n", - "some_dict[5.5] = \"JavaScript\"\n", - "some_dict[5.0] = \"Ruby\"\n", - "some_dict[5] = \"Python\"\n" + "(False == False) in [False] # makes sense\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "**Output:**\n", - "\n" + "False == (False in [False]) # makes sense\n" ] }, { @@ -413,7 +424,8 @@ { "data": { "text/plain": [ - "\"JavaScript\"\n" + "True\n", + "\n" ] }, "output_type": "execute_result", @@ -422,7 +434,7 @@ } ], "source": [ - "some_dict[5.5]\n" + "False == False in [False] # now what?\n" ] }, { @@ -435,7 +447,7 @@ { "data": { "text/plain": [ - "\"Python\"\n" + "False\n" ] }, "output_type": "execute_result", @@ -444,7 +456,7 @@ } ], "source": [ - "some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n" + "True is False == False\n" ] }, { @@ -457,7 +469,7 @@ { "data": { "text/plain": [ - "\"Python\"\n", + "True\n", "\n" ] }, @@ -467,7 +479,7 @@ } ], "source": [ - "some_dict[5] \n" + "False is False is False\n" ] }, { @@ -480,7 +492,7 @@ { "data": { "text/plain": [ - "complex\n" + "True\n" ] }, "output_type": "execute_result", @@ -489,8 +501,7 @@ } ], "source": [ - "complex_five = 5 + 0j\n", - "type(complex_five)\n" + "1 > 0 < 1\n" ] }, { @@ -503,7 +514,7 @@ { "data": { "text/plain": [ - "\"Python\"\n" + "False\n" ] }, "output_type": "execute_result", @@ -512,16 +523,35 @@ } ], "source": [ - "some_dict[complex_five]\n" + "(1 > 0) < 1\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "1 > (0 < 1)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "So, why is Python all over the place?\n", - "\n", "\n" ] }, @@ -529,10 +559,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", + "#### \ud83d\udca1 Explanation:\n", + "\n", + "As per https://docs.python.org/3/reference/expressions.html#membership-test-operations\n", + "\n", + "> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.\n", + "\n", + "While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`.\n", "\n", - "* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.\n", - "* Immutable objects with the same value always have the same hash in Python.\n" + "* `False is False is False` is equivalent to `(False is False) and (False is False)`\n", + "* `True is False == False` is equivalent to `True is False and False == False` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n", + "* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`.\n", + "* The expression `(1 > 0) < 1` is equivalent to `True < 1` and\n" ] }, { @@ -545,7 +583,7 @@ { "data": { "text/plain": [ - " True\n" + " 1\n" ] }, "output_type": "execute_result", @@ -554,7 +592,7 @@ } ], "source": [ - " 5 == 5.0 == 5 + 0j\n" + " int(True)\n" ] }, { @@ -567,7 +605,7 @@ { "data": { "text/plain": [ - " True\n" + " 2\n" ] }, "output_type": "execute_result", @@ -576,16 +614,14 @@ } ], "source": [ - " hash(5) == hash(5.0) == hash(5 + 0j)\n" + " True + 1 #not relevant for this example, but just for fun\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " **Note:** Objects with different values may also have same hash (known as [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science))).\n", - "* When the statement `some_dict[5] = \"Python\"` is executed, the existing value \"Ruby\" is overwritten with \"Python\" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`.\n", - "* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains the rationale behind it.\n", + " So, `1 < 1` evaluates to `False`\n", "\n" ] }, @@ -593,7 +629,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Deep down, we're all the same.\n" + "### \u25b6 How not to use `is` operator\n", + "The following is a very famous example present all over the internet.\n", + "\n", + "1\\.\n", + "\n" ] }, { @@ -605,7 +645,10 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "True\n", + "\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -613,8 +656,33 @@ } ], "source": [ - "class WTF:\n", - " pass\n" + "a = 256\n", + "b = 256\n", + "a is b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = 257\n", + "b = 257\n", + "a is b\n" ] }, { @@ -622,7 +690,8 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + "2\\.\n", + "\n" ] }, { @@ -635,7 +704,8 @@ { "data": { "text/plain": [ - "False\n" + "False\n", + "\n" ] }, "output_type": "execute_result", @@ -644,7 +714,9 @@ } ], "source": [ - "WTF() == WTF() # two different instances can't be equal\n" + "a = []\n", + "b = []\n", + "a is b\n" ] }, { @@ -657,7 +729,7 @@ { "data": { "text/plain": [ - "False\n" + "True\n" ] }, "output_type": "execute_result", @@ -666,7 +738,19 @@ } ], "source": [ - "WTF() is WTF() # identities are also different\n" + "a = tuple()\n", + "b = tuple()\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "**Output**\n", + "\n" ] }, { @@ -688,7 +772,17 @@ } ], "source": [ - "hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\n" + "a, b = 257, 257\n", + "a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.7.x specifically)**\n", + "\n" ] }, { @@ -701,7 +795,8 @@ { "data": { "text/plain": [ - "True\n" + ">> a is b\n", + "False\n" ] }, "output_type": "execute_result", @@ -710,7 +805,7 @@ } ], "source": [ - "id(WTF()) == id(WTF())\n" + "a, b = 257, 257\n" ] }, { @@ -726,10 +821,11 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "* When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed.\n", - "* When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same.\n", - "* So, the object's id is unique only for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id.\n", - "* But why did the `is` operator evaluated to `False`? Let's see with this snippet.\n" + "**The difference between `is` and `==`**\n", + "\n", + "* `is` operator checks if both the operands refer to the same object (i.e., it checks if the identity of the operands matches or not).\n", + "* `==` operator compares the values of both the operands and checks if they are the same.\n", + "* So `is` is for reference equality and `==` is for value equality. An example to clear things up,\n" ] }, { @@ -741,7 +837,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " False\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -749,9 +847,8 @@ } ], "source": [ - " class WTF(object):\n", - " def __init__(self): print(\"I\")\n", - " def __del__(self): print(\"D\")\n" + " class A: pass\n", + " A() is A() # These are two empty objects at two different memory locations.\n" ] }, { @@ -759,7 +856,13 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n" + "**`256` is an existing object but `257` isn't**\n", + "\n", + "When you start up python the numbers from `-5` to `256` will be allocated. These numbers are used a lot, so it makes sense just to have them ready.\n", + "\n", + "Quoting from https://docs.python.org/3/c-api/long.html\n", + "> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behavior of Python, in this case, is undefined. :-)\n", + "\n" ] }, { @@ -772,11 +875,7 @@ { "data": { "text/plain": [ - " I\n", - " I\n", - " D\n", - " D\n", - " False\n" + "10922528\n" ] }, "output_type": "execute_result", @@ -785,7 +884,7 @@ } ], "source": [ - " WTF() is WTF()\n" + "id(256)\n" ] }, { @@ -798,11 +897,7 @@ { "data": { "text/plain": [ - " I\n", - " D\n", - " I\n", - " D\n", - " True\n" + "10922528\n" ] }, "output_type": "execute_result", @@ -811,22 +906,9 @@ } ], "source": [ - " id(WTF()) == id(WTF())\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " As you may observe, the order in which the objects are destroyed is what made all the difference here.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Disorder within order *\n" + "a = 256\n", + "b = 256\n", + "id(a)\n" ] }, { @@ -838,7 +920,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "10922528\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -846,36 +930,7 @@ } ], "source": [ - "from collections import OrderedDict\n", - "\n", - "dictionary = dict()\n", - "dictionary[1] = 'a'; dictionary[2] = 'b';\n", - "\n", - "ordered_dict = OrderedDict()\n", - "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", - "\n", - "another_ordered_dict = OrderedDict()\n", - "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", - "\n", - "class DictWithHash(dict):\n", - " \"\"\"\n", - " A dict that also implements __hash__ magic.\n", - " \"\"\"\n", - " __hash__ = lambda self: 0\n", - "\n", - "class OrderedDictWithHash(OrderedDict):\n", - " \"\"\"\n", - " An OrderedDict that also implements __hash__ magic.\n", - " \"\"\"\n", - " __hash__ = lambda self: 0\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output**\n" + "id(b)\n" ] }, { @@ -888,7 +943,7 @@ { "data": { "text/plain": [ - "True\n" + "140084850247312\n" ] }, "output_type": "execute_result", @@ -897,7 +952,7 @@ } ], "source": [ - "dictionary == ordered_dict # If a == b\n" + "id(257)\n" ] }, { @@ -910,7 +965,7 @@ { "data": { "text/plain": [ - "True\n" + "140084850247440\n" ] }, "output_type": "execute_result", @@ -919,7 +974,9 @@ } ], "source": [ - "dictionary == another_ordered_dict # and b == c\n" + "x = 257\n", + "y = 257\n", + "id(x)\n" ] }, { @@ -932,11 +989,7 @@ { "data": { "text/plain": [ - "False\n", - "\n", - "# We all know that a set consists of only unique elements,\n", - "# let's try making a set of these dictionaries and see what happens...\n", - "\n" + "140084850247344\n" ] }, "output_type": "execute_result", @@ -945,7 +998,22 @@ } ], "source": [ - "ordered_dict == another_ordered_dict # the why isn't c == a ??\n" + "id(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Here the interpreter isn't smart enough while executing `y = 257` to recognize that we've already created an integer of the value `257,` and so it goes on to create another object in the memory.\n", + "\n", + "Similar optimization applies to other **immutable** objects like empty tuples as well. Since lists are mutable, that's why `[] is []` will return `False` and `() is ()` will return `True`. This explains our second snippet. Let's move on to the third one, \n", + "\n", + "**Both `a` and `b` refer to the same object when initialized with same value in the same line.**\n", + "\n", + "**Output**\n", + "\n" ] }, { @@ -958,12 +1026,7 @@ { "data": { "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "TypeError: unhashable type: 'dict'\n", - "\n", - "# Makes sense since dict don't have __hash__ implemented, let's use\n", - "# our wrapper classes.\n" + "140640774013296\n" ] }, "output_type": "execute_result", @@ -972,7 +1035,8 @@ } ], "source": [ - "len({dictionary, ordered_dict, another_ordered_dict})\n" + "a, b = 257, 257\n", + "id(a)\n" ] }, { @@ -985,7 +1049,7 @@ { "data": { "text/plain": [ - "1\n" + "140640774013296\n" ] }, "output_type": "execute_result", @@ -994,13 +1058,7 @@ } ], "source": [ - "dictionary = DictWithHash()\n", - "dictionary[1] = 'a'; dictionary[2] = 'b';\n", - "ordered_dict = OrderedDictWithHash()\n", - "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", - "another_ordered_dict = OrderedDictWithHash()\n", - "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", - "len({dictionary, ordered_dict, another_ordered_dict})\n" + "id(b)\n" ] }, { @@ -1013,7 +1071,7 @@ { "data": { "text/plain": [ - "2\n" + "140640774013392\n" ] }, "output_type": "execute_result", @@ -1022,29 +1080,9 @@ } ], "source": [ - "len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "What is going on here?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- The reason why intransitive equality didn't hold among `dictionary`, `ordered_dict` and `another_ordered_dict` is because of the way `__eq__` method is implemented in `OrderedDict` class. From the [docs](https://docs.python.org/3/library/collections.html#ordereddict-objects)\n", - " \n", - " > Equality tests between OrderedDict objects are order-sensitive and are implemented as `list(od1.items())==list(od2.items())`. Equality tests between `OrderedDict` objects and other Mapping objects are order-insensitive like regular dictionaries.\n", - "- The reason for this equality is behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used.\n", - "- Okay, so why did changing the order affect the length of the generated `set` object? The answer is the lack of intransitive equality only. Since sets are \"unordered\" collections of unique elements, the order in which elements are inserted shouldn't matter. But in this case, it does matter. Let's break it down a bit,\n" + "a = 257\n", + "b = 257\n", + "id(a)\n" ] }, { @@ -1057,7 +1095,7 @@ { "data": { "text/plain": [ - " True\n" + "140640774013488\n" ] }, "output_type": "execute_result", @@ -1066,9 +1104,18 @@ } ], "source": [ - " some_set = set()\n", - " some_set.add(dictionary) # these are the mapping objects from the snippets above\n", - " ordered_dict in some_set\n" + "id(b)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* When a and b are set to `257` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't \"know\" that there's already `257` as an object.\n", + "\n", + "* It's a compiler optimization and specifically applies to the interactive environment. When you enter two lines in a live interpreter, they're compiled separately, therefore optimized separately. If you were to try this example in a `.py` file, you would not see the same behavior, because the file is compiled all at once. This optimization is not limited to integers, it works for other immutable data types like strings (check the \"Strings are tricky example\") and floats as well,\n", + "\n" ] }, { @@ -1081,7 +1128,7 @@ { "data": { "text/plain": [ - " 1\n" + " True\n" ] }, "output_type": "execute_result", @@ -1090,8 +1137,25 @@ } ], "source": [ - " some_set.add(ordered_dict)\n", - " len(some_set)\n" + " a, b = 257.0, 257.0\n", + " a is b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* Why didn't this work for Python 3.7? The abstract reason is because such compiler optimizations are implementation specific (i.e. may change with version, OS, etc). I'm still figuring out what exact implementation change cause the issue, you can check out this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for updates.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Hash brownies\n", + "1\\.\n" ] }, { @@ -1103,9 +1167,7 @@ "outputs": [ { "data": { - "text/plain": [ - " True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -1113,7 +1175,19 @@ } ], "source": [ - " another_ordered_dict in some_set\n" + "some_dict = {}\n", + "some_dict[5.5] = \"JavaScript\"\n", + "some_dict[5.0] = \"Ruby\"\n", + "some_dict[5] = \"Python\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" ] }, { @@ -1126,8 +1200,7 @@ { "data": { "text/plain": [ - " 1\n", - "\n" + "\"JavaScript\"\n" ] }, "output_type": "execute_result", @@ -1136,8 +1209,7 @@ } ], "source": [ - " some_set.add(another_ordered_dict)\n", - " len(some_set)\n" + "some_dict[5.5]\n" ] }, { @@ -1150,7 +1222,7 @@ { "data": { "text/plain": [ - " False\n" + "\"Python\"\n" ] }, "output_type": "execute_result", @@ -1159,9 +1231,7 @@ } ], "source": [ - " another_set = set()\n", - " another_set.add(ordered_dict)\n", - " another_ordered_dict in another_set\n" + "some_dict[5.0] # \"Python\" destroyed the existence of \"Ruby\"?\n" ] }, { @@ -1174,7 +1244,8 @@ { "data": { "text/plain": [ - " 2\n" + "\"Python\"\n", + "\n" ] }, "output_type": "execute_result", @@ -1183,8 +1254,7 @@ } ], "source": [ - " another_set.add(another_ordered_dict)\n", - " len(another_set)\n" + "some_dict[5] \n" ] }, { @@ -1197,7 +1267,7 @@ { "data": { "text/plain": [ - " True\n" + "complex\n" ] }, "output_type": "execute_result", @@ -1206,7 +1276,8 @@ } ], "source": [ - " dictionary in another_set\n" + "complex_five = 5 + 0j\n", + "type(complex_five)\n" ] }, { @@ -1219,7 +1290,7 @@ { "data": { "text/plain": [ - " 2\n" + "\"Python\"\n" ] }, "output_type": "execute_result", @@ -1228,15 +1299,16 @@ } ], "source": [ - " another_set.add(another_ordered_dict)\n", - " len(another_set)\n" + "some_dict[complex_five]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " So the inconsistency is due to `another_ordered_dict in another_set` being `False` because `ordered_dict` was already present in `another_set` and as observed before, `ordered_dict == another_ordered_dict` is `False`.\n", + "\n", + "So, why is Python all over the place?\n", + "\n", "\n" ] }, @@ -1244,7 +1316,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Keep trying... *\n" + "#### \ud83d\udca1 Explanation\n", + "\n", + "* Uniqueness of keys in a Python dictionary is by *equivalence*, not identity. So even though `5`, `5.0`, and `5 + 0j` are distinct objects of different types, since they're equal, they can't both be in the same `dict` (or `set`). As soon as you insert any one of them, attempting to look up any distinct but equivalent key will succeed with the original mapped value (rather than failing with a `KeyError`):\n" ] }, { @@ -1256,7 +1330,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -1264,41 +1340,7 @@ } ], "source": [ - "def some_func():\n", - " try:\n", - " return 'from_try'\n", - " finally:\n", - " return 'from_finally'\n", - "\n", - "def another_func(): \n", - " for _ in range(3):\n", - " try:\n", - " continue\n", - " finally:\n", - " print(\"Finally!\")\n", - "\n", - "def one_more_func(): # A gotcha!\n", - " try:\n", - " for i in range(3):\n", - " try:\n", - " 1 / i\n", - " except ZeroDivisionError:\n", - " # Let's throw it here and handle it outside for loop\n", - " raise ZeroDivisionError(\"A trivial divide by zero error\")\n", - " finally:\n", - " print(\"Iteration\", i)\n", - " break\n", - " except ZeroDivisionError as e:\n", - " print(\"Zero division error occurred\", e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n", - "\n" + " 5 == 5.0 == 5 + 0j\n" ] }, { @@ -1311,8 +1353,7 @@ { "data": { "text/plain": [ - "'from_finally'\n", - "\n" + " True\n" ] }, "output_type": "execute_result", @@ -1321,7 +1362,7 @@ } ], "source": [ - "some_func()\n" + " 5 is not 5.0 is not 5 + 0j\n" ] }, { @@ -1334,10 +1375,7 @@ { "data": { "text/plain": [ - "Finally!\n", - "Finally!\n", - "Finally!\n", - "\n" + " True\n" ] }, "output_type": "execute_result", @@ -1346,7 +1384,9 @@ } ], "source": [ - "another_func()\n" + " some_dict = {}\n", + " some_dict[5.0] = \"Ruby\"\n", + " 5.0 in some_dict\n" ] }, { @@ -1359,10 +1399,7 @@ { "data": { "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "ZeroDivisionError: division by zero\n", - "\n" + " True\n" ] }, "output_type": "execute_result", @@ -1371,21 +1408,27 @@ } ], "source": [ - "1 / 0\n" + " (5 in some_dict) and (5 + 0j in some_dict)\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* This applies when setting an item as well. So when you do `some_dict[5] = \"Python\"`, Python finds the existing item with equivalent key `5.0 -> \"Ruby\"`, overwrites its value in place, and leaves the original key alone.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, "outputs": [ { "data": { "text/plain": [ - "Iteration 0\n", - "\n" + " {5.0: 'Ruby'}\n" ] }, "output_type": "execute_result", @@ -1394,33 +1437,39 @@ } ], "source": [ - "one_more_func()\n" + " some_dict\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " {5.0: 'Python'}\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n" + " some_dict[5] = \"Python\"\n", + " some_dict\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", + "* So how can we update the key to `5` (instead of `5.0`)? We can't actually do this update in place, but what we can do is first delete the key (`del some_dict[5.0]`), and then set it (`some_dict[5]`) to get the integer `5` as the key instead of floating `5.0`, though this should be needed in rare cases.\n", "\n", - "- When a `return`, `break` or `continue` statement is executed in the `try` suite of a \"try\u2026finally\" statement, the `finally` clause is also executed on the way out.\n", - "- The return value of a function is determined by the last `return` statement executed. Since the `finally` clause always executes, a `return` statement executed in the `finally` clause will always be the last one executed.\n", - "- The caveat here is, if the finally clause executes a `return` or `break` statement, the temporarily saved exception is discarded.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 For what?\n" + "* How did Python find `5` in a dictionary containing `5.0`? Python does this in constant time without having to scan through every item by using hash functions. When Python looks up a key `foo` in a dict, it first computes `hash(foo)` (which runs in constant-time). Since in Python it is required that objects that compare equal also have the same hash value ([docs](https://docs.python.org/3/reference/datamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value.\n" ] }, { @@ -1432,7 +1481,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -1440,18 +1491,7 @@ } ], "source": [ - "some_string = \"wtf\"\n", - "some_dict = {}\n", - "for i, some_dict[i] in enumerate(some_string):\n", - " i = 10\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + " 5 == 5.0 == 5 + 0j\n" ] }, { @@ -1464,7 +1504,7 @@ { "data": { "text/plain": [ - "{0: 'w', 1: 't', 2: 'f'}\n" + " True\n" ] }, "output_type": "execute_result", @@ -1473,13 +1513,14 @@ } ], "source": [ - "some_dict # An indexed dict appears.\n" + " hash(5) == hash(5.0) == hash(5 + 0j)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + " **Note:** The inverse is not necessarily true: Objects with equal hash values may themselves be unequal. (This causes what's known as a [hash collision](https://en.wikipedia.org/wiki/Collision_(computer_science)), and degrades the constant-time performance that hashing usually provides.)\n", "\n" ] }, @@ -1487,14 +1528,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as:\n", - " ```\n", - " for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\n", - " ```\n", - " Where `exprlist` is the assignment target. This means that the equivalent of `{exprlist} = {next_value}` is **executed for each item** in the iterable.\n", - " An interesting example that illustrates this:\n" + "### \u25b6 Deep down, we're all the same.\n" ] }, { @@ -1514,9 +1548,8 @@ } ], "source": [ - " for i in range(4):\n", - " print(i)\n", - " i = 10\n" + "class WTF:\n", + " pass\n" ] }, { @@ -1524,21 +1557,7 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n", - " ```\n", - " 0\n", - " 1\n", - " 2\n", - " 3\n", - " ```\n", - "\n", - " Did you expect the loop to run just once?\n", - "\n", - " **\ud83d\udca1 Explanation:**\n", - "\n", - " - The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(4)` this case) is unpacked and assigned the target list variables (`i` in this case).\n", - "\n", - "* The `enumerate(some_string)` function yields a new value `i` (a counter going up) and a character from the `some_string` in each iteration. It then sets the (just assigned) `i` key of the dictionary `some_dict` to that character. The unrolling of the loop can be simplified as:\n" + "**Output:**\n" ] }, { @@ -1550,7 +1569,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "False\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -1558,25 +1579,7 @@ } ], "source": [ - " i, some_dict[i] = (0, 'w')\n", - " i, some_dict[i] = (1, 't')\n", - " i, some_dict[i] = (2, 'f')\n", - " some_dict\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Evaluation time discrepancy\n", - "1\\.\n" + "WTF() == WTF() # two different instances can't be equal\n" ] }, { @@ -1588,7 +1591,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "False\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -1596,49 +1601,72 @@ } ], "source": [ - "array = [1, 8, 15]\n", - "# A typical generator expression\n", - "gen = (x for x in array if array.count(x) > 0)\n", - "array = [2, 8, 22]\n" + "WTF() is WTF() # identities are also different\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "**Output:**\n", - "\n" + "hash(WTF()) == hash(WTF()) # hashes _should_ be different as well\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "[8]\n" - ] + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(list(gen)) # Where did the other values go?\n" + "id(WTF()) == id(WTF())\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "2\\.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed.\n", + "* When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same.\n", + "* So, the object's id is unique only for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id.\n", + "* But why did the `is` operator evaluated to `False`? Let's see with this snippet.\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -1656,13 +1684,9 @@ } ], "source": [ - "array_1 = [1,2,3,4]\n", - "gen_1 = (x for x in array_1)\n", - "array_1 = [1,2,3,4,5]\n", - "\n", - "array_2 = [1,2,3,4]\n", - "gen_2 = (x for x in array_2)\n", - "array_2[:] = [1,2,3,4,5]\n" + " class WTF(object):\n", + " def __init__(self): print(\"I\")\n", + " def __del__(self): print(\"D\")\n" ] }, { @@ -1670,57 +1694,76 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + " **Output:**\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, 4]\n", - "\n" - ] + "data": { + "text/plain": [ + " I\n", + " I\n", + " D\n", + " D\n", + " False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(list(gen_1))\n" + " WTF() is WTF()\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, 4, 5]\n" - ] + "data": { + "text/plain": [ + " I\n", + " D\n", + " I\n", + " D\n", + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(list(gen_2))\n" + " id(WTF()) == id(WTF())\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "3\\.\n", + " As you may observe, the order in which the objects are destroyed is what made all the difference here.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Disorder within order *\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -1738,74 +1781,36 @@ } ], "source": [ - "array_3 = [1, 2, 3]\n", - "array_4 = [10, 20, 30]\n", - "gen = (i + j for i in array_3 for j in array_4)\n", + "from collections import OrderedDict\n", "\n", - "array_3 = [4, 5, 6]\n", - "array_4 = [400, 500, 600]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ + "dictionary = dict()\n", + "dictionary[1] = 'a'; dictionary[2] = 'b';\n", "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "metadata": { - "collapsed": true - }, - "execution_count": null, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[401, 501, 601, 402, 502, 602, 403, 503, 603]\n" - ] - } - ], - "source": [ - "print(list(gen))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation\n", + "ordered_dict = OrderedDict()\n", + "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", "\n", - "- In a [generator](https://wiki.python.org/moin/Generators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at runtime.\n", - "- So before runtime, `array` is re-assigned to the list `[2, 8, 22]`, and since out of `1`, `8` and `15`, only the count of `8` is greater than `0`, the generator only yields `8`.\n", - "- The differences in the output of `g1` and `g2` in the second part is due the way variables `array_1` and `array_2` are re-assigned values.\n", - "- In the first case, `array_1` is binded to the new object `[1,2,3,4,5]` and since the `in` clause is evaluated at the declaration time it still refers to the old object `[1,2,3,4]` (which is not destroyed).\n", - "- In the second case, the slice assignment to `array_2` updates the same old object `[1,2,3,4]` to `[1,2,3,4,5]`. Hence both the `g2` and `array_2` still have reference to the same object (which has now been updated to `[1,2,3,4,5]`).\n", - "- Okay, going by the logic discussed so far, shouldn't be the value of `list(g)` in the third snippet be `[11, 21, 31, 12, 22, 32, 13, 23, 33]`? (because `array_3` and `array_4` are going to behave just like `array_1`). The reason why (only) `array_4` values got updated is explained in [PEP-289](https://www.python.org/dev/peps/pep-0289/#the-details)\n", - " \n", - " > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n", - "\n" + "another_ordered_dict = OrderedDict()\n", + "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", + "\n", + "class DictWithHash(dict):\n", + " \"\"\"\n", + " A dict that also implements __hash__ magic.\n", + " \"\"\"\n", + " __hash__ = lambda self: 0\n", + "\n", + "class OrderedDictWithHash(OrderedDict):\n", + " \"\"\"\n", + " An OrderedDict that also implements __hash__ magic.\n", + " \"\"\"\n", + " __hash__ = lambda self: 0\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 How not to use `is` operator\n", - "The following is a very famous example present all over the internet.\n", "\n", - "1\\.\n", - "\n" + "**Output**\n" ] }, { @@ -1818,8 +1823,7 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "True\n" ] }, "output_type": "execute_result", @@ -1828,9 +1832,7 @@ } ], "source": [ - "a = 256\n", - "b = 256\n", - "a is b\n" + "dictionary == ordered_dict # If a == b\n" ] }, { @@ -1843,7 +1845,7 @@ { "data": { "text/plain": [ - "False\n" + "True\n" ] }, "output_type": "execute_result", @@ -1852,18 +1854,7 @@ } ], "source": [ - "a = 257\n", - "b = 257\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "2\\.\n", - "\n" + "dictionary == another_ordered_dict # and b == c\n" ] }, { @@ -1877,6 +1868,9 @@ "data": { "text/plain": [ "False\n", + "\n", + "# We all know that a set consists of only unique elements,\n", + "# let's try making a set of these dictionaries and see what happens...\n", "\n" ] }, @@ -1886,9 +1880,7 @@ } ], "source": [ - "a = []\n", - "b = []\n", - "a is b\n" + "ordered_dict == another_ordered_dict # then why isn't c == a ??\n" ] }, { @@ -1901,7 +1893,12 @@ { "data": { "text/plain": [ - "True\n" + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "TypeError: unhashable type: 'dict'\n", + "\n", + "# Makes sense since dict don't have __hash__ implemented, let's use\n", + "# our wrapper classes.\n" ] }, "output_type": "execute_result", @@ -1910,19 +1907,7 @@ } ], "source": [ - "a = tuple()\n", - "b = tuple()\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "**Output**\n", - "\n" + "len({dictionary, ordered_dict, another_ordered_dict})\n" ] }, { @@ -1935,7 +1920,7 @@ { "data": { "text/plain": [ - "True\n" + "1\n" ] }, "output_type": "execute_result", @@ -1944,17 +1929,13 @@ } ], "source": [ - "a, b = 257, 257\n", - "a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 3.7.x specifically)**\n", - "\n" + "dictionary = DictWithHash()\n", + "dictionary[1] = 'a'; dictionary[2] = 'b';\n", + "ordered_dict = OrderedDictWithHash()\n", + "ordered_dict[1] = 'a'; ordered_dict[2] = 'b';\n", + "another_ordered_dict = OrderedDictWithHash()\n", + "another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a';\n", + "len({dictionary, ordered_dict, another_ordered_dict})\n" ] }, { @@ -1967,8 +1948,7 @@ { "data": { "text/plain": [ - ">> a is b\n", - "False\n" + "2\n" ] }, "output_type": "execute_result", @@ -1977,13 +1957,15 @@ } ], "source": [ - "a, b = 257, 257\n" + "len({ordered_dict, another_ordered_dict, dictionary}) # changing the order\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "What is going on here?\n", "\n" ] }, @@ -1993,11 +1975,11 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "**The difference between `is` and `==`**\n", - "\n", - "* `is` operator checks if both the operands refer to the same object (i.e., it checks if the identity of the operands matches or not).\n", - "* `==` operator compares the values of both the operands and checks if they are the same.\n", - "* So `is` is for reference equality and `==` is for value equality. An example to clear things up,\n" + "- The reason why intransitive equality didn't hold among `dictionary`, `ordered_dict` and `another_ordered_dict` is because of the way `__eq__` method is implemented in `OrderedDict` class. From the [docs](https://docs.python.org/3/library/collections.html#ordereddict-objects)\n", + " \n", + " > Equality tests between OrderedDict objects are order-sensitive and are implemented as `list(od1.items())==list(od2.items())`. Equality tests between `OrderedDict` objects and other Mapping objects are order-insensitive like regular dictionaries.\n", + "- The reason for this equality in behavior is that it allows `OrderedDict` objects to be directly substituted anywhere a regular dictionary is used.\n", + "- Okay, so why did changing the order affect the length of the generated `set` object? The answer is the lack of intransitive equality only. Since sets are \"unordered\" collections of unique elements, the order in which elements are inserted shouldn't matter. But in this case, it does matter. Let's break it down a bit,\n" ] }, { @@ -2010,7 +1992,7 @@ { "data": { "text/plain": [ - " False\n" + " True\n" ] }, "output_type": "execute_result", @@ -2019,22 +2001,9 @@ } ], "source": [ - " class A: pass\n", - " A() is A() # These are two empty objects at two different memory locations.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**`256` is an existing object but `257` isn't**\n", - "\n", - "When you start up python the numbers from `-5` to `256` will be allocated. These numbers are used a lot, so it makes sense just to have them ready.\n", - "\n", - "Quoting from https://docs.python.org/3/c-api/long.html\n", - "> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behavior of Python, in this case, is undefined. :-)\n", - "\n" + " some_set = set()\n", + " some_set.add(dictionary) # these are the mapping objects from the snippets above\n", + " ordered_dict in some_set\n" ] }, { @@ -2047,7 +2016,7 @@ { "data": { "text/plain": [ - "10922528\n" + " 1\n" ] }, "output_type": "execute_result", @@ -2056,7 +2025,8 @@ } ], "source": [ - "id(256)\n" + " some_set.add(ordered_dict)\n", + " len(some_set)\n" ] }, { @@ -2069,7 +2039,7 @@ { "data": { "text/plain": [ - "10922528\n" + " True\n" ] }, "output_type": "execute_result", @@ -2078,9 +2048,7 @@ } ], "source": [ - "a = 256\n", - "b = 256\n", - "id(a)\n" + " another_ordered_dict in some_set\n" ] }, { @@ -2093,7 +2061,8 @@ { "data": { "text/plain": [ - "10922528\n" + " 1\n", + "\n" ] }, "output_type": "execute_result", @@ -2102,7 +2071,8 @@ } ], "source": [ - "id(b)\n" + " some_set.add(another_ordered_dict)\n", + " len(some_set)\n" ] }, { @@ -2115,7 +2085,7 @@ { "data": { "text/plain": [ - "140084850247312\n" + " False\n" ] }, "output_type": "execute_result", @@ -2124,7 +2094,9 @@ } ], "source": [ - "id(257)\n" + " another_set = set()\n", + " another_set.add(ordered_dict)\n", + " another_ordered_dict in another_set\n" ] }, { @@ -2137,7 +2109,7 @@ { "data": { "text/plain": [ - "140084850247440\n" + " 2\n" ] }, "output_type": "execute_result", @@ -2146,9 +2118,8 @@ } ], "source": [ - "x = 257\n", - "y = 257\n", - "id(x)\n" + " another_set.add(another_ordered_dict)\n", + " len(another_set)\n" ] }, { @@ -2161,7 +2132,7 @@ { "data": { "text/plain": [ - "140084850247344\n" + " True\n" ] }, "output_type": "execute_result", @@ -2170,22 +2141,7 @@ } ], "source": [ - "id(y)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Here the interpreter isn't smart enough while executing `y = 257` to recognize that we've already created an integer of the value `257,` and so it goes on to create another object in the memory.\n", - "\n", - "Similar optimization applies to other **immutable** objects like empty tuples as well. Since lists are mutable, that's why `[] is []` will return `False` and `() is ()` will return `True`. This explains our second snippet. Let's move on to the third one, \n", - "\n", - "**Both `a` and `b` refer to the same object when initialized with same value in the same line.**\n", - "\n", - "**Output**\n", - "\n" + " dictionary in another_set\n" ] }, { @@ -2198,7 +2154,7 @@ { "data": { "text/plain": [ - "140640774013296\n" + " 2\n" ] }, "output_type": "execute_result", @@ -2207,8 +2163,23 @@ } ], "source": [ - "a, b = 257, 257\n", - "id(a)\n" + " another_set.add(another_ordered_dict)\n", + " len(another_set)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " So the inconsistency is due to `another_ordered_dict in another_set` being `False` because `ordered_dict` was already present in `another_set` and as observed before, `ordered_dict == another_ordered_dict` is `False`.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Keep trying... *\n" ] }, { @@ -2220,9 +2191,7 @@ "outputs": [ { "data": { - "text/plain": [ - "140640774013296\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2230,31 +2199,41 @@ } ], "source": [ - "id(b)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "140640774013392\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "def some_func():\n", + " try:\n", + " return 'from_try'\n", + " finally:\n", + " return 'from_finally'\n", + "\n", + "def another_func(): \n", + " for _ in range(3):\n", + " try:\n", + " continue\n", + " finally:\n", + " print(\"Finally!\")\n", + "\n", + "def one_more_func(): # A gotcha!\n", + " try:\n", + " for i in range(3):\n", + " try:\n", + " 1 / i\n", + " except ZeroDivisionError:\n", + " # Let's throw it here and handle it outside for loop\n", + " raise ZeroDivisionError(\"A trivial divide by zero error\")\n", + " finally:\n", + " print(\"Iteration\", i)\n", + " break\n", + " except ZeroDivisionError as e:\n", + " print(\"Zero division error occurred\", e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, "source": [ - "a = 257\n", - "b = 257\n", - "id(a)\n" + "\n", + "**Output:**\n", + "\n" ] }, { @@ -2267,7 +2246,8 @@ { "data": { "text/plain": [ - "140640774013488\n" + "'from_finally'\n", + "\n" ] }, "output_type": "execute_result", @@ -2276,18 +2256,7 @@ } ], "source": [ - "id(b)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "* When a and b are set to `257` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't \"know\" that there's already `257` as an object.\n", - "\n", - "* It's a compiler optimization and specifically applies to the interactive environment. When you enter two lines in a live interpreter, they're compiled separately, therefore optimized separately. If you were to try this example in a `.py` file, you would not see the same behavior, because the file is compiled all at once. This optimization is not limited to integers, it works for other immutable data types like strings (check the \"Strings are tricky example\") and floats as well,\n", - "\n" + "some_func()\n" ] }, { @@ -2300,7 +2269,10 @@ { "data": { "text/plain": [ - " True\n" + "Finally!\n", + "Finally!\n", + "Finally!\n", + "\n" ] }, "output_type": "execute_result", @@ -2309,24 +2281,7 @@ } ], "source": [ - " a, b = 257.0, 257.0\n", - " a is b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "* Why didn't this work for Python 3.7? The abstract reason is because such compiler optimizations are implementation specific (i.e. may change with version, OS, etc). I'm still figuring out what exact implementation change cause the issue, you can check out this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for updates.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 `is not ...` is not `is (not ...)`\n" + "another_func()\n" ] }, { @@ -2339,7 +2294,10 @@ { "data": { "text/plain": [ - "True\n" + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "ZeroDivisionError: division by zero\n", + "\n" ] }, "output_type": "execute_result", @@ -2348,7 +2306,7 @@ } ], "source": [ - "'something' is not None\n" + "1 / 0\n" ] }, { @@ -2361,7 +2319,8 @@ { "data": { "text/plain": [ - "False\n" + "Iteration 0\n", + "\n" ] }, "output_type": "execute_result", @@ -2370,7 +2329,7 @@ } ], "source": [ - "'something' is (not None)\n" + "one_more_func()\n" ] }, { @@ -2384,10 +2343,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", + "#### \ud83d\udca1 Explanation:\n", "\n", - "- `is not` is a single binary operator, and has behavior different than using `is` and `not` separated.\n", - "- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise.\n", + "- When a `return`, `break` or `continue` statement is executed in the `try` suite of a \"try\u2026finally\" statement, the `finally` clause is also executed on the way out.\n", + "- The return value of a function is determined by the last `return` statement executed. Since the `finally` clause always executes, a `return` statement executed in the `finally` clause will always be the last one executed.\n", + "- The caveat here is, if the finally clause executes a `return` or `break` statement, the temporarily saved exception is discarded.\n", "\n" ] }, @@ -2395,7 +2355,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 A tic-tac-toe where X wins in the first attempt!\n" + "### \u25b6 For what?\n" ] }, { @@ -2415,10 +2375,10 @@ } ], "source": [ - "# Let's initialize a row\n", - "row = [\"\"] * 3 #row i['', '', '']\n", - "# Let's make a board\n", - "board = [row] * 3\n" + "some_string = \"wtf\"\n", + "some_dict = {}\n", + "for i, some_dict[i] in enumerate(some_string):\n", + " i = 10\n" ] }, { @@ -2426,8 +2386,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "**Output:**\n" ] }, { @@ -2440,7 +2399,7 @@ { "data": { "text/plain": [ - "[['', '', ''], ['', '', ''], ['', '', '']]\n" + "{0: 'w', 1: 't', 2: 'f'}\n" ] }, "output_type": "execute_result", @@ -2449,51 +2408,28 @@ } ], "source": [ - "board\n" + "some_dict # An indexed dict appears.\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['', '', '']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "board[0]\n" + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "''\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "board[0][0]\n" + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as:\n", + " ```\n", + " for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]\n", + " ```\n", + " Where `exprlist` is the assignment target. This means that the equivalent of `{exprlist} = {next_value}` is **executed for each item** in the iterable.\n", + " An interesting example that illustrates this:\n" ] }, { @@ -2505,9 +2441,7 @@ "outputs": [ { "data": { - "text/plain": [ - "[['X', '', ''], ['X', '', ''], ['X', '', '']]\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2515,35 +2449,31 @@ } ], "source": [ - "board[0][0] = \"X\"\n", - "board\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "We didn't assign three `\"X\"`s, did we?\n", - "\n" + " for i in range(4):\n", + " print(i)\n", + " i = 10\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", "\n", - "When we initialize `row` variable, this visualization explains what happens in the memory\n", + " **Output:**\n", + " ```\n", + " 0\n", + " 1\n", + " 2\n", + " 3\n", + " ```\n", "\n", - "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images/tic-tac-toe/after_row_initialized.png)\n", + " Did you expect the loop to run just once?\n", "\n", - "And when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`)\n", + " **\ud83d\udca1 Explanation:**\n", "\n", - "![image](https://raw.githubusercontent.com/satwikkansal/wtfpython/master/images/tic-tac-toe/after_board_initialized.png)\n", + " - The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(4)` in this case) is unpacked and assigned the target list variables (`i` in this case).\n", "\n", - "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", - "\n" + "* The `enumerate(some_string)` function yields a new value `i` (a counter going up) and a character from the `some_string` in each iteration. It then sets the (just assigned) `i` key of the dictionary `some_dict` to that character. The unrolling of the loop can be simplified as:\n" ] }, { @@ -2555,9 +2485,7 @@ "outputs": [ { "data": { - "text/plain": [ - "[['X', '', ''], ['', '', ''], ['', '', '']]\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2565,9 +2493,10 @@ } ], "source": [ - "board = [['']*3 for _ in range(3)]\n", - "board[0][0] = \"X\"\n", - "board\n" + " i, some_dict[i] = (0, 'w')\n", + " i, some_dict[i] = (1, 't')\n", + " i, some_dict[i] = (2, 'f')\n", + " some_dict\n" ] }, { @@ -2581,9 +2510,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The sticky output function\n", - "1\\.\n", - "\n" + "### \u25b6 Evaluation time discrepancy\n", + "1\\.\n" ] }, { @@ -2603,15 +2531,10 @@ } ], "source": [ - "funcs = []\n", - "results = []\n", - "for x in range(7):\n", - " def some_func():\n", - " return x\n", - " funcs.append(some_func)\n", - " results.append(some_func()) # note the function call here\n", - "\n", - "funcs_results = [func() for func in funcs]\n" + "array = [1, 8, 15]\n", + "# A typical generator expression\n", + "gen = (x for x in array if array.count(x) > 0)\n", + "array = [2, 8, 22]\n" ] }, { @@ -2625,28 +2548,34 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "[0, 1, 2, 3, 4, 5, 6]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "[8]\n" + ] } ], "source": [ - "results\n" + "print(list(gen)) # Where did the other values go?\n" ] }, { - "cell_type": "code", + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true @@ -2654,9 +2583,7 @@ "outputs": [ { "data": { - "text/plain": [ - "[6, 6, 6, 6, 6, 6, 6]\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2664,58 +2591,68 @@ } ], "source": [ - "funcs_results\n" + "array_1 = [1,2,3,4]\n", + "gen_1 = (x for x in array_1)\n", + "array_1 = [1,2,3,4,5]\n", + "\n", + "array_2 = [1,2,3,4]\n", + "gen_2 = (x for x in array_2)\n", + "array_2[:] = [1,2,3,4,5]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.\n", "\n", - "2\\.\n", - "\n" + "**Output:**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4]\n", + "\n" + ] } ], "source": [ - "powers_of_x = [lambda x: x**i for i in range(10)]\n", - "[f(2) for f in powers_of_x]\n" + "print(list(gen_1))\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5]\n" + ] + } + ], "source": [ - "\n" + "print(list(gen_2))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", - "\n", - "- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.\n", "\n", - "- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope.\n", + "3\\.\n", "\n" ] }, @@ -2736,11 +2673,12 @@ } ], "source": [ - " funcs = []\n", - " for x in range(7):\n", - " def some_func(x=x):\n", - " return x\n", - " funcs.append(some_func)\n" + "array_3 = [1, 2, 3]\n", + "array_4 = [10, 20, 30]\n", + "gen = (i + j for i in array_3 for j in array_4)\n", + "\n", + "array_3 = [4, 5, 6]\n", + "array_4 = [400, 500, 600]\n" ] }, { @@ -2748,30 +2686,26 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n" + "**Output:**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - " [0, 1, 2, 3, 4, 5, 6]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "[401, 501, 601, 402, 502, 602, 403, 503, 603]\n" + ] } ], "source": [ - " funcs_results = [func() for func in funcs]\n", - " funcs_results\n" + "print(list(gen))\n" ] }, { @@ -2785,30 +2719,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The chicken-egg problem *\n", - "1\\.\n" + "#### \ud83d\udca1 Explanation\n", + "\n", + "- In a [generator](https://wiki.python.org/moin/Generators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at runtime.\n", + "- So before runtime, `array` is re-assigned to the list `[2, 8, 22]`, and since out of `1`, `8` and `15`, only the count of `8` is greater than `0`, the generator only yields `8`.\n", + "- The differences in the output of `g1` and `g2` in the second part is due the way variables `array_1` and `array_2` are re-assigned values.\n", + "- In the first case, `array_1` is binded to the new object `[1,2,3,4,5]` and since the `in` clause is evaluated at the declaration time it still refers to the old object `[1,2,3,4]` (which is not destroyed).\n", + "- In the second case, the slice assignment to `array_2` updates the same old object `[1,2,3,4]` to `[1,2,3,4,5]`. Hence both the `g2` and `array_2` still have reference to the same object (which has now been updated to `[1,2,3,4,5]`).\n", + "- Okay, going by the logic discussed so far, shouldn't be the value of `list(g)` in the third snippet be `[11, 21, 31, 12, 22, 32, 13, 23, 33]`? (because `array_3` and `array_4` are going to behave just like `array_1`). The reason why (only) `array_4` values got updated is explained in [PEP-289](https://www.python.org/dev/peps/pep-0289/#the-details)\n", + " \n", + " > Only the outermost for-expression is evaluated immediately, the other expressions are deferred until the generator is run.\n", + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "isinstance(3, int)\n" + "### \u25b6 `is not ...` is not `is (not ...)`\n" ] }, { @@ -2830,7 +2758,7 @@ } ], "source": [ - "isinstance(type, object)\n" + "'something' is not None\n" ] }, { @@ -2843,7 +2771,7 @@ { "data": { "text/plain": [ - "True\n" + "False\n" ] }, "output_type": "execute_result", @@ -2852,41 +2780,33 @@ } ], "source": [ - "isinstance(object, type)\n" + "'something' is (not None)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", "\n", - "So which is the \"ultimate\" base class? There's more to the confusion by the way,\n", - "\n", - "2\\. \n", + "- `is not` is a single binary operator, and has behavior different than using `is` and `not` separated.\n", + "- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. \n", + "- In the example, `(not None)` evaluates to `True` since the value `None` is `False` in a boolean context, so the expression becomes `'something' is True`.\n", "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "class A: pass\n", - "isinstance(A, A)\n" + "### \u25b6 A tic-tac-toe where X wins in the first attempt!\n" ] }, { @@ -2898,9 +2818,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -2908,7 +2826,19 @@ } ], "source": [ - "isinstance(type, type)\n" + "# Let's initialize a row\n", + "row = [\"\"] * 3 #row i['', '', '']\n", + "# Let's make a board\n", + "board = [row] * 3\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" ] }, { @@ -2921,7 +2851,7 @@ { "data": { "text/plain": [ - "True\n" + "[['', '', ''], ['', '', ''], ['', '', '']]\n" ] }, "output_type": "execute_result", @@ -2930,16 +2860,7 @@ } ], "source": [ - "isinstance(object, object)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n" + "board\n" ] }, { @@ -2952,7 +2873,7 @@ { "data": { "text/plain": [ - "True\n" + "['', '', '']\n" ] }, "output_type": "execute_result", @@ -2961,7 +2882,7 @@ } ], "source": [ - "issubclass(int, object)\n" + "board[0]\n" ] }, { @@ -2974,7 +2895,7 @@ { "data": { "text/plain": [ - "True\n" + "''\n" ] }, "output_type": "execute_result", @@ -2983,7 +2904,7 @@ } ], "source": [ - "issubclass(type, object)\n" + "board[0][0]\n" ] }, { @@ -2996,7 +2917,7 @@ { "data": { "text/plain": [ - "False\n" + "[['X', '', ''], ['X', '', ''], ['X', '', '']]\n" ] }, "output_type": "execute_result", @@ -3005,7 +2926,8 @@ } ], "source": [ - "issubclass(object, type)\n" + "board[0][0] = \"X\"\n", + "board\n" ] }, { @@ -3013,6 +2935,7 @@ "metadata": {}, "source": [ "\n", + "We didn't assign three `\"X\"`s, did we?\n", "\n" ] }, @@ -3020,26 +2943,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", + "#### \ud83d\udca1 Explanation:\n", "\n", - "- `type` is a [metaclass](https://realpython.com/python-metaclasses/) in Python.\n", - "- **Everything** is an `object` in Python, which includes classes as well as their objects (instances).\n", - "- class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`.\n", - "- There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking about these relationships (`issubclass` and `isinstance`) in terms of Python classes. The relationship between `object` and `type` can't be reproduced in pure python. To be more precise the following relationships can't be reproduced in pure Python,\n", - " + class A is an instance of class B, and class B is an instance of class A.\n", - " + class A is an instance of itself.\n", - "- These relationships between `object` and `type` (both being instances of each other as well as themselves) exist in Python because of \"cheating\" at the implementation level.\n", + "When we initialize `row` variable, this visualization explains what happens in the memory\n", + "\n", + "![image](/images/tic-tac-toe/after_row_initialized.png)\n", + "\n", + "And when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`)\n", + "\n", + "![image](/images/tic-tac-toe/after_board_initialized.png)\n", + "\n", + "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Subclass relationships\n", - "**Output:**\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -3050,7 +2967,7 @@ { "data": { "text/plain": [ - "True\n" + "[['X', '', ''], ['', '', ''], ['', '', '']]\n" ] }, "output_type": "execute_result", @@ -3059,8 +2976,23 @@ } ], "source": [ - "from collections import Hashable\n", - "issubclass(list, object)\n" + "board = [['']*3 for _ in range(3)]\n", + "board[0][0] = \"X\"\n", + "board\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Schr\u00f6dinger's variable *\n" ] }, { @@ -3072,9 +3004,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -3082,58 +3012,23 @@ } ], "source": [ - "issubclass(object, Hashable)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "issubclass(list, Hashable)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ + "funcs = []\n", + "results = []\n", + "for x in range(7):\n", + " def some_func():\n", + " return x\n", + " funcs.append(some_func)\n", + " results.append(some_func()) # note the function call here\n", "\n", - "The Subclass relationships were expected to be transitive, right? (i.e., if `A` is a subclass of `B`, and `B` is a subclass of `C`, the `A` _should_ a subclass of `C`)\n", - "\n" + "funcs_results = [func() for func in funcs]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", "\n", - "* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass.\n", - "* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey \"`__hash__`\" method in `cls` or anything it inherits from.\n", - "* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation.\n", - "* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 All-true-ation *\n" + "**Output (Python version):**\n" ] }, { @@ -3146,7 +3041,7 @@ { "data": { "text/plain": [ - "True\n" + "[0, 1, 2, 3, 4, 5, 6]\n" ] }, "output_type": "execute_result", @@ -3155,7 +3050,7 @@ } ], "source": [ - "all([True, True, True])\n" + "results\n" ] }, { @@ -3168,8 +3063,7 @@ { "data": { "text/plain": [ - "False\n", - "\n" + "[6, 6, 6, 6, 6, 6, 6]\n" ] }, "output_type": "execute_result", @@ -3178,7 +3072,18 @@ } ], "source": [ - "all([True, True, False])\n" + "funcs_results\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "The values of `x` were different in every iteration prior to appending `some_func` to `funcs`, but all the functions return 6 when they're evaluated after the loop completes.\n", + "\n", + "2.\n", + "\n" ] }, { @@ -3191,7 +3096,7 @@ { "data": { "text/plain": [ - "True\n" + "[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]\n" ] }, "output_type": "execute_result", @@ -3200,7 +3105,23 @@ } ], "source": [ - "all([])\n" + "powers_of_x = [lambda x: x**i for i in range(10)]\n", + "[f(2) for f in powers_of_x]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "* When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the *variable*, not its *value*. The function looks up `x` in the surrounding context, rather than using the value of `x` at the time the function is created. So all of the functions use the latest value assigned to the variable for computation. We can see that it's using the `x` from the surrounding context (i.e. *not* a local variable) with:\n" ] }, { @@ -3213,7 +3134,7 @@ { "data": { "text/plain": [ - "False\n" + "ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set())\n" ] }, "output_type": "execute_result", @@ -3222,7 +3143,16 @@ } ], "source": [ - "all([[]])\n" + "import inspect\n", + "inspect.getclosurevals(funcs[0])\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since `x` is a global value, we can change the value that the `funcs` will lookup and return by updating `x`:\n", + "\n" ] }, { @@ -3235,7 +3165,7 @@ { "data": { "text/plain": [ - "True\n" + "[42, 42, 42, 42, 42, 42, 42]\n" ] }, "output_type": "execute_result", @@ -3244,7 +3174,8 @@ } ], "source": [ - "all([[[]]])\n" + "x = 42\n", + "[func() for func in funcs]\n" ] }, { @@ -3252,38 +3183,40 @@ "metadata": {}, "source": [ "\n", - "Why's this True-False alteration?\n", + "* To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why does this work?** Because this will define the variable *inside* the function's scope. It will no longer go to the surrounding (global) scope to look up the variables value but will create a local variable that stores the value of `x` at that point in time.\n", "\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- The implementation of `all` function is equivalent to\n", - "\n", - "- ```py\n", - " def all(iterable):\n", - " for element in iterable:\n", - " if not element:\n", - " return False\n", - " return True\n", - " ```\n", - "\n", - "- `all([])` returns `True` since the iterable is empty. \n", - "- `all([[]])` returns `False` because `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty.\n", - "- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`.\n", - "\n" + "funcs = []\n", + "for x in range(7):\n", + " def some_func(x=x):\n", + " return x\n", + " funcs.append(some_func)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The surprising comma\n", - "**Output (< 3.6):**\n", + "\n", + "**Output:**\n", "\n" ] }, @@ -3297,11 +3230,7 @@ { "data": { "text/plain": [ - " File \"\", line 1\n", - " def h(x, **kwargs,):\n", - " ^\n", - "SyntaxError: invalid syntax\n", - "\n" + "[0, 1, 2, 3, 4, 5, 6]\n" ] }, "output_type": "execute_result", @@ -3310,13 +3239,17 @@ } ], "source": [ - "def f(x, y,):\n", - " print(x, y)\n", - "\n", - "def g(x=4, y=5,):\n", - " print(x, y)\n", + "funcs_results = [func() for func in funcs]\n", + "funcs_results\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "\n", - "def h(x, **kwargs,):\n" + "It is not longer using the `x` in the global scope:\n", + "\n" ] }, { @@ -3329,10 +3262,7 @@ { "data": { "text/plain": [ - " File \"\", line 1\n", - " def h(*args,):\n", - " ^\n", - "SyntaxError: invalid syntax\n" + "ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set())\n" ] }, "output_type": "execute_result", @@ -3341,25 +3271,13 @@ } ], "source": [ - "def h(*args,):\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "inspect.getclosurevars(funcs[0])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- Trailing comma is not always legal in formal parameters list of a Python function.\n", - "- In Python, the argument list is defined partially with leading commas and partially with trailing commas. This conflict causes situations where a comma is trapped in the middle, and no rule accepts it.\n", - "- **Note:** The trailing comma problem is [fixed in Python 3.6](https://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n", "\n" ] }, @@ -3367,71 +3285,52 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Strings and the backslashes\n", - "**Output:**\n" + "### \u25b6 The chicken-egg problem *\n", + "1\\.\n" ] }, { "cell_type": "code", - "metadata": { - "collapsed": true - }, "execution_count": null, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\"\n", - "\n" - ] - } - ], - "source": [ - "print(\"\\\"\")\n" - ] - }, - { - "cell_type": "code", "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "\\\"\n", - "\n" - ] + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(r\"\\\"\")\n" + "isinstance(3, int)\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "File \"\", line 1\n", - " print(r\"\\\")\n", - " ^\n", - "SyntaxError: EOL while scanning string literal\n", - "\n" - ] + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(r\"\\\")\n" + "isinstance(type, object)\n" ] }, { @@ -3453,23 +3352,18 @@ } ], "source": [ - "r'\\'' == \"\\\\'\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "isinstance(object, type)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", "\n", - "- In a usual python string, the backslash is used to escape characters that may have a special meaning (like single-quote, double-quote, and the backslash itself).\n" + "So which is the \"ultimate\" base class? There's more to the confusion by the way,\n", + "\n", + "2\\. \n", + "\n" ] }, { @@ -3482,7 +3376,7 @@ { "data": { "text/plain": [ - " 'wt\"f'\n" + "False\n" ] }, "output_type": "execute_result", @@ -3491,14 +3385,30 @@ } ], "source": [ - " 'wt\\\"f'\n" - ] + "class A: pass\n", + "isinstance(A, A)\n" + ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "- In a raw string literal (as indicated by the prefix `r`), the backslashes pass themselves as is along with the behavior of escaping the following character.\n" + "isinstance(type, type)\n" ] }, { @@ -3511,7 +3421,7 @@ { "data": { "text/plain": [ - " True\n" + "True\n" ] }, "output_type": "execute_result", @@ -3520,7 +3430,16 @@ } ], "source": [ - " r'wt\\\"f' == 'wt\\\\\"f'\n" + "isinstance(object, object)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n" ] }, { @@ -3533,8 +3452,7 @@ { "data": { "text/plain": [ - " 'wt\\\\\"f'\n", - "\n" + "True\n" ] }, "output_type": "execute_result", @@ -3543,7 +3461,7 @@ } ], "source": [ - " print(repr(r'wt\\\"f')\n" + "issubclass(int, object)\n" ] }, { @@ -3556,7 +3474,7 @@ { "data": { "text/plain": [ - "\n" + "True\n" ] }, "output_type": "execute_result", @@ -3565,7 +3483,7 @@ } ], "source": [ - " print(\"\\n\")\n" + "issubclass(type, object)\n" ] }, { @@ -3578,7 +3496,7 @@ { "data": { "text/plain": [ - " '\\\\\\\\n'\n" + "False\n" ] }, "output_type": "execute_result", @@ -3587,14 +3505,14 @@ } ], "source": [ - " print(r\"\\\\n\")\n" + "issubclass(object, type)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "- This means when a parser encounters a backslash in a raw string, it expects another character following it. And in our case (`print(r\"\\\")`), the backslash escaped the trailing quote, leaving the parser without a terminating quote (hence the `SyntaxError`). That's why backslashes don't work at the end of a raw string.\n", + "\n", "\n" ] }, @@ -3602,7 +3520,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 not knot!\n" + "#### \ud83d\udca1 Explanation\n", + "\n", + "- `type` is a [metaclass](https://realpython.com/python-metaclasses/) in Python.\n", + "- **Everything** is an `object` in Python, which includes classes as well as their objects (instances).\n", + "- class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`.\n", + "- There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking about these relationships (`issubclass` and `isinstance`) in terms of Python classes. The relationship between `object` and `type` can't be reproduced in pure python. To be more precise the following relationships can't be reproduced in pure Python,\n", + " + class A is an instance of class B, and class B is an instance of class A.\n", + " + class A is an instance of itself.\n", + "- These relationships between `object` and `type` (both being instances of each other as well as themselves) exist in Python because of \"cheating\" at the implementation level.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Subclass relationships\n", + "**Output:**\n" ] }, { @@ -3614,7 +3549,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -3622,16 +3559,8 @@ } ], "source": [ - "x = True\n", - "y = False\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "from collections import Hashable\n", + "issubclass(list, object)\n" ] }, { @@ -3653,7 +3582,7 @@ } ], "source": [ - "not x == y\n" + "issubclass(object, Hashable)\n" ] }, { @@ -3666,10 +3595,7 @@ { "data": { "text/plain": [ - " File \"\", line 1\n", - " x == not y\n", - " ^\n", - "SyntaxError: invalid syntax\n" + "False\n" ] }, "output_type": "execute_result", @@ -3678,13 +3604,15 @@ } ], "source": [ - "x == not y\n" + "issubclass(list, Hashable)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "The Subclass relationships were expected to be transitive, right? (i.e., if `A` is a subclass of `B`, and `B` is a subclass of `C`, the `A` _should_ a subclass of `C`)\n", "\n" ] }, @@ -3694,10 +3622,10 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "* Operator precedence affects how an expression is evaluated, and `==` operator has higher precedence than `not` operator in Python.\n", - "* So `not x == y` is equivalent to `not (x == y)` which is equivalent to `not (True == False)` finally evaluating to `True`.\n", - "* But `x == not y` raises a `SyntaxError` because it can be thought of being equivalent to `(x == not) y` and not `x == (not y)` which you might have expected at first sight.\n", - "* The parser expected the `not` token to be a part of the `not in` operator (because both `==` and `not in` operators have the same precedence), but after not being able to find an `in` token following the `not` token, it raises a `SyntaxError`.\n", + "* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass.\n", + "* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey \"`__hash__`\" method in `cls` or anything it inherits from.\n", + "* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation.\n", + "* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/).\n", "\n" ] }, @@ -3705,7 +3633,45 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Half triple-quoted strings\n", + "### \u25b6 Methods equality and identity\n", + "1.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "class SomeClass:\n", + " def method(self):\n", + " pass\n", + "\n", + " @classmethod\n", + " def classm(cls):\n", + " pass\n", + "\n", + " @staticmethod\n", + " def staticm():\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", "**Output:**\n" ] }, @@ -3720,12 +3686,12 @@ "name": "stdout", "output_type": "stream", "text": [ - "wtfpython\n" + "True\n" ] } ], "source": [ - "print('wtfpython''')\n" + "print(SomeClass.method is SomeClass.method)\n" ] }, { @@ -3739,71 +3705,61 @@ "name": "stdout", "output_type": "stream", "text": [ - "wtfpython\n" + "False\n" ] } ], "source": [ - "print(\"wtfpython\"\"\")\n" + "print(SomeClass.classm is SomeClass.classm)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - " File \"\", line 3\n", - " print(\"\"\"wtfpython\")\n", - " ^\n", - "SyntaxError: EOF while scanning triple-quoted string literal\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] } ], "source": [ - "# The following statements raise `SyntaxError`\n", - "# print('''wtfpython')\n", - "# print(\"\"\"wtfpython\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "print(SomeClass.classm == SomeClass.classm)\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], "source": [ - "#### \ud83d\udca1 Explanation:\n", - "+ Python supports implicit [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation), Example,\n", - " ```\n", - " >>> print(\"wtf\" \"python\")\n", - " wtfpython\n", - " >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n", - " wtf\n", - " ```\n", - "+ `'''` and `\"\"\"` are also string delimiters in Python which causes a SyntaxError because the Python interpreter was expecting a terminating triple quote as delimiter while scanning the currently encountered triple quoted string literal.\n", - "\n" + "print(SomeClass.staticm is SomeClass.staticm)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 What's wrong with booleans?\n", - "1\\.\n", - "\n" + "\n", + "Accessing `classm` twice, we get an equal object, but not the *same* one? Let's see what happens\n", + "with instances of `SomeClass`:\n", + "\n", + "2.\n" ] }, { @@ -3823,17 +3779,8 @@ } ], "source": [ - "# A simple example to count the number of booleans and\n", - "# integers in an iterable of mixed data types.\n", - "mixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\n", - "integers_found_so_far = 0\n", - "booleans_found_so_far = 0\n", - "\n", - "for item in mixed_list:\n", - " if isinstance(item, int):\n", - " integers_found_so_far += 1\n", - " elif isinstance(item, bool):\n", - " booleans_found_so_far += 1\n" + "o1 = SomeClass()\n", + "o2 = SomeClass()\n" ] }, { @@ -3846,164 +3793,116 @@ }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "4\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] } ], "source": [ - "integers_found_so_far\n" + "print(o1.method == o2.method)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "0\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] } ], "source": [ - "booleans_found_so_far\n" + "print(o1.method == o1.method)\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] + } + ], "source": [ - "\n", - "\n", - "2\\.\n" + "print(o1.method is o1.method)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "'wtf'\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] } ], "source": [ - "some_bool = True\n", - "\"wtf\" * some_bool\n" + "print(o1.classm is o1.classm)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, - "outputs": [ - { - "data": { - "text/plain": [ - "''\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "some_bool = False\n", - "\"wtf\" * some_bool\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n" - ] - }, - { - "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": true - }, "outputs": [ { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] } ], "source": [ - "def tell_truth():\n", - " True = False\n", - " if True == False:\n", - " print(\"I have lost faith in truth!\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (< 3.x):**\n", - "\n" + "print(o1.classm == o1.classm == o2.classm == SomeClass.classm)\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "I have lost faith in truth!\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] } ], "source": [ - "tell_truth()\n" + "print(o1.staticm is o1.staticm is o2.staticm is SomeClass.staticm)\n" ] }, { @@ -4011,7 +3910,7 @@ "metadata": {}, "source": [ "\n", - "\n", + "Accessing` classm` or `method` twice, creates equal but not *same* objects for the same instance of `SomeClass`.\n", "\n" ] }, @@ -4019,10 +3918,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* `bool` is a subclass of `int` in Python\n", - " \n" + "#### \ud83d\udca1 Explanation\n", + "* Functions are [descriptors](https://docs.python.org/3/howto/descriptor.html). Whenever a function is accessed as an\n", + "attribute, the descriptor is invoked, creating a method object which \"binds\" the function with the object owning the\n", + "attribute. If called, the method calls the function, implicitly passing the bound object as the first argument\n", + "(this is how we get `self` as the first argument, despite not passing it explicitly).\n" ] }, { @@ -4035,7 +3935,7 @@ { "data": { "text/plain": [ - " True\n" + ">\n" ] }, "output_type": "execute_result", @@ -4044,7 +3944,16 @@ } ], "source": [ - " issubclass(bool, int)\n" + "o1.method\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Accessing the attribute multiple times creates a method object every time! Therefore `o1.method is o1.method` is\n", + "never truthy. Accessing functions as class attributes (as opposed to instance) does not create methods, however; so\n", + "`SomeClass.method is SomeClass.method` is truthy.\n" ] }, { @@ -4057,7 +3966,7 @@ { "data": { "text/plain": [ - " False\n" + "\n" ] }, "output_type": "execute_result", @@ -4066,15 +3975,15 @@ } ], "source": [ - " issubclass(int, bool)\n" + "SomeClass.method\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " \n", - "* And thus, `True` and `False` are instances of `int`\n" + "* `classmethod` transforms functions into class methods. Class methods are descriptors that, when accessed, create\n", + "a method object which binds the *class* (type) of the object, instead of the object itself.\n" ] }, { @@ -4087,7 +3996,7 @@ { "data": { "text/plain": [ - " True\n" + ">\n" ] }, "output_type": "execute_result", @@ -4096,7 +4005,15 @@ } ], "source": [ - " isinstance(True, int)\n" + "o1.classm\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Unlike functions, `classmethod`s will create a method also when accessed as class attributes (in which case they\n", + "bind the class, not to the type of it). So `SomeClass.classm is SomeClass.classm` is falsy.\n" ] }, { @@ -4109,7 +4026,7 @@ { "data": { "text/plain": [ - " True\n" + ">\n" ] }, "output_type": "execute_result", @@ -4118,15 +4035,17 @@ } ], "source": [ - " isinstance(False, int)\n" + "SomeClass.classm\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "* The integer value of `True` is `1` and that of `False` is `0`.\n" + "* A method object compares equal when both the functions are equal, and the bound objects are the same. So\n", + "`o1.method == o1.method` is truthy, although not the same object in memory.\n", + "* `staticmethod` transforms functions into a \"no-op\" descriptor, which returns the function as-is. No method\n", + "objects are ever created, so comparison with `is` is truthy.\n" ] }, { @@ -4139,7 +4058,7 @@ { "data": { "text/plain": [ - " 1\n" + "\n" ] }, "output_type": "execute_result", @@ -4148,7 +4067,7 @@ } ], "source": [ - " int(True)\n" + "o1.staticm\n" ] }, { @@ -4161,7 +4080,7 @@ { "data": { "text/plain": [ - " 0\n" + "\n" ] }, "output_type": "execute_result", @@ -4170,19 +4089,18 @@ } ], "source": [ - " int(False)\n" + "SomeClass.staticm\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for the rationale behind it.\n", - "\n", - "* Initially, Python used to have no `bool` type (people used 0 for false and non-zero value like 1 for true). `True`, `False`, and a `bool` type was added in 2.x versions, but, for backward compatibility, `True` and `False` couldn't be made constants. They just were built-in variables, and it was possible to reassign them\n", - "\n", - "* Python 3 was backward-incompatible, the issue was finally fixed, and thus the last snippet won't work with Python 3.x!\n", + "* Having to create new \"method\" objects every time Python calls instance methods and having to modify the arguments\n", + "every time in order to insert `self` affected performance badly.\n", + "CPython 3.7 [solved it](https://bugs.python.org/issue26110) by introducing new opcodes that deal with calling methods\n", + "without creating the temporary method objects. This is used only when the accessed function is actually called, so the\n", + "snippets here are not affected, and still generate methods :)\n", "\n" ] }, @@ -4190,43 +4108,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Class attributes and instance attributes\n", - "1\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "class A:\n", - " x = 1\n", - "\n", - "class B(A):\n", - " pass\n", - "\n", - "class C(A):\n", - " pass\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "### \u25b6 All-true-ation *\n" ] }, { @@ -4239,7 +4121,7 @@ { "data": { "text/plain": [ - "(1, 1, 1)\n" + "True\n" ] }, "output_type": "execute_result", @@ -4248,7 +4130,7 @@ } ], "source": [ - "A.x, B.x, C.x\n" + "all([True, True, True])\n" ] }, { @@ -4261,7 +4143,8 @@ { "data": { "text/plain": [ - "(1, 2, 1)\n" + "False\n", + "\n" ] }, "output_type": "execute_result", @@ -4270,8 +4153,7 @@ } ], "source": [ - "B.x = 2\n", - "A.x, B.x, C.x\n" + "all([True, True, False])\n" ] }, { @@ -4284,7 +4166,7 @@ { "data": { "text/plain": [ - "(3, 2, 3)\n" + "True\n" ] }, "output_type": "execute_result", @@ -4293,8 +4175,7 @@ } ], "source": [ - "A.x = 3\n", - "A.x, B.x, C.x # C.x changed, but B.x didn't\n" + "all([])\n" ] }, { @@ -4307,7 +4188,7 @@ { "data": { "text/plain": [ - "(3, 3)\n" + "False\n" ] }, "output_type": "execute_result", @@ -4316,8 +4197,7 @@ } ], "source": [ - "a = A()\n", - "a.x, A.x\n" + "all([[]])\n" ] }, { @@ -4330,7 +4210,7 @@ { "data": { "text/plain": [ - "(4, 3)\n" + "True\n" ] }, "output_type": "execute_result", @@ -4339,8 +4219,7 @@ } ], "source": [ - "a.x += 1\n", - "a.x, A.x\n" + "all([[[]]])\n" ] }, { @@ -4348,42 +4227,38 @@ "metadata": {}, "source": [ "\n", - "2\\.\n" + "Why's this True-False alteration?\n", + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "class SomeClass:\n", - " some_var = 15\n", - " some_list = [5]\n", - " another_list = [5]\n", - " def __init__(self, x):\n", - " self.some_var = x + 1\n", - " self.some_list = self.some_list + [x]\n", - " self.another_list += [x]\n" + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- The implementation of `all` function is equivalent to\n", + "\n", + "- ```py\n", + " def all(iterable):\n", + " for element in iterable:\n", + " if not element:\n", + " return False\n", + " return True\n", + " ```\n", + "\n", + "- `all([])` returns `True` since the iterable is empty. \n", + "- `all([[]])` returns `False` because `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty.\n", + "- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`.\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n", + "### \u25b6 The surprising comma\n", + "**Output (< 3.6):**\n", "\n" ] }, @@ -4397,7 +4272,11 @@ { "data": { "text/plain": [ - "[5, 420]\n" + " File \"\", line 1\n", + " def h(x, **kwargs,):\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n" ] }, "output_type": "execute_result", @@ -4406,8 +4285,13 @@ } ], "source": [ - "some_obj = SomeClass(420)\n", - "some_obj.some_list\n" + "def f(x, y,):\n", + " print(x, y)\n", + "\n", + "def g(x=4, y=5,):\n", + " print(x, y)\n", + "\n", + "def h(x, **kwargs,):\n" ] }, { @@ -4420,7 +4304,10 @@ { "data": { "text/plain": [ - "[5, 420]\n" + " File \"\", line 1\n", + " def h(*args,):\n", + " ^\n", + "SyntaxError: invalid syntax\n" ] }, "output_type": "execute_result", @@ -4429,74 +4316,97 @@ } ], "source": [ - "some_obj.another_list\n" + "def h(*args,):\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- Trailing comma is not always legal in formal parameters list of a Python function.\n", + "- In Python, the argument list is defined partially with leading commas and partially with trailing commas. This conflict causes situations where a comma is trapped in the middle, and no rule accepts it.\n", + "- **Note:** The trailing comma problem is [fixed in Python 3.6](https://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Strings and the backslashes\n", + "**Output:**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "[5, 111]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "\"\n", + "\n" + ] } ], "source": [ - "another_obj = SomeClass(111)\n", - "another_obj.some_list\n" + "print(\"\\\"\")\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "[5, 420, 111]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "\\\"\n", + "\n" + ] } ], "source": [ - "another_obj.another_list\n" + "print(r\"\\\"\")\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "File \"\", line 1\n", + " print(r\"\\\")\n", + " ^\n", + "SyntaxError: EOL while scanning string literal\n", + "\n" + ] } ], "source": [ - "another_obj.another_list is SomeClass.another_list\n" + "print(r\"\\\")\n" ] }, { @@ -4518,7 +4428,7 @@ } ], "source": [ - "another_obj.another_list is some_obj.another_list\n" + "r'\\'' == \"\\\\'\"\n" ] }, { @@ -4532,18 +4442,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", + "#### \ud83d\udca1 Explanation\n", "\n", - "* Class variables and variables in class instances are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of the current class, the parent classes are searched for it.\n", - "* The `+=` operator modifies the mutable object in-place without creating a new object. So changing the attribute of one instance affects the other instances and the class attribute as well.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Non-reflexive class method *\n" + "- In a usual python string, the backslash is used to escape characters that may have a special meaning (like single-quote, double-quote, and the backslash itself).\n" ] }, { @@ -4555,7 +4456,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " 'wt\"f'\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -4563,44 +4466,14 @@ } ], "source": [ - "class SomeClass:\n", - " def instance_method(self):\n", - " pass\n", - " \n", - " @classmethod\n", - " def class_method(cls):\n", - " pass\n" + " \"wt\\\"f\"\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "SomeClass.instance_method is SomeClass.instance_method\n" + "- In a raw string literal (as indicated by the prefix `r`), the backslashes pass themselves as is along with the behavior of escaping the following character.\n" ] }, { @@ -4613,7 +4486,7 @@ { "data": { "text/plain": [ - "False\n" + " True\n" ] }, "output_type": "execute_result", @@ -4622,7 +4495,7 @@ } ], "source": [ - "SomeClass.class_method is SomeClass.class_method\n" + " r'wt\\\"f' == 'wt\\\\\"f'\n" ] }, { @@ -4635,7 +4508,8 @@ { "data": { "text/plain": [ - "True\n" + " 'wt\\\\\"f'\n", + "\n" ] }, "output_type": "execute_result", @@ -4644,24 +4518,7 @@ } ], "source": [ - "id(SomeClass.class_method) == id(SomeClass.class_method)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- The reason `SomeClass.class_method is SomeClass.class_method` is `False` is due to the `@classmethod` decorator. \n", - "\n" + " print(repr(r'wt\\\"f')\n" ] }, { @@ -4674,7 +4531,7 @@ { "data": { "text/plain": [ - " \n" + "\n" ] }, "output_type": "execute_result", @@ -4683,7 +4540,7 @@ } ], "source": [ - " SomeClass.instance_method\n" + " print(\"\\n\")\n" ] }, { @@ -4696,7 +4553,7 @@ { "data": { "text/plain": [ - " \n" + " '\\\\n'\n" ] }, "output_type": "execute_result", @@ -4705,17 +4562,14 @@ } ], "source": [ - " SomeClass.class_method\n" + " print(r\"\\\\n\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - " A new bound method every time `SomeClass.class_method` is accessed.\n", - "\n", - "- `id(SomeClass.class_method) == id(SomeClass.class_method)` returned `True` because the second allocation of memory for `class_method` happened at the same location of first deallocation (See Deep Down, we're all the same example for more detailed explanation). \n", + "- This means when a parser encounters a backslash in a raw string, it expects another character following it. And in our case (`print(r\"\\\")`), the backslash escaped the trailing quote, leaving the parser without a terminating quote (hence the `SyntaxError`). That's why backslashes don't work at the end of a raw string.\n", "\n" ] }, @@ -4723,7 +4577,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 yielding None\n" + "### \u25b6 not knot!\n" ] }, { @@ -4743,10 +4597,8 @@ } ], "source": [ - "some_iterable = ('a', 'b')\n", - "\n", - "def some_func(val):\n", - " return \"something\"\n" + "x = True\n", + "y = False\n" ] }, { @@ -4754,8 +4606,7 @@ "metadata": {}, "source": [ "\n", - "**Output (<= 3.7.x):**\n", - "\n" + "**Output:**\n" ] }, { @@ -4768,7 +4619,7 @@ { "data": { "text/plain": [ - "['a', 'b']\n" + "True\n" ] }, "output_type": "execute_result", @@ -4777,7 +4628,7 @@ } ], "source": [ - "[x for x in some_iterable]\n" + "not x == y\n" ] }, { @@ -4790,7 +4641,10 @@ { "data": { "text/plain": [ - " at 0x7f70b0a4ad58>\n" + " File \"\", line 1\n", + " x == not y\n", + " ^\n", + "SyntaxError: invalid syntax\n" ] }, "output_type": "execute_result", @@ -4799,51 +4653,73 @@ } ], "source": [ - "[(yield x) for x in some_iterable]\n" + "x == not y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* Operator precedence affects how an expression is evaluated, and `==` operator has higher precedence than `not` operator in Python.\n", + "* So `not x == y` is equivalent to `not (x == y)` which is equivalent to `not (True == False)` finally evaluating to `True`.\n", + "* But `x == not y` raises a `SyntaxError` because it can be thought of being equivalent to `(x == not) y` and not `x == (not y)` which you might have expected at first sight.\n", + "* The parser expected the `not` token to be a part of the `not in` operator (because both `==` and `not in` operators have the same precedence), but after not being able to find an `in` token following the `not` token, it raises a `SyntaxError`.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Half triple-quoted strings\n", + "**Output:**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "['a', 'b']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "wtfpython\n" + ] } ], "source": [ - "list([(yield x) for x in some_iterable])\n" + "print('wtfpython''')\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "['a', None, 'b', None]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "wtfpython\n" + ] } ], "source": [ - "list((yield x) for x in some_iterable)\n" + "print(\"wtfpython\"\"\")\n" ] }, { @@ -4856,7 +4732,10 @@ { "data": { "text/plain": [ - "['a', 'something', 'b', 'something']\n" + " File \"\", line 3\n", + " print(\"\"\"wtfpython\")\n", + " ^\n", + "SyntaxError: EOF while scanning triple-quoted string literal\n" ] }, "output_type": "execute_result", @@ -4865,7 +4744,9 @@ } ], "source": [ - "list(some_func((yield x)) for x in some_iterable)\n" + "# The following statements raise `SyntaxError`\n", + "# print('''wtfpython')\n", + "# print(\"\"\"wtfpython\")\n" ] }, { @@ -4880,18 +4761,22 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n", - "- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n", - "- Related bug report: http://bugs.python.org/issue10544\n", - "- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n", - "\n" + "+ Python supports implicit [string literal concatenation](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation), Example,\n", + " ```\n", + " >>> print(\"wtf\" \"python\")\n", + " wtfpython\n", + " >>> print(\"wtf\" \"\") # or \"wtf\"\"\"\n", + " wtf\n", + " ```\n", + "+ `'''` and `\"\"\"` are also string delimiters in Python which causes a SyntaxError because the Python interpreter was expecting a terminating triple quote as delimiter while scanning the currently encountered triple quoted string literal.\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Yielding from... return! *\n", + "### \u25b6 What's wrong with booleans?\n", "1\\.\n", "\n" ] @@ -4913,11 +4798,17 @@ } ], "source": [ - "def some_func(x):\n", - " if x == 3:\n", - " return [\"wtf\"]\n", - " else:\n", - " yield from range(x)\n" + "# A simple example to count the number of booleans and\n", + "# integers in an iterable of mixed data types.\n", + "mixed_list = [False, 1.0, \"some_string\", 3, True, [], False]\n", + "integers_found_so_far = 0\n", + "booleans_found_so_far = 0\n", + "\n", + "for item in mixed_list:\n", + " if isinstance(item, int):\n", + " integers_found_so_far += 1\n", + " elif isinstance(item, bool):\n", + " booleans_found_so_far += 1\n" ] }, { @@ -4925,8 +4816,7 @@ "metadata": {}, "source": [ "\n", - "**Output (> 3.3):**\n", - "\n" + "**Output:**\n" ] }, { @@ -4939,7 +4829,7 @@ { "data": { "text/plain": [ - "[]\n" + "4\n" ] }, "output_type": "execute_result", @@ -4948,18 +4838,7 @@ } ], "source": [ - "list(some_func(3))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Where did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n", - "\n", - "2\\.\n", - "\n" + "integers_found_so_far\n" ] }, { @@ -4971,7 +4850,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "0\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -4979,12 +4860,7 @@ } ], "source": [ - "def some_func(x):\n", - " if x == 3:\n", - " return [\"wtf\"]\n", - " else:\n", - " for i in range(x):\n", - " yield i\n" + "booleans_found_so_far\n" ] }, { @@ -4992,8 +4868,8 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "\n", + "2\\.\n" ] }, { @@ -5006,7 +4882,7 @@ { "data": { "text/plain": [ - "[]\n" + "'wtf'\n" ] }, "output_type": "execute_result", @@ -5015,31 +4891,39 @@ } ], "source": [ - "list(some_func(3))\n" + "some_bool = True\n", + "\"wtf\" * some_bool\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "''\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "The same result, this didn't work either.\n", - "\n" + "some_bool = False\n", + "\"wtf\" * some_bool\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that,\n", - "\n", - "> \"... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator.\"\n", - "\n", - "+ In the case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically caught inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list.\n", "\n", - "+ To get `[\"wtf\"]` from the generator `some_func` we need to catch the `StopIteration` exception,\n", + "3\\.\n", "\n" ] }, @@ -5060,16 +4944,18 @@ } ], "source": [ - " try:\n", - " next(some_func(3))\n", - " except StopIteration as e:\n", - " some_string = e.value\n" + "def tell_truth():\n", + " True = False\n", + " if True == False:\n", + " print(\"I have lost faith in truth!\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "**Output (< 3.x):**\n", "\n" ] }, @@ -5083,7 +4969,7 @@ { "data": { "text/plain": [ - " [\"wtf\"]\n" + "I have lost faith in truth!\n" ] }, "output_type": "execute_result", @@ -5092,13 +4978,15 @@ } ], "source": [ - " some_string\n" + "tell_truth()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "\n" ] }, @@ -5106,9 +4994,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Nan-reflexivity *\n", - "1\\.\n", - "\n" + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* `bool` is a subclass of `int` in Python\n", + " \n" ] }, { @@ -5120,7 +5009,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -5128,19 +5019,37 @@ } ], "source": [ - "a = float('inf')\n", - "b = float('nan')\n", - "c = float('-iNf') # These strings are case-insensitive\n", - "d = float('nan')\n" + " issubclass(bool, int)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " issubclass(int, bool)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n", - "\n" + " \n", + "* And thus, `True` and `False` are instances of `int`\n" ] }, { @@ -5153,7 +5062,7 @@ { "data": { "text/plain": [ - "inf\n" + " True\n" ] }, "output_type": "execute_result", @@ -5162,7 +5071,7 @@ } ], "source": [ - "a\n" + " isinstance(True, int)\n" ] }, { @@ -5175,7 +5084,7 @@ { "data": { "text/plain": [ - "nan\n" + " True\n" ] }, "output_type": "execute_result", @@ -5184,7 +5093,15 @@ } ], "source": [ - "b\n" + " isinstance(False, int)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* The integer value of `True` is `1` and that of `False` is `0`.\n" ] }, { @@ -5197,7 +5114,7 @@ { "data": { "text/plain": [ - "-inf\n" + " 1\n" ] }, "output_type": "execute_result", @@ -5206,7 +5123,7 @@ } ], "source": [ - "c\n" + " int(True)\n" ] }, { @@ -5219,7 +5136,7 @@ { "data": { "text/plain": [ - "ValueError: could not convert string to float: some_other_string\n" + " 0\n" ] }, "output_type": "execute_result", @@ -5228,7 +5145,28 @@ } ], "source": [ - "float('some_other_string')\n" + " int(False)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for the rationale behind it.\n", + "\n", + "* Initially, Python used to have no `bool` type (people used 0 for false and non-zero value like 1 for true). `True`, `False`, and a `bool` type was added in 2.x versions, but, for backward compatibility, `True` and `False` couldn't be made constants. They just were built-in variables, and it was possible to reassign them\n", + "\n", + "* Python 3 was backward-incompatible, the issue was finally fixed, and thus the last snippet won't work with Python 3.x!\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Class attributes and instance attributes\n", + "1\\.\n" ] }, { @@ -5240,9 +5178,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -5250,7 +5186,22 @@ } ], "source": [ - "a == -c # inf==inf\n" + "class A:\n", + " x = 1\n", + "\n", + "class B(A):\n", + " pass\n", + "\n", + "class C(A):\n", + " pass\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -5263,7 +5214,7 @@ { "data": { "text/plain": [ - "True\n" + "(1, 1, 1)\n" ] }, "output_type": "execute_result", @@ -5272,7 +5223,7 @@ } ], "source": [ - "None == None # None == None\n" + "A.x, B.x, C.x\n" ] }, { @@ -5285,7 +5236,7 @@ { "data": { "text/plain": [ - "False\n" + "(1, 2, 1)\n" ] }, "output_type": "execute_result", @@ -5294,7 +5245,8 @@ } ], "source": [ - "b == d # but nan!=nan\n" + "B.x = 2\n", + "A.x, B.x, C.x\n" ] }, { @@ -5307,7 +5259,7 @@ { "data": { "text/plain": [ - "0.0\n" + "(3, 2, 3)\n" ] }, "output_type": "execute_result", @@ -5316,7 +5268,8 @@ } ], "source": [ - "50 / a\n" + "A.x = 3\n", + "A.x, B.x, C.x # C.x changed, but B.x didn't\n" ] }, { @@ -5329,7 +5282,7 @@ { "data": { "text/plain": [ - "nan\n" + "(3, 3)\n" ] }, "output_type": "execute_result", @@ -5338,7 +5291,8 @@ } ], "source": [ - "a / a\n" + "a = A()\n", + "a.x, A.x\n" ] }, { @@ -5351,7 +5305,7 @@ { "data": { "text/plain": [ - "nan\n" + "(4, 3)\n" ] }, "output_type": "execute_result", @@ -5360,7 +5314,8 @@ } ], "source": [ - "23 + b\n" + "a.x += 1\n", + "a.x, A.x\n" ] }, { @@ -5368,8 +5323,7 @@ "metadata": {}, "source": [ "\n", - "2\\.\n", - "\n" + "2\\.\n" ] }, { @@ -5381,9 +5335,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -5391,9 +5343,23 @@ } ], "source": [ - "x = float('nan')\n", - "y = x / x\n", - "y is y # identity holds\n" + "class SomeClass:\n", + " some_var = 15\n", + " some_list = [5]\n", + " another_list = [5]\n", + " def __init__(self, x):\n", + " self.some_var = x + 1\n", + " self.some_list = self.some_list + [x]\n", + " self.another_list += [x]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" ] }, { @@ -5406,7 +5372,7 @@ { "data": { "text/plain": [ - "False\n" + "[5, 420]\n" ] }, "output_type": "execute_result", @@ -5415,7 +5381,8 @@ } ], "source": [ - "y == y # equality fails of y\n" + "some_obj = SomeClass(420)\n", + "some_obj.some_list\n" ] }, { @@ -5428,7 +5395,7 @@ { "data": { "text/plain": [ - "True\n" + "[5, 420]\n" ] }, "output_type": "execute_result", @@ -5437,28 +5404,30 @@ } ], "source": [ - "[y] == [y] # but the equality succeeds for the list containing y\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "\n" + "some_obj.another_list\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[5, 111]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- `'inf'` and `'nan'` are special strings (case-insensitive), which, when explicitly typecast-ed to `float` type, are used to represent mathematical \"infinity\" and \"not a number\" respectively.\n", - "\n", - "- Since according to IEEE standards ` NaN != NaN`, obeying this rule breaks the reflexivity assumption of a collection element in Python i.e. if `x` is a part of a collection like `list`, the implementations like comparison are based on the assumption that `x == x`. Because of this assumption, the identity is compared first (since it's faster) while comparing two elements, and the values are compared only when the identities mismatch. The following snippet will make things clearer,\n", - "\n" + "another_obj = SomeClass(111)\n", + "another_obj.some_list\n" ] }, { @@ -5471,7 +5440,7 @@ { "data": { "text/plain": [ - " (False, True)\n" + "[5, 420, 111]\n" ] }, "output_type": "execute_result", @@ -5480,8 +5449,7 @@ } ], "source": [ - " x = float('nan')\n", - " x == x, [x] == [x]\n" + "another_obj.another_list\n" ] }, { @@ -5494,7 +5462,7 @@ { "data": { "text/plain": [ - " (False, True)\n" + "True\n" ] }, "output_type": "execute_result", @@ -5503,8 +5471,7 @@ } ], "source": [ - " y = float('nan')\n", - " y == y, [y] == [y]\n" + "another_obj.another_list is SomeClass.another_list\n" ] }, { @@ -5517,7 +5484,7 @@ { "data": { "text/plain": [ - " (False, False)\n" + "True\n" ] }, "output_type": "execute_result", @@ -5526,17 +5493,13 @@ } ], "source": [ - " x == y, [x] == [y]\n" + "another_obj.another_list is some_obj.another_list\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - " Since the identities of `x` and `y` are different, the values are considered, which are also different; hence the comparison returns `False` this time.\n", - "\n", - "- Interesting read: [Reflexivity, and other pillars of civilization](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n", "\n" ] }, @@ -5544,11 +5507,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Mutating the immutable!\n", - "This might seem trivial if you know how references work in Python.\n", + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* Class variables and variables in class instances are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of the current class, the parent classes are searched for it.\n", + "* The `+=` operator modifies the mutable object in-place without creating a new object. So changing the attribute of one instance affects the other instances and the class attribute as well.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 yielding None\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -5566,8 +5538,10 @@ } ], "source": [ - "some_tuple = (\"A\", \"tuple\", \"with\", \"values\")\n", - "another_tuple = ([1, 2], [3, 4], [5, 6])\n" + "some_iterable = ('a', 'b')\n", + "\n", + "def some_func(val):\n", + " return \"something\"\n" ] }, { @@ -5575,7 +5549,8 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + "**Output (<= 3.7.x):**\n", + "\n" ] }, { @@ -5588,7 +5563,7 @@ { "data": { "text/plain": [ - "TypeError: 'tuple' object does not support item assignment\n" + "['a', 'b']\n" ] }, "output_type": "execute_result", @@ -5597,7 +5572,7 @@ } ], "source": [ - "some_tuple[2] = \"change this\"\n" + "[x for x in some_iterable]\n" ] }, { @@ -5610,7 +5585,7 @@ { "data": { "text/plain": [ - "([1, 2], [3, 4], [5, 6, 1000])\n" + " at 0x7f70b0a4ad58>\n" ] }, "output_type": "execute_result", @@ -5619,8 +5594,7 @@ } ], "source": [ - "another_tuple[2].append(1000) #This throws no error\n", - "another_tuple\n" + "[(yield x) for x in some_iterable]\n" ] }, { @@ -5633,7 +5607,7 @@ { "data": { "text/plain": [ - "TypeError: 'tuple' object does not support item assignment\n" + "['a', 'b']\n" ] }, "output_type": "execute_result", @@ -5642,7 +5616,7 @@ } ], "source": [ - "another_tuple[2] += [99, 999]\n" + "list([(yield x) for x in some_iterable])\n" ] }, { @@ -5655,7 +5629,7 @@ { "data": { "text/plain": [ - "([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n" + "['a', None, 'b', None]\n" ] }, "output_type": "execute_result", @@ -5664,15 +5638,35 @@ } ], "source": [ - "another_tuple\n" + "list((yield x) for x in some_iterable)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'something', 'b', 'something']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list(some_func((yield x)) for x in some_iterable)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "But I thought tuples were immutable...\n", "\n" ] }, @@ -5681,13 +5675,10 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "\n", - "* Quoting from https://docs.python.org/2/reference/datamodel.html\n", - "\n", - " > Immutable sequences\n", - " An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.)\n", - "\n", - "* `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place.\n", + "- This is a bug in CPython's handling of `yield` in generators and comprehensions.\n", + "- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions\n", + "- Related bug report: https://bugs.python.org/issue10544\n", + "- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`.\n", "\n" ] }, @@ -5695,7 +5686,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The disappearing variable from outer scope\n" + "### \u25b6 Yielding from... return! *\n", + "1\\.\n", + "\n" ] }, { @@ -5715,11 +5708,11 @@ } ], "source": [ - "e = 7\n", - "try:\n", - " raise Exception()\n", - "except Exception as e:\n", - " pass\n" + "def some_func(x):\n", + " if x == 3:\n", + " return [\"wtf\"]\n", + " else:\n", + " yield from range(x)\n" ] }, { @@ -5727,26 +5720,30 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 2.x):**\n" + "**Output (> 3.3):**\n", + "\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "# prints nothing\n" - ] + "data": { + "text/plain": [ + "[]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(e)\n" + "list(some_func(3))\n" ] }, { @@ -5754,44 +5751,43 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 3.x):**\n" + "Where did the `\"wtf\"` go? Is it due to some special effect of `yield from`? Let's validate that,\n", + "\n", + "2\\.\n", + "\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "NameError: name 'e' is not defined\n" - ] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "def some_func(x):\n", + " if x == 3:\n", + " return [\"wtf\"]\n", + " else:\n", + " for i in range(x):\n", + " yield i\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* Source: https://docs.python.org/3/reference/compound_stmts.html#except\n", "\n", - " When an exception has been assigned using `as` target, it is cleared at the end of the `except` clause. This is as if\n", + "**Output:**\n", "\n" ] }, @@ -5804,7 +5800,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "[]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -5812,8 +5810,7 @@ } ], "source": [ - " except E as N:\n", - " foo\n" + "list(some_func(3))\n" ] }, { @@ -5821,7 +5818,23 @@ "metadata": {}, "source": [ "\n", - " was translated into\n", + "The same result, this didn't work either.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that,\n", + "\n", + "> \"... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator.\"\n", + "\n", + "+ In the case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically caught inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list.\n", + "\n", + "+ To get `[\"wtf\"]` from the generator `some_func` we need to catch the `StopIteration` exception,\n", "\n" ] }, @@ -5842,21 +5855,16 @@ } ], "source": [ - " except E as N:\n", - " try:\n", - " foo\n", - " finally:\n", - " del N\n" - ] - }, - { + " try:\n", + " next(some_func(3))\n", + " except StopIteration as e:\n", + " some_string = e.value\n" + ] + }, + { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - " This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because, with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.\n", - "\n", - "* The clauses are not scoped in Python. Everything in the example is present in the same scope, and the variable `e` got removed due to the execution of the `except` clause. The same is not the case with functions that have their separate inner-scopes. The example below illustrates this:\n", "\n" ] }, @@ -5869,7 +5877,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " [\"wtf\"]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -5877,20 +5887,23 @@ } ], "source": [ - " def f(x):\n", - " del(x)\n", - " print(x)\n", - "\n", - " x = 5\n", - " y = [5, 4, 3]\n" + " some_string\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - " **Output:**\n" + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Nan-reflexivity *\n", + "1\\.\n", + "\n" ] }, { @@ -5902,9 +5915,7 @@ "outputs": [ { "data": { - "text/plain": [ - " 5\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -5912,11 +5923,19 @@ } ], "source": [ - " >>>f(x)\n", - " UnboundLocalError: local variable 'x' referenced before assignment\n", - " >>>f(y)\n", - " UnboundLocalError: local variable 'x' referenced before assignment\n", - " x\n" + "a = float('inf')\n", + "b = float('nan')\n", + "c = float('-iNf') # These strings are case-insensitive\n", + "d = float('nan')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" ] }, { @@ -5929,7 +5948,7 @@ { "data": { "text/plain": [ - " [5, 4, 3]\n" + "inf\n" ] }, "output_type": "execute_result", @@ -5938,17 +5957,7 @@ } ], "source": [ - " y\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "* In Python 2.x, the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing.\n", - "\n", - " **Output (Python 2.x):**\n" + "a\n" ] }, { @@ -5961,7 +5970,7 @@ { "data": { "text/plain": [ - " Exception()\n" + "nan\n" ] }, "output_type": "execute_result", @@ -5970,7 +5979,7 @@ } ], "source": [ - " e\n" + "b\n" ] }, { @@ -5983,7 +5992,7 @@ { "data": { "text/plain": [ - " # Nothing is printed!\n" + "-inf\n" ] }, "output_type": "execute_result", @@ -5992,21 +6001,7 @@ } ], "source": [ - " print e\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 The mysterious key type conversion\n" + "c\n" ] }, { @@ -6018,7 +6013,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "ValueError: could not convert string to float: some_other_string\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6026,18 +6023,7 @@ } ], "source": [ - "class SomeClass(str):\n", - " pass\n", - "\n", - "some_dict = {'s': 42}\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "float('some_other_string')\n" ] }, { @@ -6050,7 +6036,7 @@ { "data": { "text/plain": [ - "str\n" + "True\n" ] }, "output_type": "execute_result", @@ -6059,7 +6045,7 @@ } ], "source": [ - "type(list(some_dict.keys())[0])\n" + "a == -c # inf==inf\n" ] }, { @@ -6072,7 +6058,7 @@ { "data": { "text/plain": [ - "{'s': 40}\n" + "True\n" ] }, "output_type": "execute_result", @@ -6081,9 +6067,7 @@ } ], "source": [ - "s = SomeClass('s')\n", - "some_dict[s] = 40\n", - "some_dict # expected: Two different keys-value pairs\n" + "None == None # None == None\n" ] }, { @@ -6096,7 +6080,7 @@ { "data": { "text/plain": [ - "str\n" + "False\n" ] }, "output_type": "execute_result", @@ -6105,26 +6089,7 @@ } ], "source": [ - "type(list(some_dict.keys())[0])\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* Both the object `s` and the string `\"s\"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class.\n", - "* `SomeClass(\"s\") == \"s\"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class.\n", - "* Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary.\n", - "* For the desired behavior, we can redefine the `__eq__` method in `SomeClass`\n" + "b == d # but nan!=nan\n" ] }, { @@ -6136,7 +6101,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "0.0\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6144,27 +6111,7 @@ } ], "source": [ - " class SomeClass(str):\n", - " def __eq__(self, other):\n", - " return (\n", - " type(self) is SomeClass\n", - " and type(other) is SomeClass\n", - " and super().__eq__(other)\n", - " )\n", - "\n", - " # When we define a custom __eq__, Python stops automatically inheriting the\n", - " # __hash__ method, so we need to define it as well\n", - " __hash__ = str.__hash__\n", - "\n", - " some_dict = {'s':42}\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - " **Output:**\n" + "50 / a\n" ] }, { @@ -6177,7 +6124,7 @@ { "data": { "text/plain": [ - " {'s': 40, 's': 42}\n" + "nan\n" ] }, "output_type": "execute_result", @@ -6186,9 +6133,7 @@ } ], "source": [ - " s = SomeClass('s')\n", - " some_dict[s] = 40\n", - " some_dict\n" + "a / a\n" ] }, { @@ -6201,7 +6146,7 @@ { "data": { "text/plain": [ - " (__main__.SomeClass, str)\n" + "nan\n" ] }, "output_type": "execute_result", @@ -6210,24 +6155,18 @@ } ], "source": [ - " keys = list(some_dict.keys())\n", - " type(keys[0]), type(keys[1])\n" + "23 + b\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "2\\.\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Let's see if you can guess this?\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -6237,7 +6176,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6245,15 +6186,31 @@ } ], "source": [ - "a, b = a[b] = {}, 5\n" + "x = float('nan')\n", + "y = x / x\n", + "y is y # identity holds\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "**Output:**\n" + "y == y # equality fails of y\n" ] }, { @@ -6266,7 +6223,7 @@ { "data": { "text/plain": [ - "{5: ({...}, 5)}\n" + "True\n" ] }, "output_type": "execute_result", @@ -6275,13 +6232,15 @@ } ], "source": [ - "a\n" + "[y] == [y] # but the equality succeeds for the list containing y\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "\n", "\n" ] }, @@ -6291,23 +6250,10 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form\n", - " ```\n", - " (target_list \"=\")+ (expression_list | yield_expression)\n", - " ```\n", - " and\n", - " \n", - "> An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.\n", - "\n", - "* The `+` in `(target_list \"=\")+` means there can be **one or more** target lists. In this case, target lists are `a, b` and `a[b]` (note the expression list is exactly one, which in our case is `{}, 5`).\n", - "\n", - "* After the expression list is evaluated, its value is unpacked to the target lists from **left to right**. So, in our case, first the `{}, 5` tuple is unpacked to `a, b` and we now have `a = {}` and `b = 5`.\n", - "\n", - "* `a` is now assigned to `{}`, which is a mutable object.\n", - "\n", - "* The second target list is `a[b]` (you may expect this to throw an error because both `a` and `b` have not been defined in the statements before. But remember, we just assigned `a` to `{}` and `b` to `5`).\n", + "- `'inf'` and `'nan'` are special strings (case-insensitive), which, when explicitly typecast-ed to `float` type, are used to represent mathematical \"infinity\" and \"not a number\" respectively.\n", "\n", - "* Now, we are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference (the `{...}` in the output refers to the same object that `a` is already referencing). Another simpler example of circular reference could be\n" + "- Since according to IEEE standards ` NaN != NaN`, obeying this rule breaks the reflexivity assumption of a collection element in Python i.e. if `x` is a part of a collection like `list`, the implementations like comparison are based on the assumption that `x == x`. Because of this assumption, the identity is compared first (since it's faster) while comparing two elements, and the values are compared only when the identities mismatch. The following snippet will make things clearer,\n", + "\n" ] }, { @@ -6320,7 +6266,7 @@ { "data": { "text/plain": [ - " [[...]]\n" + " (False, True)\n" ] }, "output_type": "execute_result", @@ -6329,8 +6275,8 @@ } ], "source": [ - " some_list = some_list[0] = [0]\n", - " some_list\n" + " x = float('nan')\n", + " x == x, [x] == [x]\n" ] }, { @@ -6343,7 +6289,7 @@ { "data": { "text/plain": [ - " [[...]]\n" + " (False, True)\n" ] }, "output_type": "execute_result", @@ -6352,7 +6298,8 @@ } ], "source": [ - " some_list[0]\n" + " y = float('nan')\n", + " y == y, [y] == [y]\n" ] }, { @@ -6365,7 +6312,7 @@ { "data": { "text/plain": [ - " True\n" + " (False, False)\n" ] }, "output_type": "execute_result", @@ -6374,7 +6321,27 @@ } ], "source": [ - " some_list is some_list[0]\n" + " x == y, [x] == [y]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + " Since the identities of `x` and `y` are different, the values are considered, which are also different; hence the comparison returns `False` this time.\n", + "\n", + "- Interesting read: [Reflexivity, and other pillars of civilization](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/)\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Mutating the immutable!\n", + "This might seem trivial if you know how references work in Python.\n", + "\n" ] }, { @@ -6386,9 +6353,7 @@ "outputs": [ { "data": { - "text/plain": [ - " True\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -6396,16 +6361,16 @@ } ], "source": [ - " some_list[0][0][0][0][0][0] == some_list\n" + "some_tuple = (\"A\", \"tuple\", \"with\", \"values\")\n", + "another_tuple = ([1, 2], [3, 4], [5, 6])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " Similar is the case in our example (`a[b][0]` is the same object as `a`)\n", "\n", - "* So to sum it up, you can break the example down to\n" + "**Output:**\n" ] }, { @@ -6417,7 +6382,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "TypeError: 'tuple' object does not support item assignment\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6425,15 +6392,7 @@ } ], "source": [ - " a, b = {}, 5\n", - " a[b] = a, b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n" + "some_tuple[2] = \"change this\"\n" ] }, { @@ -6446,7 +6405,7 @@ { "data": { "text/plain": [ - " True\n" + "([1, 2], [3, 4], [5, 6, 1000])\n" ] }, "output_type": "execute_result", @@ -6455,21 +6414,30 @@ } ], "source": [ - " a[b][0] is a\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "another_tuple[2].append(1000) #This throws no error\n", + "another_tuple\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "TypeError: 'tuple' object does not support item assignment\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "### \u25b6 Modifying a dictionary while iterating over it\n" + "another_tuple[2] += [99, 999]\n" ] }, { @@ -6481,7 +6449,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "([1, 2], [3, 4], [5, 6, 1000, 99, 999])\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -6489,12 +6459,7 @@ } ], "source": [ - "x = {0: None}\n", - "\n", - "for i in x:\n", - " del x[i]\n", - " x[i+1] = None\n", - " print(i)\n" + "another_tuple\n" ] }, { @@ -6502,20 +6467,7 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 2.7- Python 3.5):**\n", - "\n", - "```\n", - "0\n", - "1\n", - "2\n", - "3\n", - "4\n", - "5\n", - "6\n", - "7\n", - "```\n", - "\n", - "Yes, it runs for exactly **eight** times and stops.\n", + "But I thought tuples were immutable...\n", "\n" ] }, @@ -6525,11 +6477,13 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "* Iteration over a dictionary that you edit at the same time is not supported.\n", - "* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.\n", - "* How deleted keys are handled and when the resize occurs might be different for different Python implementations.\n", - "* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread.\n", - "* Python 3.8 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this.\n", + "* Quoting from https://docs.python.org/3/reference/datamodel.html\n", + "\n", + " > Immutable sequences\n", + " An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.)\n", + "\n", + "* `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place.\n", + "* There's also an explanation in [official Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works).\n", "\n" ] }, @@ -6537,7 +6491,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 The out of scope variable\n" + "### \u25b6 The disappearing variable from outer scope\n" ] }, { @@ -6557,13 +6511,11 @@ } ], "source": [ - "a = 1\n", - "def some_func():\n", - " return a\n", - "\n", - "def another_func():\n", - " a += 1\n", - " return a\n" + "e = 7\n", + "try:\n", + " raise Exception()\n", + "except Exception as e:\n", + " pass\n" ] }, { @@ -6571,51 +6523,53 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + "**Output (Python 2.x):**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "1\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "# prints nothing\n" + ] } ], "source": [ - "some_func()\n" + "print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "UnboundLocalError: local variable 'a' referenced before assignment\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "NameError: name 'e' is not defined\n" + ] } ], "source": [ - "another_func()\n" + "print(e)\n" ] }, { @@ -6630,9 +6584,11 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.\n", - "* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.\n", - "* To modify the outer scope variable `a` in `another_func`, use `global` keyword.\n" + "\n", + "* Source: https://docs.python.org/3/reference/compound_stmts.html#except\n", + "\n", + " When an exception has been assigned using `as` target, it is cleared at the end of the `except` clause. This is as if\n", + "\n" ] }, { @@ -6652,10 +6608,8 @@ } ], "source": [ - " def another_func()\n", - " global a\n", - " a += 1\n", - " return a\n" + " except E as N:\n", + " foo\n" ] }, { @@ -6663,7 +6617,8 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n" + " was translated into\n", + "\n" ] }, { @@ -6675,9 +6630,7 @@ "outputs": [ { "data": { - "text/plain": [ - " 2\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -6685,23 +6638,24 @@ } ], "source": [ - " another_func()\n" + " except E as N:\n", + " try:\n", + " foo\n", + " finally:\n", + " del N\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + " This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because, with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.\n", + "\n", + "* The clauses are not scoped in Python. Everything in the example is present in the same scope, and the variable `e` got removed due to the execution of the `except` clause. The same is not the case with functions that have their separate inner-scopes. The example below illustrates this:\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Deleting a list item while iterating\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -6719,22 +6673,12 @@ } ], "source": [ - "list_1 = [1, 2, 3, 4]\n", - "list_2 = [1, 2, 3, 4]\n", - "list_3 = [1, 2, 3, 4]\n", - "list_4 = [1, 2, 3, 4]\n", - "\n", - "for idx, item in enumerate(list_1):\n", - " del item\n", - "\n", - "for idx, item in enumerate(list_2):\n", - " list_2.remove(item)\n", - "\n", - "for idx, item in enumerate(list_3[:]):\n", - " list_3.remove(item)\n", + " def f(x):\n", + " del(x)\n", + " print(x)\n", "\n", - "for idx, item in enumerate(list_4):\n", - " list_4.pop(idx)\n" + " x = 5\n", + " y = [5, 4, 3]\n" ] }, { @@ -6742,7 +6686,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + " **Output:**\n" ] }, { @@ -6755,7 +6699,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4]\n" + " 5\n" ] }, "output_type": "execute_result", @@ -6764,7 +6708,11 @@ } ], "source": [ - "list_1\n" + " >>>f(x)\n", + " UnboundLocalError: local variable 'x' referenced before assignment\n", + " >>>f(y)\n", + " UnboundLocalError: local variable 'x' referenced before assignment\n", + " x\n" ] }, { @@ -6777,7 +6725,7 @@ { "data": { "text/plain": [ - "[2, 4]\n" + " [5, 4, 3]\n" ] }, "output_type": "execute_result", @@ -6786,7 +6734,17 @@ } ], "source": [ - "list_2\n" + " y\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* In Python 2.x, the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing.\n", + "\n", + " **Output (Python 2.x):**\n" ] }, { @@ -6799,7 +6757,7 @@ { "data": { "text/plain": [ - "[]\n" + " Exception()\n" ] }, "output_type": "execute_result", @@ -6808,7 +6766,7 @@ } ], "source": [ - "list_3\n" + " e\n" ] }, { @@ -6821,7 +6779,7 @@ { "data": { "text/plain": [ - "[2, 4]\n" + " # Nothing is printed!\n" ] }, "output_type": "execute_result", @@ -6830,15 +6788,13 @@ } ], "source": [ - "list_4\n" + " print e\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "Can you guess why the output is `[2, 4]`?\n", "\n" ] }, @@ -6846,33 +6802,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " 139798789457608\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - " some_list = [1, 2, 3, 4]\n", - " id(some_list)\n" + "### \u25b6 The mysterious key type conversion\n" ] }, { @@ -6884,9 +6814,7 @@ "outputs": [ { "data": { - "text/plain": [ - " 139798779601192\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -6894,55 +6822,18 @@ } ], "source": [ - " id(some_list[:]) # Notice that python creates new object for sliced list.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Difference between `del`, `remove`, and `pop`:**\n", - "* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).\n", - "* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.\n", - "* `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified.\n", - "\n", - "**Why the output is `[2, 4]`?**\n", - "- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.\n", + "class SomeClass(str):\n", + " pass\n", "\n", - "* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example\n", - "* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.\n", - "\n" + "some_dict = {'s': 42}\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Lossy zip of iterators *\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "[0, 1, 2, 3, 4, 5, 6]\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "numbers = list(range(7))\n", - "numbers\n" + "\n", + "**Output:**\n" ] }, { @@ -6955,7 +6846,7 @@ { "data": { "text/plain": [ - "([0, 1, 2], [3, 4, 5, 6])\n" + "str\n" ] }, "output_type": "execute_result", @@ -6964,8 +6855,7 @@ } ], "source": [ - "first_three, remaining = numbers[:3], numbers[3:]\n", - "first_three, remaining\n" + "type(list(some_dict.keys())[0])\n" ] }, { @@ -6978,8 +6868,7 @@ { "data": { "text/plain": [ - "[(0, 0), (1, 1), (2, 2)]\n", - "# so far so good, let's zip the remaining\n" + "{'s': 40}\n" ] }, "output_type": "execute_result", @@ -6988,8 +6877,9 @@ } ], "source": [ - "numbers_iter = iter(numbers)\n", - "list(zip(numbers_iter, first_three)) \n" + "s = SomeClass('s')\n", + "some_dict[s] = 40\n", + "some_dict # expected: Two different keys-value pairs\n" ] }, { @@ -7002,7 +6892,7 @@ { "data": { "text/plain": [ - "[(4, 3), (5, 4), (6, 5)]\n" + "str\n" ] }, "output_type": "execute_result", @@ -7011,14 +6901,13 @@ } ], "source": [ - "list(zip(numbers_iter, remaining))\n" + "type(list(some_dict.keys())[0])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Where did element `3` go from the `numbers` list?\n", "\n" ] }, @@ -7028,7 +6917,10 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,\n" + "* Both the object `s` and the string `\"s\"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class.\n", + "* `SomeClass(\"s\") == \"s\"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class.\n", + "* Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary.\n", + "* For the desired behavior, we can redefine the `__eq__` method in `SomeClass`\n" ] }, { @@ -7048,25 +6940,27 @@ } ], "source": [ - " def zip(*iterables):\n", - " sentinel = object()\n", - " iterators = [iter(it) for it in iterables]\n", - " while iterators:\n", - " result = []\n", - " for it in iterators:\n", - " elem = next(it, sentinel)\n", - " if elem is sentinel: return\n", - " result.append(elem)\n", - " yield tuple(result)\n" + " class SomeClass(str):\n", + " def __eq__(self, other):\n", + " return (\n", + " type(self) is SomeClass\n", + " and type(other) is SomeClass\n", + " and super().__eq__(other)\n", + " )\n", + "\n", + " # When we define a custom __eq__, Python stops automatically inheriting the\n", + " # __hash__ method, so we need to define it as well\n", + " __hash__ = str.__hash__\n", + "\n", + " some_dict = {'s':42}\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "- So the function takes in arbitrary number of itreable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. \n", - "- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.\n", - "- The correct way to do the above using `zip` would be,\n" + "\n", + " **Output:**\n" ] }, { @@ -7079,7 +6973,7 @@ { "data": { "text/plain": [ - " [(0, 0), (1, 1), (2, 2)]\n" + " {'s': 40, 's': 42}\n" ] }, "output_type": "execute_result", @@ -7088,9 +6982,9 @@ } ], "source": [ - " numbers = list(range(7))\n", - " numbers_iter = iter(numbers)\n", - " list(zip(first_three, numbers_iter))\n" + " s = SomeClass('s')\n", + " some_dict[s] = 40\n", + " some_dict\n" ] }, { @@ -7103,7 +6997,7 @@ { "data": { "text/plain": [ - " [(3, 3), (4, 4), (5, 5), (6, 6)]\n" + " (__main__.SomeClass, str)\n" ] }, "output_type": "execute_result", @@ -7112,14 +7006,14 @@ } ], "source": [ - " list(zip(remaining, numbers_iter))\n" + " keys = list(some_dict.keys())\n", + " type(keys[0]), type(keys[1])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " The first argument of zip should be the one with fewest elements.\n", "\n" ] }, @@ -7127,28 +7021,27 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Loop variables leaking out!\n", - "1\\.\n" + "### \u25b6 Let's see if you can guess this?\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "for x in range(7):\n", - " if x == 6:\n", - " print(x, ': for x inside loop')\n", - "print(x, ': x in global')\n" + "a, b = a[b] = {}, 5\n" ] }, { @@ -7168,7 +7061,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "{5: ({...}, 5)}\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7176,48 +7071,39 @@ } ], "source": [ - "6 : for x inside loop\n", - "6 : x in global\n" + "a\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "But `x` was never defined outside the scope of for loop...\n", - "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "metadata": { - "collapsed": true - }, - "execution_count": null, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [] - } - ], - "source": [ - "# This time let's initialize x first\n", - "x = -1\n", - "for x in range(7):\n", - " if x == 6:\n", - " print(x, ': for x inside loop')\n", - "print(x, ': x in global')\n" + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation:\n", "\n", - "**Output:**\n" + "* According to [Python language reference](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), assignment statements have the form\n", + " ```\n", + " (target_list \"=\")+ (expression_list | yield_expression)\n", + " ```\n", + " and\n", + " \n", + "> An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.\n", + "\n", + "* The `+` in `(target_list \"=\")+` means there can be **one or more** target lists. In this case, target lists are `a, b` and `a[b]` (note the expression list is exactly one, which in our case is `{}, 5`).\n", + "\n", + "* After the expression list is evaluated, its value is unpacked to the target lists from **left to right**. So, in our case, first the `{}, 5` tuple is unpacked to `a, b` and we now have `a = {}` and `b = 5`.\n", + "\n", + "* `a` is now assigned to `{}`, which is a mutable object.\n", + "\n", + "* The second target list is `a[b]` (you may expect this to throw an error because both `a` and `b` have not been defined in the statements before. But remember, we just assigned `a` to `{}` and `b` to `5`).\n", + "\n", + "* Now, we are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference (the `{...}` in the output refers to the same object that `a` is already referencing). Another simpler example of circular reference could be\n" ] }, { @@ -7229,7 +7115,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " [[...]]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7237,132 +7125,83 @@ } ], "source": [ - "6 : for x inside loop\n", - "6 : x in global\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "3\\.\n", - "\n", - "**Output (Python 2.x):**\n" + " some_list = some_list[0] = [0]\n", + " some_list\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "[0, 1, 2, 3, 4]\n" - ] + "data": { + "text/plain": [ + " [[...]]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "x = 1\n", - "print([x for x in range(5)])\n" + " some_list[0]\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "4\n" - ] + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(x)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 3.x):**\n" + " some_list is some_list[0]\n" ] }, { "cell_type": "code", - "metadata": { - "collapsed": true - }, "execution_count": null, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[0, 1, 2, 3, 4]\n" - ] - } - ], - "source": [ - "x = 1\n", - "print([x for x in range(5)])\n" - ] - }, - { - "cell_type": "code", "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n" - ] + "data": { + "text/plain": [ + " True\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(x)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + " some_list[0][0][0][0][0][0] == some_list\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.\n", - "\n", - "- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What\u2019s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog:\n", + " Similar is the case in our example (`a[b][0]` is the same object as `a`)\n", "\n", - " > \"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.\"\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Beware of default mutable arguments!\n" + "* So to sum it up, you can break the example down to\n" ] }, { @@ -7382,17 +7221,15 @@ } ], "source": [ - "def some_func(default_arg=[]):\n", - " default_arg.append(\"some_string\")\n", - " return default_arg\n" + " a, b = {}, 5\n", + " a[b] = a, b\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n" + " And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`\n" ] }, { @@ -7405,7 +7242,7 @@ { "data": { "text/plain": [ - "['some_string']\n" + " True\n" ] }, "output_type": "execute_result", @@ -7414,51 +7251,21 @@ } ], "source": [ - "some_func()\n" + " a[b][0] is a\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['some_string', 'some_string']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "some_func()\n" + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['some_string']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "some_func([])\n" + "### \u25b6 Modifying a dictionary while iterating over it\n" ] }, { @@ -7470,9 +7277,7 @@ "outputs": [ { "data": { - "text/plain": [ - "['some_string', 'some_string', 'some_string']\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -7480,13 +7285,33 @@ } ], "source": [ - "some_func()\n" + "x = {0: None}\n", + "\n", + "for i in x:\n", + " del x[i]\n", + " x[i+1] = None\n", + " print(i)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "**Output (Python 2.7- Python 3.5):**\n", + "\n", + "```\n", + "0\n", + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "```\n", + "\n", + "Yes, it runs for exactly **eight** times and stops.\n", "\n" ] }, @@ -7496,10 +7321,22 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.\n", + "* Iteration over a dictionary that you edit at the same time is not supported.\n", + "* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.\n", + "* How deleted keys are handled and when the resize occurs might be different for different Python implementations.\n", + "* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread.\n", + "* Python 3.7.6 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 The out of scope variable\n", + "1\\.\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -7517,9 +7354,13 @@ } ], "source": [ - " def some_func(default_arg=[]):\n", - " default_arg.append(\"some_string\")\n", - " return default_arg\n" + "a = 1\n", + "def some_func():\n", + " return a\n", + "\n", + "def another_func():\n", + " a += 1\n", + " return a\n" ] }, { @@ -7527,7 +7368,7 @@ "metadata": {}, "source": [ "\n", - " **Output:**\n" + "2\\.\n" ] }, { @@ -7539,9 +7380,7 @@ "outputs": [ { "data": { - "text/plain": [ - " ([],)\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -7549,7 +7388,26 @@ } ], "source": [ - " some_func.__defaults__ #This will show the default argument values for the function\n" + "def some_closure_func():\n", + " a = 1\n", + " def some_inner_func():\n", + " return a\n", + " return some_inner_func()\n", + "\n", + "def another_closure_func():\n", + " a = 1\n", + " def another_inner_func():\n", + " a += 1\n", + " return a\n", + " return another_inner_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -7562,7 +7420,7 @@ { "data": { "text/plain": [ - " (['some_string'],)\n" + "1\n" ] }, "output_type": "execute_result", @@ -7571,8 +7429,7 @@ } ], "source": [ - " some_func()\n", - " some_func.__defaults__\n" + "some_func()\n" ] }, { @@ -7585,7 +7442,8 @@ { "data": { "text/plain": [ - " (['some_string', 'some_string'],)\n" + "UnboundLocalError: local variable 'a' referenced before assignment\n", + "\n" ] }, "output_type": "execute_result", @@ -7594,8 +7452,7 @@ } ], "source": [ - " some_func()\n", - " some_func.__defaults__\n" + "another_func()\n" ] }, { @@ -7608,7 +7465,7 @@ { "data": { "text/plain": [ - " (['some_string', 'some_string'],)\n" + "1\n" ] }, "output_type": "execute_result", @@ -7617,17 +7474,7 @@ } ], "source": [ - " some_func([])\n", - " some_func.__defaults__\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:\n", - "\n" + "some_closure_func()\n" ] }, { @@ -7639,7 +7486,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "UnboundLocalError: local variable 'a' referenced before assignment\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7647,11 +7496,7 @@ } ], "source": [ - " def some_func(default_arg=None):\n", - " if not default_arg:\n", - " default_arg = []\n", - " default_arg.append(\"some_string\")\n", - " return default_arg\n" + "another_closure_func()\n" ] }, { @@ -7665,7 +7510,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Catching the Exceptions\n" + "#### \ud83d\udca1 Explanation:\n", + "* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.\n", + "* To modify the outer scope variable `a` in `another_func`, we have to use the `global` keyword.\n" ] }, { @@ -7685,18 +7532,10 @@ } ], "source": [ - "some_list = [1, 2, 3]\n", - "try:\n", - " # This should raise an ``IndexError``\n", - " print(some_list[4])\n", - "except IndexError, ValueError:\n", - " print(\"Caught!\")\n", - "\n", - "try:\n", - " # This should raise a ``ValueError``\n", - " some_list.remove(4)\n", - "except IndexError, ValueError:\n", - " print(\"Caught again!\")\n" + " def another_func()\n", + " global a\n", + " a += 1\n", + " return a\n" ] }, { @@ -7704,7 +7543,7 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 2.x):**\n" + " **Output:**\n" ] }, { @@ -7716,7 +7555,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " 2\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7724,17 +7565,15 @@ } ], "source": [ - "Caught!\n", - "\n", - "ValueError: list.remove(x): x not in list\n" + " another_func()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output (Python 3.x):**\n" + "* In `another_closure_func`, `a` becomes local to the scope of `another_inner_func`, but it has not been initialized previously in the same scope, which is why it throws an error. \n", + "* To modify the outer scope variable `a` in `another_inner_func`, use the `nonlocal` keyword. The nonlocal statement is used to refer to variables defined in the nearest outer (excluding the global) scope.\n" ] }, { @@ -7754,26 +7593,21 @@ } ], "source": [ - " File \"\", line 3\n", - " except IndexError, ValueError:\n", - " ^\n", - "SyntaxError: invalid syntax\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + " def another_func():\n", + " a = 1\n", + " def another_inner_func():\n", + " nonlocal a\n", + " a += 1\n", + " return a\n", + " return another_inner_func()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", "\n", - "* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example,\n" + " **Output:**\n" ] }, { @@ -7785,7 +7619,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " 2\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7793,25 +7629,23 @@ } ], "source": [ - " some_list = [1, 2, 3]\n", - " try:\n", - " # This should raise a ``ValueError``\n", - " some_list.remove(4)\n", - " except (IndexError, ValueError), e:\n", - " print(\"Caught again!\")\n", - " print(e)\n" + " another_func()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " **Output (Python 2.x):**\n", - " ```\n", - " Caught again!\n", - " list.remove(x): x not in list\n", - " ```\n", - " **Output (Python 3.x):**\n" + "* The keywords `global` and `nonlocal` tell the python interpreter to not delcare new variables and look them up in the corresponding outer scopes.\n", + "* Read [this](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Deleting a list item while iterating\n" ] }, { @@ -7831,10 +7665,22 @@ } ], "source": [ - " File \"\", line 4\n", - " except (IndexError, ValueError), e:\n", - " ^\n", - " IndentationError: unindent does not match any outer indentation level\n" + "list_1 = [1, 2, 3, 4]\n", + "list_2 = [1, 2, 3, 4]\n", + "list_3 = [1, 2, 3, 4]\n", + "list_4 = [1, 2, 3, 4]\n", + "\n", + "for idx, item in enumerate(list_1):\n", + " del item\n", + "\n", + "for idx, item in enumerate(list_2):\n", + " list_2.remove(item)\n", + "\n", + "for idx, item in enumerate(list_3[:]):\n", + " list_3.remove(item)\n", + "\n", + "for idx, item in enumerate(list_4):\n", + " list_4.pop(idx)\n" ] }, { @@ -7842,7 +7688,7 @@ "metadata": {}, "source": [ "\n", - "* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example,\n" + "**Output:**\n" ] }, { @@ -7854,7 +7700,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "[1, 2, 3, 4]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7862,33 +7710,7 @@ } ], "source": [ - " some_list = [1, 2, 3]\n", - " try:\n", - " some_list.remove(4)\n", - "\n", - " except (IndexError, ValueError) as e:\n", - " print(\"Caught again!\")\n", - " print(e)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " **Output:**\n", - " ```\n", - " Caught again!\n", - " list.remove(x): x not in list\n", - " ```\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Same operands, different story!\n", - "1\\.\n" + "list_1\n" ] }, { @@ -7900,7 +7722,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "[2, 4]\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -7908,17 +7732,7 @@ } ], "source": [ - "a = [1, 2, 3, 4]\n", - "b = a\n", - "a = a + [5, 6, 7, 8]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "list_2\n" ] }, { @@ -7931,7 +7745,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4, 5, 6, 7, 8]\n" + "[]\n" ] }, "output_type": "execute_result", @@ -7940,7 +7754,7 @@ } ], "source": [ - "a\n" + "list_3\n" ] }, { @@ -7953,7 +7767,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4]\n" + "[2, 4]\n" ] }, "output_type": "execute_result", @@ -7962,7 +7776,7 @@ } ], "source": [ - "b\n" + "list_4\n" ] }, { @@ -7970,37 +7784,18 @@ "metadata": {}, "source": [ "\n", - "2\\.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "a = [1, 2, 3, 4]\n", - "b = a\n", - "a += [5, 6, 7, 8]\n" + "Can you guess why the output is `[2, 4]`?\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation:\n", "\n", - "**Output:**\n" + "* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.\n", + "\n" ] }, { @@ -8013,7 +7808,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4, 5, 6, 7, 8]\n" + " 139798789457608\n" ] }, "output_type": "execute_result", @@ -8022,7 +7817,8 @@ } ], "source": [ - "a\n" + " some_list = [1, 2, 3, 4]\n", + " id(some_list)\n" ] }, { @@ -8035,7 +7831,7 @@ { "data": { "text/plain": [ - "[1, 2, 3, 4, 5, 6, 7, 8]\n" + " 139798779601192\n" ] }, "output_type": "execute_result", @@ -8044,27 +7840,24 @@ } ], "source": [ - "b\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + " id(some_list[:]) # Notice that python creates new object for sliced list.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", "\n", - "* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this.\n", + "**Difference between `del`, `remove`, and `pop`:**\n", + "* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).\n", + "* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.\n", + "* `pop` removes the element at a specific index and returns it, raises `IndexError` if an invalid index is specified.\n", "\n", - "* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged.\n", + "**Why the output is `[2, 4]`?**\n", + "- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.\n", "\n", - "* The expression `a += [5,6,7,8]` is actually mapped to an \"extend\" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place.\n", + "* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example\n", + "* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.\n", "\n" ] }, @@ -8072,7 +7865,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Be careful with chained operations\n" + "### \u25b6 Lossy zip of iterators *\n" ] }, { @@ -8085,7 +7878,7 @@ { "data": { "text/plain": [ - "False\n" + "[0, 1, 2, 3, 4, 5, 6]\n" ] }, "output_type": "execute_result", @@ -8094,7 +7887,8 @@ } ], "source": [ - "(False == False) in [False] # makes sense\n" + "numbers = list(range(7))\n", + "numbers\n" ] }, { @@ -8107,7 +7901,7 @@ { "data": { "text/plain": [ - "False\n" + "([0, 1, 2], [3, 4, 5, 6])\n" ] }, "output_type": "execute_result", @@ -8116,7 +7910,8 @@ } ], "source": [ - "False == (False in [False]) # makes sense\n" + "first_three, remaining = numbers[:3], numbers[3:]\n", + "first_three, remaining\n" ] }, { @@ -8129,8 +7924,8 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "[(0, 0), (1, 1), (2, 2)]\n", + "# so far so good, let's zip the remaining\n" ] }, "output_type": "execute_result", @@ -8139,7 +7934,8 @@ } ], "source": [ - "False == False in [False] # now what?\n" + "numbers_iter = iter(numbers)\n", + "list(zip(numbers_iter, first_three)) \n" ] }, { @@ -8152,7 +7948,7 @@ { "data": { "text/plain": [ - "False\n" + "[(4, 3), (5, 4), (6, 5)]\n" ] }, "output_type": "execute_result", @@ -8161,7 +7957,24 @@ } ], "source": [ - "True is False == False\n" + "list(zip(numbers_iter, remaining))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Where did element `3` go from the `numbers` list?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function,\n" ] }, { @@ -8173,10 +7986,7 @@ "outputs": [ { "data": { - "text/plain": [ - "True\n", - "\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8184,7 +7994,25 @@ } ], "source": [ - "False is False is False\n" + " def zip(*iterables):\n", + " sentinel = object()\n", + " iterators = [iter(it) for it in iterables]\n", + " while iterators:\n", + " result = []\n", + " for it in iterators:\n", + " elem = next(it, sentinel)\n", + " if elem is sentinel: return\n", + " result.append(elem)\n", + " yield tuple(result)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "- So the function takes in arbitrary number of iterable objects, adds each of their items to the `result` list by calling the `next` function on them, and stops whenever any of the iterable is exhausted. \n", + "- The caveat here is when any iterable is exhausted, the existing elements in the `result` list are discarded. That's what happened with `3` in the `numbers_iter`.\n", + "- The correct way to do the above using `zip` would be,\n" ] }, { @@ -8197,7 +8025,7 @@ { "data": { "text/plain": [ - "True\n" + " [(0, 0), (1, 1), (2, 2)]\n" ] }, "output_type": "execute_result", @@ -8206,7 +8034,9 @@ } ], "source": [ - "1 > 0 < 1\n" + " numbers = list(range(7))\n", + " numbers_iter = iter(numbers)\n", + " list(zip(first_three, numbers_iter))\n" ] }, { @@ -8219,7 +8049,7 @@ { "data": { "text/plain": [ - "False\n" + " [(3, 3), (4, 4), (5, 5), (6, 6)]\n" ] }, "output_type": "execute_result", @@ -8228,35 +8058,14 @@ } ], "source": [ - "(1 > 0) < 1\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "False\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "1 > (0 < 1)\n" + " list(zip(remaining, numbers_iter))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + " The first argument of zip should be the one with fewest elements.\n", "\n" ] }, @@ -8264,40 +8073,36 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "As per https://docs.python.org/2/reference/expressions.html#not-in\n", - "\n", - "> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.\n", - "\n", - "While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`.\n", - "\n", - "* `False is False is False` is equivalent to `(False is False) and (False is False)`\n", - "* `True is False == False` is equivalent to `True is False and False == False` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`.\n", - "* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`.\n", - "* The expression `(1 > 0) < 1` is equivalent to `True < 1` and\n" + "### \u25b6 Loop variables leaking out!\n", + "1\\.\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - " 1\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [] } ], "source": [ - " int(True)\n" + "for x in range(7):\n", + " if x == 6:\n", + " print(x, ': for x inside loop')\n", + "print(x, ': x in global')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -8309,9 +8114,7 @@ "outputs": [ { "data": { - "text/plain": [ - " 2\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8319,46 +8122,40 @@ } ], "source": [ - " True + 1 #not relevant for this example, but just for fun\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " So, `1 < 1` evaluates to `False`\n", - "\n" + "6 : for x inside loop\n", + "6 : x in global\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Name resolution ignoring class scope\n", - "1\\.\n" + "\n", + "But `x` was never defined outside the scope of for loop...\n", + "\n", + "2\\.\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [] } ], "source": [ - "x = 5\n", - "class SomeClass:\n", - " x = 17\n", - " y = (x for i in range(10))\n" + "# This time let's initialize x first\n", + "x = -1\n", + "for x in range(7):\n", + " if x == 6:\n", + " print(x, ': for x inside loop')\n", + "print(x, ': x in global')\n" ] }, { @@ -8378,9 +8175,7 @@ "outputs": [ { "data": { - "text/plain": [ - "5\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8388,7 +8183,8 @@ } ], "source": [ - "list(SomeClass.y)[0]\n" + "6 : for x inside loop\n", + "6 : x in global\n" ] }, { @@ -8396,60 +8192,48 @@ "metadata": {}, "source": [ "\n", - "2\\.\n" + "3\\.\n", + "\n", + "**Output (Python 2.x):**\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 2, 3, 4]\n" + ] } ], "source": [ - "x = 5\n", - "class SomeClass:\n", - " x = 17\n", - " y = [x for i in range(10)]\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.x):**\n" + "x = 1\n", + "print([x for x in range(5)])\n" ] }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "17\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n" + ] } ], "source": [ - "SomeClass.y[0]\n" + "print(x)\n" ] }, { @@ -8462,24 +8246,41 @@ }, { "cell_type": "code", + "metadata": { + "collapsed": true + }, "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 1, 2, 3, 4]\n" + ] + } + ], + "source": [ + "x = 1\n", + "print([x for x in range(5)])\n" + ] + }, + { + "cell_type": "code", "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - "5\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n" + ] } ], "source": [ - "SomeClass.y[0]\n" + "print(x)\n" ] }, { @@ -8493,10 +8294,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", - "- Scopes nested inside class definition ignore names bound at the class level.\n", - "- A generator expression has its own scope.\n", - "- Starting from Python 3.X, list comprehensions also have their own scope.\n", + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.\n", + "\n", + "- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What\u2019s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) changelog:\n", + "\n", + " > \"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular, the loop control variables are no longer leaked into the surrounding scope.\"\n", "\n" ] }, @@ -8504,11 +8308,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Needles in a Haystack *\n", - "I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios,\n", - "\n", - "1\\.\n", - "\n" + "### \u25b6 Beware of default mutable arguments!\n" ] }, { @@ -8528,7 +8328,9 @@ } ], "source": [ - "x, y = (0, 1) if True else None, None\n" + "def some_func(default_arg=[]):\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" ] }, { @@ -8536,8 +8338,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "**Output:**\n" ] }, { @@ -8550,7 +8351,7 @@ { "data": { "text/plain": [ - "((0, 1), None)\n" + "['some_string']\n" ] }, "output_type": "execute_result", @@ -8559,50 +8360,89 @@ } ], "source": [ - "x, y # expected (0, 1)\n" + "some_func()\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string', 'some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "2\\.\n", - "\n" + "some_func()\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [] + "data": { + "text/plain": [ + "['some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "t = ('one', 'two')\n", - "for i in t:\n", - " print(i)\n", - "\n", - "t = ('one')\n", - "for i in t:\n", - " print(i)\n", - "\n", - "t = ()\n", - "print(t)\n" + "some_func([])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['some_string', 'some_string', 'some_string']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_func()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation:\n", "\n", - "**Output:**\n", + "- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.\n", "\n" ] }, @@ -8623,12 +8463,9 @@ } ], "source": [ - "one\n", - "two\n", - "o\n", - "n\n", - "e\n", - "tuple()\n" + " def some_func(default_arg=[]):\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" ] }, { @@ -8636,25 +8473,7 @@ "metadata": {}, "source": [ "\n", - "3\\.\n", - "\n", - "```\n", - "ten_words_list = [\n", - " \"some\",\n", - " \"very\",\n", - " \"big\",\n", - " \"list\",\n", - " \"that\"\n", - " \"consists\",\n", - " \"of\",\n", - " \"exactly\",\n", - " \"ten\",\n", - " \"words\"\n", - "]\n", - "```\n", - "\n", - "**Output**\n", - "\n" + " **Output:**\n" ] }, { @@ -8667,7 +8486,7 @@ { "data": { "text/plain": [ - "9\n" + " ([],)\n" ] }, "output_type": "execute_result", @@ -8676,16 +8495,30 @@ } ], "source": [ - "len(ten_words_list)\n" + " some_func.__defaults__ #This will show the default argument values for the function\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string'],)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "\n", - "4\\. Not asserting strongly enough\n", - "\n" + " some_func()\n", + " some_func.__defaults__\n" ] }, { @@ -8697,7 +8530,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " (['some_string', 'some_string'],)\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -8705,8 +8540,31 @@ } ], "source": [ - "a = \"python\"\n", - "b = \"javascript\"\n" + " some_func()\n", + " some_func.__defaults__\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " (['some_string', 'some_string'],)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_func([])\n", + " some_func.__defaults__\n" ] }, { @@ -8714,7 +8572,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", + "- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:\n", "\n" ] }, @@ -8727,9 +8585,7 @@ "outputs": [ { "data": { - "text/plain": [ - "# No AssertionError is raised\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8737,19 +8593,27 @@ } ], "source": [ - "# An assert statement with an assertion failure message.\n", - "assert(a == b, \"Both languages are different\")\n" + " def some_func(default_arg=None):\n", + " if default_arg is None:\n", + " default_arg = []\n", + " default_arg.append(\"some_string\")\n", + " return default_arg\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "5\\.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Catching the Exceptions\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -8768,14 +8632,17 @@ ], "source": [ "some_list = [1, 2, 3]\n", - "some_dict = {\n", - " \"key_1\": 1,\n", - " \"key_2\": 2,\n", - " \"key_3\": 3\n", - "}\n", + "try:\n", + " # This should raise an ``IndexError``\n", + " print(some_list[4])\n", + "except IndexError, ValueError:\n", + " print(\"Caught!\")\n", "\n", - "some_list = some_list.append(4) \n", - "some_dict = some_dict.update({\"key_4\": 4})\n" + "try:\n", + " # This should raise a ``ValueError``\n", + " some_list.remove(4)\n", + "except IndexError, ValueError:\n", + " print(\"Caught again!\")\n" ] }, { @@ -8783,57 +8650,78 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "**Output (Python 2.x):**\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "None\n" - ] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(some_list)\n" + "Caught!\n", + "\n", + "ValueError: list.remove(x): x not in list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" ] }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [ - "None\n" - ] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "print(some_dict)\n" + " File \"\", line 3\n", + " except IndexError, ValueError:\n", + " ^\n", + "SyntaxError: invalid syntax\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "6\\.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example,\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -8851,28 +8739,25 @@ } ], "source": [ - "def some_recursive_func(a):\n", - " if a[0] == 0:\n", - " return \n", - " a[0] -= 1\n", - " some_recursive_func(a)\n", - " return a\n", - "\n", - "def similar_recursive_func(a):\n", - " if a == 0:\n", - " return a\n", - " a -= 1\n", - " similar_recursive_func(a)\n", - " return a\n" + " some_list = [1, 2, 3]\n", + " try:\n", + " # This should raise a ``ValueError``\n", + " some_list.remove(4)\n", + " except (IndexError, ValueError), e:\n", + " print(\"Caught again!\")\n", + " print(e)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n", - "\n" + " **Output (Python 2.x):**\n", + " ```\n", + " Caught again!\n", + " list.remove(x): x not in list\n", + " ```\n", + " **Output (Python 3.x):**\n" ] }, { @@ -8884,9 +8769,7 @@ "outputs": [ { "data": { - "text/plain": [ - "[0, 0]\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8894,7 +8777,1395 @@ } ], "source": [ - "some_recursive_func([5, 0])\n" + " File \"\", line 4\n", + " except (IndexError, ValueError), e:\n", + " ^\n", + " IndentationError: unindent does not match any outer indentation level\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " some_list = [1, 2, 3]\n", + " try:\n", + " some_list.remove(4)\n", + "\n", + " except (IndexError, ValueError) as e:\n", + " print(\"Caught again!\")\n", + " print(e)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " **Output:**\n", + " ```\n", + " Caught again!\n", + " list.remove(x): x not in list\n", + " ```\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Same operands, different story!\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = [1, 2, 3, 4]\n", + "b = a\n", + "a = a + [5, 6, 7, 8]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = [1, 2, 3, 4]\n", + "b = a\n", + "a += [5, 6, 7, 8]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6, 7, 8]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "b\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this.\n", + "\n", + "* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged.\n", + "\n", + "* The expression `a += [5,6,7,8]` is actually mapped to an \"extend\" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Name resolution ignoring class scope\n", + "1\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 5\n", + "class SomeClass:\n", + " x = 17\n", + " y = (x for i in range(10))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "list(SomeClass.y)[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 5\n", + "class SomeClass:\n", + " x = 17\n", + " y = [x for i in range(10)]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 2.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "17\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "SomeClass.y[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (Python 3.x):**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "5\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "SomeClass.y[0]\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "- Scopes nested inside class definition ignore names bound at the class level.\n", + "- A generator expression has its own scope.\n", + "- Starting from Python 3.X, list comprehensions also have their own scope.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Needles in a Haystack *\n", + "I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios,\n", + "\n", + "1\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x, y = (0, 1) if True else None, None\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "((0, 1), None)\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x, y # expected (0, 1)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "2\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [] + } + ], + "source": [ + "t = ('one', 'two')\n", + "for i in t:\n", + " print(i)\n", + "\n", + "t = ('one')\n", + "for i in t:\n", + " print(i)\n", + "\n", + "t = ()\n", + "print(t)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "one\n", + "two\n", + "o\n", + "n\n", + "e\n", + "tuple()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "3\\.\n", + "\n", + "```\n", + "ten_words_list = [\n", + " \"some\",\n", + " \"very\",\n", + " \"big\",\n", + " \"list\",\n", + " \"that\"\n", + " \"consists\",\n", + " \"of\",\n", + " \"exactly\",\n", + " \"ten\",\n", + " \"words\"\n", + "]\n", + "```\n", + "\n", + "**Output**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "9\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len(ten_words_list)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "4\\. Not asserting strongly enough\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "a = \"python\"\n", + "b = \"javascript\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "# No AssertionError is raised\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "# An assert statement with an assertion failure message.\n", + "assert(a == b, \"Both languages are different\")\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "5\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_list = [1, 2, 3]\n", + "some_dict = {\n", + " \"key_1\": 1,\n", + " \"key_2\": 2,\n", + " \"key_3\": 3\n", + "}\n", + "\n", + "some_list = some_list.append(4) \n", + "some_dict = some_dict.update({\"key_4\": 4})\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "print(some_list)\n" + ] + }, + { + "cell_type": "code", + "metadata": { + "collapsed": true + }, + "execution_count": null, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "print(some_dict)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "6\\.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "def some_recursive_func(a):\n", + " if a[0] == 0:\n", + " return\n", + " a[0] -= 1\n", + " some_recursive_func(a)\n", + " return a\n", + "\n", + "def similar_recursive_func(a):\n", + " if a == 0:\n", + " return a\n", + " a -= 1\n", + " similar_recursive_func(a)\n", + " return a\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 0]\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "some_recursive_func([5, 0])\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "similar_recursive_func(5)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`.\n", + "\n", + "* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character.\n", + "\n", + "* `()` is a special token and denotes empty `tuple`.\n", + "\n", + "* In 3, as you might have already figured out, there's a missing comma after 5th element (`\"that\"`) in the list. So by implicit string literal concatenation,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ten_words_list\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up,\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " AssertionError\n", + " \n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " a = \"python\"\n", + " b = \"javascript\"\n", + " assert a == b\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " :1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n", + " \n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " assert (a == b, \"Values are not equal\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + " AssertionError: Values are not equal\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " assert a == b, \"Values are not equal\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).\n", + "\n", + "* Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignation of an immutable (`a -= 1`) is not an alteration of the value.\n", + "\n", + "* Being aware of these nitpicks can save you hours of debugging effort in the long run. \n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Splitsies *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a']\n", + "\n", + "# is same as\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'a'.split()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "['a']\n", + "\n", + "# but\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "'a'.split(' ')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "0\n", + "\n", + "# isn't the same as\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len(''.split())\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "1\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "len(''.split(' '))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/3/library/stdtypes.html#str.split)\n", + " > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.\n", + " > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.\n", + "- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['', 'a', '']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ' a '.split(' ')\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['a']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ' a '.split()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ['']\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " ''.split(' ')\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 All sorted? *\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "x = 7, 8, 9\n", + "sorted(x) == x\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "sorted(x) == sorted(x)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "False\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "y = reversed(x)\n", + "sorted(y) == sorted(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. \n", + "\n", + "- ```py\n", + " >>> [] == tuple()\n", + " False\n", + " >>> x = 7, 8, 9\n", + " >>> type(x), type(sorted(x))\n", + " (tuple, list)\n", + " ```\n", + "\n", + "- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first.\n", + "\n", + "- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list.\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + " ([7, 8, 9], [])\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + " x = 7, 8, 9\n", + " y = reversed(x)\n", + " sorted(y), sorted(y)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Midnight time doesn't exist?\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "from datetime import datetime\n", + "\n", + "midnight = datetime(2018, 1, 1, 0, 0)\n", + "midnight_time = midnight.time()\n", + "\n", + "noon = datetime(2018, 1, 1, 12, 0)\n", + "noon_time = noon.time()\n", + "\n", + "if midnight_time:\n", + " print(\"Time at midnight is\", midnight_time)\n", + "\n", + "if noon_time:\n", + " print(\"Time at noon is\", noon_time)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output (< 3.5):**\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "('Time at noon is', datetime.time(12, 0))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The midnight time is not printed.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "\n", + "Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of \"empty.\"\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Okay Python, Can you make me fly?\n", + "Well, here you go\n", + "\n" ] }, { @@ -8906,9 +10177,7 @@ "outputs": [ { "data": { - "text/plain": [ - "4\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8916,13 +10185,16 @@ } ], "source": [ - "similar_recursive_func(5)\n" + "import antigravity\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "**Output:**\n", + "Sshh... It's a super-secret.\n", "\n" ] }, @@ -8931,37 +10203,42 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "\n", - "* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`.\n", - "\n", - "* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character.\n", - "\n", - "* `()` is a special token and denotes empty `tuple`.\n", - "\n", - "* In 3, as you might have already figured out, there's a missing comma after 5th element (`\"that\"`) in the list. So by implicit string literal concatenation,\n", + "+ `antigravity` module is one of the few easter eggs released by Python developers.\n", + "+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](https://xkcd.com/353/) about Python.\n", + "+ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 `goto`, but why?\n" + ] + }, { "cell_type": "code", - "execution_count": null, "metadata": { "collapsed": true }, + "execution_count": null, "outputs": [ { - "data": { - "text/plain": [ - " ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words']\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null + "name": "stdout", + "output_type": "stream", + "text": [] } ], "source": [ - " ten_words_list\n" + "from goto import goto, label\n", + "for i in range(9):\n", + " for j in range(9):\n", + " for k in range(9):\n", + " print(\"I am trapped, please rescue!\")\n", + " if k == 2:\n", + " goto .breakout # breaking out from a deeply nested loop\n", + "label .breakout\n", + "print(\"Freedom!\")\n" ] }, { @@ -8969,8 +10246,7 @@ "metadata": {}, "source": [ "\n", - "* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up,\n", - "\n" + "**Output (Python 2.3):**\n" ] }, { @@ -8982,12 +10258,7 @@ "outputs": [ { "data": { - "text/plain": [ - " Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - " AssertionError\n", - " \n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -8995,9 +10266,36 @@ } ], "source": [ - " a = \"python\"\n", - " b = \"javascript\"\n", - " assert a == b\n" + "I am trapped, please rescue!\n", + "I am trapped, please rescue!\n", + "Freedom!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004.\n", + "- Current versions of Python do not have this module.\n", + "- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Brace yourself!\n", + "If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing,\n", + "\n" ] }, { @@ -9009,10 +10307,7 @@ "outputs": [ { "data": { - "text/plain": [ - " :1: SyntaxWarning: assertion is always true, perhaps remove parentheses?\n", - " \n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -9020,7 +10315,15 @@ } ], "source": [ - " assert (a == b, \"Values are not equal\")\n" + "from __future__ import braces\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -9032,11 +10335,7 @@ "outputs": [ { "data": { - "text/plain": [ - " Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - " AssertionError: Values aren not equal\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -9044,7 +10343,9 @@ } ], "source": [ - " assert a == b, \"Values are not equal\"\n" + " File \"some_file.py\", line 1\n", + " from __future__ import braces\n", + "SyntaxError: not a chance\n" ] }, { @@ -9052,11 +10353,7 @@ "metadata": {}, "source": [ "\n", - "* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)).\n", - "\n", - "* Last one should be fairly obvious, passing mutable object (like `list` ) results in a call by reference, whereas an immutable object (like `int`) results in a call by value.\n", - "\n", - "* Being aware of these nitpicks can save you hours of debugging effort in the long run. \n", + "Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)?\n", "\n" ] }, @@ -9064,31 +10361,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Splitsies *\n" + "#### \ud83d\udca1 Explanation:\n", + "+ The `__future__` module is normally used to provide features from future versions of Python. The \"future\" in this specific context is however, ironic.\n", + "+ This is an easter egg concerned with the community's feelings on this issue.\n", + "+ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file.\n", + "+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement.\n", + "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "['a']\n", - "\n", - "# is same as\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "'a'.split()\n" + "### \u25b6 Let's meet Friendly Language Uncle For Life\n", + "**Output (Python 3.x)**\n" ] }, { @@ -9101,9 +10387,11 @@ { "data": { "text/plain": [ - "['a']\n", - "\n", - "# but\n" + " File \"some_file.py\", line 1\n", + " \"Ruby\" != \"Python\"\n", + " ^\n", + "SyntaxError: invalid syntax\n", + "\n" ] }, "output_type": "execute_result", @@ -9112,7 +10400,8 @@ } ], "source": [ - "'a'.split(' ')\n" + "from __future__ import barry_as_FLUFL\n", + "\"Ruby\" != \"Python\" # there's no doubt about it\n" ] }, { @@ -9125,9 +10414,7 @@ { "data": { "text/plain": [ - "0\n", - "\n", - "# isn't the same as\n" + "True\n" ] }, "output_type": "execute_result", @@ -9136,7 +10423,29 @@ } ], "source": [ - "len(''.split())\n" + "\"Ruby\" <> \"Python\"\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "There we go.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means).\n", + "- Quoting from the PEP-401\n", + " \n", + " > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.\n", + "- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/).\n", + "- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working,\n" ] }, { @@ -9148,9 +10457,7 @@ "outputs": [ { "data": { - "text/plain": [ - "1\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -9158,7 +10465,8 @@ } ], "source": [ - "len(''.split(' '))\n" + " from __future__ import barry_as_FLUFL\n", + " print(eval('\"Ruby\" <> \"Python\"'))\n" ] }, { @@ -9172,12 +10480,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/2.7/library/stdtypes.html#str.split)\n", - " > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`.\n", - " > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`.\n", - "- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear,\n" + "### \u25b6 Even Python understands that love is complicated\n" ] }, { @@ -9189,9 +10492,7 @@ "outputs": [ { "data": { - "text/plain": [ - " ['', 'a', '']\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -9199,7 +10500,43 @@ } ], "source": [ - " ' a '.split(' ')\n" + "import this\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Wait, what's **this**? `this` is love :heart:\n", + "\n", + "**Output:**\n", + "```\n", + "The Zen of Python, by Tim Peters\n", + "\n", + "Beautiful is better than ugly.\n", + "Explicit is better than implicit.\n", + "Simple is better than complex.\n", + "Complex is better than complicated.\n", + "Flat is better than nested.\n", + "Sparse is better than dense.\n", + "Readability counts.\n", + "Special cases aren't special enough to break the rules.\n", + "Although practicality beats purity.\n", + "Errors should never pass silently.\n", + "Unless explicitly silenced.\n", + "In the face of ambiguity, refuse the temptation to guess.\n", + "There should be one-- and preferably only one --obvious way to do it.\n", + "Although that way may not be obvious at first unless you're Dutch.\n", + "Now is better than never.\n", + "Although never is often better than *right* now.\n", + "If the implementation is hard to explain, it's a bad idea.\n", + "If the implementation is easy to explain, it may be a good idea.\n", + "Namespaces are one honking great idea -- let's do more of those!\n", + "```\n", + "\n", + "It's the Zen of Python!\n", + "\n" ] }, { @@ -9212,7 +10549,7 @@ { "data": { "text/plain": [ - " ['a']\n" + "True\n" ] }, "output_type": "execute_result", @@ -9221,7 +10558,8 @@ } ], "source": [ - " ' a '.split()\n" + "love = this\n", + "this is love\n" ] }, { @@ -9234,7 +10572,7 @@ { "data": { "text/plain": [ - " ['']\n" + "False\n" ] }, "output_type": "execute_result", @@ -9243,21 +10581,7 @@ } ], "source": [ - " ''.split(' ')\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 All sorted? *\n" + "love is True\n" ] }, { @@ -9279,8 +10603,7 @@ } ], "source": [ - "x = 7, 8, 9\n", - "sorted(x) == x\n" + "love is False\n" ] }, { @@ -9293,8 +10616,7 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "True\n" ] }, "output_type": "execute_result", @@ -9303,7 +10625,7 @@ } ], "source": [ - "sorted(x) == sorted(x)\n" + "love is not True or False\n" ] }, { @@ -9316,7 +10638,7 @@ { "data": { "text/plain": [ - "False\n" + "True\n" ] }, "output_type": "execute_result", @@ -9325,8 +10647,7 @@ } ], "source": [ - "y = reversed(x)\n", - "sorted(y) == sorted(y)\n" + "love is not True or False; love is love # Love is complicated\n" ] }, { @@ -9342,60 +10663,21 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. \n", - "\n", - "- ```py\n", - " >>> [] == tuple()\n", - " False\n", - " >>> x = 7, 8, 9\n", - " >>> type(x), type(sorted(x))\n", - " (tuple, list)\n", - " ```\n", - "\n", - "- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first.\n", - "\n", - "- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list.\n", + "* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)).\n", + "* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens).\n", + "* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators).\n", "\n" ] }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - " ([7, 8, 9], [])\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - " x = 7, 8, 9\n", - " y = reversed(x)\n", - " sorted(y), sorted(y)\n" - ] - }, { "cell_type": "markdown", "metadata": {}, "source": [ + "### \u25b6 Yes, it exists!\n", + "**The `else` clause for loops.** One typical example might be:\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Midnight time doesn't exist?\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -9413,19 +10695,13 @@ } ], "source": [ - "from datetime import datetime\n", - "\n", - "midnight = datetime(2018, 1, 1, 0, 0)\n", - "midnight_time = midnight.time()\n", - "\n", - "noon = datetime(2018, 1, 1, 12, 0)\n", - "noon_time = noon.time()\n", - "\n", - "if midnight_time:\n", - " print(\"Time at midnight is\", midnight_time)\n", - "\n", - "if noon_time:\n", - " print(\"Time at noon is\", noon_time)\n" + " def does_exists_num(l, to_find):\n", + " for num in l:\n", + " if num == to_find:\n", + " print(\"Exists!\")\n", + " break\n", + " else:\n", + " print(\"Does not exist\")\n" ] }, { @@ -9433,8 +10709,7 @@ "metadata": {}, "source": [ "\n", - "**Output (< 3.5):**\n", - "\n" + "**Output:**\n" ] }, { @@ -9446,7 +10721,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "Exists!\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -9454,34 +10731,8 @@ } ], "source": [ - "('Time at noon is', datetime.time(12, 0))\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The midnight time is not printed.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of \"empty.\"\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Okay Python, Can you make me fly?\n", - "Well, here you go\n", - "\n" + "some_list = [1, 2, 3, 4, 5]\n", + "does_exists_num(some_list, 4)\n" ] }, { @@ -9493,7 +10744,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "Does not exist\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -9501,7 +10754,7 @@ } ], "source": [ - "import antigravity\n" + "does_exists_num(some_list, -1)\n" ] }, { @@ -9509,52 +10762,33 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "Sshh... It's a super-secret.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "+ `antigravity` module is one of the few easter eggs released by Python developers.\n", - "+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python.\n", - "+ Well, there's more to it. There's **another easter egg inside the easter egg**. If you look at the [code](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), there's a function defined that purports to implement the [XKCD's geohashing algorithm](https://xkcd.com/426/).\n", + "**The `else` clause in exception handling.** An example,\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 `goto`, but why?\n" - ] - }, { "cell_type": "code", + "execution_count": null, "metadata": { "collapsed": true }, - "execution_count": null, "outputs": [ { - "name": "stdout", - "output_type": "stream", - "text": [] + "data": { + "text/plain": [] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null } ], "source": [ - "from goto import goto, label\n", - "for i in range(9):\n", - " for j in range(9):\n", - " for k in range(9):\n", - " print(\"I am trapped, please rescue!\")\n", - " if k == 2:\n", - " goto .breakout # breaking out from a deeply nested loop\n", - "label .breakout\n", - "print(\"Freedom!\")\n" + "try:\n", + " pass\n", + "except:\n", + " print(\"Exception occurred!!!\")\n", + "else:\n", + " print(\"Try block executed successfully...\")\n" ] }, { @@ -9562,7 +10796,7 @@ "metadata": {}, "source": [ "\n", - "**Output (Python 2.3):**\n" + "**Output:**\n" ] }, { @@ -9582,9 +10816,7 @@ } ], "source": [ - "I am trapped, please rescue!\n", - "I am trapped, please rescue!\n", - "Freedom!\n" + "Try block executed successfully...\n" ] }, { @@ -9599,47 +10831,16 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004.\n", - "- Current versions of Python do not have this module.\n", - "- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Brace yourself!\n", - "If you are one of the people who doesn't like using whitespace in Python to denote scopes, you can use the C-style {} by importing,\n", + "- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a \"nobreak\" clause.\n", + "- `else` clause after a try block is also called \"completion clause\" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.\n", "\n" ] }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "from __future__ import braces\n" - ] - }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n" + "### \u25b6 Ellipsis *\n" ] }, { @@ -9653,44 +10854,22 @@ "data": { "text/plain": [] }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - " File \"some_file.py\", line 1\n", - " from __future__ import braces\n", - "SyntaxError: not a chance\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Braces? No way! If you think that's disappointing, use Java. Okay, another surprising thing, can you find where's the `SyntaxError` raised in `__future__` module [code](https://github.com/python/cpython/blob/master/Lib/__future__.py)?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "#### \ud83d\udca1 Explanation:\n", - "+ The `__future__` module is normally used to provide features from future versions of Python. The \"future\" in this specific context is however, ironic.\n", - "+ This is an easter egg concerned with the community's feelings on this issue.\n", - "+ The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file.\n", - "+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement.\n", - "\n" + "def some_func():\n", + " Ellipsis\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Let's meet Friendly Language Uncle For Life\n", - "**Output (Python 3.x)**\n" + "\n", + "**Output**\n" ] }, { @@ -9703,10 +10882,7 @@ { "data": { "text/plain": [ - " File \"some_file.py\", line 1\n", - " \"Ruby\" != \"Python\"\n", - " ^\n", - "SyntaxError: invalid syntax\n", + "# No output, No Error\n", "\n" ] }, @@ -9716,8 +10892,7 @@ } ], "source": [ - "from __future__ import barry_as_FLUFL\n", - "\"Ruby\" != \"Python\" # there's no doubt about it\n" + "some_func()\n" ] }, { @@ -9730,7 +10905,10 @@ { "data": { "text/plain": [ - "True\n" + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "NameError: name 'SomeRandomString' is not defined\n", + "\n" ] }, "output_type": "execute_result", @@ -9739,29 +10917,7 @@ } ], "source": [ - "\"Ruby\" <> \"Python\"\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "There we go.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means).\n", - "- Quoting from the PEP-401\n", - " \n", - " > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.\n", - "- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/).\n", - "- It works well in an interactive environment, but it will raise a `SyntaxError` when you run via python file (see this [issue](https://github.com/satwikkansal/wtfpython/issues/94)). However, you can wrap the statement inside an `eval` or `compile` to get it working,\n" + "SomeRandomString\n" ] }, { @@ -9773,7 +10929,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "Ellipsis\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -9781,8 +10939,7 @@ } ], "source": [ - " from __future__ import barry_as_FLUFL\n", - " print(eval('\"Ruby\" <> \"Python\"'))\n" + "Ellipsis\n" ] }, { @@ -9796,7 +10953,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Even Python understands that love is complicated\n" + "#### \ud83d\udca1 Explanation\n", + "- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`.\n" ] }, { @@ -9808,7 +10966,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + " Ellipsis\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -9816,43 +10976,16 @@ } ], "source": [ - "import this\n" + " ...\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "Wait, what's **this**? `this` is love :heart:\n", - "\n", - "**Output:**\n", - "```\n", - "The Zen of Python, by Tim Peters\n", - "\n", - "Beautiful is better than ugly.\n", - "Explicit is better than implicit.\n", - "Simple is better than complex.\n", - "Complex is better than complicated.\n", - "Flat is better than nested.\n", - "Sparse is better than dense.\n", - "Readability counts.\n", - "Special cases aren't special enough to break the rules.\n", - "Although practicality beats purity.\n", - "Errors should never pass silently.\n", - "Unless explicitly silenced.\n", - "In the face of ambiguity, refuse the temptation to guess.\n", - "There should be one-- and preferably only one --obvious way to do it.\n", - "Although that way may not be obvious at first unless you're Dutch.\n", - "Now is better than never.\n", - "Although never is often better than *right* now.\n", - "If the implementation is hard to explain, it's a bad idea.\n", - "If the implementation is easy to explain, it may be a good idea.\n", - "Namespaces are one honking great idea -- let's do more of those!\n", - "```\n", - "\n", - "It's the Zen of Python!\n", - "\n" + "- Eliipsis can be used for several purposes,\n", + " + As a placeholder for code that hasn't been written yet (just like `pass` statement)\n", + " + In slicing syntax to represent the full slices in remaining direction\n" ] }, { @@ -9865,7 +10998,17 @@ { "data": { "text/plain": [ - "True\n" + " array([\n", + " [\n", + " [0, 1],\n", + " [2, 3]\n", + " ],\n", + "\n", + " [\n", + " [4, 5],\n", + " [6, 7]\n", + " ]\n", + " ])\n" ] }, "output_type": "execute_result", @@ -9874,8 +11017,15 @@ } ], "source": [ - "love = this\n", - "this is love\n" + " import numpy as np\n", + " three_dimensional_array = np.arange(8).reshape(2, 2, 2)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions\n" ] }, { @@ -9888,7 +11038,8 @@ { "data": { "text/plain": [ - "False\n" + " array([[1, 3],\n", + " [5, 7]])\n" ] }, "output_type": "execute_result", @@ -9897,7 +11048,7 @@ } ], "source": [ - "love is True\n" + " three_dimensional_array[:,:,1]\n" ] }, { @@ -9910,7 +11061,8 @@ { "data": { "text/plain": [ - "False\n" + " array([[1, 3],\n", + " [5, 7]])\n" ] }, "output_type": "execute_result", @@ -9919,7 +11071,27 @@ } ], "source": [ - "love is False\n" + " three_dimensional_array[..., 1] # using Ellipsis.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`)\n", + " + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`))\n", + " + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the \"no argument passed\" and \"None value passed\" scenarios).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Inpinity\n", + "The spelling is intended. Please, don't submit a patch for this.\n", + "\n", + "**Output (Python 3.x):**\n" ] }, { @@ -9932,7 +11104,7 @@ { "data": { "text/plain": [ - "True\n" + "314159\n" ] }, "output_type": "execute_result", @@ -9941,7 +11113,8 @@ } ], "source": [ - "love is not True or False\n" + "infinity = float('infinity')\n", + "hash(infinity)\n" ] }, { @@ -9954,7 +11127,7 @@ { "data": { "text/plain": [ - "True\n" + "-314159\n" ] }, "output_type": "execute_result", @@ -9963,7 +11136,7 @@ } ], "source": [ - "love is not True or False; love is love # Love is complicated\n" + "hash(float('-inf'))\n" ] }, { @@ -9978,10 +11151,8 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "\n", - "* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)).\n", - "* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens).\n", - "* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators).\n", + "- Hash of infinity is 10\u2075 x \u03c0.\n", + "- Interestingly, the hash of `float('-inf')` is \"-10\u2075 x \u03c0\" in Python 3, whereas \"-10\u2075 x e\" in Python 2.\n", "\n" ] }, @@ -9989,9 +11160,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Yes, it exists!\n", - "**The `else` clause for loops.** One typical example might be:\n", - "\n" + "### \u25b6 Let's mangle\n", + "1\\.\n" ] }, { @@ -10011,13 +11181,10 @@ } ], "source": [ - " def does_exists_num(l, to_find):\n", - " for num in l:\n", - " if num == to_find:\n", - " print(\"Exists!\")\n", - " break\n", - " else:\n", - " print(\"Does not exist\")\n" + "class Yo(object):\n", + " def __init__(self):\n", + " self.__honey = True\n", + " self.bro = True\n" ] }, { @@ -10038,7 +11205,7 @@ { "data": { "text/plain": [ - "Exists!\n" + "True\n" ] }, "output_type": "execute_result", @@ -10047,8 +11214,7 @@ } ], "source": [ - "some_list = [1, 2, 3, 4, 5]\n", - "does_exists_num(some_list, 4)\n" + "Yo().bro\n" ] }, { @@ -10061,7 +11227,7 @@ { "data": { "text/plain": [ - "Does not exist\n" + "AttributeError: 'Yo' object has no attribute '__honey'\n" ] }, "output_type": "execute_result", @@ -10070,16 +11236,7 @@ } ], "source": [ - "does_exists_num(some_list, -1)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**The `else` clause in exception handling.** An example,\n", - "\n" + "Yo().__honey\n" ] }, { @@ -10091,7 +11248,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "True\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -10099,12 +11258,7 @@ } ], "source": [ - "try:\n", - " pass\n", - "except:\n", - " print(\"Exception occurred!!!\")\n", - "else:\n", - " print(\"Try block executed successfully...\")\n" + "Yo()._Yo__honey\n" ] }, { @@ -10112,7 +11266,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" + "2\\.\n" ] }, { @@ -10132,31 +11286,42 @@ } ], "source": [ - "Try block executed successfully...\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + "class Yo(object):\n", + " def __init__(self):\n", + " # Let's try something symmetrical this time\n", + " self.__honey__ = True\n", + " self.bro = True\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a \"nobreak\" clause.\n", - "- `else` clause after a try block is also called \"completion clause\" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.\n", - "\n" + "\n", + "**Output:**\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True\n", + "\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "### \u25b6 Ellipsis *\n" + "Yo().bro\n" ] }, { @@ -10168,7 +11333,11 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "AttributeError: 'Yo' object has no attribute '_Yo__honey__'\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -10176,8 +11345,7 @@ } ], "source": [ - "def some_func():\n", - " Ellipsis\n" + "Yo()._Yo__honey__\n" ] }, { @@ -10185,7 +11353,10 @@ "metadata": {}, "source": [ "\n", - "**Output**\n" + "Why did `Yo()._Yo__honey` work?\n", + "\n", + "3\\.\n", + "\n" ] }, { @@ -10197,10 +11368,7 @@ "outputs": [ { "data": { - "text/plain": [ - "# No output, No Error\n", - "\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -10208,7 +11376,19 @@ } ], "source": [ - "some_func()\n" + "_A__variable = \"Some value\"\n", + "\n", + "class A(object):\n", + " def some_func(self):\n", + " return __variable # not initialized anywhere yet\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -10223,7 +11403,7 @@ "text/plain": [ "Traceback (most recent call last):\n", " File \"\", line 1, in \n", - "NameError: name 'SomeRandomString' is not defined\n", + "AttributeError: 'A' object has no attribute '__variable'\n", "\n" ] }, @@ -10233,7 +11413,7 @@ } ], "source": [ - "SomeRandomString\n" + "A().__variable\n" ] }, { @@ -10246,7 +11426,7 @@ { "data": { "text/plain": [ - "Ellipsis\n" + "'Some value'\n" ] }, "output_type": "execute_result", @@ -10255,13 +11435,14 @@ } ], "source": [ - "Ellipsis\n" + "A().some_func()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", "\n" ] }, @@ -10269,8 +11450,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation\n", - "- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`.\n" + "#### \ud83d\udca1 Explanation:\n", + "\n", + "* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.\n", + "* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a \"dunder\") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front.\n", + "* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class.\n", + "* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores.\n", + "* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope.\n", + "* Also, if the mangled name is longer than 255 characters, truncation will happen.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Skipping lines?\n", + "**Output:**\n" ] }, { @@ -10283,7 +11479,7 @@ { "data": { "text/plain": [ - " Ellipsis\n" + "11\n" ] }, "output_type": "execute_result", @@ -10292,16 +11488,30 @@ } ], "source": [ - " ...\n" + "value = 11\n", + "valu\u0435 = 32\n", + "value\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "- Eliipsis can be used for several purposes,\n", - " + As a placeholder for code that hasn't been written yet (just like `pass` statement)\n", - " + In slicing syntax to represent the full slices in remaining direction\n" + "\n", + "Wut?\n", + "\n", + "**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter.\n", + "\n" ] }, { @@ -10314,17 +11524,7 @@ { "data": { "text/plain": [ - " array([\n", - " [\n", - " [0, 1],\n", - " [2, 3]\n", - " ],\n", - "\n", - " [\n", - " [4, 5],\n", - " [6, 7]\n", - " ]\n", - " ])\n" + "1077\n" ] }, "output_type": "execute_result", @@ -10333,15 +11533,29 @@ } ], "source": [ - " import numpy as np\n", - " three_dimensional_array = np.arange(8).reshape(2, 2, 2)\n" + "ord('\u0435') # cyrillic 'e' (Ye)\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "101\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - " So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions\n" + "ord('e') # latin 'e', as used in English and typed using standard keyboard\n" ] }, { @@ -10354,8 +11568,8 @@ { "data": { "text/plain": [ - " array([[1, 3],\n", - " [5, 7]])\n" + "False\n", + "\n" ] }, "output_type": "execute_result", @@ -10364,7 +11578,7 @@ } ], "source": [ - " three_dimensional_array[:,:,1]\n" + "'\u0435' == 'e'\n" ] }, { @@ -10377,8 +11591,7 @@ { "data": { "text/plain": [ - " array([[1, 3],\n", - " [5, 7]])\n" + "42\n" ] }, "output_type": "execute_result", @@ -10387,16 +11600,17 @@ } ], "source": [ - " three_dimensional_array[..., 1] # using Ellipsis.\n" + "value = 42 # latin e\n", + "valu\u0435 = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here\n", + "value\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`)\n", - " + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`))\n", - " + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the \"no argument passed\" and \"None value passed\" scenarios).\n", + "\n", + "The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example.\n", "\n" ] }, @@ -10404,10 +11618,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Inpinity\n", - "The spelling is intended. Please, don't submit a patch for this.\n", - "\n", - "**Output (Python 3.x):**\n" + "### \u25b6 Teleportation\n" ] }, { @@ -10419,9 +11630,7 @@ "outputs": [ { "data": { - "text/plain": [ - "314159\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -10429,8 +11638,24 @@ } ], "source": [ - "infinity = float('infinity')\n", - "hash(infinity)\n" + "# `pip install numpy` first.\n", + "import numpy as np\n", + "\n", + "def energy_send(x):\n", + " # Initializing a numpy array\n", + " np.array([float(x)])\n", + "\n", + "def energy_receive():\n", + " # Return an empty numpy array\n", + " return np.empty((), dtype=np.float).tolist()\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:**\n" ] }, { @@ -10443,7 +11668,7 @@ { "data": { "text/plain": [ - "-314159\n" + "123.456\n" ] }, "output_type": "execute_result", @@ -10452,13 +11677,16 @@ } ], "source": [ - "hash(float('-inf'))\n" + "energy_send(123.456)\n", + "energy_receive()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "Where's the Nobel Prize?\n", "\n" ] }, @@ -10467,8 +11695,9 @@ "metadata": {}, "source": [ "#### \ud83d\udca1 Explanation:\n", - "- Hash of infinity is 10\u2075 x \u03c0.\n", - "- Interestingly, the hash of `float('-inf')` is \"-10\u2075 x \u03c0\" in Python 3, whereas \"-10\u2075 x e\" in Python 2.\n", + "\n", + "* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate.\n", + "* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always).\n", "\n" ] }, @@ -10476,8 +11705,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Let's mangle\n", - "1\\.\n" + "### \u25b6 Well, something is fishy...\n" ] }, { @@ -10497,10 +11725,14 @@ } ], "source": [ - "class Yo(object):\n", - " def __init__(self):\n", - " self.__honey = True\n", - " self.bro = True\n" + "def square(x):\n", + " \"\"\"\n", + " A simple function to calculate the square of a number by addition.\n", + " \"\"\"\n", + " sum_so_far = 0\n", + " for counter in range(x):\n", + " sum_so_far = sum_so_far + x\n", + " return sum_so_far\n" ] }, { @@ -10508,29 +11740,8 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], - "source": [ - "Yo().bro\n" + "**Output (Python 2.x):**\n", + "\n" ] }, { @@ -10543,7 +11754,7 @@ { "data": { "text/plain": [ - "AttributeError: 'Yo' object has no attribute '__honey'\n" + "10\n" ] }, "output_type": "execute_result", @@ -10552,37 +11763,34 @@ } ], "source": [ - "Yo().__honey\n" + "square(10)\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [ - "True\n" - ] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "Yo()._Yo__honey\n" + "\n", + "Shouldn't that be 100?\n", + "\n", + "**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation\n", + "\n", + "* **Don't mix tabs and spaces!** The character just preceding return is a \"tab\", and the code is indented by multiple of \"4 spaces\" elsewhere in the example.\n", + "* This is how Python handles tabs:\n", + " \n", + " > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>\n", + "* So the \"tab\" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.\n", + "* Python 3 is kind enough to throw an error for such cases automatically.\n", "\n", - "2\\.\n" + " **Output (Python 3.x):**\n" ] }, { @@ -10602,19 +11810,21 @@ } ], "source": [ - "class Yo(object):\n", - " def __init__(self):\n", - " # Let's try something symmetrical this time\n", - " self.__honey__ = True\n", - " self.bro = True\n" + " TabError: inconsistent use of tabs and spaces in indentation\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n" + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 `+=` is faster\n" ] }, { @@ -10627,8 +11837,8 @@ { "data": { "text/plain": [ - "True\n", - "\n" + "0.25748300552368164\n", + "# using \"+=\", three strings:\n" ] }, "output_type": "execute_result", @@ -10637,7 +11847,8 @@ } ], "source": [ - "Yo().bro\n" + "# using \"+\", three strings:\n", + "timeit.timeit(\"s1 = s1 + s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" ] }, { @@ -10650,9 +11861,7 @@ { "data": { "text/plain": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "AttributeError: 'Yo' object has no attribute '_Yo__honey__'\n" + "0.012188911437988281\n" ] }, "output_type": "execute_result", @@ -10661,50 +11870,30 @@ } ], "source": [ - "Yo()._Yo__honey__\n" + "timeit.timeit(\"s1 += s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "Why did `Yo()._Yo__honey` work?\n", - "\n", - "3\\.\n", "\n" ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [ - { - "data": { - "text/plain": [] - }, - "output_type": "execute_result", - "metadata": {}, - "execution_count": null - } - ], + "cell_type": "markdown", + "metadata": {}, "source": [ - "_A__variable = \"Some value\"\n", - "\n", - "class A(object):\n", - " def some_func(self):\n", - " return __variable # not initialized anywhere yet\n" + "#### \ud83d\udca1 Explanation:\n", + "+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "**Output:**\n" + "### \u25b6 Let's make a giant string!\n" ] }, { @@ -10716,9 +11905,7 @@ "outputs": [ { "data": { - "text/plain": [ - "'Some value'\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -10726,44 +11913,44 @@ } ], "source": [ - "Traceback (most recent call last):\n", - " File \"\", line 1, in \n", - "AttributeError: 'A' object has no attribute '__variable'\n", + "def add_string_with_plus(iters):\n", + " s = \"\"\n", + " for i in range(iters):\n", + " s += \"xyz\"\n", + " assert len(s) == 3*iters\n", "\n", - "A().some_func()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ + "def add_bytes_with_plus(iters):\n", + " s = b\"\"\n", + " for i in range(iters):\n", + " s += b\"xyz\"\n", + " assert len(s) == 3*iters\n", "\n", - "\n" + "def add_string_with_format(iters):\n", + " fs = \"{}\"*iters\n", + " s = fs.format(*([\"xyz\"]*iters))\n", + " assert len(s) == 3*iters\n", + "\n", + "def add_string_with_join(iters):\n", + " l = []\n", + " for i in range(iters):\n", + " l.append(\"xyz\")\n", + " s = \"\".join(l)\n", + " assert len(s) == 3*iters\n", + "\n", + "def convert_list_to_string(l, iters):\n", + " s = \"\".join(l)\n", + " assert len(s) == 3*iters\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", "\n", - "* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces.\n", - "* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a \"dunder\") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front.\n", - "* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class.\n", - "* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores.\n", - "* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope.\n", - "* Also, if the mangled name is longer than 255 characters, truncation will happen.\n", + "**Output:**\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Skipping lines?\n", - "**Output:**\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -10774,7 +11961,7 @@ { "data": { "text/plain": [ - "11\n" + "124 \u00b5s \u00b1 4.73 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" ] }, "output_type": "execute_result", @@ -10783,30 +11970,12 @@ } ], "source": [ - "value = 11\n", - "valu\u0435 = 32\n", - "value\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Wut?\n", - "\n", - "**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation\n", + "# Executed in ipython shell using %timeit for better readability of results.\n", + "# You can also use the timeit module in normal python shell/scriptm=, example usage below\n", + "# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())\n", "\n", - "Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter.\n", - "\n" + "NUM_ITERS = 1000\n", + "%timeit -n1000 add_string_with_plus(NUM_ITERS)\n" ] }, { @@ -10819,7 +11988,7 @@ { "data": { "text/plain": [ - "1077\n" + "211 \u00b5s \u00b1 10.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10828,7 +11997,7 @@ } ], "source": [ - "ord('\u0435') # cyrillic 'e' (Ye)\n" + "%timeit -n1000 add_bytes_with_plus(NUM_ITERS)\n" ] }, { @@ -10841,7 +12010,7 @@ { "data": { "text/plain": [ - "101\n" + "61 \u00b5s \u00b1 2.18 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10850,7 +12019,7 @@ } ], "source": [ - "ord('e') # latin 'e', as used in English and typed using standard keyboard\n" + "%timeit -n1000 add_string_with_format(NUM_ITERS)\n" ] }, { @@ -10863,8 +12032,7 @@ { "data": { "text/plain": [ - "False\n", - "\n" + "117 \u00b5s \u00b1 3.21 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10873,7 +12041,7 @@ } ], "source": [ - "'\u0435' == 'e'\n" + "%timeit -n1000 add_string_with_join(NUM_ITERS)\n" ] }, { @@ -10886,7 +12054,7 @@ { "data": { "text/plain": [ - "42\n" + "10.1 \u00b5s \u00b1 1.06 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10895,9 +12063,8 @@ } ], "source": [ - "value = 42 # latin e\n", - "valu\u0435 = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here\n", - "value\n" + "l = [\"xyz\"]*NUM_ITERS\n", + "%timeit -n1000 convert_list_to_string(l, NUM_ITERS)\n" ] }, { @@ -10905,17 +12072,10 @@ "metadata": {}, "source": [ "\n", - "The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example.\n", + "Let's increase the number of iterations by a factor of 10.\n", "\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Teleportation\n" - ] - }, { "cell_type": "code", "execution_count": null, @@ -10925,7 +12085,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "1.26 ms \u00b1 76.8 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -10933,24 +12095,8 @@ } ], "source": [ - "# `pip install nump` first.\n", - "import numpy as np\n", - "\n", - "def energy_send(x):\n", - " # Initializing a numpy array\n", - " np.array([float(x)])\n", - "\n", - "def energy_receive():\n", - " # Return an empty numpy array\n", - " return np.empty((), dtype=np.float).tolist()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output:**\n" + "NUM_ITERS = 10000\n", + "%timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time\n" ] }, { @@ -10963,7 +12109,7 @@ { "data": { "text/plain": [ - "123.456\n" + "6.82 ms \u00b1 134 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -10972,35 +12118,7 @@ } ], "source": [ - "energy_send(123.456)\n", - "energy_receive()\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Where's the Nobel Prize?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation:\n", - "\n", - "* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate.\n", - "* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always).\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### \u25b6 Well, something is fishy...\n" + "%timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase\n" ] }, { @@ -11012,7 +12130,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "645 \u00b5s \u00b1 24.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -11020,23 +12140,7 @@ } ], "source": [ - "def square(x):\n", - " \"\"\"\n", - " A simple function to calculate the square of a number by addition.\n", - " \"\"\"\n", - " sum_so_far = 0\n", - " for counter in range(x):\n", - " sum_so_far = sum_so_far + x\n", - " return sum_so_far\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "**Output (Python 2.x):**\n", - "\n" + "%timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase\n" ] }, { @@ -11049,7 +12153,7 @@ { "data": { "text/plain": [ - "10\n" + "1.17 ms \u00b1 7.25 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -11058,34 +12162,7 @@ } ], "source": [ - "square(10)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "Shouldn't that be 100?\n", - "\n", - "**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### \ud83d\udca1 Explanation\n", - "\n", - "* **Don't mix tabs and spaces!** The character just preceding return is a \"tab\", and the code is indented by multiple of \"4 spaces\" elsewhere in the example.\n", - "* This is how Python handles tabs:\n", - " \n", - " > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>\n", - "* So the \"tab\" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.\n", - "* Python 3 is kind enough to throw an error for such cases automatically.\n", - "\n", - " **Output (Python 3.x):**\n" + "%timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase\n" ] }, { @@ -11097,7 +12174,9 @@ "outputs": [ { "data": { - "text/plain": [] + "text/plain": [ + "86.3 \u00b5s \u00b1 2 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + ] }, "output_type": "execute_result", "metadata": {}, @@ -11105,7 +12184,8 @@ } ], "source": [ - " TabError: inconsistent use of tabs and spaces in indentation\n" + "l = [\"xyz\"]*NUM_ITERS\n", + "%timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase\n" ] }, { @@ -11119,7 +12199,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 `+=` is faster\n" + "#### \ud83d\udca1 Explanation\n", + "- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces.\n", + "- Don't use `+` for generating long strings \u2014 In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function)\n", + "- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings).\n", + "- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.\n", + "- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + \"x\" + \"y\" + \"z\"` instead of `s += \"xyz\"`, the increase would have been quadratic.\n" ] }, { @@ -11132,8 +12217,7 @@ { "data": { "text/plain": [ - "0.25748300552368164\n", - "# using \"+=\", three strings:\n" + " 388 \u00b5s \u00b1 22.4 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" ] }, "output_type": "execute_result", @@ -11142,8 +12226,13 @@ } ], "source": [ - "# using \"+\", three strings:\n", - "timeit.timeit(\"s1 = s1 + s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" + " def add_string_with_plus(iters):\n", + " s = \"\"\n", + " for i in range(iters):\n", + " s = s + \"x\" + \"y\" + \"z\"\n", + " assert len(s) == 3*iters\n", + "\n", + " %timeit -n100 add_string_with_plus(1000)\n" ] }, { @@ -11156,7 +12245,7 @@ { "data": { "text/plain": [ - "0.012188911437988281\n" + " 9 ms \u00b1 298 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" ] }, "output_type": "execute_result", @@ -11165,22 +12254,16 @@ } ], "source": [ - "timeit.timeit(\"s1 += s2 + s3\", setup=\"s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000\", number=100)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n" + " %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### \ud83d\udca1 Explanation:\n", - "+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.\n", + "- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which,\n", + " \n", + " > There should be one-- and preferably only one --obvious way to do it.\n", "\n" ] }, @@ -11188,7 +12271,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### \u25b6 Let's make a giant string!\n" + "### \u25b6 Slowing down `dict` lookups *\n" ] }, { @@ -11208,33 +12291,8 @@ } ], "source": [ - "def add_string_with_plus(iters):\n", - " s = \"\"\n", - " for i in range(iters):\n", - " s += \"xyz\"\n", - " assert len(s) == 3*iters\n", - "\n", - "def add_bytes_with_plus(iters):\n", - " s = b\"\"\n", - " for i in range(iters):\n", - " s += b\"xyz\"\n", - " assert len(s) == 3*iters\n", - "\n", - "def add_string_with_format(iters):\n", - " fs = \"{}\"*iters\n", - " s = fs.format(*([\"xyz\"]*iters))\n", - " assert len(s) == 3*iters\n", - "\n", - "def add_string_with_join(iters):\n", - " l = []\n", - " for i in range(iters):\n", - " l.append(\"xyz\")\n", - " s = \"\".join(l)\n", - " assert len(s) == 3*iters\n", - "\n", - "def convert_list_to_string(l, iters):\n", - " s = \"\".join(l)\n", - " assert len(s) == 3*iters\n" + "some_dict = {str(i): 1 for i in range(1_000_000)}\n", + "another_dict = {str(i): 1 for i in range(1_000_000)}\n" ] }, { @@ -11242,8 +12300,7 @@ "metadata": {}, "source": [ "\n", - "**Output:**\n", - "\n" + "**Output:**\n" ] }, { @@ -11256,7 +12313,7 @@ { "data": { "text/plain": [ - "124 \u00b5s \u00b1 4.73 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" + "28.6 ns \u00b1 0.115 ns per loop (mean \u00b1 std. dev. of 7 runs, 10000000 loops each)\n" ] }, "output_type": "execute_result", @@ -11265,12 +12322,7 @@ } ], "source": [ - "# Executed in ipython shell using %timeit for better readability of results.\n", - "# You can also use the timeit module in normal python shell/scriptm=, example usage below\n", - "# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())\n", - "\n", - "NUM_ITERS = 1000\n", - "%timeit -n1000 add_string_with_plus(NUM_ITERS)\n" + "%timeit some_dict['5']\n" ] }, { @@ -11283,7 +12335,8 @@ { "data": { "text/plain": [ - "211 \u00b5s \u00b1 10.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "37.2 ns \u00b1 0.265 ns per loop (mean \u00b1 std. dev. of 7 runs, 10000000 loops each)\n", + "\n" ] }, "output_type": "execute_result", @@ -11292,7 +12345,8 @@ } ], "source": [ - "%timeit -n1000 add_bytes_with_plus(NUM_ITERS)\n" + "some_dict[1] = 1\n", + "%timeit some_dict['5']\n" ] }, { @@ -11305,7 +12359,7 @@ { "data": { "text/plain": [ - "61 \u00b5s \u00b1 2.18 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "28.5 ns \u00b1 0.142 ns per loop (mean \u00b1 std. dev. of 7 runs, 10000000 loops each)\n" ] }, "output_type": "execute_result", @@ -11314,7 +12368,7 @@ } ], "source": [ - "%timeit -n1000 add_string_with_format(NUM_ITERS)\n" + "%timeit another_dict['5']\n" ] }, { @@ -11327,7 +12381,9 @@ { "data": { "text/plain": [ - "117 \u00b5s \u00b1 3.21 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "Traceback (most recent call last):\n", + " File \"\", line 1, in \n", + "KeyError: 1\n" ] }, "output_type": "execute_result", @@ -11336,7 +12392,7 @@ } ], "source": [ - "%timeit -n1000 add_string_with_join(NUM_ITERS)\n" + "another_dict[1] # Trying to access a key that doesn't exist\n" ] }, { @@ -11349,7 +12405,7 @@ { "data": { "text/plain": [ - "10.1 \u00b5s \u00b1 1.06 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "38.5 ns \u00b1 0.0913 ns per loop (mean \u00b1 std. dev. of 7 runs, 10000000 loops each)\n" ] }, "output_type": "execute_result", @@ -11358,19 +12414,37 @@ } ], "source": [ - "l = [\"xyz\"]*NUM_ITERS\n", - "%timeit -n1000 convert_list_to_string(l, NUM_ITERS)\n" + "%timeit another_dict['5']\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Why are same lookups becoming slower?\n", + "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys.\n", + "+ The specialized function (named `lookdict_unicode` in CPython's [source](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method.\n", + "+ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function.\n", + "+ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary. That's why attempting a failed lookup has the same effect.\n", "\n", - "Let's increase the number of iterations by a factor of 10.\n", "\n" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### \u25b6 Bloating instance `dict`s *\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -11380,9 +12454,7 @@ "outputs": [ { "data": { - "text/plain": [ - "1.26 ms \u00b1 76.8 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" - ] + "text/plain": [] }, "output_type": "execute_result", "metadata": {}, @@ -11390,8 +12462,27 @@ } ], "source": [ - "NUM_ITERS = 10000\n", - "%timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time\n" + "import sys\n", + "\n", + "class SomeClass:\n", + " def __init__(self):\n", + " self.some_attr1 = 1\n", + " self.some_attr2 = 2\n", + " self.some_attr3 = 3\n", + " self.some_attr4 = 4\n", + "\n", + "\n", + "def dict_size(o):\n", + " return sys.getsizeof(o.__dict__)\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "**Output:** (Python 3.8, other Python 3 versions may vary a little)\n" ] }, { @@ -11404,7 +12495,7 @@ { "data": { "text/plain": [ - "6.82 ms \u00b1 134 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "104\n" ] }, "output_type": "execute_result", @@ -11413,7 +12504,9 @@ } ], "source": [ - "%timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase\n" + "o1 = SomeClass()\n", + "o2 = SomeClass()\n", + "dict_size(o1)\n" ] }, { @@ -11426,7 +12519,7 @@ { "data": { "text/plain": [ - "645 \u00b5s \u00b1 24.5 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "104\n" ] }, "output_type": "execute_result", @@ -11435,7 +12528,7 @@ } ], "source": [ - "%timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase\n" + "dict_size(o2)\n" ] }, { @@ -11448,7 +12541,7 @@ { "data": { "text/plain": [ - "1.17 ms \u00b1 7.25 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "232\n" ] }, "output_type": "execute_result", @@ -11457,7 +12550,9 @@ } ], "source": [ - "%timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase\n" + "del o1.some_attr1\n", + "o3 = SomeClass()\n", + "dict_size(o3)\n" ] }, { @@ -11470,7 +12565,7 @@ { "data": { "text/plain": [ - "86.3 \u00b5s \u00b1 2 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "232\n" ] }, "output_type": "execute_result", @@ -11479,27 +12574,40 @@ } ], "source": [ - "l = [\"xyz\"]*NUM_ITERS\n", - "%timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase\n" + "dict_size(o1)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "\n", + "Let's try again... In a new interpreter:\n", "\n" ] }, { - "cell_type": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "104 # as expected\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], "source": [ - "#### \ud83d\udca1 Explanation\n", - "- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces.\n", - "- Don't use `+` for generating long strings \u2014 In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function)\n", - "- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings).\n", - "- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.\n", - "- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + \"x\" + \"y\" + \"z\"` instead of `s += \"xyz\"`, the increase would have been quadratic.\n" + "o1 = SomeClass()\n", + "o2 = SomeClass()\n", + "dict_size(o1)\n" ] }, { @@ -11512,7 +12620,7 @@ { "data": { "text/plain": [ - " 388 \u00b5s \u00b1 22.4 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 1000 loops each)\n" + "360\n" ] }, "output_type": "execute_result", @@ -11521,13 +12629,9 @@ } ], "source": [ - " def add_string_with_plus(iters):\n", - " s = \"\"\n", - " for i in range(iters):\n", - " s = s + \"x\" + \"y\" + \"z\"\n", - " assert len(s) == 3*iters\n", - "\n", - " %timeit -n100 add_string_with_plus(1000)\n" + "o1.some_attr5 = 5\n", + "o1.some_attr6 = 6\n", + "dict_size(o1)\n" ] }, { @@ -11540,7 +12644,7 @@ { "data": { "text/plain": [ - " 9 ms \u00b1 298 \u00b5s per loop (mean \u00b1 std. dev. of 7 runs, 100 loops each)\n" + "272\n" ] }, "output_type": "execute_result", @@ -11549,16 +12653,52 @@ } ], "source": [ - " %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time\n" + "dict_size(o2)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "232\n" + ] + }, + "output_type": "execute_result", + "metadata": {}, + "execution_count": null + } + ], + "source": [ + "o3 = SomeClass()\n", + "dict_size(o3)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which,\n", - " \n", - " > There should be one-- and preferably only one --obvious way to do it.\n", + "\n", + "What makes those dictionaries become bloated? And why are newly created objects bloated as well?\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### \ud83d\udca1 Explanation:\n", + "+ CPython is able to reuse the same \"keys\" object in multiple dictionaries. This was added in [PEP 412](https://www.python.org/dev/peps/pep-0412/) with the motivation to reduce memory usage, specifically in dictionaries of instances - where keys (instance attributes) tend to be common to all instances.\n", + "+ This optimization is entirely seamless for instance dictionaries, but it is disabled if certain assumptions are broken.\n", + "+ Key-sharing dictionaries do not support deletion; if an instance attribute is deleted, the dictionary is \"unshared\", and key-sharing is disabled for all future instances of the same class.\n", + "+ Additionaly, if the dictionary keys have be resized (because new keys are inserted), they are kept shared *only* if they are used by a exactly single dictionary (this allows adding many attributes in the `__init__` of the very first created instance, without causing an \"unshare\"). If multiple instances exist when a resize happens, key-sharing is disabled for all future instances of the same class: CPython can't tell if your instances are using the same set of attributes anymore, and decides to bail out on attempting to share their keys.\n", + "+ A small tip, if you aim to lower your program's memory footprint: don't delete instance attributes, and make sure to initialize all attributes in your `__init__`!\n", + "\n", "\n" ] }, @@ -11636,7 +12776,7 @@ " ```py\n", " >>> some_string = \"wtfpython\"\n", " >>> f'{some_string=}'\n", - " \"string='wtfpython'\"\n", + " \"some_string='wtfpython'\"\n", " ``` \n", "\n", "* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!):\n", @@ -11653,7 +12793,7 @@ " print(dis.dis(f))\n", " ```\n", " \n", - "* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module.\n", + "* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) module.\n", "\n", "* Sometimes, the `print` method might not print values immediately. For example,\n", "\n", @@ -11665,7 +12805,7 @@ " time.sleep(3)\n", " ```\n", "\n", - " This will print the `wtfpython` after 10 seconds due to the `end` argument because the output buffer is flushed either after encountering `\\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument.\n", + " This will print the `wtfpython` after 3 seconds due to the `end` argument because the output buffer is flushed either after encountering `\\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument.\n", "\n", "* List slicing with out of the bounds indices throws no errors\n", " ```py\n", @@ -11684,7 +12824,7 @@ " True\n", " ```\n", "\n", - "* `int('\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.\n", + "* `int('\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python.\n", "\n", "* You can separate numeric literals with underscores (for better readability) from Python 3 onwards.\n", "\n", @@ -11706,8 +12846,6 @@ " return result\n", " ```\n", " The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string.\n", - "\n", - "**That's all folks!**\n", "\n" ] }, @@ -11760,6 +12898,17 @@ "source": [ "```py\n", ">>> (a := \"wtf_walrus\") # This works though\n", + "```\n", + "```py\n", + "'wtf_walrus'\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", ">>> a\n", "```\n", "```py\n", @@ -11798,6 +12947,17 @@ "source": [ "```py\n", ">>> (a := 6, 9)\n", + "```\n", + "```py\n", + "(6, 9)\n", + "```\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "```py\n", ">>> a\n", "```\n", "```py\n", @@ -11954,7 +13114,7 @@ "\n", "- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. \n", "\n", - "- The syntax of the Walrus operator is of the form `NAME: expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", + "- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, \n", "\n", " - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6')\n", "\n" @@ -12055,7 +13215,7 @@ "metadata": {}, "source": [ "\n", - "Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.\n", + "Phew, deleted at last. You might have guessed what saved `__del__` from being called in our first attempt to delete `x`. Let's add more twists to the example.\n", "\n", "2\\.\n" ] @@ -12104,9 +13264,9 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "+ `del x` doesn\u2019t directly call `x.__del__()`.\n", - "+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x\u2019s reference count reaches zero.\n", - "+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.\n", - "+ Calling `globals` caused the existing reference to be destroyed, and hence we can see \"Deleted!\" being printed (finally!).\n", + "+ When `del x` is encountered, Python deletes the name `x` from current scope and decrements by 1 the reference count of the object `x` referenced. `__del__()` is called only when the object's reference count reaches zero.\n", + "+ In the second output snippet, `__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object (specifically, the `_` magic variable which references the result value of the last non `None` expression on the REPL), thus preventing the reference count from reaching zero when `del y` was encountered.\n", + "+ Calling `globals` (or really, executing anything that will have a non `None` result) caused `_` to reference the new result, dropping the existing reference. Now the reference count reached 0 and we can see \"Deleted!\" being printed (finally!).\n", "\n" ] }, @@ -12184,7 +13344,7 @@ "source": [ "#### \ud83d\udca1 Explanation:\n", "\n", - "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore get imported. This may lead to errors during runtime.\n", + "- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore don't get imported. This may lead to errors during runtime.\n", "- Had we used `from ... import a, b, c` syntax, the above `NameError` wouldn't have occurred.\n" ] }, @@ -12298,6 +13458,7 @@ "* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator\n", "* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65\n", "* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues\n", + "* WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/).\n", "\n", "# \ud83c\udf93 License\n", "\n", From de4b851c72f97d58303a3a09d3a519dc261aa850 Mon Sep 17 00:00:00 2001 From: abdo Date: Wed, 3 Feb 2021 02:01:07 +0300 Subject: [PATCH 041/210] Fix typo getclosurevals -> getclosurevars --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 27ed3ab6..9cadd2af 100644 --- a/README.md +++ b/README.md @@ -1027,7 +1027,7 @@ The values of `x` were different in every iteration prior to appending `some_fun * When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the *variable*, not its *value*. The function looks up `x` in the surrounding context, rather than using the value of `x` at the time the function is created. So all of the functions use the latest value assigned to the variable for computation. We can see that it's using the `x` from the surrounding context (i.e. *not* a local variable) with: ```py >>> import inspect ->>> inspect.getclosurevals(funcs[0]) +>>> inspect.getclosurevars(funcs[0]) ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) ``` Since `x` is a global value, we can change the value that the `funcs` will lookup and return by updating `x`: From 9d0ad9ed98f372f2ad7ae74f4d8e6c50386a5398 Mon Sep 17 00:00:00 2001 From: Umutambyi Gad Date: Sun, 14 Feb 2021 00:55:41 +0100 Subject: [PATCH 042/210] =?UTF-8?q?=F0=9F=93=9D=20Fixed=20simple=20typos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9cadd2af..c6d80b69 100644 --- a/README.md +++ b/README.md @@ -2135,7 +2135,7 @@ UnboundLocalError: local variable 'a' referenced before assignment >>> another_func() 2 ``` -* The keywords `global` and `nonlocal` tell the python interpreter to not delcare new variables and look them up in the corresponding outer scopes. +* The keywords `global` and `nonlocal` tell the python interpreter to not declare new variables and look them up in the corresponding outer scopes. * Read [this](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. --- @@ -3114,7 +3114,7 @@ Ellipsis >>> ... Ellipsis ``` -- Eliipsis can be used for several purposes, +- Ellipsis can be used for several purposes, + As a placeholder for code that hasn't been written yet (just like `pass` statement) + In slicing syntax to represent the full slices in remaining direction ```py From f0bd1cb481947a81a5ea164aa333d5224f194702 Mon Sep 17 00:00:00 2001 From: Chris Milson Date: Thu, 18 Feb 2021 19:05:40 +0900 Subject: [PATCH 043/210] Update explanation for All-true-ation #255 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c6d80b69..7f48185c 100644 --- a/README.md +++ b/README.md @@ -1273,8 +1273,8 @@ Why's this True-False alteration? ``` - `all([])` returns `True` since the iterable is empty. -- `all([[]])` returns `False` because `not []` is `True` is equivalent to `not False` as the list inside the iterable is empty. -- `all([[[]]])` and higher recursive variants are always `True` since `not [[]]`, `not [[[]]]`, and so on are equivalent to `not True`. +- `all([[]])` returns `False` because the passed array has one element, `[]`, and in python, an empty list is falsy. +- `all([[[]]])` and higher recursive variants are always `True`. This is because the passed array's single element (`[[...]]`) is no longer empty, and lists with values are truthy. --- From 6e187cf84b3c23c4fc872b0d99b648d3b3d229ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20De=20Freitas?= <37962411+JoseDeFreitas@users.noreply.github.com> Date: Wed, 24 Feb 2021 19:49:05 -0500 Subject: [PATCH 044/210] Add Spanish translation reference --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f48185c..9a74ca37 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

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

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

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

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From fe9ed47217714e38e527c7b205f458e23c8b3b87 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Wed, 11 May 2022 22:27:47 +0530 Subject: [PATCH 056/210] Update Spanish translation link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6c5ba669..7f6d9ec8 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From be377779b69e45c2174e11142d01d55f4a0e6690 Mon Sep 17 00:00:00 2001 From: Matt Kohl <95224098+mattkohl-flex@users.noreply.github.com> Date: Tue, 31 May 2022 15:36:12 +0100 Subject: [PATCH 057/210] Update README.md Grammatical fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f6d9ec8..b5ee9d74 100644 --- a/README.md +++ b/README.md @@ -619,7 +619,7 @@ True * When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed. * When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same. * So, the object's id is unique only for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id. -* But why did the `is` operator evaluated to `False`? Let's see with this snippet. +* But why did the `is` operator evaluate to `False`? Let's see with this snippet. ```py class WTF(object): def __init__(self): print("I") From d3a25fa14ea0d484aa556053ea0ce2cfcff7a8c0 Mon Sep 17 00:00:00 2001 From: jeffreykennethli Date: Fri, 3 Jun 2022 10:15:21 -0400 Subject: [PATCH 058/210] Update link and add parenthesis to chained operators section --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b5ee9d74..5de07cc6 100644 --- a/README.md +++ b/README.md @@ -384,15 +384,15 @@ False #### 💡 Explanation: -As per https://docs.python.org/3/reference/expressions.html#membership-test-operations +As per https://docs.python.org/3/reference/expressions.html#comparisons > Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once. While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. * `False is False is False` is equivalent to `(False is False) and (False is False)` -* `True is False == False` is equivalent to `True is False and False == False` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. -* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`. +* `True is False == False` is equivalent to `(True is False) and (False == False)` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. +* `1 > 0 < 1` is equivalent to `(1 > 0) and (0 < 1)` which evaluates to `True`. * The expression `(1 > 0) < 1` is equivalent to `True < 1` and ```py >>> int(True) From feeb410009774e9fac21ea76cd9f78964a9e0328 Mon Sep 17 00:00:00 2001 From: Alexander Mayorov Date: Sat, 17 Sep 2022 21:13:35 +0400 Subject: [PATCH 059/210] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5de07cc6..6a13c0fa 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

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

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From ab82f9647cc966a776776a9a6c2cdddf5ec925a3 Mon Sep 17 00:00:00 2001 From: Raigorx Hellscream <10247765+raigorx@users.noreply.github.com> Date: Thu, 31 Aug 2023 17:49:04 -0400 Subject: [PATCH 065/210] Update README.md https://docs.python.org/3/library/collections.abc.html#collections.abc.Hashable --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b3915124..1d5dca79 100644 --- a/README.md +++ b/README.md @@ -1121,7 +1121,7 @@ False **Output:** ```py ->>> from collections import Hashable +>>> from collections.abc import Hashable >>> issubclass(list, object) True >>> issubclass(object, Hashable) From 5e8cfd7dbe8139484a970e162a82e9fa38951e1e Mon Sep 17 00:00:00 2001 From: Raigorx Hellscream <10247765+raigorx@users.noreply.github.com> Date: Fri, 1 Sep 2023 17:05:04 -0400 Subject: [PATCH 066/210] typo: strings-and-the-backslashes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1d5dca79..2ec1c2e9 100644 --- a/README.md +++ b/README.md @@ -1343,7 +1343,7 @@ True ```py >>> r'wt\"f' == 'wt\\"f' True - >>> print(repr(r'wt\"f') + >>> print(repr(r'wt\"f')) 'wt\\"f' >>> print("\n") From 1b1b9d4b7015f71e45cfaa7268e539cef00d499b Mon Sep 17 00:00:00 2001 From: Sean Date: Thu, 5 Oct 2023 16:20:26 +0800 Subject: [PATCH 067/210] Invert logo color for dark theme --- README.md | 2 +- images/logo-dark.png | Bin 0 -> 13052 bytes 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 images/logo-dark.png diff --git a/README.md b/README.md index 1d5dca79..bb3100fc 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

+

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

diff --git a/images/logo-dark.png b/images/logo-dark.png new file mode 100644 index 0000000000000000000000000000000000000000..9d7791f3a30ae76158b3f33d84cdf0f31de2e3c2 GIT binary patch literal 13052 zcmbWe1z4QR(jbhxyJxTjcNqrv!5sz<4DK>mfZ!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Em1noEs#MJ%~RW-v2sB}Y7wDVmfY(`#na7VKZ#o~;0xvRdXmXQ5^ zKjCFD@v%=1Rqcr5dCmsjhub+d{fhL%UFyqZWceAg$}$D(Pz;mp{Wh~2^Lvt13JqJv zYChe7BTh7>lX%j}f$Wq#2GhJR_4wUBd2pcf(|S=_s&l5Z#}h(;qCj0aeT_UcUrV3? z$6-h{n_`j|O!?1Zq%q-}C}jDjTzcu8`}ghV{==yUk&hZ)XInPf3ZEhOUc7TG zg9k@_u+N%Xxj5KRP1mFVPHI|jt4Ch^JioTbouv4a$v}~Uu_0m=X6H8?G#%X3r&SK_ zLe^Q0*~pi(pA@km^rG4ic|dqzD&63mR(S0G_BH9^TlHHCcy*z_9QObZ zyV*k_D;T_OGc56*L;=hu5HIsqCZ{h*?>DKgaKp2ZbL8;YP4$@TOr+oZItEXcDJBkc zV*&mIeTGvVDuQt`5s=3#K=n{`i?KtMqpYs{sjAqP+5Ka$IRmo%Pal{_1TM1zKz_wRZ>(O@SbXhuvT;y>IF@2;gu)SYX0zG*CqGpVsp=&fKeHn@@KH~s1 zj{jlWZTj#~e~0mOJp^QttBrFKEf0&6p#kP&UEniEPouq2Ak}Z4!+WTCRVX8R; Date: Thu, 25 Jan 2024 11:19:34 +0300 Subject: [PATCH 068/210] Translate header to russian - As discussed with maintainer, create folder for storing translations It will give more control, everything will be stored in 1 repository and it eliminates possible deletion or making translation private --- translations/README-ru.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 translations/README-ru.md diff --git a/translations/README-ru.md b/translations/README-ru.md new file mode 100644 index 00000000..897f6583 --- /dev/null +++ b/translations/README-ru.md @@ -0,0 +1,17 @@ +

+

What the f*ck Python! 😱

+

Изучение и понимание Python с помощью нестандартного поведения и "магического" поведения.

+ +Переводы: [English Original](https://github.com/satwikkansal/wtfpython) [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/nifadyev/wtfpython/tree/main/translations/README-ru.md) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) + +Альтернативные способы: [Интерактивный сайт](https://wtfpython-interactive.vercel.app) | [Интерактивный Jupiter notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) + +Python, будучи прекрасно спроектированным высокоуровневым языком программирования, предоставляет множество возможностей для удобства программиста. Но иногда результаты работы Python кода могут показаться неочевидными на первый взгляд. + +**wtfpython** задуман как проект, пытающийся объяснить, что именно происходит под капотом некоторых неочевидных фрагментов кода и менее известных возможностей Python. + +Если вы опытный программист на Python, вы можете принять это как вызов и правильно объяснить WTF ситуации с первой попытки. Возможно, вы уже сталкивались с некоторыми из них раньше, и я смогу оживить ваши старые добрые воспоминания! 😅 + +PS: Если вы уже читали **wtfpython** раньше, с изменениями можно ознакомиться [здесь](https://github.com/satwikkansal/wtfpython/releases/) (примеры, отмеченные звездочкой - это примеры, добавленные в последней основной редакции). + +Ну что ж, приступим... From 489ccb18a7f51ba027a9563fcfb9a1e502652b5a Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 25 Jan 2024 16:34:40 +0300 Subject: [PATCH 069/210] Translate Structure of the Examples to russian --- translations/README-ru.md | 45 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 897f6583..4278ba5f 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -15,3 +15,48 @@ Python, будучи прекрасно спроектированным выс PS: Если вы уже читали **wtfpython** раньше, с изменениями можно ознакомиться [здесь](https://github.com/satwikkansal/wtfpython/releases/) (примеры, отмеченные звездочкой - это примеры, добавленные в последней основной редакции). Ну что ж, приступим... + +# Содержание + +- [Содержание](#содержание) +- [Структура примера](#структура-примера) + + +# Структура примера + +Все примеры имеют следующую структуру: + +> ### ▶ Какой-то заголовок +> +> ```py +> # Неочевидный фрагмент кода +> # Подготовка к магии... +> ``` +> +> **Вывод (Python версия):** +> +> ```py +> >>> triggering_statement +> Неожиданные результаты +> ``` +> +> (Опционально): Краткое описание неожиданного результата +> +> +> #### 💡 Объяснение +> +> * Краткое объяснение того, что происходит и почему это происходит. +> +> ```py +> # Код +> # Дополнительные примеры для дальнейшего разъяснения (если необходимо) +> ``` +> +> **Вывод (Python версия):** +> +> ```py +> >>> trigger # какой-нибудь пример, позволяющий легко раскрыть магию +> # обоснованный вывод +> ``` + +**Важно:** Все примеры протестированы на интерактивном интерпретаторе Python 3.5.2, и они должны работать для всех версий Python, если это явно не указано перед выводом. From b5b8b83c0a8b2a175a81bbfe375804f3130e9b25 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 25 Jan 2024 16:43:04 +0300 Subject: [PATCH 070/210] Translate usage to russian --- translations/README-ru.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/translations/README-ru.md b/translations/README-ru.md index 4278ba5f..9f505338 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -20,7 +20,7 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - [Содержание](#содержание) - [Структура примера](#структура-примера) - +- [Применение](#применение) # Структура примера @@ -60,3 +60,21 @@ PS: Если вы уже читали **wtfpython** раньше, с измен > ``` **Важно:** Все примеры протестированы на интерактивном интерпретаторе Python 3.5.2, и они должны работать для всех версий Python, если это явно не указано перед выводом. + +# Применение + +Хороший способ получить максимальную пользу от этих примеров - читать их последовательно, причем для каждого из них важно: + +- Внимательно изучить исходный код. Если вы опытный программист на Python, то в большинстве случаев сможете предугадать, что произойдет дальше. +- Прочитать фрагменты вывода и, + - Проверить, совпадают ли выходные данные с вашими ожиданиями. + - Убедиться, что вы знаете точную причину, по которой вывод получился именно таким. + - Если ответ отрицательный (что совершенно нормально), сделать глубокий вдох и прочитать объяснение (а если пример все еще непонятен, и создайте issue [здесь](https://github.com/satwikkansal/wtfpython/issues/new)). + - Если "да", ощутите мощь своих познаний в Python и переходите к следующему примеру. + +PS: Вы также можете читать WTFPython в командной строке, используя [pypi package](https://pypi.python.org/pypi/wtfpython), + +```sh +pip install wtfpython -U +wtfpython +``` From 86140390adcaece9fd84ece152af4c8a0701557f Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 25 Jan 2024 17:01:26 +0300 Subject: [PATCH 071/210] Translate First things first! example to russian --- translations/README-ru.md | 127 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 9f505338..325980a3 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -21,6 +21,10 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - [Содержание](#содержание) - [Структура примера](#структура-примера) - [Применение](#применение) +- [👀 Примеры](#-примеры) + - [Секция: Напряги мозги!](#секция-напряги-мозги) + - [▶ Первым делом!](#-первым-делом) + - [💡 Обьяснение](#-обьяснение) # Структура примера @@ -78,3 +82,126 @@ PS: Вы также можете читать WTFPython в командной с pip install wtfpython -U wtfpython ``` + +# 👀 Примеры + +## Секция: Напряги мозги! + +### ▶ Первым делом! + + + + +По какой-то причине "моржовый оператор" (англ. walrus) `:=` в Python 3.8 стал довольно популярным. Давайте проверим его, + +1\. + +```py +# Python version 3.8+ + +>>> a = "wtf_walrus" +>>> a +'wtf_walrus' + +>>> a := "wtf_walrus" +File "", line 1 + a := "wtf_walrus" + ^ +SyntaxError: invalid syntax + +>>> (a := "wtf_walrus") # А этот код работает +'wtf_walrus' +>>> a +'wtf_walrus' +``` + +2 \. + +```py +# Python version 3.8+ + +>>> a = 6, 9 +>>> a +(6, 9) + +>>> (a := 6, 9) +(6, 9) +>>> a +6 + +>>> a, b = 6, 9 # Типичная распаковка +>>> a, b +(6, 9) +>>> (a, b = 16, 19) # Упс + File "", line 1 + (a, b = 16, 19) + ^ +SyntaxError: invalid syntax + +>>> (a, b := 16, 19) # На выводе получаем странный кортеж из 3 элементов +(6, 16, 19) + +>>> a # Значение переменной остается неизменной? +6 + +>>> b +16 +``` + +#### 💡 Обьяснение + +**Быстрый разбор что такое "моржовый оператор"** + +"Моржовый оператор" (`:=`) был представлен в Python 3.8, может быть полезен в ситуациях, когда вы хотите присвоить значения переменным в выражении. + +```py +def some_func(): + # Предположим, что здесь выполняются требовательные к ресурсам вычисления + # time.sleep(1000) + return 5 + +# Поэтому вместо, +if some_func(): + print(some_func()) # Плохая практика, поскольку вычисления происходят дважды. + +# Или +a = some_func() +if a: + print(a) + +# Можно лаконично написать +if a := some_func(): + print(a) +``` + +**Вывод (> 3.8):** + +```py +5 +5 +5 +``` + +Использование `:=` сэкономило одну строку кода и неявно предотвратило вызов `some_func` дважды. + +- "выражение присваивания", не обернутое в скобки, иначе говоря использование моржового оператора, ограничено на верхнем уровне, отсюда `SyntaxError` в выражении `a := "wtf_walrus"` в первом фрагменте. После оборачивания в скобки, `a` было присвоено значение, как и ожидалось. + +- В то же время оборачивание скобками выражения, содержащего оператор `=`, не допускается. Отсюда синтаксическая ошибка в `(a, b = 6, 9)`. + +- Синтаксис моржового оператора имеет вид `NAME:= expr`, где `NAME` - допустимый идентификатор, а `expr` - допустимое выражение. Следовательно, упаковка и распаковка итерируемых объектов не поддерживается, что означает, + + - `(a := 6, 9)` эквивалентно `((a := 6), 9)` и в конечном итоге `(a, 9)` (где значение `a` равно `6`) + + ```py + >>> (a := 6, 9) == ((a := 6), 9) + True + >>> x = (a := 696, 9) + >>> x + (696, 9) + >>> x[0] is a # Оба ссылаются на одну и ту же ячейку памяти + True + ``` + + - Аналогично, `(a, b := 16, 19)` эквивалентно `(a, (b := 16), 19)`, которое есть не что иное, как кортеж из 3 элементов. + +--- From c91a6073fbf0916a0c003b48e4903c3f53213889 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 30 Jan 2024 21:33:44 +0300 Subject: [PATCH 072/210] Translate Strings can be tricky sometimes example to russian --- translations/README-ru.md | 79 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 325980a3..3e7170b9 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -25,6 +25,8 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - [Секция: Напряги мозги!](#секция-напряги-мозги) - [▶ Первым делом!](#-первым-делом) - [💡 Обьяснение](#-обьяснение) + - [▶ Строки иногда ведут себя непредсказуемо](#-строки-иногда-ведут-себя-непредсказуемо) + - [💡 Объяснение](#-объяснение) # Структура примера @@ -205,3 +207,80 @@ if a := some_func(): - Аналогично, `(a, b := 16, 19)` эквивалентно `(a, (b := 16), 19)`, которое есть не что иное, как кортеж из 3 элементов. --- + +### ▶ Строки иногда ведут себя непредсказуемо + + +1\. + +```py +>>> a = "some_string" +>>> id(a) +140420665652016 +>>> id("some" + "_" + "string") # Обратите внимание, оба идентификатора одинаковы +140420665652016 +``` + +2\. + +```py +>>> a = "wtf" +>>> b = "wtf" +>>> a is b +True + +>>> a = "wtf!" +>>> b = "wtf!" +>>> a is b +False +``` + +3\. + +```py +>>> a, b = "wtf!", "wtf!" +>>> a is b # Актуально для версий Python, кроме 3.7.x +True + +>>> a = "wtf!"; b = "wtf!" +>>> a is b # Выражение вернет True или False в зависимости вызываемой среды (python shell / ipython / скрипт). +False +``` + +```py +# На этот раз в файле +a = "wtf!" +b = "wtf!" +print(a is b) + +# Выводит True при запуске модуля +``` + +4\. + +**Output (< Python3.7 )** + +```py +>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' +True +>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' +False +``` + +Логично, правда? + +#### 💡 Объяснение + +- Поведение в первом и втором фрагментах связано с оптимизацией CPython (называемой интернированием строк ((англ. string interning))), которая пытается использовать существующие неизменяемые объекты в некоторых случаях вместо того, чтобы каждый раз создавать новый объект. +- После "интернирования" многие переменные могут ссылаться на один и тот же строковый объект в памяти (тем самым экономя память). +- В приведенных выше фрагментах строки неявно интернированы. Решение о том, когда неявно интернировать строку, зависит от реализации. Правила для интернирования строк следующие: + - Все строки длиной 0 или 1 символа интернируются. + - Строки интернируются во время компиляции (`'wtf'` будет интернирована, но `''.join(['w'', 't'', 'f'])` - нет) + - Строки, не состоящие из букв ASCII, цифр или знаков подчеркивания, не интернируются. В примере выше `'wtf!'` не интернируется из-за `!`. Реализацию этого правила в CPython можно найти [здесь](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) + ![image](/images/string-intern/string_intern.png) +- Когда переменные `a` и `b` принимают значение `"wtf!"` в одной строке, интерпретатор Python создает новый объект, а затем одновременно ссылается на вторую переменную. Если это выполняется в отдельных строках, он не "знает", что уже существует `"wtf!"` как объект (потому что `"wtf!"` не является неявно интернированным в соответствии с фактами, упомянутыми выше). Это оптимизация во время компиляции, не применяется к версиям CPython 3.7.x (более подробное обсуждение смотрите здесь [issue](https://github.com/satwikkansal/wtfpython/issues/100)). +- Единица компиляции в интерактивной среде IPython состоит из одного оператора, тогда как в случае модулей она состоит из всего модуля. `a, b = "wtf!", "wtf!"` - это одно утверждение, тогда как `a = "wtf!"; b = "wtf!"` - это два утверждения в одной строке. Это объясняет, почему тождества различны в `a = "wtf!"; b = "wtf!"`, но одинаковы при вызове в модуле. +- Резкое изменение в выводе четвертого фрагмента связано с [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) техникой, известной как складывание констант (англ. Constant folding). Это означает, что выражение `'a'*20` заменяется на `'aaaaaaaaaaaaaaaaaaaa'` во время компиляции, чтобы сэкономить несколько тактов во время выполнения. Складывание констант происходит только для строк длиной менее 21. (Почему? Представьте себе размер файла `.pyc`, созданного в результате выполнения выражения `'a'*10**10`). [Вот](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) исходный текст реализации для этого. +- Примечание: В Python 3.7 складывание констант было перенесено из оптимизатора peephole в новый оптимизатор AST с некоторыми изменениями в логике, поэтому четвертый фрагмент не работает в Python 3.7. Подробнее об изменении можно прочитать [здесь](https://bugs.python.org/issue11549). + +--- From e2d6ee66ccd58ebfe0a188b2ea73cf7c961aa01c Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 18 Apr 2024 14:45:13 +0300 Subject: [PATCH 073/210] Translate Be careful with chained operations example --- translations/README-ru.md | 49 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/translations/README-ru.md b/translations/README-ru.md index 3e7170b9..92b9e822 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -275,7 +275,7 @@ False - После "интернирования" многие переменные могут ссылаться на один и тот же строковый объект в памяти (тем самым экономя память). - В приведенных выше фрагментах строки неявно интернированы. Решение о том, когда неявно интернировать строку, зависит от реализации. Правила для интернирования строк следующие: - Все строки длиной 0 или 1 символа интернируются. - - Строки интернируются во время компиляции (`'wtf'` будет интернирована, но `''.join(['w'', 't'', 'f'])` - нет) + - Строки интернируются во время компиляции (`'wtf'` будет интернирована, но `''.join(['w'', 't', 'f'])` - нет) - Строки, не состоящие из букв ASCII, цифр или знаков подчеркивания, не интернируются. В примере выше `'wtf!'` не интернируется из-за `!`. Реализацию этого правила в CPython можно найти [здесь](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) ![image](/images/string-intern/string_intern.png) - Когда переменные `a` и `b` принимают значение `"wtf!"` в одной строке, интерпретатор Python создает новый объект, а затем одновременно ссылается на вторую переменную. Если это выполняется в отдельных строках, он не "знает", что уже существует `"wtf!"` как объект (потому что `"wtf!"` не является неявно интернированным в соответствии с фактами, упомянутыми выше). Это оптимизация во время компиляции, не применяется к версиям CPython 3.7.x (более подробное обсуждение смотрите здесь [issue](https://github.com/satwikkansal/wtfpython/issues/100)). @@ -284,3 +284,50 @@ False - Примечание: В Python 3.7 складывание констант было перенесено из оптимизатора peephole в новый оптимизатор AST с некоторыми изменениями в логике, поэтому четвертый фрагмент не работает в Python 3.7. Подробнее об изменении можно прочитать [здесь](https://bugs.python.org/issue11549). --- + + +### ▶ Осторожнее с цепочкой операций + +```py +>>> (False == False) in [False] # логично +False +>>> False == (False in [False]) # все еще логично +False +>>> False == False in [False] # а теперь что? + +True + +>>> True is False == False +False +>>> False is False is False +True + +>>> 1 > 0 < 1 +True +>>> (1 > 0) < 1 +False +>>> 1 > (0 < 1) +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 и b op2 c и ... y opN z, за исключением того, что каждое выражение оценивается не более одного раза. + +Хотя такое поведение может показаться глупым в приведенных выше примерах, оно просто фантастично для таких вещей, как `a == b == c` и `0 <= x <= 100`. + +* `False is False is False` эквивалентно `(False is False) и (False is False)`. +* `True is False == False` эквивалентно `(True is False) and (False == False)` и так как первая часть высказывания (`True is False`) оценивается в `False`, то все выражение приводится к `False`. +* `1 > 0 < 1` эквивалентно `(1 > 0) и (0 < 1)`, которое приводится к `True`. +* Выражение `(1 > 0) < 1` эквивалентно `True < 1` и + ```py + >>> int(True) + 1 + >>> True + 1 # не относится к данному примеру, но просто для интереса + 2 + ``` + В итоге, `1 < 1` выполняется и дает результат `False` + +--- From a7985b9edc4a17165d2715126d6a806612511f46 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 18 Apr 2024 15:08:23 +0300 Subject: [PATCH 074/210] Translate How not to use is operator example --- translations/README-ru.md | 125 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 92b9e822..f1d9cf9c 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -331,3 +331,128 @@ False В итоге, `1 < 1` выполняется и дает результат `False` --- + + +### ▶ Как не надо использовать оператор `is` + +Ниже приведен очень известный пример. + +1\. + +```py +>>> a = 256 +>>> b = 256 +>>> a is b +True + +>>> a = 257 +>>> b = 257 +>>> a is b +False +``` + +2\. + +```py +>>> a = [] +>>> b = [] +>>> a is b +False + +>>> a = tuple() +>>> b = tuple() +>>> a is b +True +``` + +3\. +**Результат** + +```py +>>> a, b = 257, 257 +>>> a is b +True +``` + +**Вывод (только для Python 3.7.x)** + +```py +>>> a, b = 257, 257 +>>> a is b +False +``` + +#### 💡 Объяснение: + +**Разница между `is` и `==`**. + +* Оператор `is` проверяет, ссылаются ли оба операнда на один и тот же объект (т.е. проверяет, совпадают ли идентификаторы операндов или нет). +* Оператор `==` сравнивает значения обоих операндов и проверяет, одинаковы ли они. +* Таким образом, оператор `is` предназначен для равенства ссылок, а `==` - для равенства значений. Пример, чтобы прояснить ситуацию, + ```py + >>> class A: pass + >>> A() is A() # 2 пустых объекта в разных ячейках памяти + False + ``` + +**`256` - существующий объект, а `257` - нет**. + +При запуске python числа от `-5` до `256` записываются в память. Эти числа используются часто, поэтому имеет смысл просто иметь их наготове. + +Перевод цитаты из [документации](https://docs.python.org/3/c-api/long.html) +> Текущая реализация хранит массив целочисленных объектов для всех целых чисел от -5 до 256, когда вы создаете int в этом диапазоне, вы просто получаете обратно ссылку на существующий объект. + +```py +>>> id(256) +10922528 +>>> a = 256 +>>> b = 256 +>>> id(a) +10922528 +>>> id(b) +10922528 +>>> id(257) +140084850247312 +>>> x = 257 +>>> y = 257 +>>> id(x) +140084850247440 +>>> id(y) +140084850247344 +``` + +Интерпретатор не понимает, что до выполнения выражения `y = 257` целое число со значением `257` уже создано, и поэтому он продолжает создавать другой объект в памяти. + +Подобная оптимизация применима и к другим **изменяемым** объектам, таким как пустые кортежи. Поскольку списки являются изменяемыми, поэтому `[] is []` вернет `False`, а `() is ()` вернет `True`. Это объясняет наш второй фрагмент. Перейдем к третьему, + +**И `a`, и `b` ссылаются на один и тот же объект при инициализации одним и тем же значением в одной и той же строкеi**. + +**Вывод** + +```py +>>> a, b = 257, 257 +>>> id(a) +140640774013296 +>>> id(b) +140640774013296 +>>> a = 257 +>>> b = 257 +>>> id(a) +140640774013392 +>>> id(b) +140640774013488 +``` + +* Когда a и b инициализируются со значением `257` в одной строке, интерпретатор Python создает новый объект, а затем одновременно ссылается на него во второй переменной. Если делать это в отдельных строках, интерпретатор не "знает", что объект `257` уже существует. + +* Это оптимизация компилятора и относится именно к интерактивной среде. Когда вы вводите две строки в интерпретаторе, они компилируются отдельно, поэтому оптимизируются отдельно. Если выполнить этот пример в файле `.py', поведение будет отличаться, потому что файл компилируется весь сразу. Эта оптимизация не ограничивается целыми числами, она работает и для других неизменяемых типов данных, таких как строки (проверьте пример "Строки - это сложно") и плавающие числа, + + ```py + >>> a, b = 257.0, 257.0 + >>> a is b + True + ``` + +* Почему это не сработало в Python 3.7? Абстрактная причина в том, что такие оптимизации компилятора зависят от реализации (т.е. могут меняться в зависимости от версии, ОС и т.д.). Я все еще выясняю, какое именно изменение реализации вызвало проблему, вы можете проверить этот [issue](https://github.com/satwikkansal/wtfpython/issues/100) для получения обновлений. + +--- From 2840050acb1dbd6f3b67faf7b676c441bdd3e9a1 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 19 Apr 2024 12:10:22 +0300 Subject: [PATCH 075/210] Translate Hash brownies and Deep down, we're all the same examples --- translations/README-ru.md | 117 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index f1d9cf9c..358317c6 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -456,3 +456,120 @@ False * Почему это не сработало в Python 3.7? Абстрактная причина в том, что такие оптимизации компилятора зависят от реализации (т.е. могут меняться в зависимости от версии, ОС и т.д.). Я все еще выясняю, какое именно изменение реализации вызвало проблему, вы можете проверить этот [issue](https://github.com/satwikkansal/wtfpython/issues/100) для получения обновлений. --- + + +### ▶ Мистическое хэширование + +1\. +```py +some_dict = {} +some_dict[5.5] = "JavaScript" +some_dict[5.0] = "Ruby" +some_dict[5] = "Python" +``` + +**Вывод:** + +```py +>>> some_dict[5.5] +"JavaScript" +>>> some_dict[5.0] # "Python" уничтожил "Ruby"? +"Python" +>>> some_dict[5] +"Python" + +>>> complex_five = 5 + 0j +>>> type(complex_five) +complex +>>> some_dict[complex_five] +"Python" +``` + +Так почему же Python повсюду? + + +#### 💡 Объяснение + +* Уникальность ключей в словаре Python определяется *эквивалентностью*, а не тождеством. Поэтому, даже если `5`, `5.0` и `5 + 0j` являются различными объектами разных типов, поскольку они равны, они не могут находиться в одном и том же `dict` (или `set`). Как только вы вставите любой из них, попытка поиска по любому другому, но эквивалентному ключу будет успешной с исходным сопоставленным значением (а не завершится ошибкой `KeyError`): + ```py + >>> 5 == 5.0 == 5 + 0j + True + >>> 5 is not 5.0 is not 5 + 0j + True + >>> some_dict = {} + >>> some_dict[5.0] = "Ruby" + >>> 5.0 in some_dict + True + >>> (5 in some_dict) and (5 + 0j in some_dict) + True + ``` +* Это применимо и во время присваения значения элементу. Поэтому, в выражении `some_dict[5] = "Python"` Python находит существующий элемент с эквивалентным ключом `5.0 -> "Ruby"`, перезаписывает его значение на место, а исходный ключ оставляет в покое. + ```py + >>> some_dict + {5.0: 'Ruby'} + >>> some_dict[5] = "Python" + >>> some_dict + {5.0: 'Python'} + ``` +* Итак, как мы можем обновить ключ до `5` (вместо `5.0`)? На самом деле мы не можем сделать это обновление на месте, но что мы можем сделать, так это сначала удалить ключ (`del some_dict[5.0]`), а затем установить его (`some_dict[5]`), чтобы получить целое число `5` в качестве ключа вместо плавающего `5.0`, хотя это нужно в редких случаях. + +* Как Python нашел `5` в словаре, содержащем `5.0`? Python делает это за постоянное время без необходимости сканирования каждого элемента, используя хэш-функции. Когда Python ищет ключ `foo` в словаре, он сначала вычисляет `hash(foo)` (что выполняется в постоянном времени). Поскольку в Python требуется, чтобы объекты, которые сравниваются одинаково, имели одинаковое хэш-значение ([docs](https://docs.python.org/3/reference/datamodel.html#object.__hash__) здесь), `5`, `5.0` и `5 + 0j` имеют одинаковое хэш-значение. + ```py + >>> 5 == 5.0 == 5 + 0j + True + >>> hash(5) == hash(5.0) == hash(5 + 0j) + True + ``` + **Примечание:** Обратное не обязательно верно: Объекты с одинаковыми хэш-значениями сами могут быть неравными. (Это вызывает так называемую [хэш-коллизию](https://en.wikipedia.org/wiki/Collision_(computer_science)) и ухудшает производительность постоянного времени, которую обычно обеспечивает хэширование). + +--- + + +### ▶ В глубине души мы все одинаковы. + +```py +class WTF: + pass +``` + +**Вывод:** +```py +>>> WTF() == WTF() # разные экземпляры класса не могут быть равны +False +>>> WTF() is WTF() # идентификаторы также различаются +False +>>> hash(WTF()) == hash(WTF()) # хэши тоже должны отличаться +True +>>> id(WTF()) == id(WTF()) +True +``` +#### 💡 Объяснение: + +* При вызове `id` Python создал объект класса `WTF` и передал его функции `id`. Функция `id` забирает свой `id` (местоположение в памяти) и выбрасывает объект. Объект уничтожается. +* Когда мы делаем это дважды подряд, Python выделяет ту же самую область памяти и для второго объекта. Поскольку (в CPython) `id` использует участок памяти в качестве идентификатора объекта, идентификатор двух объектов одинаков. +* Таким образом, id объекта уникален только во время жизни объекта. После уничтожения объекта или до его создания, другой объект может иметь такой же id. +* Но почему выражение с оператором `is` равно `False`? Давайте посмотрим с помощью этого фрагмента. + ```py + class WTF(object): + def __init__(self): print("I") + def __del__(self): print("D") + ``` + + **Вывод:** + ```py + >>> WTF() is WTF() + I + I + D + D + False + >>> id(WTF()) == id(WTF()) + I + D + I + D + True + ``` + Как вы можете заметить, все дело в порядке уничтожения объектов. + +--- From 47fa96c31a1ba190dcea437ccc957896c26597d2 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 19 Apr 2024 12:28:37 +0300 Subject: [PATCH 076/210] Translate Disorder within order example --- translations/README-ru.md | 99 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 358317c6..a6835777 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -573,3 +573,102 @@ True Как вы можете заметить, все дело в порядке уничтожения объектов. --- + + +### ▶ Беспорядок внутри порядка * + +```py +from collections import OrderedDict + +dictionary = dict() +dictionary[1] = 'a'; dictionary[2] = 'b'; + +ordered_dict = OrderedDict() +ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; + +another_ordered_dict = OrderedDict() +another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; + +class DictWithHash(dict): + """ + A dict that also implements __hash__ magic. + """ + __hash__ = lambda self: 0 + +class OrderedDictWithHash(OrderedDict): + """ + An OrderedDict that also implements __hash__ magic. + """ + __hash__ = lambda self: 0 +``` + +**Вывод** +```py +>>> dictionary == ordered_dict # a == b +True +>>> dictionary == another_ordered_dict # b == c +True +>>> ordered_dict == another_ordered_dict # почему же c != a ?? +False + +# Мы все знаем, что множество состоит только из уникальных элементов, +# давайте попробуем составить множество из этих словарей и посмотрим, что получится... + +>>> len({dictionary, ordered_dict, another_ordered_dict}) +Traceback (most recent call last): + File "", line 1, in +TypeError: unhashable type: 'dict' + +# Логично, поскольку в словаре не реализовано магический метод __hash__, попробуем использовать +# наши классы-обертки. +>>> dictionary = DictWithHash() +>>> dictionary[1] = 'a'; dictionary[2] = 'b'; +>>> ordered_dict = OrderedDictWithHash() +>>> ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; +>>> another_ordered_dict = OrderedDictWithHash() +>>> another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; +>>> len({dictionary, ordered_dict, another_ordered_dict}) +1 +>>> len({ordered_dict, another_ordered_dict, dictionary}) # changing the order +2 +``` + +Что здесь происходит? + +#### 💡 Объяснение: + +- Переходное (интрантизивное) равенство между `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` и другими объектами Mapping нечувствительны к порядку, как обычные словари. +- Причина такого поведения равенства в том, что оно позволяет напрямую подставлять объекты `OrderedDict` везде, где используется обычный словарь. +- Итак, почему изменение порядка влияет на длину генерируемого объекта `set`? Ответ заключается только в отсутствии переходного равенства. Поскольку множества являются "неупорядоченными" коллекциями уникальных элементов, порядок вставки элементов не должен иметь значения. Но в данном случае он имеет значение. Давайте немного разберемся в этом, + ```py + >>> some_set = set() + >>> some_set.add(dictionary) # используем объекты из фрагмента кода выше + >>> 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_ordered_dict` в `another_set` равно `False`, потому что `ordered_dict` уже присутствовал в `another_set` и, как было замечено ранее, `ordered_dict == another_ordered_dict` равно `False`. + +--- From 83bdff8e3379aa046bb60346b91b163785be6506 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 19 Apr 2024 12:36:33 +0300 Subject: [PATCH 077/210] Translate Keep trying example --- translations/README-ru.md | 61 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index a6835777..d164aaf4 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -672,3 +672,64 @@ TypeError: unhashable type: 'dict' Таким образом, выражение `another_ordered_dict` в `another_set` равно `False`, потому что `ordered_dict` уже присутствовал в `another_set` и, как было замечено ранее, `ordered_dict == another_ordered_dict` равно `False`. --- + + +### ▶ Продолжай пытаться... * + +```py +def some_func(): + try: + return 'from_try' + finally: + return 'from_finally' + +def another_func(): + for _ in range(3): + try: + continue + finally: + print("Finally!") + +def one_more_func(): # Попался! + try: + for i in range(3): + try: + 1 / i + except ZeroDivisionError: + # Вызовем исключение и обработаем его за пределами цикла + raise ZeroDivisionError("A trivial divide by zero error") + finally: + print("Iteration", i) + break + except ZeroDivisionError as e: + print("Zero division error occurred", e) +``` + +**Результат:** + +```py +>>> some_func() +'from_finally' + +>>> another_func() +Finally! +Finally! +Finally! + +>>> 1 / 0 +Traceback (most recent call last): + File "", line 1, in +ZeroDivisionError: division by zero + +>>> one_more_func() +Iteration 0 + +``` + +#### 💡 Объяснение: + +- Когда один из операторов `return`, `break` или `continue` выполняется в блоке `try` оператора "try...finally", на выходе также выполняется пункт `finally`. +- Возвращаемое значение функции определяется последним выполненным оператором `return`. Поскольку блок `finally` выполняется всегда, оператор `return`, выполненный в блоке `finally`, всегда будет последним. +- Предостережение - если в блоке `finally` выполняется оператор `return` или `break`, то временно сохраненное исключение отбрасывается. + +--- From 654da92e887babdec7994b64b819e93c33e7859b Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 19 Apr 2024 12:43:52 +0300 Subject: [PATCH 078/210] Translate For what? example --- translations/README-ru.md | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index d164aaf4..5b584edb 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -733,3 +733,57 @@ Iteration 0 - Предостережение - если в блоке `finally` выполняется оператор `return` или `break`, то временно сохраненное исключение отбрасывается. --- + + +### ▶ Для чего? + +```py +some_string = "wtf" +some_dict = {} +for i, some_dict[i] in enumerate(some_string): + i = 10 +``` + +**Вывод:** +```py +>>> some_dict # Словарь с индексами +{0: 'w', 1: 't', 2: 'f'} +``` + +#### 💡 Объяснение: + +* Оператор `for` определяется в [грамматике Python](https://docs.python.org/3/reference/grammar.html) как: + ``` + for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] + ``` + Где `exprlist` - цель присваивания. Это означает, что эквивалент `{exprlist} = {next_value}` **выполняется для каждого элемента** в итерируемом объекте. + Интересный пример, иллюстрирующий это: + ```py + for i in range(4): + print(i) + i = 10 + ``` + + **Результат:** + ``` + 0 + 1 + 2 + 3 + ``` + + Не ожидали, что цикл будет запущен только один раз? + + **💡 Объяснение:**. + + - Оператор присваивания `i = 10` никогда не влияет на итерации цикла из-за того, как циклы for работают в Python. Перед началом каждой итерации следующий элемент, предоставляемый итератором (в данном случае `range(4)`), распаковывается и присваивается переменной целевого списка (в данном случае `i`). + +* Функция `enumerate(some_string)` на каждой итерации выдает новое значение `i` (счетчик-инкремент) и символ из `some_string`. Затем она устанавливает (только что присвоенный) ключ `i` словаря `some_dict` на этот символ. Развертывание цикла можно упростить следующим образом: + ```py + >>> i, some_dict[i] = (0, 'w') + >>> i, some_dict[i] = (1, 't') + >>> i, some_dict[i] = (2, 'f') + >>> some_dict + ``` + +--- From 259fb23c7b0fd3ab6b32d809c7fa051eddc8f16b Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 19 Apr 2024 14:27:26 +0300 Subject: [PATCH 079/210] Translate Evaluation time discrepancy example --- translations/README-ru.md | 69 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 5b584edb..d89a3cec 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -787,3 +787,72 @@ for i, some_dict[i] in enumerate(some_string): ``` --- + + +### ▶ Расхождение во времени исполнения + +1\. +```py +array = [1, 8, 15] +# Типичный генератор +gen = (x for x in array if array.count(x) > 0) +array = [2, 8, 22] +``` + +**Вывод:** + +```py +>>> print(list(gen)) # Куда подевались остальные значения? +[8] +``` + +2\. + +```py +array_1 = [1,2,3,4] +gen_1 = (x for x in array_1) +array_1 = [1,2,3,4,5] + +array_2 = [1,2,3,4] +gen_2 = (x for x in array_2) +array_2[:] = [1,2,3,4,5] +``` + +**Вывод:** +```py +>>> print(list(gen_1)) +[1, 2, 3, 4] + +>>> print(list(gen_2)) +[1, 2, 3, 4, 5] +``` + +3\. + +```py +array_3 = [1, 2, 3] +array_4 = [10, 20, 30] +gen = (i + j for i in array_3 for j in array_4) + +array_3 = [4, 5, 6] +array_4 = [400, 500, 600] +``` + +**Вывод:** +```py +>>> print(list(gen)) +[401, 501, 601, 402, 502, 602, 403, 503, 603] +``` + +#### 💡 Пояснение + +- В выражении [генераторе](https://wiki.python.org/moin/Generators) условие `in` оценивается во время объявления, но условие `if` оценивается во время выполнения. +- Перед выполнением кода, значение переменной `array` изменяется на список `[2, 8, 22]`, а поскольку из `1`, `8` и `15` только счетчик `8` больше `0`, генератор выдает только `8`. +- Различия в выводе `g1` и `g2` во второй части связаны с тем, как переменным `array_1` и `array_2` присваиваются новые значения. + - В первом случае `array_1` привязывается к новому объекту `[1,2,3,4,5]`, а поскольку `in` выражение исполняется во время объявления, оно по-прежнему ссылается на старый объект `[1,2,3,4]` (который не уничтожается). + - Во втором случае присвоение среза `array_2` обновляет тот же старый объект `[1,2,3,4]` до `[1,2,3,4,5]`. Следовательно, и `g2`, и `array_2` по-прежнему имеют ссылку на один и тот же объект (который теперь обновлен до `[1,2,3,4,5]`). +- Хорошо, следуя приведенной выше логике, не должно ли значение `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-выражение исполняется немедленно, остальные выражения откладываются до запуска генератора. + +--- From 497b9de72b073a38c071f4170073b513e5c3f7b2 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 19 Apr 2024 14:31:02 +0300 Subject: [PATCH 080/210] Translate is not ...is (not ...) example --- translations/README-ru.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/translations/README-ru.md b/translations/README-ru.md index d89a3cec..0f4387d5 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -844,7 +844,7 @@ array_4 = [400, 500, 600] [401, 501, 601, 402, 502, 602, 403, 503, 603] ``` -#### 💡 Пояснение +#### 💡 Объяснение - В выражении [генераторе](https://wiki.python.org/moin/Generators) условие `in` оценивается во время объявления, но условие `if` оценивается во время выполнения. - Перед выполнением кода, значение переменной `array` изменяется на список `[2, 8, 22]`, а поскольку из `1`, `8` и `15` только счетчик `8` больше `0`, генератор выдает только `8`. @@ -856,3 +856,21 @@ array_4 = [400, 500, 600] > Только крайнее for-выражение исполняется немедленно, остальные выражения откладываются до запуска генератора. --- + + +### ▶ `is not ...` не является `is (not ...)` + +```py +>>> 'something' is not None +True +>>> 'something' is (not None) +False +``` + +#### 💡 Объяснение + +- `is not` является единым бинарным оператором, и его поведение отличается от раздельного использования `is` и `not`. +- `is not` имеет значение `False`, если переменные по обе стороны оператора указывают на один и тот же объект, и `True` в противном случае. +- В примере `(not None)` оценивается в `True`, поскольку значение `None` является `False` в булевом контексте, поэтому выражение становится `'something' is True`. + +--- From 361ac5f49ba590b3d33697a28d23eb2e9be1b74e Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 19 Apr 2024 14:41:30 +0300 Subject: [PATCH 081/210] Translate A tic-tac-toe where X wins in the first attempt! example --- translations/README-ru.md | 48 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 0f4387d5..6e390806 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -874,3 +874,51 @@ False - В примере `(not None)` оценивается в `True`, поскольку значение `None` является `False` в булевом контексте, поэтому выражение становится `'something' is True`. --- + + +### ▶ Крестики-нолики, где X побеждает с первой попытки! + + +```py +# Инициализируем переменную row +row = [""] * 3 #row i['', '', ''] +# Инициализируем игровую сетку +board = [row] * 3 +``` + +**Результат:** + +```py +>>> board +[['', '', ''], ['', '', ''], ['', '', '']] +>>> board[0] +['', '', ''] +>>> board[0][0] +'' +>>> board[0][0] = "X" +>>> board +[['X', '', ''], ['X', '', ''], ['X', '', '']] +``` + +Мы же не назначили три `"Х"`? + +#### 💡 Объяснение: + +Когда мы инициализируем переменную `row`, эта визуализация объясняет, что происходит в памяти + +![image](/images/tic-tac-toe/after_row_initialized.png) + +А когда переменная `board` инициализируется путем умножения `row`, вот что происходит в памяти (каждый из элементов `board[0]`, `board[1]` и `board[2]` является ссылкой на тот же список, на который ссылается `row`) + +![image](/images/tic-tac-toe/after_board_initialized.png) + +Мы можем избежать этого сценария, не используя переменную `row` для генерации `board`. (Подробнее в [issue](https://github.com/satwikkansal/wtfpython/issues/68)). + +```py +>>> board = [['']*3 for _ in range(3)] +>>> board[0][0] = "X" +>>> board +[['X', '', ''], ['', '', ''], ['', '', '']] +``` + +--- From 4576463fccebbf9cfabd9f904bde94e1dc013795 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 19 Apr 2024 15:02:10 +0300 Subject: [PATCH 082/210] =?UTF-8?q?Translate=20=20Schr=C3=B6dinger's=20var?= =?UTF-8?q?iable=20*=20example?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- translations/README-ru.md | 77 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 6e390806..09df51c8 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -922,3 +922,80 @@ board = [row] * 3 ``` --- + + +### ▶ Переменная Шредингера * + + + +```py +funcs = [] +results = [] +for x in range(7): + def some_func(): + return x + funcs.append(some_func) + results.append(some_func()) # обратите внимание на вызов функции + +funcs_results = [func() for func in funcs] +``` + +**Вывод (Python version):** +```py +>>> results +[0, 1, 2, 3, 4, 5, 6] +>>> funcs_results +[6, 6, 6, 6, 6, 6, 6] +``` + +Значения `x` были разными в каждой итерации до добавления `some_func` к `funcs`, но все функции возвращают `6`, когда они исполняются после завершения цикла. + +2. + +```py +>>> powers_of_x = [lambda x: x**i for i in range(10)] +>>> [f(2) for f in powers_of_x] +[512, 512, 512, 512, 512, 512, 512, 512, 512, 512] +``` + +#### 💡 Объяснение: +* При определении функции внутри цикла, которая использует переменную цикла в своем теле, цикл функции привязывается к *переменной*, а не к ее *значению*. Функция ищет `x` в окружающем контексте, а не использует значение `x` на момент создания функции. Таким образом, все функции используют для вычислений последнее значение, присвоенное переменной. Мы можем видеть, что используется `x` из глобального контекста (т.е. *не* локальная переменная): +```py +>>> import inspect +>>> inspect.getclosurevars(funcs[0]) +ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) +``` +Так как `x` - глобальная переменная, можно изменить ее значение, которое будет использовано и возвращено из `funcs` + +```py +>>> x = 42 +>>> [func() for func in funcs] +[42, 42, 42, 42, 42, 42, 42] +``` + +* Чтобы получить желаемое поведение, вы можете передать переменную цикла как именованную переменную в функцию. **Почему это работает?** Потому что это определит переменную *внутри* области видимости функции. Она больше не будет обращаться к глобальной области видимости для поиска значения переменной, а создаст локальную переменную, которая будет хранить значение `x` в данный момент времени. + +```py +funcs = [] +for x in range(7): + def some_func(x=x): + return x + funcs.append(some_func) +``` + +**Вывод:** + +```py +>>> funcs_results = [func() for func in funcs] +>>> funcs_results +[0, 1, 2, 3, 4, 5, 6] +``` + +`x` больше не используется в глобальной области видимости + +```py +>>> inspect.getclosurevars(funcs[0]) +ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) +``` + +--- From 446a3a09bb04556dc5d2423339b1e8845ec18b0e Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sun, 21 Apr 2024 10:32:21 +0300 Subject: [PATCH 083/210] Translate Chicken egg problem example --- translations/README-ru.md | 51 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 09df51c8..3d299f3f 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -999,3 +999,54 @@ ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) ``` --- + + +### ▶ Проблема курицы и яйца * + +1\. +```py +>>> isinstance(3, int) +True +>>> isinstance(type, object) +True +>>> isinstance(object, type) +True +``` + +Так какой же базовый класс является "окончательным"? Кстати, это еще не все, + +2\. + +```py +>>> class A: pass +>>> isinstance(A, A) +False +>>> isinstance(type, type) +True +>>> isinstance(object, object) +True +``` + +3\. + +```py +>>> issubclass(int, object) +True +>>> issubclass(type, object) +True +>>> issubclass(object, type) +False +``` + + +#### 💡 Объяснение + +- `type` - это [метакласс](https://realpython.com/python-metaclasses/) в Python. +- **Все** в Python является `объектом`, что включает в себя как классы, так и их объекты (экземпляры). +- Класс `type` является метаклассом класса `object`, и каждый класс (включая `type`) наследуется прямо или косвенно от `object`. +- У `object` и `type` нет реального базового класса. Путаница в приведенных выше фрагментах возникает потому, что мы думаем об этих отношениях (`issubclass` и `isinstance`) в терминах классов Python. Отношения между `object` и `type` не могут быть воспроизведены в чистом Python. Точнее говоря, следующие отношения не могут быть воспроизведены в чистом Python, + + класс A является экземпляром класса B, а класс B является экземпляром класса A. + + класс A является экземпляром самого себя. +- Эти отношения между `object` и `type` (оба являются экземплярами друг друга, а также самих себя) существуют в Python из-за "обмана" на уровне реализации. + +--- From a32eaca58f2129ecf5976aec912577ad35d81b82 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sun, 21 Apr 2024 10:41:17 +0300 Subject: [PATCH 084/210] Translate Sublass relationships example --- translations/README-ru.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 3d299f3f..e79facc1 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1050,3 +1050,28 @@ False - Эти отношения между `object` и `type` (оба являются экземплярами друг друга, а также самих себя) существуют в Python из-за "обмана" на уровне реализации. --- + + +### ▶ Отношения между подклассами + +**Вывод:** +```py +>>> from collections import Hashable +>>> issubclass(list, object) +True +>>> issubclass(object, Hashable) +True +>>> issubclass(list, Hashable) +False +``` + +Предполагается, что отношения подклассов должны быть транзитивными, верно? (т.е. если `A` является подклассом `B`, а `B` является подклассом `C`, то `A` _должен_ быть подклассом `C`) + +#### 💡 Объяснение + +* Отношения подклассов не обязательно являются транзитивными в Python. Можно переопределить магический метод `__subclasscheck__` в метаклассе. +* Когда вызывается `issubclass(cls, Hashable)`, он просто ищет не-фальшивый метод "`__hash__`" в `cls` или во всем, от чего он наследуется. +* Поскольку `object` является хэшируемым, а `list` - нехэшируемым, это нарушает отношение транзитивности. +* Более подробное объяснение можно найти [здесь] (https://www.naftaliharris.com/blog/python-subclass-intransitivity/). + +--- From 6e246d1487c6e1700aa1d0a16c2bc98b18c83649 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sun, 21 Apr 2024 10:57:44 +0300 Subject: [PATCH 085/210] Translate Methods equality and identity example --- translations/README-ru.md | 102 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index e79facc1..b5627b69 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1075,3 +1075,105 @@ False * Более подробное объяснение можно найти [здесь] (https://www.naftaliharris.com/blog/python-subclass-intransitivity/). --- + + +### ▶ Равенство и тождество методов + + +1. +```py +class SomeClass: + def method(self): + pass + + @classmethod + def classm(cls): + pass + + @staticmethod + def staticm(): + pass +``` + +**Результат:** +```py +>>> print(SomeClass.method is SomeClass.method) +True +>>> print(SomeClass.classm is SomeClass.classm) +False +>>> print(SomeClass.classm == SomeClass.classm) +True +>>> print(SomeClass.staticm is SomeClass.staticm) +True +``` + +Обращаясь к `classm` дважды, мы получаем одинаковый объект, но не *тот же самый*? Давайте посмотрим, что происходит +с экземплярами `SomeClass`: + +2. +```py +o1 = SomeClass() +o2 = SomeClass() +``` + +**Вывод:** +```py +>>> print(o1.method == o2.method) +False +>>> print(o1.method == o1.method) +True +>>> print(o1.method is o1.method) +False +>>> print(o1.classm is o1.classm) +False +>>> print(o1.classm == o1.classm == o2.classm == SomeClass.classm) +True +>>> print(o1.staticm is o1.staticm is o2.staticm is SomeClass.staticm) +True +``` + +Повторный доступ к `классу` или `методу` создает одинаковые, но не *те же самые* объекты для одного и того же экземпляра `какого-либо класса`. + +#### 💡 Объяснение +* Функции являются [дескрипторами](https://docs.python.org/3/howto/descriptor.html). Всякий раз, когда к функции обращаются как к +атрибута, вызывается дескриптор, создавая объект метода, который "связывает" функцию с объектом, владеющим атрибутом. При вызове метод вызывает функцию, неявно передавая связанный объект в качестве первого аргумента +(именно так мы получаем `self` в качестве первого аргумента, несмотря на то, что не передаем его явно). +```py +>>> o1.method +> +``` +* При многократном обращении к атрибуту каждый раз создается объект метода! Поэтому `o1.method is o1.method` всегда ложно. Однако доступ к функциям как к атрибутам класса (в отличие от экземпляра) не создает методов; поэтому +`SomeClass.method is SomeClass.method` является истинным. +```py +>>> SomeClass.method + +``` +* `classmethod` преобразует функции в методы класса. Методы класса - это дескрипторы, которые при обращении к ним создают +объект метода, который связывает *класс* (тип) объекта, а не сам объект. +```py +>>> o1.classm +> +``` +* В отличие от функций, `classmethod` будет создавать метод и при обращении к нему как к атрибуту класса (в этом случае они +привязываются к классу, а не к его типу). Поэтому `SomeClass.classm is SomeClass.classm` является ошибочным. +```py +>>> SomeClass.classm +> +``` +* Объект-метод равен, если обе функции равны, а связанные объекты одинаковы. Поэтому +`o1.method == o1.method` является истинным, хотя и не является одним и тем же объектом в памяти. +* `staticmethod` преобразует функции в дескриптор "no-op", который возвращает функцию как есть. Методы-объекты +никогда не создается, поэтому сравнение с `is` является истинным. +```py +>>> o1.staticm + +>>> SomeClass.staticm + +``` +* Необходимость создавать новые объекты "метод" каждый раз, когда Python вызывает методы экземпляра, и необходимость изменять аргументы +каждый раз, чтобы вставить `self`, сильно сказывается на производительности. +CPython 3.7 [решил эту проблему](https://bugs.python.org/issue26110), введя новые опкоды, которые работают с вызовом методов +без создания временных объектов методов. Это используется только при фактическом вызове функции доступа, так что +приведенные здесь фрагменты не затронуты и по-прежнему генерируют методы :) + +--- From 191ea8343bffe58765fd16f2f43d1acec7fd75e8 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 12:02:32 +0300 Subject: [PATCH 086/210] Translate The surprising comma example --- translations/README-ru.md | 71 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index b5627b69..c191aff3 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1177,3 +1177,74 @@ CPython 3.7 [решил эту проблему](https://bugs.python.org/issue26 приведенные здесь фрагменты не затронуты и по-прежнему генерируют методы :) --- + + +### ▶ All-true-ation (непереводимая игра слов) * + + +```py +>>> all([True, True, True]) +True +>>> all([True, True, False]) +False + +>>> all([]) +True +>>> all([[]]) +False +>>> all([[[]]]) +True +``` + +Почему это изменение True-False? + +#### 💡 Объяснение: + +- Реализация функции `all`: + +- ```py + def all(iterable): + for element in iterable: + if not element: + return False + return True + ``` + +- `all([])` возвращает `True`, поскольку итерируемый массив пуст. +- `all([[]])` возвращает `False`, поскольку переданный массив имеет один элемент, `[]`, а в python пустой список является ложным. +- `all([[[[]]])` и более высокие рекурсивные варианты всегда `True`. Это происходит потому, что единственный элемент переданного массива (`[[...]]`) уже не пуст, а списки со значениями являются истинными. + +--- + + +### ▶ Неожиданная запятая + +**Вывод (< 3.6):** + +```py +>>> def f(x, y,): +... print(x, y) +... +>>> def g(x=4, y=5,): +... print(x, y) +... +>>> def h(x, **kwargs,): + File "", line 1 + def h(x, **kwargs,): + ^ +SyntaxError: invalid syntax + +>>> def h(*args,): + File "", line 1 + def h(*args,): + ^ +SyntaxError: invalid syntax +``` + +#### 💡 Объяснение: + +- Запятая в конце списка аргументов функции Python не всегда законна. +- В Python список аргументов определяется частично с помощью ведущих запятых, а частично с помощью запятых в конце списка. Этот конфликт приводит к ситуациям, когда запятая оказывается в середине, и ни одно из правил не выполняется. +- **Примечание:** Проблема с запятыми в конце списка аргументов [исправлена в Python 3.6](https://bugs.python.org/issue9232). Варианты использования запятых в конце выражения приведены в [обсуждении](https://bugs.python.org/issue9232#msg248399). + +--- From 293575b7c44cb3c1dac6eead794ab15cc492a0d1 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 12:08:53 +0300 Subject: [PATCH 087/210] Translate String and backslashes example --- translations/README-ru.md | 44 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index c191aff3..387f8d76 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1248,3 +1248,47 @@ SyntaxError: invalid syntax - **Примечание:** Проблема с запятыми в конце списка аргументов [исправлена в Python 3.6](https://bugs.python.org/issue9232). Варианты использования запятых в конце выражения приведены в [обсуждении](https://bugs.python.org/issue9232#msg248399). --- + + +### ▶ Строки и обратные слэши + +**Вывод:** +```py +>>> print("\"") +" + +>>> print(r"\"") +\" + +>>> print(r"\") +File "", line 1 + print(r"\") + ^ +SyntaxError: EOL while scanning string literal + +>>> r'\'' == "\\'" +True +``` + +#### 💡 Объяснение + +- В обычной строке обратная слэш используется для экранирования символов, которые могут иметь специальное значение (например, одинарная кавычка, двойная кавычка и сам обратный слэш). + ```py + >>> "wt\"f" + 'wt"f' + ``` +- В необработанном строковом литерале (на что указывает префикс `r`) обратный слэш передается как есть, вместе с поведением экранирования следующего символа. + ```py + >>> r'wt\"f' == 'wt\\"f' + True + >>> print(repr(r'wt\"f') + 'wt\\"f' + + >>> print("\n") + + >>> print(r"\\n") + '\\n' + ``` +- Это означает, что когда синтаксический анализатор встречает обратный слэш в необработанной строке, он ожидает, что за ней последует другой символ. А в нашем случае (`print(r"\")`) обратная слэш экранирует двойную кавычку, оставив парсер без завершающей кавычки (отсюда `SyntaxError`). Вот почему обратный слеш не работает в конце необработанной строки. + +--- From 5eeb1053aaeaa72e7b052c569eeb52638e21a661 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 12:13:13 +0300 Subject: [PATCH 088/210] Translate Not knot example --- translations/README-ru.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 387f8d76..0af0e511 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1291,4 +1291,32 @@ True ``` - Это означает, что когда синтаксический анализатор встречает обратный слэш в необработанной строке, он ожидает, что за ней последует другой символ. А в нашем случае (`print(r"\")`) обратная слэш экранирует двойную кавычку, оставив парсер без завершающей кавычки (отсюда `SyntaxError`). Вот почему обратный слеш не работает в конце необработанной строки. +-- + + +### ▶ Не узел! (eng. not knot!) + +```py +x = True +y = False +``` + +**Результат:** +```py +>>> not x == y +True +>>> x == not y + File "", line 1 + x == not y + ^ +SyntaxError: invalid syntax +``` + +#### 💡 Объяснение + +* Старшинство операторов влияет на выполнение выражения, и оператор `==` имеет более высокий приоритет, чем оператор `not` в Python. +* Поэтому `not x == y` эквивалентно `not (x == y)`, что эквивалентно `not (True == False)`, в итоге равное `True`. +* Но `x == not y` вызывает `SyntaxError`, потому что его можно считать эквивалентным `(x == not) y`, а не `x == (not y)`, что можно было бы ожидать на первый взгляд. +* Парсер ожидал, что ключевое слово `not` будет частью оператора `not in` (потому что оба оператора `==` и `not in` имеют одинаковый приоритет), но после того, как он не смог найти ключевое слово `in`, следующее за `not`, он выдает `SyntaxError`. + --- From 8a1536986f14f1bfddfd0c434f4fb178e6171fcb Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 12:19:28 +0300 Subject: [PATCH 089/210] Translate Half triple-quoted strings example --- translations/README-ru.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 0af0e511..2a8ac332 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1320,3 +1320,33 @@ SyntaxError: invalid syntax * Парсер ожидал, что ключевое слово `not` будет частью оператора `not in` (потому что оба оператора `==` и `not in` имеют одинаковый приоритет), но после того, как он не смог найти ключевое слово `in`, следующее за `not`, он выдает `SyntaxError`. --- + + +### ▶ Строки наполовину в тройных кавычках + +**Вывод:** +```py +>>> print('wtfpython''') +wtfpython +>>> print("wtfpython""") +wtfpython +>>> # Выражения ниже приводят к `SyntaxError` +>>> # print('''wtfpython') +>>> # print("""wtfpython") + File "", line 3 + print("""wtfpython") + ^ +SyntaxError: EOF while scanning triple-quoted string literal +``` + +#### 💡 Объяснение: ++ Python поддерживает неявную [конкатенацию строковых литералов](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation), Пример, + ``` + >>> print("wtf" "python") + wtfpython + >>> print("wtf" "") # or "wtf""" + wtf + ``` ++ `'''` и `"""` также являются разделителями строк в Python, что вызывает SyntaxError, поскольку интерпретатор Python ожидал завершающую тройную кавычку в качестве разделителя при сканировании текущего встреченного строкового литерала с тройной кавычкой. + +--- From a0069d842e8c79d257590697eff9773bed37ace2 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 13:58:11 +0300 Subject: [PATCH 090/210] Translate What's wrong with booleans? example --- translations/README-ru.md | 90 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 2a8ac332..70a77439 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1350,3 +1350,93 @@ SyntaxError: EOF while scanning triple-quoted string literal + `'''` и `"""` также являются разделителями строк в Python, что вызывает SyntaxError, поскольку интерпретатор Python ожидал завершающую тройную кавычку в качестве разделителя при сканировании текущего встреченного строкового литерала с тройной кавычкой. --- + +### ▶ Что не так с логическими значениями? + +1\. + +```py +# Простой пример счетчика логических переменных и целых чисел +# в итерируемом объекте со значениями разных типов данных +mixed_list = [False, 1.0, "some_string", 3, True, [], False] +integers_found_so_far = 0 +booleans_found_so_far = 0 + +for item in mixed_list: + if isinstance(item, int): + integers_found_so_far += 1 + elif isinstance(item, bool): + booleans_found_so_far += 1 +``` + +**Результат:** +```py +>>> integers_found_so_far +4 +>>> booleans_found_so_far +0 +``` + + +2\. +```py +>>> some_bool = True +>>> "wtf" * some_bool +'wtf' +>>> some_bool = False +>>> "wtf" * some_bool +'' +``` + +3\. + +```py +def tell_truth(): + True = False + if True == False: + print("I have lost faith in truth!") +``` + +**Результат (< 3.x):** + +```py +>>> tell_truth() +I have lost faith in truth! +``` + + + +#### 💡 Объяснение: + +* `bool` это подкласс класса `int` в Python + + ```py + >>> issubclass(bool, int) + True + >>> issubclass(int, bool) + False + ``` + +* `True` и `False` - экземпляры класса `int` + ```py + >>> isinstance(True, int) + True + >>> isinstance(False, int) + True + ``` + +* Целочисленное значение `True` равно `1`, а `False` равно `0`. + ```py + >>> int(True) + 1 + >>> int(False) + 0 + ``` + +* Объяснение на [StackOverflow](https://stackoverflow.com/a/8169049/4354153). + +* Изначально в Python не было типа `bool` (использовали 0 для false и ненулевое значение 1 для true). В версиях 2.x были добавлены `True`, `False` и тип `bool`, но для обратной совместимости `True` и `False` нельзя было сделать константами. Они просто были встроенными переменными, и их можно было переназначить. + +* Python 3 был несовместим с предыдущими версиями, эту проблему наконец-то исправили, и поэтому последний фрагмент не будет работать с Python 3.x! + +--- From 972d1334fb1b75f154a355138b4e9abbc629d42c Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 14:03:16 +0300 Subject: [PATCH 091/210] Translate Class attributes and instance atributes example --- translations/README-ru.md | 71 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 70a77439..23a67c53 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1440,3 +1440,74 @@ I have lost faith in truth! * Python 3 был несовместим с предыдущими версиями, эту проблему наконец-то исправили, и поэтому последний фрагмент не будет работать с Python 3.x! --- + + +### ▶ Атрибуты класса и экземпляра + +1\. +```py +class A: + x = 1 + +class B(A): + pass + +class C(A): + pass +``` + +**Результат:** +```py +>>> A.x, B.x, C.x +(1, 1, 1) +>>> B.x = 2 +>>> A.x, B.x, C.x +(1, 2, 1) +>>> A.x = 3 +>>> A.x, B.x, C.x # Значение C.x изменилось , но B.x - нет +(3, 2, 3) +>>> a = A() +>>> a.x, A.x +(3, 3) +>>> a.x += 1 +>>> a.x, A.x +(4, 3) +``` + +2\. +```py +class SomeClass: + some_var = 15 + some_list = [5] + another_list = [5] + def __init__(self, x): + self.some_var = x + 1 + self.some_list = self.some_list + [x] + self.another_list += [x] +``` + +**Результат:** + +```py +>>> some_obj = SomeClass(420) +>>> some_obj.some_list +[5, 420] +>>> some_obj.another_list +[5, 420] +>>> another_obj = SomeClass(111) +>>> another_obj.some_list +[5, 111] +>>> another_obj.another_list +[5, 420, 111] +>>> another_obj.another_list is SomeClass.another_list +True +>>> another_obj.another_list is some_obj.another_list +True +``` + +#### 💡 Объяснение: + +* Переменные класса и переменные экземпляров класса внутренне обрабатываются как словари объекта класса. Если имя переменной не найдено в словаре текущего класса, оно ищется в родительских классах. +* Оператор += изменяет объект на месте, не создавая новый объект. Таким образом, изменение атрибута одного экземпляра влияет на другие экземпляры и атрибут класса также. + +--- From ecaab6dca1f6b87e11fd38bf0ddcff303f9eb214 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 14:05:53 +0300 Subject: [PATCH 092/210] Translate Yielding None example --- translations/README-ru.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 23a67c53..5f3f4bb4 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1511,3 +1511,36 @@ True * Оператор += изменяет объект на месте, не создавая новый объект. Таким образом, изменение атрибута одного экземпляра влияет на другие экземпляры и атрибут класса также. --- + + +### ▶ Возврат None из генератора + +```py +some_iterable = ('a', 'b') + +def some_func(val): + return "something" +``` + +**Результат (<= 3.7.x):** + +```py +>>> [x for x in some_iterable] +['a', 'b'] +>>> [(yield x) for x in some_iterable] + at 0x7f70b0a4ad58> +>>> list([(yield x) for x in some_iterable]) +['a', 'b'] +>>> list((yield x) for x in some_iterable) +['a', None, 'b', None] +>>> list(some_func((yield x)) for x in some_iterable) +['a', 'something', 'b', 'something'] +``` + +#### 💡 Объяснение: +- Это баг в обработке yield в генераторах и списочных выражениях CPython. +- Исходный код и объяснение можно найти [здесь](https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions) +- Связанный [отчет об ошибке](https://bugs.python.org/issue10544) +- В Python 3.8+ yield внутри списочных выражений больше не допускается и выдает `SyntaxError`. + +--- From 51d13b87cf0b3b2dd50cb1a84dc867329771ae45 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 14:13:11 +0300 Subject: [PATCH 093/210] Translate Yielding from... return example --- translations/README-ru.md | 66 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 5f3f4bb4..638536d3 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1544,3 +1544,69 @@ def some_func(val): - В Python 3.8+ yield внутри списочных выражений больше не допускается и выдает `SyntaxError`. --- + + +### ▶ Yield from возвращает... * + +1\. + +```py +def some_func(x): + if x == 3: + return ["wtf"] + else: + yield from range(x) +``` + +**Результат (> 3.3):** + +```py +>>> list(some_func(3)) +[] +``` + +Куда исчезло `"wtf"`? Это связано с каким-то особым эффектом `yield from`? Проверим это. + +2\. + +```py +def some_func(x): + if x == 3: + return ["wtf"] + else: + for i in range(x): + yield i +``` + +**Результат:** + +```py +>>> list(some_func(3)) +[] +``` + +То же самое, это тоже не сработало. Что происходит? + +#### 💡 Объяснение: + ++ С Python 3.3 стало возможным использовать оператор `return` в генераторах с возвращением значения (см. [PEP380](https://www.python.org/dev/peps/pep-0380/)). В [официальной документации](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) говорится, что + +> "... `return expr` в генераторе вызывает исключение `StopIteration(expr)` при выходе из генератора." + ++ В случае `some_func(3)` `StopIteration` возникает в начале из-за оператора `return`. Исключение `StopIteration` автоматически перехватывается внутри обертки `list(...)` и цикла `for`. Поэтому два вышеприведенных фрагмента приводят к пустому списку. + ++ Чтобы получить `["wtf"]` из генератора `some_func`, нужно перехватить исключение `StopIteration`. + + ```py + try: + next(some_func(3)) + except StopIteration as e: + some_string = e.value + ``` + + ```py + >>> some_string + ["wtf"] + ``` + +--- From 495c8402542277bfbda65d6c314a87e2664b76c4 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 14:21:35 +0300 Subject: [PATCH 094/210] Translate Nan-reflexivity example --- translations/README-ru.md | 75 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 638536d3..9183b74c 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1610,3 +1610,78 @@ def some_func(x): ``` --- + + +### ▶ Nan-рефлексивность * + + + +1\. + +```py +a = float('inf') +b = float('nan') +c = float('-iNf') # Эти строки не чувствительны к регистру +d = float('nan') +``` + +**Результат:** + +```py +>>> a +inf +>>> b +nan +>>> c +-inf +>>> float('some_other_string') +ValueError: could not convert string to float: some_other_string +>>> a == -c # inf==inf +True +>>> None == None # None == None +True +>>> b == d # но nan!=nan +False +>>> 50 / a +0.0 +>>> a / a +nan +>>> 23 + b +nan +``` + +2\. + +```py +>>> x = float('nan') +>>> y = x / x +>>> y is y # идендичность сохраняется +True +>>> y == y # сравнение ложно для y +False +>>> [y] == [y] # но сравнение истинно для списка, содержащего y +True +``` + +#### 💡 Объяснение: + +- `'inf'` и `'nan'` - это специальные строки (без учета регистра), которые при явном приведении к типу `float` используются для представления математической "бесконечности" и "не число" соответственно. + +- Согласно стандартам IEEE `NaN != NaN`, но соблюдение этого правила нарушает предположение о рефлексивности элемента коллекции в Python, то есть если `x` является частью коллекции, такой как `list`, реализации, методы сравнения предполагают, что `x == x`. Поэтому при сравнении элементов сначала сравниваются их идентификаторы (так как это быстрее), а значения сравниваются только при несовпадении идентификаторов. Следующий фрагмент сделает вещи более ясными: + + ```py + >>> x = float('nan') + >>> x == x, [x] == [x] + (False, True) + >>> y = float('nan') + >>> y == y, [y] == [y] + (False, True) + >>> x == y, [x] == [y] + (False, False) + ``` + + Поскольку идентификаторы `x` и `y` разные, рассматриваются значения, которые также различаются; следовательно, на этот раз сравнение возвращает `False`. + +- Интересное чтение: [Рефлексивность и другие основы цивилизации](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) + +--- From f2b1d7e8c290f21559b4748413b9faac13173a69 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 14:33:23 +0300 Subject: [PATCH 095/210] Translate Mutating the immutable! example --- translations/README-ru.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 9183b74c..30384e7a 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1685,3 +1685,42 @@ True - Интересное чтение: [Рефлексивность и другие основы цивилизации](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) --- + + +### ▶ Мутируем немутируемое! + + + +Это может показаться тривиальным, если вы знаете, как работают ссылки в Python. + +```py +some_tuple = ("A", "tuple", "with", "values") +another_tuple = ([1, 2], [3, 4], [5, 6]) +``` + +**Результат:** +```py +>>> some_tuple[2] = "change this" +TypeError: 'tuple' object does not support item assignment +>>> another_tuple[2].append(1000) # Не приводит к исключениям +>>> another_tuple +([1, 2], [3, 4], [5, 6, 1000]) +>>> another_tuple[2] += [99, 999] +TypeError: 'tuple' object does not support item assignment +>>> another_tuple +([1, 2], [3, 4], [5, 6, 1000, 99, 999]) +``` + +Но кортежи неизменяемы... Что происходит? + +#### 💡 Объяснение: + +* Перевод цитаты из [документации](https://docs.python.org/3/reference/datamodel.html) + + > Неизменяемые последовательности + Объект неизменяемого типа последовательности не может измениться после создания. (Если объект содержит ссылки на другие объекты, эти объекты могут быть изменяемыми и могут быть изменены; однако набор объектов, на которые непосредственно ссылается неизменяемый объект, не может изменяться.) + +* Оператор `+=` изменяет список на месте. Присваивание элемента не работает, но когда возникает исключение, элемент уже был изменен на месте. +* Также есть объяснение в официальном [Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works). + +--- From 58de881f9320e4f18fba43a52d53601fb99d5303 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 14:51:49 +0300 Subject: [PATCH 096/210] Translate The dissapearing variable from outer scope example --- translations/README-ru.md | 82 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 30384e7a..382aab86 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1724,3 +1724,85 @@ TypeError: 'tuple' object does not support item assignment * Также есть объяснение в официальном [Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works). --- + + +### ▶ Исчезающая переменная из внешней области видимости + + +```py +e = 7 +try: + raise Exception() +except Exception as e: + pass +``` + +**Результат (Python 2.x):** +```py +>>> print(e) +# Ничего не выводит +``` + +**Результат (Python 3.x):** +```py +>>> print(e) +NameError: name 'e' is not defined +``` + +#### 💡 Объяснение: + +* [Источник](https://docs.python.org/3/reference/compound_stmts.html#except) + +Когда исключение было назначено с помощью ключевого слова `as`, оно очищается в конце блока `except`. Это происходит так, как если бы + + ```py + except E as N: + foo + ``` + +разворачивалось до + + ```py + except E as N: + try: + foo + finally: + del N + ``` + +Это означает, что исключению должно быть присвоено другое имя, чтобы на него можно было ссылаться после завершения блока `except`. Исключения очищаются, потому что с прикрепленным к ним трейсбэком они образуют цикл ссылок со стеком вызовов, сохраняя все локальные объекты в этой стэке до следующей сборки мусора. + +* В Python clauses не имеют области видимости. В примере все объекты в одной области видимости, а переменная `e` была удалена из-за выполнения блока `except`. Этого нельзя сказать о функциях, которые имеют отдельные внутренние области видимости. Пример ниже иллюстрирует это: + +```py + def f(x): + del(x) + print(x) + + 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] + ``` + +* В Python 2.x, имя переменной `e` назначается на экземпляр `Exception()`, и при попытки вывести значение `e` ничего не выводится. + + **Результат (Python 2.x):** + ```py + >>> e + Exception() + >>> print e + # Ничего не выводится! + ``` + +--- From f96f5117c57be7e9d1de0cd603976d5320b78a00 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 15:08:54 +0300 Subject: [PATCH 097/210] Translate The mysterious key type conversion example --- translations/README-ru.md | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 382aab86..e032170f 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1806,3 +1806,60 @@ NameError: name 'e' is not defined ``` --- + + +### ▶ Загадочное преобразование типов ключей + +```py +class SomeClass(str): + pass + +some_dict = {'s': 42} +``` + +**Результат:** +```py +>>> type(list(some_dict.keys())[0]) +str +>>> s = SomeClass('s') +>>> some_dict[s] = 40 +>>> some_dict # Ожидается 2 разные пары ключ-значение +{'s': 40} +>>> type(list(some_dict.keys())[0]) +str +``` + +#### 💡 Объяснение: + +* И объект `s`, и строка `"s"` хэшируются до одного и того же значения, потому что `SomeClass` наследует метод `__hash__` класса `str`. +* Выражение `SomeClass("s") == "s"` эквивалентно `True`, потому что `SomeClass` также наследует метод `__eq__` класса `str`. +* Поскольку оба объекта хэшируются на одно и то же значение и равны, они представлены одним и тем же ключом в словаре. +* Чтобы добиться желаемого поведения, мы можем переопределить метод `__eq__` в `SomeClass`. + ```py + class SomeClass(str): + def __eq__(self, other): + return ( + type(self) is SomeClass + and type(other) is SomeClass + and super().__eq__(other) + ) + + # При переопределении метода __eq__, Python прекращает автоматическое наследование метода + # __hash__, поэтому его нужно вручную определить + __hash__ = str.__hash__ + + some_dict = {'s':42} + ``` + + **Результат:** + ```py + >>> s = SomeClass('s') + >>> some_dict[s] = 40 + >>> some_dict + {'s': 40, 's': 42} + >>> keys = list(some_dict.keys()) + >>> type(keys[0]), type(keys[1]) + (__main__.SomeClass, str) + ``` + +--- From c125f25fb5841000d2ca9eaa1e11ddc5023757fd Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 15:19:58 +0300 Subject: [PATCH 098/210] Translate Let's see if you can guess this? example --- translations/README-ru.md | 58 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index e032170f..2c35c8f3 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1863,3 +1863,61 @@ str ``` --- + + +### ▶ Посмотрим, сможете ли вы угадать что здесь? + +```py +a, b = a[b] = {}, 5 +``` + +**Результат:** +```py +>>> a +{5: ({...}, 5)} +``` + +#### 💡 Объяснение: + +* Согласно [документации](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), выражения присваивания имеют вид + ``` + (target_list "=")+ (expression_list | yield_expression) + ``` + и + +> Оператор присваивания исполняет список выражений (помните, что это может быть одно выражение или список, разделенный запятыми, в последнем случае получается кортеж) и присваивает единственный результирующий объект каждому из целевых списков, слева направо. + +* `+` в `(target_list "=")+` означает, что может быть **один или более** целевых списков. В данном случае целевыми списками являются `a, b` и `a[b]` (обратите внимание, что список выражений ровно один, в нашем случае это `{}, 5`). + +* После исполнения списка выражений его значение распаковывается в целевые списки **слева направо**. Так, в нашем случае сначала кортеж `{}, 5` распаковывается в `a, b`, и теперь у нас есть `a = {}` и `b = 5`. + +* Теперь `a` имеет значение `{}`, которое является изменяемым объектом. + +* Вторым целевым списком является `a[b]` (вы можете ожидать, что это вызовет ошибку, поскольку `a` и `b` не были определены в предыдущих утверждениях. Но помните, мы только что присвоили `a` значение `{}` и `b` - `5`). + +* Теперь мы устанавливаем ключ `5` в словаре в кортеж `({}, 5)`, создавая круговую ссылку (`{...}` в выводе ссылается на тот же объект, на который уже ссылается `a`). Другим более простым примером круговой ссылки может быть + +```py + >>> some_list + [[...]] + >>> some_list[0] + [[...]] + >>> some_list is some_list[0] + True + >>> some_list[0][0][0][0][0][0] == some_list + True + ``` + Аналогичный случай в примере выше (`a[b][0]` - это тот же объект, что и `a`) + +* Подводя итог, можно разбить пример на следующие пункты + ```py + a, b = {}, 5 + a[b] = a, b + ``` + А циклическая ссылка может быть оправдана тем, что `a[b][0]` - тот же объект, что и `a` + ```py + >>> a[b][0] is a + True + ``` + + --- From 3fc9e9e028c9d55eeb4c6933e0f712aeadd6241d Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 15:24:31 +0300 Subject: [PATCH 099/210] Translate Exceeds the linit for integer string conversion example --- translations/README-ru.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 2c35c8f3..6309e601 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1921,3 +1921,33 @@ a, b = a[b] = {}, 5 ``` --- + + +### ▶ Превышение предела целочисленного преобразования строк +```py +>>> # Python 3.10.6 +>>> int("2" * 5432) +>>> # Python 3.10.8 +>>> int("2" * 5432) +``` +**Вывод:** +```py +>>> # Python 3.10.6 +222222222222222222222222222222222222222222222222222222222222222... +>>> # Python 3.10.8 +Traceback (most recent call last): + ... +ValueError: Exceeds the limit (4300) for integer string conversion: + value has 5432 digits; use sys.set_int_max_str_digits() + to increase the limit. +``` +#### 💡 Объяснение: +Этот вызов `int()` прекрасно работает в Python 3.10.6 и вызывает ошибку `ValueError` в Python 3.10.8, 3.11. Обратите внимание, что Python все еще может работать с большими целыми числами. Ошибка возникает только при преобразовании между целыми числами и строками. +К счастью, вы можете увеличить предел допустимого количества цифр. Для этого можно воспользоваться одним из следующих способов: +- `-X int_max_str_digits` - флаг командной строкиcommand-line flag +- `set_int_max_str_digits()` - функция из модуля `sys` +- `PYTHONINTMAXSTRDIGITS` - переменная окружения + +[Смотри документацию](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) для получения более подробной информации об изменении лимита по умолчанию, если вы ожидаете, что ваш код превысит это значение. + +--- From eccd68a4bd276b7dd7b1dda7a9bbbca44407f40e Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 22 Apr 2024 15:37:59 +0300 Subject: [PATCH 100/210] Translate Modifying dictionary while iterating over it example --- translations/README-ru.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 6309e601..f880219c 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1951,3 +1951,42 @@ ValueError: Exceeds the limit (4300) for integer string conversion: [Смотри документацию](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) для получения более подробной информации об изменении лимита по умолчанию, если вы ожидаете, что ваш код превысит это значение. --- + + +## Секция: Скользкие склоны + +### ▶ Изменение словаря во время прохода по нему + +```py +x = {0: None} + +for i in x: + del x[i] + x[i+1] = None + print(i) +``` + +**Результат (Python 2.7- Python 3.5):** + +``` +0 +1 +2 +3 +4 +5 +6 +7 +``` + +Да, цикл выполняет ровно **восемь** итераций и завершается. + +#### 💡 Объяснение: + +* Проход по словарю и его одновременное редактирование не поддерживается. +* Выполняется восемь проходов, потому что именно в этот момент словарь изменяет размер, чтобы вместить больше ключей (у нас есть восемь записей об удалении, поэтому необходимо изменить размер). На самом деле это деталь реализации. +* То, как обрабатываются удаленные ключи и когда происходит изменение размера, может отличаться в разных реализациях Python. +* Так что для версий Python, отличных от Python 2.7 - Python 3.5, количество записей может отличаться от 8 (но каким бы ни было количество записей, оно будет одинаковым при каждом запуске). Обсуждения по этому поводу имеются в [issue](https://github.com/satwikkansal/wtfpython/issues/53) и на [StackOverflow](https://stackoverflow.com/questions/44763802/bug-in-python-dict). +* В Python 3.7.6 и выше при попытке запустить пример вызывается исключение `RuntimeError: dictionary keys changed during iteration`. + +--- From b1a8aadd704c13ecac3d771a6903afdaeee1d080 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 08:53:40 +0300 Subject: [PATCH 101/210] Translate Stubborn operation example --- translations/README-ru.md | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index f880219c..cdf51331 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1990,3 +1990,50 @@ for i in x: * В Python 3.7.6 и выше при попытке запустить пример вызывается исключение `RuntimeError: dictionary keys changed during iteration`. --- + + +### ▶ Упрямая операция `del` + + + +```py +class SomeClass: + def __del__(self): + print("Deleted!") +``` + +**Результат:** +1\. +```py +>>> x = SomeClass() +>>> y = x +>>> del x # должно быть выведено "Deleted!" +>>> del y +Deleted! +``` + +Фух, наконец-то удалили. Вы, наверное, догадались, что спасло `__del__` от вызова в нашей первой попытке удалить `x`. Давайте добавим в пример еще больше изюминок. + +2\. +```py +>>> x = SomeClass() +>>> y = x +>>> del x +>>> y # проверяем, существует ли y +<__main__.SomeClass instance at 0x7f98a1a67fc8> +>>> del y # Как и в прошлом примере, вывод должен содержать "Deleted!" +>>> globals() # но вывод пуст. Проверим все глобальные переменные +Deleted! +{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None} +``` + +Вот сейчас переменная `y` удалена :confused: + +#### 💡 Объяснение: + ++ `del x` не вызывает напрямую `x.__del__()`. ++ Когда встречается `del x`, Python удаляет имя `x` из текущей области видимости и уменьшает на 1 количество ссылок на объект, на который ссылается `x`. `__del__()` вызывается только тогда, когда счетчик ссылок объекта достигает нуля. ++ Во втором фрагменте вывода `__del__()` не была вызвана, потому что предыдущий оператор (`>>> y`) в интерактивном интерпретаторе создал еще одну ссылку на тот же объект (в частности, магическую переменную `_`, которая ссылается на значение результата последнего не `None` выражения в REPL), тем самым не позволив счетчику ссылок достичь нуля, когда было встречено `del y`. ++ Вызов `globals` (или вообще выполнение чего-либо, что будет иметь результат, отличный от `None`) заставил `_` сослаться на новый результат, отбросив существующую ссылку. Теперь количество ссылок достигло 0, и мы можем видеть, как выводится "Deleted!" (наконец-то!). + +--- From 2aa7b375406ec86cea79199c8696f30ea8800f32 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 09:02:25 +0300 Subject: [PATCH 102/210] Translate The out of scope varibale example --- translations/README-ru.md | 83 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index cdf51331..726b3ea0 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2037,3 +2037,86 @@ Deleted! + Вызов `globals` (или вообще выполнение чего-либо, что будет иметь результат, отличный от `None`) заставил `_` сослаться на новый результат, отбросив существующую ссылку. Теперь количество ссылок достигло 0, и мы можем видеть, как выводится "Deleted!" (наконец-то!). --- + + +### ▶ Переменная за пределами видимости + + +1\. +```py +a = 1 +def some_func(): + return a + +def another_func(): + a += 1 + return a +``` + +2\. +```py +def some_closure_func(): + a = 1 + def some_inner_func(): + return a + return some_inner_func() + +def another_closure_func(): + a = 1 + def another_inner_func(): + a += 1 + return a + return another_inner_func() +``` + +**Результат:** +```py +>>> some_func() +1 +>>> another_func() +UnboundLocalError: local variable 'a' referenced before assignment + +>>> some_closure_func() +1 +>>> another_closure_func() +UnboundLocalError: local variable 'a' referenced before assignment +``` + +#### 💡 Объяснение: +* Когда вы делаете присваивание переменной в области видимости, она становится локальной для этой области. Так `a` становится локальной для области видимости `another_func`, но она не была инициализирована ранее в той же области видимости, что приводит к ошибке. +* Для изменения переменной `a` из внешней области видимости внутри функции `another_func`, необходимо использовать ключевое слово `global`. + ```py + def another_func() + global a + a += 1 + return a + ``` + + **Результат:** + ```py + >>> another_func() + 2 + ``` +* В `another_closure_func` переменная `a` становится локальной для области видимости `another_inner_func`, но она не была инициализирована ранее в той же области видимости, поэтому выдает ошибку. +* Чтобы изменить переменную внешней области видимости `a` в `another_inner_func`, используйте ключевое слово `nonlocal`. Утверждение nonlocal используется для обращения к переменным, определенным в ближайшей внешней (за исключением глобальной) области видимости. + + ```py + def another_func(): + a = 1 + def another_inner_func(): + nonlocal a + a += 1 + return a + return another_inner_func() + ``` + + **Результат:** + ```py + >>> another_func() + 2 + ``` + +* Ключевые слова `global` и `nonlocal` указывают интерпретатору python не объявлять новые переменные и искать их в соответствующих внешних областях видимости. +* Прочитайте [это](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) короткое, но потрясающее руководство, чтобы узнать больше о том, как работают пространства имен и разрешение областей видимости в Python. + +--- From e8cd593e62dfd3002dda6500fba32763ef8b9d19 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 10:58:11 +0300 Subject: [PATCH 103/210] Translate Deleting list item while iterating over it example --- translations/README-ru.md | 60 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 726b3ea0..b1020778 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2120,3 +2120,63 @@ UnboundLocalError: local variable 'a' referenced before assignment * Прочитайте [это](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) короткое, но потрясающее руководство, чтобы узнать больше о том, как работают пространства имен и разрешение областей видимости в Python. --- + + +### ▶ Удаление элемента списка во время прохода по списку + +```py +list_1 = [1, 2, 3, 4] +list_2 = [1, 2, 3, 4] +list_3 = [1, 2, 3, 4] +list_4 = [1, 2, 3, 4] + +for idx, item in enumerate(list_1): + del item + +for idx, item in enumerate(list_2): + list_2.remove(item) + +for idx, item in enumerate(list_3[:]): + list_3.remove(item) + +for idx, item in enumerate(list_4): + list_4.pop(idx) +``` + +**Результат:** +```py +>>> list_1 +[1, 2, 3, 4] +>>> list_2 +[2, 4] +>>> list_3 +[] +>>> list_4 +[2, 4] +``` + +Есть предположения, почему вывод `[2, 4]`? + +#### 💡 Объяснение: + +* Никогда не стоит изменять объект, над которым выполняется итерация. Правильным способом будет итерация по копии объекта, и `list_3[:]` делает именно это. + ```py + >>> some_list = [1, 2, 3, 4] + >>> id(some_list) + 139798789457608 + >>> id(some_list[:]) # Notice that python creates new object for sliced list. + 139798779601192 + ``` + +**Разница между `del`, `remove` и `pop`:** +* `del var_name` просто удаляет привязку `var_name` из локального или глобального пространства имен (поэтому `list_1` не затрагивается). +* `remove` удаляет первое подходящее значение, а не конкретный индекс, вызывает `ValueError`, если значение не найдено. +* `pop` удаляет элемент по определенному индексу и возвращает его, вызывает `IndexError`, если указан неверный индекс. + +**Почему на выходе получается `[2, 4]`? +- Проход по списку выполняется индекс за индексом, и когда мы удаляем `1` из `list_2` или `list_4`, содержимое списков становится `[2, 3, 4]`. Оставшиеся элементы сдвинуты вниз, то есть `2` находится на индексе 0, а `3` - на индексе 1. Поскольку на следующей итерации будет просматриваться индекс 1 (который и есть `3`), `2` будет пропущен полностью. Аналогичное произойдет с каждым альтернативным элементом в последовательности списка. + +* Объяснение примера можно найти на [StackOverflow](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it). +* Также посмотрите на похожий пример на [StackOverflow](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items), связанный со словарями. + +--- From 3df9d0e4e322cafdeef3b1d94491046e7ad79603 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 11:07:40 +0300 Subject: [PATCH 104/210] Translate Lossy zip of iterators example --- translations/README-ru.md | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index b1020778..d4928feb 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2180,3 +2180,53 @@ for idx, item in enumerate(list_4): * Также посмотрите на похожий пример на [StackOverflow](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items), связанный со словарями. --- + + +### ▶ Сжатие итераторов с потерями * + + +```py +>>> numbers = list(range(7)) +>>> numbers +[0, 1, 2, 3, 4, 5, 6] +>>> first_three, remaining = numbers[:3], numbers[3:] +>>> first_three, remaining +([0, 1, 2], [3, 4, 5, 6]) +>>> numbers_iter = iter(numbers) +>>> list(zip(numbers_iter, first_three)) +[(0, 0), (1, 1), (2, 2)] +# пока все хорошо, сожмем оставшуюся часть итератора +>>> list(zip(numbers_iter, remaining)) +[(4, 3), (5, 4), (6, 5)] +``` +Куда пропал элемент `3` из списка `numbers`? + +#### 💡 Объяснение: + +- Согласно [документации](https://docs.python.org/3.12/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) + ``` +- Таким образом, функция принимает произвольное количество итерируемых объектов, добавляет каждый из их элементов в список `result`, вызывая для них функцию `next`, и останавливается всякий раз, когда любой из итерируемых объектов исчерпывается. +- Нюанс заключается в том, что при исчерпании любого итерируемого объекта существующие элементы в списке `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)] + ``` + Первый аргумент сжатия должен иметь наименьшее число элементов + +--- From 473e4229f249b9d0c08e9bb9f07c62f778e14dd5 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 11:23:47 +0300 Subject: [PATCH 105/210] Translate Loop variables leaking out example --- translations/README-ru.md | 65 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index d4928feb..b78689d2 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2230,3 +2230,68 @@ for idx, item in enumerate(list_4): Первый аргумент сжатия должен иметь наименьшее число элементов --- + + +### ▶ Утечка переменных внутри цикла + +1\. +```py +for x in range(7): + if x == 6: + print(x, ': for x inside loop') +print(x, ': x in global') +``` + +**Вывод:** +```py +6 : for x inside loop +6 : x in global +``` + +Но `x` не была определена за пределами цикла `for`... + +2\. +```py +# В этот раз определим x до цикла +x = -1 +for x in range(7): + if x == 6: + print(x, ': for x inside loop') +print(x, ': x in global') +``` + +**Вывод:** +```py +6 : for x inside loop +6 : x in global +``` + +3\. + +**Вывод (Python 2.x):** +```py +>>> x = 1 +>>> print([x for x in range(5)]) +[0, 1, 2, 3, 4] +>>> print(x) +4 +``` + +**Вывод (Python 3.x):** +```py +>>> x = 1 +>>> print([x for x in range(5)]) +[0, 1, 2, 3, 4] +>>> print(x) +1 +``` + +#### 💡 Объяснение: + +- В Python циклы for используют область видимости, в которой они существуют, и оставляют свою определенную переменную цикла после завершения. Это также относится к случаям, когда мы явно определили переменную цикла for в глобальном пространстве имен. В этом случае будет произведена перепривязка существующей переменной. + +- Различия в выводе интерпретаторов Python 2.x и Python 3.x для примера с пониманием списков можно объяснить следующим изменением, задокументированным в журнале изменений [What's New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html): + + > "Генераторы списков ("list comprehensions") больше не поддерживает синтаксическую форму `[... for var in item1, item2, ...]`. Вместо этого используйте `[... for var in (item1, item2, ...)]`. Кроме того, обратите внимание, что генераторы списков имеют другую семантику: они ближе к синтаксическому сахару для генераторного выражения внутри конструктора `list()`, и, в частности, управляющие переменные цикла больше не просачиваются в окружающую область видимости." + +--- From 7ce56da1d8d65f6339723e275fdd01249e4e836a Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 11:39:15 +0300 Subject: [PATCH 106/210] Translate Beware of default mutable arguments example --- translations/README-ru.md | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index b78689d2..070cf6a6 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2295,3 +2295,62 @@ print(x, ': x in global') > "Генераторы списков ("list comprehensions") больше не поддерживает синтаксическую форму `[... for var in item1, item2, ...]`. Вместо этого используйте `[... for var in (item1, item2, ...)]`. Кроме того, обратите внимание, что генераторы списков имеют другую семантику: они ближе к синтаксическому сахару для генераторного выражения внутри конструктора `list()`, и, в частности, управляющие переменные цикла больше не просачиваются в окружающую область видимости." --- + + +### ▶ Остерегайтесь изменяемых аргументов по умолчанию! + + +```py +def some_func(default_arg=[]): + default_arg.append("some_string") + return default_arg +``` + +**Результат:** +```py +>>> some_func() +['some_string'] +>>> some_func() +['some_string', 'some_string'] +>>> some_func([]) +['some_string'] +>>> some_func() +['some_string', 'some_string', 'some_string'] +``` + +#### 💡 Объяснение: + +- Изменяемые аргументы функций по умолчанию в Python на самом деле не инициализируются каждый раз, когда вы вызываете функцию. Вместо этого в качестве значения по умолчанию используется недавно присвоенное им значение. Когда мы явно передали `[]` в `some_func в качестве аргумента, значение по умолчанию переменной `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'],) + ``` + +- Чтобы избежать ошибок, связанных с изменяемыми аргументами, принято использовать `None` в качестве значения по умолчанию, а затем проверять, передано ли какое-либо значение в функцию, соответствующую этому аргументу. Пример: + + ```py + def some_func(default_arg=None): + if default_arg is None: + default_arg = [] + default_arg.append("some_string") + return default_arg + ``` + +--- From c2dd151ed551935145a395e83228c064f3a4d322 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 11:45:32 +0300 Subject: [PATCH 107/210] Translate Catching the Exceptions example --- translations/README-ru.md | 76 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 070cf6a6..135ddaec 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2354,3 +2354,79 @@ def some_func(default_arg=[]): ``` --- + + +### ▶ Ловля исключений + +```py +some_list = [1, 2, 3] +try: + # Должно вернуться ``IndexError`` + print(some_list[4]) +except IndexError, ValueError: + print("Caught!") + +try: + # Должно вернуться ``ValueError`` + some_list.remove(4) +except IndexError, ValueError: + print("Caught again!") +``` + +**Результат (Python 2.x):** +```py +Caught! + +ValueError: list.remove(x): x not in list +``` + +**Результат (Python 3.x):** +```py + File "", line 3 + except IndexError, ValueError: + ^ +SyntaxError: invalid syntax +``` + +#### 💡 Объяснение + +* Чтобы добавить несколько Исключений в блок `except`, необходимо передать их в виде кортежа с круглыми скобками в качестве первого аргумента. Второй аргумент - это необязательное имя, которое при передаче свяжет экземпляр исключения, который был пойман. Пример, + ```py + some_list = [1, 2, 3] + try: + # Должно возникнуть ``ValueError`` + some_list.remove(4) + except (IndexError, ValueError), e: + print("Caught again!") + print(e) + ``` + **Результат (Python 2.x):** + ``` + Caught again! + list.remove(x): x not in list + ``` + **Результат (Python 3.x):** + ```py + File "", line 4 + except (IndexError, ValueError), e: + ^ + IndentationError: unindent does not match any outer indentation level + ``` + +* Отделение исключения от переменной запятой является устаревшим и не работает в Python 3; правильнее использовать `as`. Пример, + ```py + some_list = [1, 2, 3] + try: + some_list.remove(4) + + except (IndexError, ValueError) as e: + print("Caught again!") + print(e) + ``` + **Результат:** + ``` + Caught again! + list.remove(x): x not in list + ``` + +--- From 40503d5ac55eea21e4a69c46f9f91bab58a1f8eb Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 12:02:54 +0300 Subject: [PATCH 108/210] Translate Same operands, different story example --- translations/README-ru.md | 43 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 135ddaec..b588ff7c 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2430,3 +2430,46 @@ SyntaxError: invalid syntax ``` --- + + +### ▶ Одни и те же операнды, разная история! + +1\. +```py +a = [1, 2, 3, 4] +b = a +a = a + [5, 6, 7, 8] +``` + +**Результат:** +```py +>>> a +[1, 2, 3, 4, 5, 6, 7, 8] +>>> b +[1, 2, 3, 4] +``` + +2\. +```py +a = [1, 2, 3, 4] +b = a +a += [5, 6, 7, 8] +``` + +**Результат:** +```py +>>> a +[1, 2, 3, 4, 5, 6, 7, 8] +>>> b +[1, 2, 3, 4, 5, 6, 7, 8] +``` + +#### 💡 Объяснение: + +* Выражение `a += b` не всегда ведет себя так же, как и `a = a + b`. Классы *могут* по-разному реализовывать операторы *`op=`*, а списки ведут себя так. + +* Выражение `a = a + [5,6,7,8]` создает новый список и устанавливает ссылку `a` на этот новый список, оставляя `b` неизменным. + +* Выражение `a += [5,6,7,8]` фактически отображается на функцию "extend", которая работает со списком так, что `a` и `b` по-прежнему указывают на тот же самый список, который был изменен на месте. + +--- From a25fe26adc9b76e78ec4f2688f430da3d3da03b7 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 12:07:47 +0300 Subject: [PATCH 109/210] Translate Name resolution ignoring class scope example --- translations/README-ru.md | 44 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index b588ff7c..315e9e57 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2473,3 +2473,47 @@ a += [5, 6, 7, 8] * Выражение `a += [5,6,7,8]` фактически отображается на функцию "extend", которая работает со списком так, что `a` и `b` по-прежнему указывают на тот же самый список, который был изменен на месте. --- + + +### ▶ Разрешение имен игнорирует область видимости класса + +1\. +```py +x = 5 +class SomeClass: + x = 17 + y = (x for i in range(10)) +``` + +**Результат:** +```py +>>> list(SomeClass.y)[0] +5 +``` + +2\. +```py +x = 5 +class SomeClass: + x = 17 + y = [x for i in range(10)] +``` + +**Результат (Python 2.x):** +```py +>>> SomeClass.y[0] +17 +``` + +**Результат (Python 3.x):** +```py +>>> SomeClass.y[0] +5 +``` + +#### 💡 Объяснение +- Области видимости, вложенные внутрь определения класса, игнорируют имена, связанные на уровне класса. +- Выражение-генератор имеет свою собственную область видимости. +- Начиная с версии Python 3.X, списковые вычисления также имеют свою собственную область видимости. + +--- From 0d28d47f0846aca77c1feea0ff3faa8f330e7dba Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 12:18:36 +0300 Subject: [PATCH 110/210] Translate Rounding like a banker example --- translations/README-ru.md | 52 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 315e9e57..1f495653 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2517,3 +2517,55 @@ class SomeClass: - Начиная с версии Python 3.X, списковые вычисления также имеют свою собственную область видимости. --- + + +### ▶ Округляясь как банкир * + +Реализуем простейшую функцию по получению среднего элемента списка: +```py +def get_middle(some_list): + mid_index = round(len(some_list) / 2) + return some_list[mid_index - 1] +``` + +**Python 3.x:** +```py +>>> get_middle([1]) # вроде неплохо +1 +>>> get_middle([1,2,3]) # все еще хорошо +2 +>>> get_middle([1,2,3,4,5]) # что-то не то? +2 +>>> len([1,2,3,4,5]) / 2 # хорошо +2.5 +>>> round(len([1,2,3,4,5]) / 2) # почему снова так? +2 +``` + +Кажется, Python округлил 2.5 до 2. + +#### 💡 Объяснение: + +- Это не ошибка округления float, на самом деле такое поведение намеренно. Начиная с Python 3.0, `round()` использует [округление банкира](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even), где дроби .5 округляются до ближайшего **четного** числа. + +```py +>>> round(0.5) +0 +>>> round(1.5) +2 +>>> round(2.5) +2 +>>> import numpy # поведение numpy аналогично +>>> numpy.round(0.5) +0.0 +>>> numpy.round(1.5) +2.0 +>>> numpy.round(2.5) +2.0 +``` + +- Это рекомендуемый способ округления дробей до .5, описанный в [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules). Однако в школах чаще всего преподают другой способ (округление от нуля), поэтому округление банкира, скорее всего, не так хорошо известно. Более того, некоторые из самых популярных языков программирования (например, JavaScript, Java, C/C++, Ruby, Rust) также не используют округление банкира. Таким образом, для Python это все еще довольно специфично и может привести к путанице при округлении дробей. + +- Дополнительную информацию можно найти в [документации](https://docs.python.org/3/library/functions.html#round) функции `round` или на [StackOverflow](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior). + +--- From 2043112a9d8271a15cab21a040f1f7bd7bd7b016 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 23 Apr 2024 12:32:24 +0300 Subject: [PATCH 111/210] Translate Needles in a haystack example --- translations/README-ru.md | 176 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 1f495653..123b59e0 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2569,3 +2569,179 @@ def get_middle(some_list): - Дополнительную информацию можно найти в [документации](https://docs.python.org/3/library/functions.html#round) функции `round` или на [StackOverflow](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior). --- + + +### ▶ Иголки в стоге сена * + + + +Я не встречал ни одного питониста на данный момент, который не встречался с одним из следующих сценариев, + +1\. + +```py +x, y = (0, 1) if True else None, None +``` + +**Результат:** + +```py +>>> x, y # ожидается (0, 1) +((0, 1), None) +``` + +2\. + +```py +t = ('one', 'two') +for i in t: + print(i) + +t = ('one') +for i in t: + print(i) + +t = () +print(t) +``` + +**Результат:** + +```py +one +two +o +n +e +tuple() +``` + +3\. + +```py +ten_words_list = [ + "some", + "very", + "big", + "list", + "that" + "consists", + "of", + "exactly", + "ten", + "words" +] +``` + +**Результат** + +```py +>>> len(ten_words_list) +9 +``` + +4\. Недостаточно твердое утверждение + +```py +a = "python" +b = "javascript" +``` + +**Результат:** + +```py +# assert выражение с сообщением об ошиб +>>> assert(a == b, "Both languages are different") +# Исключение AssertionError не возникло +``` + +5\. + +```py +some_list = [1, 2, 3] +some_dict = { + "key_1": 1, + "key_2": 2, + "key_3": 3 +} + +some_list = some_list.append(4) +some_dict = some_dict.update({"key_4": 4}) +``` + +**Результат:** + +```py +>>> print(some_list) +None +>>> print(some_dict) +None +``` + +6\. + +```py +def some_recursive_func(a): + if a[0] == 0: + return + a[0] -= 1 + some_recursive_func(a) + return a + +def similar_recursive_func(a): + if a == 0: + return a + a -= 1 + similar_recursive_func(a) + return a +``` + +**Результат:** + +```py +>>> some_recursive_func([5, 0]) +[0, 0] +>>> similar_recursive_func(5) +4 +``` + +#### 💡 Объяснение: + +* Для 1 примера правильным выражением для ожидаемого поведения является `x, y = (0, 1) if True else (None, None)`. + +* Для 2 примера правильным выражением для ожидаемого поведения будет `t = ('one',)` или `t = 'one',` (пропущена запятая), иначе интерпретатор рассматривает `t` как `str` и перебирает его символ за символом. + +* `()` - специальное выражение, обозначающая пустой `tuple`. + +* В 3 примере, как вы, возможно, уже поняли, пропущена запятая после 5-го элемента (`"that"`) в списке. Таким образом, неявная конкатенация строковых литералов, + + ```py + >>> ten_words_list + ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] + ``` + +* В 4-ом фрагменте не возникло `AssertionError`, потому что вместо "проверки" отдельного выражения `a == b`, мы "проверяем" весь кортеж. Следующий фрагмент прояснит ситуацию, + + ```py + >>> a = "python" + >>> b = "javascript" + >>> assert a == b + Traceback (most recent call last): + File "", line 1, in + AssertionError + + >>> assert (a == b, "Values are not equal") + :1: SyntaxWarning: assertion is always true, perhaps remove parentheses? + + >>> assert a == b, "Values are not equal" + Traceback (most recent call last): + File "", line 1, in + AssertionError: Values are not equal + ``` +* Что касается пятого фрагмента, то большинство методов, изменяющих элементы последовательности/маппингов, такие как `list.append`, `dict.update`, `list.sort` и т. д., изменяют объекты на месте и возвращают `None`. Это делается для того, чтобы повысить производительность, избегая создания копии объекта, если операция может быть выполнена на месте (подробнее в [документации](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). + +* Последнее должно быть достаточно очевидным, изменяемый объект (например, `list`) может быть изменен в функции, а переназначение неизменяемого (`a -= 1`) не является изменением значения. + +* Знание этих тонкостей может сэкономить вам часы отладки в долгосрочной перспективе. + +--- From bbb086a521d9a4c22f5fa97b32107c089cc8d938 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 11:27:46 +0300 Subject: [PATCH 112/210] Translate Splitsies example --- translations/README-ru.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 123b59e0..ae55c30f 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2745,3 +2745,40 @@ def similar_recursive_func(a): * Знание этих тонкостей может сэкономить вам часы отладки в долгосрочной перспективе. --- + + +### ▶ Сплиты (splitsies) * + +```py +>>> 'a'.split() +['a'] + +# эквивалентно +>>> 'a'.split(' ') +['a'] + +# но +>>> len(''.split()) +0 + +# не эквивалентно +>>> len(''.split(' ')) +1 +``` + +#### 💡 Объяснение + +- Может показаться, что разделителем по умолчанию для split является одиночный пробел `' '`, но согласно [документации](https://docs.python.org/3/library/stdtypes.html#str.split) + > если sep не указан или равен `none`, применяется другой алгоритм разбиения: последовательные пробельные символы рассматриваются как один разделитель, и результат не будет содержать пустых строк в начале или конце, если в строке есть ведущие или завершающие пробелы. Следовательно, разбиение пустой строки или строки, состоящей только из пробельных символов, с разделителем none возвращает `[]`. + > если задан sep, то последовательные разделители не группируются вместе и считаются разделителями пустых строк (например, `'1,,2'.split(',')` возвращает `['1', '', '2']`). Разделение пустой строки с указанным разделителем возвращает `['']`. +- Обратите внимание, как обрабатываются ведущие и завершающие пробелы в следующем фрагменте, + ```py + >>> ' a '.split(' ') + ['', 'a', ''] + >>> ' a '.split() + ['a'] + >>> ''.split(' ') + [''] + ``` + +--- From 8f60bc1d0b38a52bd0c0b6add29d10db2cc728f9 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 11:35:57 +0300 Subject: [PATCH 113/210] Translate Wild imports example --- translations/README-ru.md | 61 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index ae55c30f..95cf37e5 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2782,3 +2782,64 @@ def similar_recursive_func(a): ``` --- + + +### ▶ Подстановочное импортирование (wild imports) * + + + +```py +# File: module.py + +def some_weird_name_func_(): + print("works!") + +def _another_weird_name_func(): + print("works!") + +``` + +**Результат** + +```py +>>> from module import * +>>> some_weird_name_func_() +"works!" +>>> _another_weird_name_func() +Traceback (most recent call last): + File "", line 1, in +NameError: name '_another_weird_name_func' is not defined +``` + +#### 💡 Объяснение: + +- Часто рекомендуется не использовать импорт с подстановочными знаками (wildcard import). Первая очевидная причина заключается в том, что при импорте с подстановочным знаком имена с ведущим подчеркиванием не импортируются. Это может привести к ошибкам во время выполнения. + +- Если бы мы использовали синтаксис `from ... import a, b, c`, приведенная выше `NameError` не возникла бы. + ```py + >>> from module import some_weird_name_func_, _another_weird_name_func + >>> _another_weird_name_func() + works! + ``` +- Если вы действительно хотите использовать импорт с подстановочными знаками, то нужно определить список `__all__` в вашем модуле, который будет содержать публичные объекты, доступные при wildcard импортировании. + ```py + __all__ = ['_another_weird_name_func'] + + def some_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 + ``` + +--- From f84272fc5c054821043b7b02918f25a5bd465145 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 11:39:29 +0300 Subject: [PATCH 114/210] Translate All sorted? example --- translations/README-ru.md | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 95cf37e5..750dc2e7 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2843,3 +2843,45 @@ NameError: name '_another_weird_name_func' is not defined ``` --- + + +### ▶ Все ли отсортировано? * + + + +```py +>>> x = 7, 8, 9 +>>> sorted(x) == x +False +>>> sorted(x) == sorted(x) +True + +>>> y = reversed(x) +>>> sorted(y) == sorted(y) +False +``` + +#### 💡 Объяснение: + +- Метод `sorted` всегда возвращает список, а сравнение списка и кортежа всегда возвращает `False`. + +- ```py + >>> [] == tuple() + False + >>> x = 7, 8, 9 + >>> type(x), type(sorted(x)) + (tuple, list) + ``` + +- В отличие от метода `sorted, метод `reversed` возвращает итератор. Почему? Потому что сортировка требует, чтобы итератор либо изменялся на месте, либо использовал дополнительный контейнер (список), в то время как реверсирование может работать просто путем итерации от последнего индекса к первому. + +- Поэтому при сравнении `sorted(y) == sorted(y)` первый вызов `sorted()` будет потреблять итератор `y`, а следующий вызов просто вернет пустой список. + + ```py + >>> x = 7, 8, 9 + >>> y = reversed(x) + >>> sorted(y), sorted(y) + ([7, 8, 9], []) + ``` + +--- From 039adfa04ae4c2730a8c31942259978bdf2d5725 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 11:43:00 +0300 Subject: [PATCH 115/210] Translate Midnight time does not exist? example --- translations/README-ru.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 750dc2e7..92c7cb9d 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2885,3 +2885,37 @@ False ``` --- + + +### ▶ Полночи не существует? + +```py +from datetime import datetime + +midnight = datetime(2018, 1, 1, 0, 0) +midnight_time = midnight.time() + +noon = datetime(2018, 1, 1, 12, 0) +noon_time = noon.time() + +if midnight_time: + print("Time at midnight is", midnight_time) + +if noon_time: + print("Time at noon is", noon_time) +``` + +**Результат (< 3.5):** + +```py +('Time at noon is', datetime.time(12, 0)) +``` +Полночное время не выведено. + +#### 💡 Объяснение: + + +До Python 3.5 булево значение для объекта `datetime.time` считалось `False`, если оно представляло полночь по UTC. При использовании синтаксиса `if obj:` для проверки того, что `obj` является null или эквивалентом "пусто", возникает ошибка. + +--- +--- From 662b720b5ca0394b4004fa7ae230ef8eb1f9883c Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 11:47:58 +0300 Subject: [PATCH 116/210] Translate Okay Python, can you make me fly? example --- translations/README-ru.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 92c7cb9d..2d879965 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2919,3 +2919,28 @@ if noon_time: --- --- + + + +## Секция: Скрытые сокровища! + +Секция содержит менее известные интересные нюансы работы Python, которые неизвестны большинству новичков. + +### ▶ Python, можешь ли ты помочь взлелеть? + +Что ж, поехали + +```py +import antigravity +``` + +**Результат:** +Sshh... It's a super-secret. + +#### 💡 Объяснение: + ++ Модуль `antigravity` - одно из немногих пасхальных яиц, выпущенных разработчиками Python. ++ `import antigravity` открывает веб-браузер, указывающий на [классический комикс XKCD](https://xkcd.com/353/) о Python. ++ Это еще не все. Внутри пасхального яйца находится **еще одно пасхальное яйцо**. Если вы посмотрите на [код](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), там определена функция, которая якобы реализует [алгоритм геохашинга XKCD](https://xkcd.com/426/). + +--- From 124b0f027df4b2e3fde7e10af823322f62b40050 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 11:58:51 +0300 Subject: [PATCH 117/210] Translate goto, but why? example --- translations/README-ru.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 2d879965..27e25859 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2944,3 +2944,33 @@ Sshh... It's a super-secret. + Это еще не все. Внутри пасхального яйца находится **еще одно пасхальное яйцо**. Если вы посмотрите на [код](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), там определена функция, которая якобы реализует [алгоритм геохашинга XKCD](https://xkcd.com/426/). --- + + +### ▶ `goto`, но почему? + + +```py +from goto import goto, label +for i in range(9): + for j in range(9): + for k in range(9): + print("I am trapped, please rescue!") + if k == 2: + goto .breakout # выход из глубоко вложенного цикла +label .breakout +print("Freedom!") +``` + +**Результат (Python 2.3):** +```py +I am trapped, please rescue! +I am trapped, please rescue! +Freedom! +``` + +#### 💡 Объяснение: +- Рабочая версия `goto` в Python была [анонсирована](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) в качестве первоапрельской шутки 1 апреля 2004 года. +- В текущих версиях Python этот модуль отсутствует. +- Хотя он работает, но, пожалуйста, не используйте его. Вот [причина](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) того, почему `goto` отсутствует в Python. + +--- From 8ab55b73931edc8e16c430090fc387178fb1740e Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 12:02:09 +0300 Subject: [PATCH 118/210] Translate Brace yourself example --- translations/README-ru.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 27e25859..b75c6f0c 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -2974,3 +2974,31 @@ Freedom! - Хотя он работает, но, пожалуйста, не используйте его. Вот [причина](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) того, почему `goto` отсутствует в Python. --- + + +### ▶ Держитесь! + +Если вы относитесь к тем людям, которым не нравится использование пробелов в Python для обозначения диапазонов, вы можете использовать C-стиль {} импортировав это, + +```py +from __future__ import braces +``` + +**Результат:** +```py + File "some_file.py", line 1 + from __future__ import braces +SyntaxError: not a chance +``` + +Скобочки? Ни за что! Если это разочаровывало вас, используйте Java. Хорошо, еще одна удивительная вещь, можете ли вы найти ошибку +`SyntaxError` которая вызвана в модуле `__future__` [код](https://github.com/python/cpython/blob/master/Lib/__future__.py)? + +#### 💡 Объяснение: + ++ Модуль `__future__` обычно используется для предоставления возможностей из будущих версий Python. Однако "будущее" в данном конкретном контексте - это ирония. ++ Это пасхальное яйцо, связанное с мнением сообщества по этому вопросу. ++ Код на самом деле присутствует [здесь](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) в файле `future.c`. ++ Когда компилятор CPython встречает оператор [future](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), он сначала запускает соответствующий код в `future.c`, а затем рассматривает его как обычный оператор импорта. + +--- From e2d0be0e2adfa33e2504ed673442739dbfac08aa Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 12:09:26 +0300 Subject: [PATCH 119/210] Translate Meet Friendly Language Uncle For Life example --- translations/README-ru.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index b75c6f0c..4cc91ba6 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3002,3 +3002,37 @@ SyntaxError: not a chance + Когда компилятор CPython встречает оператор [future](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), он сначала запускает соответствующий код в `future.c`, а затем рассматривает его как обычный оператор импорта. --- + + +### ▶ Давайте познакомимся с дружелюбным Дядей Барри + +Непереводимая игра слов: Friendly Language Uncle For Life (FLUFL) + +**Результат (Python 3.x)** +```py +>>> from __future__ import barry_as_FLUFL +>>> "Ruby" != "Python" # в этом нет сомнений + File "some_file.py", line 1 + "Ruby" != "Python" + ^ +SyntaxError: invalid syntax + +>>> "Ruby" <> "Python" +True +``` + +Вот так просто. + +#### 💡 Объяснение: +- Это относится к [PEP-401](https://www.python.org/dev/peps/pep-0401/), выпущенному 1 Апреля 2009 (вы знаете, о чем это говорит). +- Цитата из PEP-401 + + > Признав, что оператор неравенства `!=` в Python 3.0 был ужасной, вызывающей боль ошибкой, FLUFL восстанавливает оператор `<>` (ромб) в качестве единственного написания. +- У Дяди Барри было еще много чего рассказать в PEP; вы можете прочитать их [здесь](https://www.python.org/dev/peps/pep-0401/). +- Это работает хорошо в интерактивной среде, но при запуске через файл python вызывает `SyntaxError` (смотри этот [issue](https://github.com/satwikkansal/wtfpython/issues/94)). Однако вы можете обернуть оператор внутри `eval` или `compile`, чтобы заставить его работать (но зачем?) + ```py + from __future__ import barry_as_FLUFL + print(eval('"Ruby" <> "Python"')) + ``` + +--- From 664bb038d42bbab9184d3e7fdfe371dfa83d80a0 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 12:12:47 +0300 Subject: [PATCH 120/210] Translate Even Python understands that love is complicated example --- translations/README-ru.md | 58 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 4cc91ba6..7106a5a1 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3036,3 +3036,61 @@ True ``` --- + + +### ▶ Даже Python понимает, что любовь - это сложно. + +```py +import this +``` + +Подождите, что **это** (this) такое? Это любовь! :heart: + +**Результат:** +``` +Дзен Python, от Тима Петерса + +Красивое лучше, чем уродливое. +Явное лучше, чем неявное. +Простое лучше, чем сложное. +Сложное лучше, чем запутанное. +Плоское лучше, чем вложенное. +Разреженное лучше, чем плотное. +Читаемость имеет значение. +Особые случаи не настолько особые, чтобы нарушать правила. +При этом практичность важнее безупречности. +Ошибки никогда не должны замалчиваться. +Если они не замалчиваются явно. +Встретив двусмысленность, отбрось искушение угадать. +Должен существовать один и, желательно, только один очевидный способ сделать это. +Хотя он поначалу может быть и не очевиден, если вы не голландец [^1]. +Сейчас лучше, чем никогда. +Хотя никогда зачастую лучше, чем прямо сейчас. +Если реализацию сложно объяснить — идея плоха. +Если реализацию легко объяснить — идея, возможно, хороша. +Пространства имён — отличная штука! Будем делать их больше! +``` + +Это Дзен Python! + +```py +>>> love = this +>>> this is love +True +>>> love is True +False +>>> love is False +False +>>> love is not True or False +True +>>> love is not True or False; love is love # Love is complicated +True +``` + +#### 💡 Объяснение: + +* Модуль `this` в Python - это пасхальное яйцо для The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)). +* И если вы думаете, что это уже достаточно интересно, посмотрите реализацию [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Забавный факт - **код для дзена нарушает сам себя** (и это, вероятно, единственное место, где это происходит, но это не точно). +* Что касается утверждения `любовь не является истиной или ложью; любовь - это любовь`, иронично, но описательно (если нет, пожалуйста, посмотрите примеры, связанные с операторами `is` и `is not`). + +--- From 193c83916395713f3fe85ebbcb29f036a23b4603 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 12:17:37 +0300 Subject: [PATCH 121/210] Translate Yes, it exists example --- translations/README-ru.md | 47 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 7106a5a1..92fcdbb9 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3094,3 +3094,50 @@ True * Что касается утверждения `любовь не является истиной или ложью; любовь - это любовь`, иронично, но описательно (если нет, пожалуйста, посмотрите примеры, связанные с операторами `is` и `is not`). --- + + +### ▶ Да, оно существует! + +**Ключевое слово `else` в связвке с циклом `for`.** Один из стандартных примеров: + +```py + def does_exists_num(l, to_find): + for num in l: + if num == to_find: + print("Exists!") + break + else: + print("Does not exist") +``` + +**Результат:** +```py +>>> some_list = [1, 2, 3, 4, 5] +>>> does_exists_num(some_list, 4) +Exists! +>>> does_exists_num(some_list, -1) +Does not exist +``` + +**Использование `else` блока во время обработки исключения.** Пример, + +```py +try: + pass +except: + print("Exception occurred!!!") +else: + print("Try block executed successfully...") +``` + +**Результат:** +```py +Try block executed successfully... +``` + +#### 💡 Объяснение: + +- Блок `else` после цикла выполняется только тогда, когда нет явного `break` после всех итераций. Вы можете думать об этом как о блоке "nobreak". +- Блок `else` после блока `try` также называется "блоком завершения", поскольку достижение `else` в операторе `try` означает, что блок попыток действительно успешно завершен. + +--- From be9c3bb0ae6e6bebe700bb01c6b6398fe4391782 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 12:24:34 +0300 Subject: [PATCH 122/210] Translate Ellipsis example --- translations/README-ru.md | 61 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 92fcdbb9..bf9ea26f 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3141,3 +3141,64 @@ Try block executed successfully... - Блок `else` после блока `try` также называется "блоком завершения", поскольку достижение `else` в операторе `try` означает, что блок попыток действительно успешно завершен. --- + + +### ▶ Многоточие * + +```py +def some_func(): + Ellipsis +``` + +**Результат** +```py +>>> some_func() +# Ни вывода, ни ошибки + +>>> SomeRandomString +Traceback (most recent call last): + File "", line 1, in +NameError: name 'SomeRandomString' is not defined + +>>> Ellipsis +Ellipsis +``` + +#### 💡 Объяснение +- В Python, `Ellipsis` - глобальный встроенный объект, эквивалентный `...`. + ```py + >>> ... + Ellipsis + ``` +- Многоточие может использоваться в нескольких случаях, + + В качестве заполнителя для кода, который еще не написан (аналогично оператору `pass`) + + В синтаксисе срезов (slices) для представления полных срезов в оставшемся направлении + ``py + >>> import numpy as np + >>> three_dimensional_array = np.arange(8).reshape(2, 2, 2) + array([ + [ + [0, 1], + [2, 3] + ], + + [ + [4, 5], + [6, 7] + ] + ]) + ``` + Таким образом, наш `трехмерный_массив` представляет собой массив массивов массивов. Допустим, мы хотим вывести второй элемент (индекс `1`) всех внутренних массивов, мы можем использовать `Ellipsis`, чтобы обойти все предыдущие измерения + ``py + >>> three_dimensional_array[:,::,1] + array([[1, 3], + [5, 7]]) + >>> three_dimensional_array[..., 1] # использование Ellipsis. + array([[1, 3], + [5, 7]]) + ``` + Примечание: это будет работать для любого количества измерений. Можно даже выбрать срез в первом и последнем измерении и игнорировать средние (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`) + + В [подсказках типов](https://docs.python.org/3/library/typing.html) для указания только части типа (например, `(Callable[..., int]` или `Tuple[str, ...]`)) + + Вы также можете использовать `Ellipsis` в качестве аргумента функции по умолчанию (в случаях, когда вы хотите провести различие между сценариями "аргумент не передан" и "значение не передано"). + +--- From 3b9d9bdcd10a5f07b1035c7dd587cc1608c9c67c Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 15:29:06 +0300 Subject: [PATCH 123/210] Translate Inpinity example --- translations/README-ru.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/translations/README-ru.md b/translations/README-ru.md index bf9ea26f..a0ee30f7 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3189,7 +3189,7 @@ Ellipsis ]) ``` Таким образом, наш `трехмерный_массив` представляет собой массив массивов массивов. Допустим, мы хотим вывести второй элемент (индекс `1`) всех внутренних массивов, мы можем использовать `Ellipsis`, чтобы обойти все предыдущие измерения - ``py + ```py >>> three_dimensional_array[:,::,1] array([[1, 3], [5, 7]]) @@ -3202,3 +3202,23 @@ Ellipsis + Вы также можете использовать `Ellipsis` в качестве аргумента функции по умолчанию (в случаях, когда вы хотите провести различие между сценариями "аргумент не передан" и "значение не передано"). --- + + +### ▶ Писконечность (Inpinity) + +В заголовке нет ошибки, так и задумано, пожалуйста, не создавайте issue или pull request с изменением. + +**Результат (Python 3.x):** +```py +>>> infinity = float('infinity') +>>> hash(infinity) +314159 +>>> hash(float('-inf')) +-314159 +``` + +#### 💡 Объяснение: +- Хэш бесконечности - 10⁵ x π. +- Интересно, что хэш `float('-inf')` - "-10⁵ x π" в Python 3, тогда как в Python 2 - "-10⁵ x e". + +--- From b5c20d02ea1b55316864dfe011fd4afc86ccf69b Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 15:39:50 +0300 Subject: [PATCH 124/210] Translate Name mangling example --- translations/README-ru.md | 77 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index a0ee30f7..9eb5ed4a 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3222,3 +3222,80 @@ Ellipsis - Интересно, что хэш `float('-inf')` - "-10⁵ x π" в Python 3, тогда как в Python 2 - "-10⁵ x e". --- + + +### ▶ Давайте искажать + +1\. +```py +class Yo(object): + def __init__(self): + self.__honey = True + self.bro = True +``` + +**Результат:** +```py +>>> Yo().bro +True +>>> Yo().__honey +AttributeError: 'Yo' object has no attribute '__honey' +>>> Yo()._Yo__honey +True +``` + +2\. +```py +class Yo(object): + def __init__(self): + # Попробуем симметричные двойные подчеркивания в названии атрибута + self.__honey__ = True + self.bro = True +``` + +**Результат:** +```py +>>> Yo().bro +True + +>>> Yo()._Yo__honey__ +Traceback (most recent call last): + File "", line 1, in +AttributeError: 'Yo' object has no attribute '_Yo__honey__' +``` + +Почему обращение к `Yo()._Yo__honey` сработало? + +3\. + +```py +_A__variable = "Some value" + +class A(object): + def some_func(self): + return __variable # переменная еще не инициализирована +``` + +**Результат:** +```py +>>> A().__variable +Traceback (most recent call last): + File "", line 1, in +AttributeError: 'A' object has no attribute '__variable' + +>>> A().some_func() +'Some value' +``` + + +#### 💡 Объяснение: + +* [Искажение имени](https://en.wikipedia.org/wiki/Name_mangling) используется для предотвращения коллизий имен между различными пространствами имен. +* В Python интерпретатор изменяет (mangles) имена членов класса, начинающиеся с `__` (двойное подчеркивание, оно же "дундер") и не заканчивающиеся более чем одним подчеркиванием в конце, добавляя перед ними `_NameOfTheClass`. +* Таким образом, чтобы получить доступ к атрибуту `__honey` в первом фрагменте, мы должны были добавить `_Yo` спереди, что предотвратило бы конфликты с тем же атрибутом `name`, определенным в любом другом классе. +* Но почему тогда это не сработало во втором фрагменте? Потому что при манипулировании именами исключаются имена, заканчивающиеся двойным подчеркиванием. +* Третий фрагмент также является следствием манипулирования именами. Имя `__variable` в операторе `return __variable` было искажено до `_A__variable`, что также является именем переменной, которую мы объявили во внешней области видимости. +* Кроме того, если длина искаженного имени превышает 255 символов, произойдет усечение (truncation). + +--- +--- From a5f12582753a0ae9a64137f93f877faa6de490a5 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 15:47:58 +0300 Subject: [PATCH 125/210] Translate Skipping lines? example --- translations/README-ru.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 9eb5ed4a..c8af1b46 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3299,3 +3299,41 @@ AttributeError: 'A' object has no attribute '__variable' --- --- + +## Секция: Внешность обманчива! + +### ▶ Пропускаем строки? + +**Результат:** +```py +>>> value = 11 +>>> valuе = 32 +>>> value +11 +``` + +Что за дела? + +**Заметка:** самый простой способ воспроизвести это - просто скопировать утверждения из приведенного выше фрагмента и вставить их в свой файл/оболочку. + +#### 💡 Объяснение + +Некоторые незападные символы выглядят идентично буквам английского алфавита, но интерпретатор считает их разными. + +```py +>>> ord('е') # кириллическое 'е' (ye) +1077 +>>> ord('e') # латинское 'e', используемое в английском языке и набираемое с помощью стандартной клавиатуры +101 +>>> 'е' == 'е' +false + +>>> value = 42 # латинское "е +>>> valuе = 23 # кириллическое "е", интерпретатор python 2.x вызовет здесь `syntaxerror` +>>> value +42 +``` + +Встроенная функция `ord()` возвращает юникод [кодовую точку символа](https://en.wikipedia.org/wiki/code_point), и разные кодовые позиции кириллического 'e' и латинского 'e' оправдывают поведение приведенного выше примера. + +--- From eab5d5968e1e01b429e6d16a4327428ec588742b Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 15:52:39 +0300 Subject: [PATCH 126/210] Translate Teleportation example --- translations/README-ru.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index c8af1b46..507222fc 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3337,3 +3337,37 @@ false Встроенная функция `ord()` возвращает юникод [кодовую точку символа](https://en.wikipedia.org/wiki/code_point), и разные кодовые позиции кириллического 'e' и латинского 'e' оправдывают поведение приведенного выше примера. --- + + +### ▶ Телепортация + + + +```py +# Прежде всего выполним `pip install numpy`. +import numpy as np + +def energy_send(x): + # Инициализация numpy массива + np.array([float(x)]) + +def energy_receive(): + # Возвращаем пустой numpy массив + return np.empty((), dtype=np.float).tolist() +``` + +**Результат:** +```py +>>> energy_send(123.456) +>>> energy_receive() +123.456 +``` + +Где моя Нобелевская премия? + +#### 💡 Объяснение: + +* Обратите внимание, что массив `numpy`, созданный в функции `energy_send`, не возвращается, так что место в памяти свободно для перераспределения. +* `numpy.empty()` возвращает следующий свободный участок памяти без его повторной инициализации. Этот участок памяти просто оказывается тем же самым, который был только что освобожден (обычно, но не всегда). + +--- From 551b251c054587547c0a9324506558e80e0f776d Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 16:02:55 +0300 Subject: [PATCH 127/210] Translate Well, something is fishy example --- translations/README-ru.md | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 507222fc..b17447ad 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3371,3 +3371,45 @@ def energy_receive(): * `numpy.empty()` возвращает следующий свободный участок памяти без его повторной инициализации. Этот участок памяти просто оказывается тем же самым, который был только что освобожден (обычно, но не всегда). --- + + +### ▶ Что-то не так... + +```py +def square(x): + """ + Простая функция по вычислению квадрата числа путем суммирования. + """ + sum_so_far = 0 + for counter in range(x): + sum_so_far = sum_so_far + x + return sum_so_far +``` + +**Результат (Python 2.x):** + +```py +>>> square(10) +10 +``` + +Разве не должно быть 100? + +**Заметка:** Если у вас не получается воспроизвести это, попробуйте запустить файл [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) через оболочку. + +#### 💡 Объяснение + +* **Не смешивайте табы и пробелы!** Символ, непосредственно предшествующий return, является "табом", а код в других местах примера имеет отступ в 4 пробела. +* Вот как Python обрабатывает табы: + + > Сначала табы заменяются (слева направо) на пробелы от одного до восьми так, чтобы общее количество символов до замены включительно было кратно восьми <...>. +* Таким образом, "табы" в последней строке функции `square` заменяется восемью пробелами, и она попадает в цикл. +* Python 3 достаточно любезен, чтобы автоматически выдавать ошибку для таких случаев. + + **Результат (Python 3.x):** + ```py + TabError: inconsistent use of tabs and spaces in indentation + ``` + +--- +--- From ebe5f59a9dca2b771898f06f8cf823fc8740464a Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 16:06:24 +0300 Subject: [PATCH 128/210] Translate += is faster example --- translations/README-ru.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index b17447ad..032fef9b 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3413,3 +3413,23 @@ def square(x): --- --- + +## Секция: Разное + + +### ▶ `+=` быстрее + + +```py +# Использование "+", 3 строки: +>>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) +0.25748300552368164 +# Использование "+=", 3 строки: +>>> timeit.timeit("s1 += s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) +0.012188911437988281 +``` + +#### 💡 Объяснение: ++ Операнд `+=` быстре `+` для "сложения" 2 и более строк, так как первая строка (например, `s1` for `s1 += s2 + s3`) не уничтожается во время формирования финальной строки. + +--- From 00e420fc516cd4c29a248cbeae5681fb92e6cac3 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 16:16:10 +0300 Subject: [PATCH 129/210] Translate Let's make a giant string! example --- translations/README-ru.md | 99 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/translations/README-ru.md b/translations/README-ru.md index 032fef9b..bb7a1eac 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3430,6 +3430,103 @@ def square(x): ``` #### 💡 Объяснение: -+ Операнд `+=` быстре `+` для "сложения" 2 и более строк, так как первая строка (например, `s1` for `s1 += s2 + s3`) не уничтожается во время формирования финальной строки. ++ Операнд `+=` быстрее `+` для "сложения" 2 и более строк, так как первая строка (например, `s1` for `s1 += s2 + s3`) не уничтожается во время формирования финальной строки. + +--- + + +### ▶ Сделаем гигантскую строку! + +```py +def add_string_with_plus(iters): + s = "" + for i in range(iters): + s += "xyz" + assert len(s) == 3*iters + +def add_bytes_with_plus(iters): + s = b"" + for i in range(iters): + s += b"xyz" + assert len(s) == 3*iters + +def add_string_with_format(iters): + fs = "{}"*iters + s = fs.format(*(["xyz"]*iters)) + assert len(s) == 3*iters + +def add_string_with_join(iters): + l = [] + for i in range(iters): + l.append("xyz") + s = "".join(l) + assert len(s) == 3*iters + +def convert_list_to_string(l, iters): + s = "".join(l) + assert len(s) == 3*iters +``` + +**Результат:** + +```py +# Фрагменты выполняются в оболочке `ipython` с использованием `%timeit` для лучшей читаемости результатов. +# Вы также можете использовать модуль timeit в обычной оболочке python shell/scriptm=, пример использования ниже +# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) + +>>> NUM_ITERS = 1000 +>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) +124 µs ± 4.73 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) +>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) +211 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_format(NUM_ITERS) +61 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_join(NUM_ITERS) +117 µs ± 3.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> l = ["xyz"]*NUM_ITERS +>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) +10.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +``` + +Увеличим число итераций в 10 раз. + +```py +>>> NUM_ITERS = 10000 +>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) # Линейное увеличение времени выполнения +1.26 ms ± 76.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Квадратичное увеличение +6.82 ms ± 134 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_format(NUM_ITERS) # Линейное увеличение +645 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_join(NUM_ITERS) # Линейное увеличение +1.17 ms ± 7.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> l = ["xyz"]*NUM_ITERS +>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Линейное увеличение +86.3 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +``` + +#### 💡 Объяснение + +- Подробнее о [timeit](https://docs.python.org/3/library/timeit.html) или [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) вы можете прочитать по этим ссылкам. Они используются для измерения времени выполнения фрагментов кода. +- Не используйте `+` для генерации длинных строк - В Python `str` неизменяема, поэтому левая и правая строки должны быть скопированы в новую строку для каждой пары конкатенаций. Если вы конкатенируете четыре строки длины 10, то вместо 40 символов вы скопируете (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 символов. С увеличением количества и размера строки ситуация ухудшается в квадратичной прогрессии (что подтверждается временем выполнения функции `add_bytes_with_plus`). +- Поэтому рекомендуется использовать синтаксис `.format.` или `%` (правда, для очень коротких строк они немного медленнее, чем `+`). +- Или лучше, если у вас уже есть содержимое в виде итерируемого объекта, тогда используйте `''.join(iterable_object)`, что гораздо быстрее. +- В отличие от `add_bytes_with_plus` из-за оптимизаций `+=`, рассмотренных в предыдущем примере, `add_string_with_plus` не показало квадратичного увеличения времени выполнения. Если бы оператор был `s = s + "x" + "y" + "z"` вместо `s += "xyz"`, увеличение было бы квадратичным. + ```py + def add_string_with_plus(iters): + s = "" + for i in range(iters): + s = s + "x" + "y" + "z" + assert len(s) == 3*iters + + >>> %timeit -n100 add_string_with_plus(1000) + 388 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) + >>> %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time + 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) + ``` + +- Такое число способов форматирования и создания гигантской строки несколько противоречит [Zen of Python](https://www.python.org/dev/peps/pep-0020/), согласно которому, + + > должен быть один - и желательно только один - очевидный способ сделать это. --- From 4b4951d7558dd3e76d841c747a19a9a7edd6ecdc Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 16:21:51 +0300 Subject: [PATCH 130/210] Translate Slowing down dict lookups example --- translations/README-ru.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index bb7a1eac..570c8b4d 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3530,3 +3530,39 @@ def convert_list_to_string(l, iters): > должен быть один - и желательно только один - очевидный способ сделать это. --- + + +### ▶ Замедляем поиск по `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)} +``` + +**Результат:** +```py +>>> %timeit some_dict['5'] +28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +>>> some_dict[1] = 1 +>>> %timeit some_dict['5'] +37.2 ns ± 0.265 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) + +>>> %timeit another_dict['5'] +28.5 ns ± 0.142 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +>>> another_dict[1] # Пытаемся получить значение по несуществующему ключу +Traceback (most recent call last): + File "", line 1, in +KeyError: 1 +>>> %timeit another_dict['5'] +38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +``` +Почему одни и те же выражения становятся медленнее? + +#### 💡 Объяснение: + ++ В CPython есть общая функция поиска по словарю, которая работает со всеми типами ключей (`str`, `int`, любой объект ...), и специализированная для распространенного случая словарей, состоящих только из `str`-ключей. ++ Специализированная функция (названная `lookdict_unicode` в [исходный код CPython](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) знает, что все существующие ключи (включая искомый ключ) являются строками, и использует более быстрое и простое сравнение строк для сравнения ключей, вместо вызова метода `__eq__`. ++ При первом обращении к экземпляру `dict` с ключом, не являющимся `str`, он модифицируется, чтобы в дальнейшем для поиска использовалась общая функция. ++ Этот процесс не обратим для конкретного экземпляра `dict`, и ключ даже не обязательно должен существовать в словаре. Поэтому попытка неудачного поиска имеет тот же эффект. + +--- From 9e2508ae6a95e61a2d924bbb61951aef4311307f Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 16:28:57 +0300 Subject: [PATCH 131/210] Translate Bloating instance dict's example --- translations/README-ru.md | 64 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 570c8b4d..58940731 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3566,3 +3566,67 @@ KeyError: 1 + Этот процесс не обратим для конкретного экземпляра `dict`, и ключ даже не обязательно должен существовать в словаре. Поэтому попытка неудачного поиска имеет тот же эффект. --- + + +### ▶ Раздуваем экземпляры словарей * + +```py +import sys + +class SomeClass: + def __init__(self): + self.some_attr1 = 1 + self.some_attr2 = 2 + self.some_attr3 = 3 + self.some_attr4 = 4 + + +def dict_size(o): + return sys.getsizeof(o.__dict__) + +``` + +**Результат:** (Python 3.8, другие версии Python 3 могут немного отличаться) +```py +>>> o1 = SomeClass() +>>> o2 = SomeClass() +>>> dict_size(o1) +104 +>>> dict_size(o2) +104 +>>> del o1.some_attr1 +>>> o3 = SomeClass() +>>> dict_size(o3) +232 +>>> dict_size(o1) +232 +``` + +Попробуем снова... В новом сессии интерпретатора: + +```py +>>> o1 = SomeClass() +>>> o2 = SomeClass() +>>> dict_size(o1) +104 # как ожидается +>>> o1.some_attr5 = 5 +>>> o1.some_attr6 = 6 +>>> dict_size(o1) +360 +>>> dict_size(o2) +272 +>>> o3 = SomeClass() +>>> dict_size(o3) +232 +``` + +Что заставляет эти словари раздуваться? И почему только созданные объекты также раздуваются? + +#### 💡 Объяснение: ++ CPython может повторно использовать один и тот же объект "keys" в нескольких словарях. Это было добавлено в [PEP 412](https://www.python.org/dev/peps/pep-0412/) с целью сокращения использования памяти, особенно в экземплярах словарей - где ключи (атрибуты экземпляра), как правило, общие для всех экземпляров. ++ Эта оптимизация совершенно беспроблемна для экземпляров словарей, но она не работает, если нарушены некоторые условия. ++ Словари с общим доступом к ключам не поддерживают удаление; если атрибут экземпляра удаляется, словарь становится "не общим", и общий доступ к ключам отключается для всех последующих экземпляров того же класса. ++ Кроме того, если размер ключей словаря был изменен (из-за вставки новых ключей), они остаются общими *только* если они используются только одним словарем (это позволяет добавить много атрибутов в `__init__` самого первого созданного экземпляра, не вызывая "unshare"). Если на момент изменения размера существует несколько экземпляров, совместное использование ключей отключается для всех последующих экземпляров одного класса: CPython не может определить, используют ли ваши экземпляры один и тот же набор атрибутов, и решает отказаться от попытки поделиться ключами. ++ Небольшой совет, если вы стремитесь уменьшить занимаемый программой объем памяти: не удаляйте атрибуты экземпляров и обязательно инициализируйте все атрибуты в `__init__`! + +--- From f71b997a450c69e97916f0c49b0b68a740161048 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 24 Apr 2024 17:00:05 +0300 Subject: [PATCH 132/210] Translate Minor ones example --- translations/README-ru.md | 141 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 58940731..3e2f5717 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3630,3 +3630,144 @@ def dict_size(o): + Небольшой совет, если вы стремитесь уменьшить занимаемый программой объем памяти: не удаляйте атрибуты экземпляров и обязательно инициализируйте все атрибуты в `__init__`! --- + + +### ▶ Минорное * + +* `join()` - строковая операция вместо списочной. (может показаться неочевидным при первом использовании) + + **💡 Объяснение:** Если `join()` - это строковый метод, то он может работать с любым итеруемыми объектами (список, кортеж, итераторы). Если бы это был списковый метод, то его пришлось бы реализовывать отдельно для каждого типа. Кроме того, нет особого смысла помещать метод, специфичный для строки, в общий API объекта `list`. + +* Несколько странных, но семантически правильных утверждений: + + `[] = ()` - семантически корректное утверждение (распаковка пустого `кортежа` в пустой `список`) + + `'a'[0][0][0][0][0]` также является семантически корректным утверждением, поскольку в Python строки являются [последовательностями](https://docs.python.org/3/glossary.html#term-sequence)(итерируемыми объектами, поддерживающими доступ к элементам с использованием целочисленных индексов). + + `3 --0-- 5 == 8` и `--5 == 5` - оба семантически корректные утверждения и имеют значение `True`. + +* Учитывая, что `a` - это число, `++a` и `--a` являются корректными утверждениями Python, но ведут себя не так, как аналогичные утверждения в таких языках, как C, C++ или Java. + ```py + >>> a = 5 + >>> a + 5 + >>> ++a + 5 + >>> --a + 5 + ``` + + **💡 Объяснение:** + + В грамматике Python нет оператора `++`. На самом деле это два оператора `+`. + + `++a` преобразуется в `+(+a)`, а затем в `a`. Аналогично для утверждения `--a`. + + На [StackOverflow](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) обсуждается обоснование отсутствия операторов инкремента и декремента в Python. + +* Вы наверняка знаете об операторе Walrus в Python. Но слышали ли вы когда-нибудь об операторе *пространственного инкремента*? + ```py + >>> a = 42 + >>> a -=- 1 + >>> a + 43 + ``` + Он используется как альтернативный оператор инкрементации, вместе с другим оператором + ```py + >>> a +=+ 1 + >>> a + >>> 44 + ``` + **💡 Объяснение:** Этот розыгрыш взят из твита [Raymond Hettinger](https://twitter.com/raymondh/status/1131103570856632321?lang=en). На самом деле оператор захвата пространства - это просто неправильно отформатированное `a -= (-1)`. Что эквивалентно `a = a - (- 1)`. Аналогично для случая `a += (+ 1)`. + +* В Python есть недокументированный оператор [обратная импликация](https://en.wikipedia.org/wiki/Converse_implication). + ```py + >>> False ** False == True + True + >>> False ** True == False + True + >>> True ** False == True + True + >>> True ** True == True + True + ``` + + **💡 Объяснение:** Если заменить `False` и `True` на 0 и 1 и произвести математические вычисления, то таблица истинности будет эквивалентна оператору обратной импликации. ([Источник](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 + ``` + + **💡 Объяснение:** Оператор `@` был добавлен в Python 3.5 с учетом пожеланий научного сообщества. Любой объект может перегрузить магический метод `__matmul__`, чтобы определить поведение этого оператора. + +* Начиная с Python 3.8 для быстрой отладки можно использовать типичный синтаксис f-строк, например `f'{some_var=}`. Пример, + ```py + >>> some_string = "wtfpython" + >>> f'{some_string=}' + "some_string='wtfpython'" + ``` + +* Python использует 2 байта для хранения локальных переменных в функциях. Теоретически это означает, что в функции может быть определено только 65536 переменных. Однако в python есть удобное решение, которое можно использовать для хранения более 2^16 имен переменных. Следующий код демонстрирует, что происходит в стеке, когда определено более 65536 локальных переменных (Внимание: этот код печатает около 2^18 строк текста, так что будьте готовы!): + ```py + import dis + exec(""" + def f(): + """ + """ + """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) + + f() + + print(dis.dis(f)) + ``` + +* Несколько потоков Python не смогут выполнять ваш *Python-код* одновременно (да, вы не ослышались!). Может показаться интуитивно понятным породить несколько потоков и позволить им выполнять ваш Python код одновременно, но из-за [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) в Python, все, что вы делаете, это заставляете ваши потоки выполняться на одном и том же ядре по очереди. Потоки Python хороши для задач, связанных с IO, но чтобы добиться реального распараллеливания в Python для задач, связанных с процессором, вы можете использовать модуль Python [multiprocessing](https://docs.python.org/3/library/multiprocessing.html). + +* Иногда метод `print` может выводить значения с задержкой. Например, + ```py + # Файл some_file.py + import time + + print("wtfpython", end="_") + time.sleep(3) + ``` + + Это выведет `wtfpython` через 3 секунды из-за аргумента `end`, потому что выходной буфер очищается либо при появлении `\n`, либо когда программа завершает выполнение. Мы можем принудительно отчистить буфер, передав аргумент `flush=True`. + +* Срез списка индексом, превышающим длину списка, не приводит к ошибкам + ```py + >>> some_list = [1, 2, 3, 4, 5] + >>> some_list[111:] + [] + ``` + +* При срезе итерируемого объекта не всегда создается новый объект. Например, + ```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` в Python 3. В Python десятичные символы включают в себя символы цифр и все символы, которые могут быть использованы для формирования десятично-радиксных чисел, например U+0660, ARABIC-INDIC DIGIT ZERO. Вот [интересная история](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/), связанная с таким поведением Python. + +* Начиная с Python 3 вы можете разделять числовые литералы символами подчеркивания (для лучшей читаемости). + ```py + >>> six_million = 6_000_000 + >>> six_million + 6000000 + >>> hex_address = 0xF00D_CAFE + >>> hex_address + 4027435774 + ``` + +* `'abc'.count('') == 4`. Вот примерная реализация метода `count`, которая немного разъяснит ситуацию + ```py + def count(s, sub): + result = 0 + for i in range(len(s) + 1 - len(sub)): + result += (s[i:i + len(sub)] == sub) + return result + ``` + Такое поведение связано с совпадением пустой подстроки(`''`) со срезами длины 0 в исходной строке. + +--- +--- From 05ad6cf2af4afa2e359a6a378faf5727bd082045 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 25 Apr 2024 11:00:05 +0300 Subject: [PATCH 133/210] Translate Contributing example --- translations/README-ru.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 3e2f5717..389de557 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3771,3 +3771,17 @@ def dict_size(o): --- --- + +# Вклад в проект + +Как можно внести свой вклад в развитие wtfpython, + +- Предложить новые примеры +- Помочь в переводе (См. [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation)) +- Мелкие исправления, такие как указание на устаревшие фрагменты, опечатки, ошибки форматирования и т.д. +- Выявление пробелов (таких как недостаточное объяснение, избыточные примеры и т. д.) +- Любые творческие предложения, чтобы сделать этот проект более интересным и полезным. + +Пожалуйста, смотрите [CONTRIBUTING.md](/CONTRIBUTING.md) для более подробной информации. Не стесняйтесь создать новый [issue](https://github.com/satwikkansal/wtfpython/issues/new) для обсуждения. + +PS: Пожалуйста, не обращайтесь к нам с просьбами об обратной ссылке, ссылки не будут добавлены, если они не имеют отношения к проекту. From d7d7e970d715b3ef7cc84f7bda6d7bcf3f1bd373 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 25 Apr 2024 11:04:25 +0300 Subject: [PATCH 134/210] Translate Aknowledgements and links example --- translations/README-ru.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 389de557..4e48efa1 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3785,3 +3785,19 @@ def dict_size(o): Пожалуйста, смотрите [CONTRIBUTING.md](/CONTRIBUTING.md) для более подробной информации. Не стесняйтесь создать новый [issue](https://github.com/satwikkansal/wtfpython/issues/new) для обсуждения. PS: Пожалуйста, не обращайтесь к нам с просьбами об обратной ссылке, ссылки не будут добавлены, если они не имеют отношения к проекту. + +# Благодарности + +Идея и дизайн этой коллекции были изначально вдохновлены потрясающим проектом Дениса Дована [wtfjs](https://github.com/denysdovhan/wtfjs). Подавляющая поддержка со стороны питонистов придала проекту ту форму, в которой он находится сейчас. + +#### Несколько хороших ссылок! +* 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 +* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines +* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python +* https://www.python.org/doc/humor/ +* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator +* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 +* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues +* Ветки обсуждения WFTPython на [Hacker News](https://news.ycombinator.com/item?id=21862073) и [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). From f0afccc347ff1eaa9f75dd20cdbaa6b3c6f0ff87 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 25 Apr 2024 11:08:22 +0300 Subject: [PATCH 135/210] Translate License and remaining info example --- translations/README-ru.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/translations/README-ru.md b/translations/README-ru.md index 4e48efa1..c986982d 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -3801,3 +3801,24 @@ PS: Пожалуйста, не обращайтесь к нам с просьб * https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 * https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues * Ветки обсуждения WFTPython на [Hacker News](https://news.ycombinator.com/item?id=21862073) и [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). + +# 🎓 Лицензия + +[![WTFPL 2.0][license-image]][license-url] + +© [Satwik Kansal](https://satwikkansal.xyz) + +[license-url]: http://www.wtfpl.net +[license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square + +## Удиви своих друзей! + +Если вам нравится `wtfpython`, вы можете поделиться проектом, используя быстрые ссылки, + +[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!) + +### Нужна PDF версия? + +Я получил несколько запросов на pdf (и epub) версию wtfpython. Вы можете добавить свои данные [здесь](https://form.jotform.com/221593245656057), чтобы получить их, как только они будут готовы. + +**Вот и все, друзья!** Для получения новых материалов, подобных этому, вы можете добавить свой email [сюда](https://form.jotform.com/221593598380062). From 2c623dd33a8865e00be7261bb27a191df2e67d59 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 25 Apr 2024 11:12:29 +0300 Subject: [PATCH 136/210] Actualize Table of contents --- translations/README-ru.md | 86 ++++++++++++++++++++++++++++++++++----- 1 file changed, 76 insertions(+), 10 deletions(-) diff --git a/translations/README-ru.md b/translations/README-ru.md index c986982d..2f30ae06 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -17,16 +17,82 @@ PS: Если вы уже читали **wtfpython** раньше, с измен Ну что ж, приступим... # Содержание - -- [Содержание](#содержание) -- [Структура примера](#структура-примера) -- [Применение](#применение) -- [👀 Примеры](#-примеры) - - [Секция: Напряги мозги!](#секция-напряги-мозги) - - [▶ Первым делом!](#-первым-делом) - - [💡 Обьяснение](#-обьяснение) - - [▶ Строки иногда ведут себя непредсказуемо](#-строки-иногда-ведут-себя-непредсказуемо) - - [💡 Объяснение](#-объяснение) +* [Содержание](#Содержание) +* [Структура примера](#Структура-примера) +* [Применение](#Применение) +* [👀 Примеры](#👀-Примеры) + * [Секция: Напряги мозги!](#Секция:-Напряги-мозги!) + * [▶ Первым делом!](#▶-Первым-делом!) + * [▶ Строки иногда ведут себя непредсказуемо](#▶-Строки-иногда-ведут-себя-непредсказуемо) + * [▶ Осторожнее с цепочкой операций](#▶-Осторожнее-с-цепочкой-операций) + * [▶ Как не надо использовать оператор `is`](#▶-Как-не-надо-использовать-оператор-`is`) + * [▶ Мистическое хэширование](#▶-Мистическое-хэширование) + * [▶ В глубине души мы все одинаковы.](#▶-В-глубине-души-мы-все-одинаковы.) + * [▶ Беспорядок внутри порядка *](#▶-Беспорядок-внутри-порядка--*) + * [▶ Продолжай пытаться... *](#▶-Продолжай-пытаться...-*) + * [▶ Для чего?](#▶-Для-чего?) + * [▶ Расхождение во времени исполнения](#▶-Расхождение-во-времени-исполнения) + * [▶ `is not ...` не является `is (not ...)`](#▶-`is-not-...`-не-является-`is-(not-...)`) + * [▶ Крестики-нолики, где X побеждает с первой попытки!](#▶-Крестики-нолики,-где-X-побеждает-с-первой-попытки!) + * [▶ Переменная Шредингера *](#▶-Переменная-Шредингера-*) + * [▶ Проблема курицы и яйца *](#▶-Проблема-курицы-и-яйца-*) + * [▶ Отношения между подклассами](#▶-Отношения-между-подклассами) + * [▶ Равенство и тождество методов](#▶-Равенство-и-тождество-методов) + * [▶ All-true-ation (непереводимая игра слов) *](#▶-All-true-ation-(непереводимая-игра-слов)-*) + * [▶ Неожиданная запятая](#▶-Неожиданная-запятая) + * [▶ Строки и обратные слэши](#▶-Строки-и-обратные-слэши) + * [▶ Не узел! (eng. not knot!)](#▶-Не-узел!-(eng.-not-knot!)) + * [▶ Строки наполовину в тройных кавычках](#▶-Строки-наполовину-в-тройных-кавычках) + * [▶ Что не так с логическими значениями?](#▶-Что-не-так-с-логическими-значениями?) + * [▶ Атрибуты класса и экземпляра](#▶-Атрибуты-класса-и-экземпляра) + * [▶ Возврат None из генератора](#▶-Возврат-None-из-генератора) + * [▶ Yield from возвращает... *](#▶-Yield-from-возвращает...-*) + * [▶ Nan-рефлексивность *](#▶-Nan-рефлексивность-*) + * [▶ Мутируем немутируемое!](#▶-Мутируем-немутируемое!) + * [▶ Исчезающая переменная из внешней области видимости](#▶-Исчезающая-переменная-из-внешней-области-видимости) + * [▶ Превышение предела целочисленного преобразования строк](#▶-Превышение-предела-целочисленного-преобразования-строк) + * [Секция: Скользкие склоны](#Секция:-Скользкие-склоны) + * [▶ Изменение словаря во время прохода по нему](#▶-Изменение-словаря-во-время-прохода-по-нему) + * [▶ Упрямая операция `del`](#▶-Упрямая-операция-`del`) + * [▶ Переменная за пределами видимости](#▶-Переменная-за-пределами-видимости) + * [▶ Удаление элемента списка во время прохода по списку](#▶-Удаление-элемента-списка-во-время-прохода-по-списку) + * [▶ Сжатие итераторов с потерями *](#▶-Сжатие-итераторов-с-потерями-*) + * [▶ Утечка переменных внутри цикла](#▶-Утечка-переменных-внутри-цикла) + * [▶ Остерегайтесь изменяемых аргументов по умолчанию!](#▶-Остерегайтесь-изменяемых-аргументов-по-умолчанию!) + * [▶ Ловля исключений](#▶-Ловля-исключений) + * [▶ Одни и те же операнды, разная история!](#▶-Одни-и-те-же-операнды,-разная-история!) + * [▶ Разрешение имен игнорирует область видимости класса](#▶-Разрешение-имен-игнорирует-область-видимости-класса) + * [▶ Округляясь как банкир *](#▶-Округляясь-как-банкир-*) + * [▶ Иголки в стоге сена *](#▶-Иголки-в-стоге-сена-*) + * [▶ Сплиты (splitsies) *](#▶-Сплиты-(splitsies)-*) + * [▶ Подстановочное импортирование (wild imports) *](#▶-Подстановочное-импортирование-(wild-imports)-*) + * [▶ Все ли отсортировано? *](#▶-Все-ли-отсортировано?-*) + * [▶ Полночи не существует?](#▶-Полночи-не-существует?) + * [Секция: Скрытые сокровища!](#Секция:-Скрытые-сокровища!) + * [▶ Python, можешь ли ты помочь взлелеть?](#▶-Python,-можешь-ли-ты-помочь-взлелеть?) + * [▶ `goto`, но почему?](#▶-`goto`,-но-почему?) + * [▶ Держитесь!](#▶-Держитесь!) + * [▶ Давайте познакомимся с дружелюбным Дядей Барри](#▶-Давайте-познакомимся-с-дружелюбным-Дядей-Барри) + * [▶ Даже Python понимает, что любовь - это сложно.](#▶-Даже-Python-понимает,-что-любовь---это-сложно.) + * [▶ Да, оно существует!](#▶-Да,-оно-существует!) + * [▶ Многоточие *](#▶-Многоточие-*) + * [▶ Писконечность (Inpinity)](#▶-Писконечность-(Inpinity)) + * [▶ Давайте искажать](#▶-Давайте-искажать) + * [Секция: Внешность обманчива!](#Секция:-Внешность-обманчива!) + * [▶ Пропускаем строки?](#▶-Пропускаем-строки?) + * [▶ Телепортация](#▶-Телепортация) + * [▶ Что-то не так...](#▶-Что-то-не-так...) + * [Секция: Разное](#Секция:-Разное) + * [▶ `+=` быстрее](#▶-`+=`-быстрее) + * [▶ Сделаем гигантскую строку!](#▶-Сделаем-гигантскую-строку!) + * [▶ Замедляем поиск по `dict` *](#▶-Замедляем-поиск-по-`dict`-*) + * [▶ Раздуваем экземпляры словарей *](#▶-Раздуваем-экземпляры-словарей-*) + * [▶ Минорное *](#▶-Минорное-*) +* [Вклад в проект](#Вклад-в-проект) +* [Благодарности](#Благодарности) +* [🎓 Лицензия](#🎓-Лицензия) + * [Удиви своих друзей!](#Удиви-своих-друзей!) + * [Нужна PDF версия?](#Нужна-PDF-версия?) # Структура примера From 5bbdcdd5a505880c22c55f28860276f6eeab6a65 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 26 Apr 2024 10:44:11 +0300 Subject: [PATCH 137/210] Translate CONTRIBUTORS, fix Markdown table syntax --- CONTRIBUTORS.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ca0e88a2..8a22a49b 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1,6 +1,6 @@ -Following are the wonderful people (in no specific order) who have contributed their examples to wtfpython. +Ниже перечислены (без определенного порядка) замечательные люди, которые внесли вклад в развитие wtfpython. -| Contributor | Github | Issues | +| Автор | Github | Issues | |-------------|--------|--------| | Lucas-C | [Lucas-C](https://github.com/Lucas-C) | [#36](https://github.com/satwikkansal/wtfpython/issues/36) | | MittalAshok | [MittalAshok](https://github.com/MittalAshok) | [#23](https://github.com/satwikkansal/wtfpython/issues/23) | @@ -18,25 +18,25 @@ Following are the wonderful people (in no specific order) who have contributed t | leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [#112](https://github.com/satwikkansal/wtfpython/issues/112) | | mishaturnbull | [mishaturnbull](https://github.com/mishaturnbull) | [#108](https://github.com/satwikkansal/wtfpython/issues/108) | | MuseBoy | [MuseBoy](https://github.com/MuseBoy) | [#101](https://github.com/satwikkansal/wtfpython/issues/101) | -| Ghost account | N/A | [#96](https://github.com/satwikkansal/wtfpython/issues/96) +| Ghost account | N/A | [#96](https://github.com/satwikkansal/wtfpython/issues/96) | | koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) | | jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) | | Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208), [#210](https://github.com/satwikkansal/wtfpython/issues/210), [#233](https://github.com/satwikkansal/wtfpython/issues/233) | | Diptangsu Goswami | [diptangsu](https://github.com/diptangsu) | [#193](https://github.com/satwikkansal/wtfpython/issues/193) | -| Charles | [charles-l](https://github.com/charles-l) | [#245](https://github.com/satwikkansal/wtfpython/issues/245) -| LiquidFun | [LiquidFun](https://github.com/LiquidFun) | [#267](https://github.com/satwikkansal/wtfpython/issues/267) +| Charles | [charles-l](https://github.com/charles-l) | [#245](https://github.com/satwikkansal/wtfpython/issues/245) | +| LiquidFun | [LiquidFun](https://github.com/LiquidFun) | [#267](https://github.com/satwikkansal/wtfpython/issues/267) | --- -**Translations** +**Переводчики** -| Translator | Github | Language | +| Переводчик | Github | Язык | |-------------|--------|--------| | leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [Chinese](https://github.com/leisurelicht/wtfpython-cn) | | vuduclyunitn | [vuduclyunitn](https://github.com/vuduclyunitn) | [Vietnamese](https://github.com/vuduclyunitn/wtfptyhon-vi) | | José De Freitas | [JoseDeFreitas](https://github.com/JoseDeFreitas) | [Spanish](https://github.com/JoseDeFreitas/wtfpython-es) | +| Vadim Nifadev | [nifadyev](https://github.com/nifadyev) | [Russian](https://github.com/satwikkansal/wtfpython/tree/main/translations/README-ru.md) | +Спасибо всем за ваше время и за то, что делаете wtfpython еще более потрясающим! :smile: -Thank you all for your time and making wtfpython more awesome! :smile: - -PS: This list is updated after every major release, if I forgot to add your contribution here, please feel free to raise a Pull request. +PS: Этот список обновляется после каждого крупного релиза, если я забыл добавить сюда ваш вклад, пожалуйста, не стесняйтесь сделать Pull request. From d0dd3ad2b7f5ccf73aeb9aba2d2f570f5cfff218 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sat, 27 Apr 2024 12:21:12 +0300 Subject: [PATCH 138/210] Fix typos and spelling --- translations/README-ru.md | 396 ++++++++++++++++++++++---------------- 1 file changed, 228 insertions(+), 168 deletions(-) diff --git a/translations/README-ru.md b/translations/README-ru.md index 2f30ae06..9cde0244 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -1,98 +1,163 @@

What the f*ck Python! 😱

-

Изучение и понимание Python с помощью нестандартного поведения и "магического" поведения.

+

Изучение и понимание Python с помощью удивительных примеров поведения.

-Переводы: [English Original](https://github.com/satwikkansal/wtfpython) [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/nifadyev/wtfpython/tree/main/translations/README-ru.md) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Переводы: [English Original](https://github.com/satwikkansal/wtfpython) [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/main/translations/README-ru.md) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Альтернативные способы: [Интерактивный сайт](https://wtfpython-interactive.vercel.app) | [Интерактивный Jupiter notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) -Python, будучи прекрасно спроектированным высокоуровневым языком программирования, предоставляет множество возможностей для удобства программиста. Но иногда результаты работы Python кода могут показаться неочевидными на первый взгляд. +Python, будучи прекрасно спроектированным высокоуровневым языком программирования, предоставляет множество возможностей для удобства программиста. Но иногда поведение Python кода могут показаться запутывающим на первый взгляд. -**wtfpython** задуман как проект, пытающийся объяснить, что именно происходит под капотом некоторых неочевидных фрагментов кода и менее известных возможностей Python. +**wtfpython** задуман как проект, пытающийся объяснить, что именно происходит под капотом неочевидных фрагментов кода и малоизвестных возможностей Python. -Если вы опытный программист на Python, вы можете принять это как вызов и правильно объяснить WTF ситуации с первой попытки. Возможно, вы уже сталкивались с некоторыми из них раньше, и я смогу оживить ваши старые добрые воспоминания! 😅 +Если вы опытный питонист, вы можете принять это как вызов и правильно объяснить WTF ситуации с первой попытки. Возможно, вы уже сталкивались с некоторыми из них раньше, и я смогу оживить ваши старые добрые воспоминания! 😅 PS: Если вы уже читали **wtfpython** раньше, с изменениями можно ознакомиться [здесь](https://github.com/satwikkansal/wtfpython/releases/) (примеры, отмеченные звездочкой - это примеры, добавленные в последней основной редакции). Ну что ж, приступим... # Содержание -* [Содержание](#Содержание) -* [Структура примера](#Структура-примера) -* [Применение](#Применение) -* [👀 Примеры](#👀-Примеры) - * [Секция: Напряги мозги!](#Секция:-Напряги-мозги!) - * [▶ Первым делом!](#▶-Первым-делом!) - * [▶ Строки иногда ведут себя непредсказуемо](#▶-Строки-иногда-ведут-себя-непредсказуемо) - * [▶ Осторожнее с цепочкой операций](#▶-Осторожнее-с-цепочкой-операций) - * [▶ Как не надо использовать оператор `is`](#▶-Как-не-надо-использовать-оператор-`is`) - * [▶ Мистическое хэширование](#▶-Мистическое-хэширование) - * [▶ В глубине души мы все одинаковы.](#▶-В-глубине-души-мы-все-одинаковы.) - * [▶ Беспорядок внутри порядка *](#▶-Беспорядок-внутри-порядка--*) - * [▶ Продолжай пытаться... *](#▶-Продолжай-пытаться...-*) - * [▶ Для чего?](#▶-Для-чего?) - * [▶ Расхождение во времени исполнения](#▶-Расхождение-во-времени-исполнения) - * [▶ `is not ...` не является `is (not ...)`](#▶-`is-not-...`-не-является-`is-(not-...)`) - * [▶ Крестики-нолики, где X побеждает с первой попытки!](#▶-Крестики-нолики,-где-X-побеждает-с-первой-попытки!) - * [▶ Переменная Шредингера *](#▶-Переменная-Шредингера-*) - * [▶ Проблема курицы и яйца *](#▶-Проблема-курицы-и-яйца-*) - * [▶ Отношения между подклассами](#▶-Отношения-между-подклассами) - * [▶ Равенство и тождество методов](#▶-Равенство-и-тождество-методов) - * [▶ All-true-ation (непереводимая игра слов) *](#▶-All-true-ation-(непереводимая-игра-слов)-*) - * [▶ Неожиданная запятая](#▶-Неожиданная-запятая) - * [▶ Строки и обратные слэши](#▶-Строки-и-обратные-слэши) - * [▶ Не узел! (eng. not knot!)](#▶-Не-узел!-(eng.-not-knot!)) - * [▶ Строки наполовину в тройных кавычках](#▶-Строки-наполовину-в-тройных-кавычках) - * [▶ Что не так с логическими значениями?](#▶-Что-не-так-с-логическими-значениями?) - * [▶ Атрибуты класса и экземпляра](#▶-Атрибуты-класса-и-экземпляра) - * [▶ Возврат None из генератора](#▶-Возврат-None-из-генератора) - * [▶ Yield from возвращает... *](#▶-Yield-from-возвращает...-*) - * [▶ Nan-рефлексивность *](#▶-Nan-рефлексивность-*) - * [▶ Мутируем немутируемое!](#▶-Мутируем-немутируемое!) - * [▶ Исчезающая переменная из внешней области видимости](#▶-Исчезающая-переменная-из-внешней-области-видимости) - * [▶ Превышение предела целочисленного преобразования строк](#▶-Превышение-предела-целочисленного-преобразования-строк) - * [Секция: Скользкие склоны](#Секция:-Скользкие-склоны) - * [▶ Изменение словаря во время прохода по нему](#▶-Изменение-словаря-во-время-прохода-по-нему) - * [▶ Упрямая операция `del`](#▶-Упрямая-операция-`del`) - * [▶ Переменная за пределами видимости](#▶-Переменная-за-пределами-видимости) - * [▶ Удаление элемента списка во время прохода по списку](#▶-Удаление-элемента-списка-во-время-прохода-по-списку) - * [▶ Сжатие итераторов с потерями *](#▶-Сжатие-итераторов-с-потерями-*) - * [▶ Утечка переменных внутри цикла](#▶-Утечка-переменных-внутри-цикла) - * [▶ Остерегайтесь изменяемых аргументов по умолчанию!](#▶-Остерегайтесь-изменяемых-аргументов-по-умолчанию!) - * [▶ Ловля исключений](#▶-Ловля-исключений) - * [▶ Одни и те же операнды, разная история!](#▶-Одни-и-те-же-операнды,-разная-история!) - * [▶ Разрешение имен игнорирует область видимости класса](#▶-Разрешение-имен-игнорирует-область-видимости-класса) - * [▶ Округляясь как банкир *](#▶-Округляясь-как-банкир-*) - * [▶ Иголки в стоге сена *](#▶-Иголки-в-стоге-сена-*) - * [▶ Сплиты (splitsies) *](#▶-Сплиты-(splitsies)-*) - * [▶ Подстановочное импортирование (wild imports) *](#▶-Подстановочное-импортирование-(wild-imports)-*) - * [▶ Все ли отсортировано? *](#▶-Все-ли-отсортировано?-*) - * [▶ Полночи не существует?](#▶-Полночи-не-существует?) - * [Секция: Скрытые сокровища!](#Секция:-Скрытые-сокровища!) - * [▶ Python, можешь ли ты помочь взлелеть?](#▶-Python,-можешь-ли-ты-помочь-взлелеть?) - * [▶ `goto`, но почему?](#▶-`goto`,-но-почему?) - * [▶ Держитесь!](#▶-Держитесь!) - * [▶ Давайте познакомимся с дружелюбным Дядей Барри](#▶-Давайте-познакомимся-с-дружелюбным-Дядей-Барри) - * [▶ Даже Python понимает, что любовь - это сложно.](#▶-Даже-Python-понимает,-что-любовь---это-сложно.) - * [▶ Да, оно существует!](#▶-Да,-оно-существует!) - * [▶ Многоточие *](#▶-Многоточие-*) - * [▶ Писконечность (Inpinity)](#▶-Писконечность-(Inpinity)) - * [▶ Давайте искажать](#▶-Давайте-искажать) - * [Секция: Внешность обманчива!](#Секция:-Внешность-обманчива!) - * [▶ Пропускаем строки?](#▶-Пропускаем-строки?) - * [▶ Телепортация](#▶-Телепортация) - * [▶ Что-то не так...](#▶-Что-то-не-так...) - * [Секция: Разное](#Секция:-Разное) - * [▶ `+=` быстрее](#▶-`+=`-быстрее) - * [▶ Сделаем гигантскую строку!](#▶-Сделаем-гигантскую-строку!) - * [▶ Замедляем поиск по `dict` *](#▶-Замедляем-поиск-по-`dict`-*) - * [▶ Раздуваем экземпляры словарей *](#▶-Раздуваем-экземпляры-словарей-*) - * [▶ Минорное *](#▶-Минорное-*) -* [Вклад в проект](#Вклад-в-проект) -* [Благодарности](#Благодарности) -* [🎓 Лицензия](#🎓-Лицензия) - * [Удиви своих друзей!](#Удиви-своих-друзей!) - * [Нужна PDF версия?](#Нужна-PDF-версия?) +- [Содержание](#содержание) +- [Структура примера](#структура-примера) +- [Применение](#применение) +- [👀 Примеры](#-примеры) + - [Секция: Напряги мозги!](#секция-напряги-мозги) + - [▶ Первым делом!](#-первым-делом) + - [💡 Обьяснение](#-обьяснение) + - [▶ Строки иногда ведут себя непредсказуемо](#-строки-иногда-ведут-себя-непредсказуемо) + - [💡 Объяснение](#-объяснение) + - [▶ Осторожнее с цепочкой операций](#-осторожнее-с-цепочкой-операций) + - [💡 Объяснение:](#-объяснение-1) + - [▶ Как не надо использовать оператор `is`](#-как-не-надо-использовать-оператор-is) + - [💡 Объяснение:](#-объяснение-2) + - [▶ Мистическое хеширование](#-мистическое-хеширование) + - [💡 Объяснение](#-объяснение-3) + - [▶ В глубине души мы все одинаковы.](#-в-глубине-души-мы-все-одинаковы) + - [💡 Объяснение:](#-объяснение-4) + - [▶ Беспорядок внутри порядка \*](#-беспорядок-внутри-порядка-) + - [💡 Объяснение:](#-объяснение-5) + - [▶ Продолжай пытаться... \*](#-продолжай-пытаться-) + - [💡 Объяснение:](#-объяснение-6) + - [▶ Для чего?](#-для-чего) + - [💡 Объяснение:](#-объяснение-7) + - [▶ Расхождение во времени исполнения](#-расхождение-во-времени-исполнения) + - [💡 Объяснение](#-объяснение-8) + - [▶ `is not ...` не является `is (not ...)`](#-is-not--не-является-is-not-) + - [💡 Объяснение](#-объяснение-9) + - [▶ Крестики-нолики, где X побеждает с первой попытки!](#-крестики-нолики-где-x-побеждает-с-первой-попытки) + - [💡 Объяснение:](#-объяснение-10) + - [▶ Переменная Шредингера \*](#-переменная-шредингера-) + - [💡 Объяснение:](#-объяснение-11) + - [▶ Проблема курицы и яйца \*](#-проблема-курицы-и-яйца-) + - [💡 Объяснение](#-объяснение-12) + - [▶ Отношения между подклассами](#-отношения-между-подклассами) + - [💡 Объяснение](#-объяснение-13) + - [▶ Равенство и тождество методов](#-равенство-и-тождество-методов) + - [💡 Объяснение](#-объяснение-14) + - [▶ All-true-ation (непереводимая игра слов) \*](#-all-true-ation-непереводимая-игра-слов-) + - [💡 Объяснение:](#-объяснение-15) + - [💡 Объяснение:](#-объяснение-16) + - [▶ Строки и обратные слэши](#-строки-и-обратные-слэши) + - [💡 Объяснение](#-объяснение-17) + - [▶ Не узел! (англ. not knot!)](#-не-узел-англ-not-knot) + - [💡 Объяснение](#-объяснение-18) + - [▶ Строки, наполовину обернутые в тройные кавычки](#-строки-наполовину-обернутые-в-тройные-кавычки) + - [💡 Объяснение:](#-объяснение-19) + - [▶ Что не так с логическими значениями?](#-что-не-так-с-логическими-значениями) + - [💡 Объяснение:](#-объяснение-20) + - [▶ Атрибуты класса и экземпляра](#-атрибуты-класса-и-экземпляра) + - [💡 Объяснение:](#-объяснение-21) + - [▶ Возврат None из генератора](#-возврат-none-из-генератора) + - [💡 Объяснение:](#-объяснение-22) + - [▶ Yield from возвращает... \*](#-yield-from-возвращает-) + - [💡 Объяснение:](#-объяснение-23) + - [▶ Nan-рефлексивность \*](#-nan-рефлексивность-) + - [💡 Объяснение:](#-объяснение-24) + - [▶ Изменяем неизменяемое!](#-изменяем-неизменяемое) + - [💡 Объяснение:](#-объяснение-25) + - [▶ Исчезающая переменная из внешней области видимости](#-исчезающая-переменная-из-внешней-области-видимости) + - [💡 Объяснение:](#-объяснение-26) + - [▶ Загадочное преобразование типов ключей](#-загадочное-преобразование-типов-ключей) + - [💡 Объяснение:](#-объяснение-27) + - [▶ Посмотрим, сможете ли вы угадать что здесь?](#-посмотрим-сможете-ли-вы-угадать-что-здесь) + - [💡 Объяснение:](#-объяснение-28) + - [▶ Превышение предела целочисленного преобразования строк](#-превышение-предела-целочисленного-преобразования-строк) + - [💡 Объяснение:](#-объяснение-29) + - [Секция: Скользкие склоны](#секция-скользкие-склоны) + - [▶ Изменение словаря во время прохода по нему](#-изменение-словаря-во-время-прохода-по-нему) + - [💡 Объяснение:](#-объяснение-30) + - [▶ Упрямая операция `del`](#-упрямая-операция-del) + - [💡 Объяснение:](#-объяснение-31) + - [▶ Переменная за пределами видимости](#-переменная-за-пределами-видимости) + - [💡 Объяснение:](#-объяснение-32) + - [▶ Удаление элемента списка во время прохода по списку](#-удаление-элемента-списка-во-время-прохода-по-списку) + - [💡 Объяснение:](#-объяснение-33) + - [▶ Сжатие итераторов с потерями \*](#-сжатие-итераторов-с-потерями-) + - [💡 Объяснение:](#-объяснение-34) + - [▶ Утечка переменных внутри цикла](#-утечка-переменных-внутри-цикла) + - [💡 Объяснение:](#-объяснение-35) + - [▶ Остерегайтесь изменяемых аргументов по умолчанию!](#-остерегайтесь-изменяемых-аргументов-по-умолчанию) + - [💡 Объяснение:](#-объяснение-36) + - [▶ Ловля исключений](#-ловля-исключений) + - [💡 Объяснение](#-объяснение-37) + - [▶ Одни и те же операнды, разная история!](#-одни-и-те-же-операнды-разная-история) + - [💡 Объяснение:](#-объяснение-38) + - [▶ Разрешение имен игнорирует область видимости класса](#-разрешение-имен-игнорирует-область-видимости-класса) + - [💡 Объяснение](#-объяснение-39) + - [▶ Округляясь как банкир \*](#-округляясь-как-банкир-) + - [💡 Объяснение:](#-объяснение-40) + - [▶ Иголки в стоге сена \*](#-иголки-в-стоге-сена-) + - [💡 Объяснение:](#-объяснение-41) + - [▶ Сплиты (splitsies) \*](#-сплиты-splitsies-) + - [💡 Объяснение](#-объяснение-42) + - [▶ Подстановочное импортирование (wild imports) \*](#-подстановочное-импортирование-wild-imports-) + - [💡 Объяснение:](#-объяснение-43) + - [▶ Все ли отсортировано? \*](#-все-ли-отсортировано-) + - [💡 Объяснение:](#-объяснение-44) + - [▶ Полночи не существует?](#-полночи-не-существует) + - [💡 Объяснение:](#-объяснение-45) + - [Секция: Скрытые сокровища!](#секция-скрытые-сокровища) + - [▶ Python, можешь ли ты помочь взлететь?](#-python-можешь-ли-ты-помочь-взлететь) + - [💡 Объяснение:](#-объяснение-46) + - [▶ `goto`, но почему?](#-goto-но-почему) + - [💡 Объяснение:](#-объяснение-47) + - [▶ Держитесь!](#-держитесь) + - [💡 Объяснение:](#-объяснение-48) + - [▶ Давайте познакомимся с дружелюбным Дядей Барри](#-давайте-познакомимся-с-дружелюбным-дядей-барри) + - [💡 Объяснение:](#-объяснение-49) + - [▶ Даже Python понимает, что любовь - это сложно.](#-даже-python-понимает-что-любовь---это-сложно) + - [💡 Объяснение:](#-объяснение-50) + - [▶ Да, оно существует!](#-да-оно-существует) + - [💡 Объяснение:](#-объяснение-51) + - [▶ Многоточие \*](#-многоточие-) + - [💡 Объяснение](#-объяснение-52) + - [▶ Писконечность (Inpinity)](#-писконечность-inpinity) + - [💡 Объяснение:](#-объяснение-53) + - [▶ Давайте искажать](#-давайте-искажать) + - [💡 Объяснение:](#-объяснение-54) + - [Секция: Внешность обманчива!](#секция-внешность-обманчива) + - [▶ Пропускаем строки?](#-пропускаем-строки) + - [💡 Объяснение](#-объяснение-55) + - [▶ Телепортация](#-телепортация) + - [💡 Объяснение:](#-объяснение-56) + - [▶ Что-то не так...](#-что-то-не-так) + - [💡 Объяснение](#-объяснение-57) + - [Секция: Разное](#секция-разное) + - [▶ `+=` быстрее `+`](#--быстрее-) + - [💡 Объяснение:](#-объяснение-58) + - [▶ Сделаем гигантскую строку!](#-сделаем-гигантскую-строку) + - [💡 Объяснение](#-объяснение-59) + - [▶ Замедляем поиск по `dict` \*](#-замедляем-поиск-по-dict-) + - [💡 Объяснение:](#-объяснение-60) + - [▶ Раздуваем экземпляры словарей \*](#-раздуваем-экземпляры-словарей-) + - [💡 Объяснение:](#-объяснение-61) + - [▶ Минорное \*](#-минорное-) +- [Вклад в проект](#вклад-в-проект) +- [Благодарности](#благодарности) + - [Несколько хороших ссылок!](#несколько-хороших-ссылок) +- [🎓 Лицензия](#-лицензия) + - [Удиви своих друзей!](#удиви-своих-друзей) + - [Нужна PDF версия?](#нужна-pdf-версия) # Структура примера @@ -137,11 +202,11 @@ PS: Если вы уже читали **wtfpython** раньше, с измен Хороший способ получить максимальную пользу от этих примеров - читать их последовательно, причем для каждого из них важно: -- Внимательно изучить исходный код. Если вы опытный программист на Python, то в большинстве случаев сможете предугадать, что произойдет дальше. +- Внимательно изучить исходный код. Если вы опытный Python программист, то в большинстве случаев сможете предугадать, что произойдет дальше. - Прочитать фрагменты вывода и, - Проверить, совпадают ли выходные данные с вашими ожиданиями. - Убедиться, что вы знаете точную причину, по которой вывод получился именно таким. - - Если ответ отрицательный (что совершенно нормально), сделать глубокий вдох и прочитать объяснение (а если пример все еще непонятен, и создайте issue [здесь](https://github.com/satwikkansal/wtfpython/issues/new)). + - Если ответ отрицательный (что совершенно нормально), сделать глубокий вдох и прочитать объяснение (а если пример все еще непонятен, и создайте [issue](https://github.com/satwikkansal/wtfpython/issues/new)). - Если "да", ощутите мощь своих познаний в Python и переходите к следующему примеру. PS: Вы также можете читать WTFPython в командной строке, используя [pypi package](https://pypi.python.org/pypi/wtfpython), @@ -344,7 +409,7 @@ False - Строки интернируются во время компиляции (`'wtf'` будет интернирована, но `''.join(['w'', 't', 'f'])` - нет) - Строки, не состоящие из букв ASCII, цифр или знаков подчеркивания, не интернируются. В примере выше `'wtf!'` не интернируется из-за `!`. Реализацию этого правила в CPython можно найти [здесь](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) ![image](/images/string-intern/string_intern.png) -- Когда переменные `a` и `b` принимают значение `"wtf!"` в одной строке, интерпретатор Python создает новый объект, а затем одновременно ссылается на вторую переменную. Если это выполняется в отдельных строках, он не "знает", что уже существует `"wtf!"` как объект (потому что `"wtf!"` не является неявно интернированным в соответствии с фактами, упомянутыми выше). Это оптимизация во время компиляции, не применяется к версиям CPython 3.7.x (более подробное обсуждение смотрите здесь [issue](https://github.com/satwikkansal/wtfpython/issues/100)). +- Когда переменные `a` и `b` принимают значение `"wtf!"` в одной строке, интерпретатор Python создает новый объект, а затем одновременно ссылается на вторую переменную. Если это выполняется в отдельных строках, он не "знает", что уже существует `"wtf!"` как объект (потому что `"wtf!"` не является неявно интернированным в соответствии с фактами, упомянутыми выше). Это оптимизация во время компиляции, не применяется к версиям CPython 3.7.x (более подробное обсуждение смотрите [здесь](https://github.com/satwikkansal/wtfpython/issues/100)). - Единица компиляции в интерактивной среде IPython состоит из одного оператора, тогда как в случае модулей она состоит из всего модуля. `a, b = "wtf!", "wtf!"` - это одно утверждение, тогда как `a = "wtf!"; b = "wtf!"` - это два утверждения в одной строке. Это объясняет, почему тождества различны в `a = "wtf!"; b = "wtf!"`, но одинаковы при вызове в модуле. - Резкое изменение в выводе четвертого фрагмента связано с [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) техникой, известной как складывание констант (англ. Constant folding). Это означает, что выражение `'a'*20` заменяется на `'aaaaaaaaaaaaaaaaaaaa'` во время компиляции, чтобы сэкономить несколько тактов во время выполнения. Складывание констант происходит только для строк длиной менее 21. (Почему? Представьте себе размер файла `.pyc`, созданного в результате выполнения выражения `'a'*10**10`). [Вот](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) исходный текст реализации для этого. - Примечание: В Python 3.7 складывание констант было перенесено из оптимизатора peephole в новый оптимизатор AST с некоторыми изменениями в логике, поэтому четвертый фрагмент не работает в Python 3.7. Подробнее об изменении можно прочитать [здесь](https://bugs.python.org/issue11549). @@ -378,7 +443,7 @@ False #### 💡 Объяснение: -Согласно https://docs.python.org/3/reference/expressions.html#comparisons +Согласно [документации](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 и b op2 c и ... y opN z, за исключением того, что каждое выражение оценивается не более одного раза. @@ -491,7 +556,7 @@ False Подобная оптимизация применима и к другим **изменяемым** объектам, таким как пустые кортежи. Поскольку списки являются изменяемыми, поэтому `[] is []` вернет `False`, а `() is ()` вернет `True`. Это объясняет наш второй фрагмент. Перейдем к третьему, -**И `a`, и `b` ссылаются на один и тот же объект при инициализации одним и тем же значением в одной и той же строкеi**. +**И `a`, и `b` ссылаются на один и тот же объект при инициализации одним и тем же значением в одной и той же строке**. **Вывод** @@ -511,7 +576,7 @@ False * Когда a и b инициализируются со значением `257` в одной строке, интерпретатор Python создает новый объект, а затем одновременно ссылается на него во второй переменной. Если делать это в отдельных строках, интерпретатор не "знает", что объект `257` уже существует. -* Это оптимизация компилятора и относится именно к интерактивной среде. Когда вы вводите две строки в интерпретаторе, они компилируются отдельно, поэтому оптимизируются отдельно. Если выполнить этот пример в файле `.py', поведение будет отличаться, потому что файл компилируется весь сразу. Эта оптимизация не ограничивается целыми числами, она работает и для других неизменяемых типов данных, таких как строки (проверьте пример "Строки - это сложно") и плавающие числа, +* Эта оптимизация компилятора относится именно к интерактивной среде. Когда вы вводите две строки в интерпретаторе, они компилируются отдельно, поэтому оптимизируются отдельно. Если выполнить этот пример в файле `.py', поведение будет отличаться, потому что файл компилируется целиком. Эта оптимизация не ограничивается целыми числами, она работает и для других неизменяемых типов данных, таких как строки (смотреть пример "Строки - это сложно") и плавающие числа, ```py >>> a, b = 257.0, 257.0 @@ -519,12 +584,12 @@ False True ``` -* Почему это не сработало в Python 3.7? Абстрактная причина в том, что такие оптимизации компилятора зависят от реализации (т.е. могут меняться в зависимости от версии, ОС и т.д.). Я все еще выясняю, какое именно изменение реализации вызвало проблему, вы можете проверить этот [issue](https://github.com/satwikkansal/wtfpython/issues/100) для получения обновлений. +* Почему это не сработало в Python 3.7? Абстрактная причина в том, что такие оптимизации компилятора зависят от реализации (т.е. могут меняться в зависимости от версии, ОС и т.д.). Я все еще выясняю, какое именно изменение реализации вызвало проблему, вы можете следить за этим [issue](https://github.com/satwikkansal/wtfpython/issues/100) для получения обновлений. --- -### ▶ Мистическое хэширование +### ▶ Мистическое хеширование 1\. ```py @@ -556,7 +621,7 @@ complex #### 💡 Объяснение -* Уникальность ключей в словаре Python определяется *эквивалентностью*, а не тождеством. Поэтому, даже если `5`, `5.0` и `5 + 0j` являются различными объектами разных типов, поскольку они равны, они не могут находиться в одном и том же `dict` (или `set`). Как только вы вставите любой из них, попытка поиска по любому другому, но эквивалентному ключу будет успешной с исходным сопоставленным значением (а не завершится ошибкой `KeyError`): +* Уникальность ключей в словаре Python определяется *эквивалентностью*, а не тождеством. Поэтому, даже если `5`, `5.0` и `5 + 0j` являются различными объектами разных типов, поскольку они эквивалентны, они не могут находиться в одном и том же `dict` (или `set`). Как только вы вставите любой из них, попытка поиска по любому другому, но эквивалентному ключу будет успешной с исходным сопоставленным значением (а не завершится ошибкой `KeyError`): ```py >>> 5 == 5.0 == 5 + 0j True @@ -569,7 +634,7 @@ complex >>> (5 in some_dict) and (5 + 0j in some_dict) True ``` -* Это применимо и во время присваения значения элементу. Поэтому, в выражении `some_dict[5] = "Python"` Python находит существующий элемент с эквивалентным ключом `5.0 -> "Ruby"`, перезаписывает его значение на место, а исходный ключ оставляет в покое. +* Это применимо и во время присваивания значения элементу. Поэтому, в выражении `some_dict[5] = "Python"` Python находит существующий элемент с эквивалентным ключом `5.0 -> "Ruby"`, перезаписывает его значение на место, а исходный ключ оставляет в покое. ```py >>> some_dict {5.0: 'Ruby'} @@ -577,16 +642,17 @@ complex >>> some_dict {5.0: 'Python'} ``` -* Итак, как мы можем обновить ключ до `5` (вместо `5.0`)? На самом деле мы не можем сделать это обновление на месте, но что мы можем сделать, так это сначала удалить ключ (`del some_dict[5.0]`), а затем установить его (`some_dict[5]`), чтобы получить целое число `5` в качестве ключа вместо плавающего `5.0`, хотя это нужно в редких случаях. +* Итак, как мы можем обновить ключ до `5` (вместо `5.0`)? На самом деле мы не можем сделать это обновление на месте, но все же это возможно, нужно сначала удалить ключ (`del some_dict[5.0]`), а затем установить его (`some_dict[5]`), чтобы получить целое число `5` в качестве ключа вместо плавающего `5.0`, хотя это нужно в редких случаях. + +* Как Python нашел `5` в словаре, содержащем `5.0`? Python делает это за постоянное время без необходимости сканирования каждого элемента, используя хэш-функции. Когда Python ищет ключ `foo` в словаре, он сначала вычисляет `hash(foo)` (что выполняется в постоянном времени). Поскольку в Python требуется, чтобы объекты, которые одинаковы в сравнении, имели одинаковое хэш-значение (смотри [документацию](https://docs.python.org/3/reference/datamodel.html#object.__hash__)), `5`, `5.0` и `5 + 0j` выполняют это условие. -* Как Python нашел `5` в словаре, содержащем `5.0`? Python делает это за постоянное время без необходимости сканирования каждого элемента, используя хэш-функции. Когда Python ищет ключ `foo` в словаре, он сначала вычисляет `hash(foo)` (что выполняется в постоянном времени). Поскольку в Python требуется, чтобы объекты, которые сравниваются одинаково, имели одинаковое хэш-значение ([docs](https://docs.python.org/3/reference/datamodel.html#object.__hash__) здесь), `5`, `5.0` и `5 + 0j` имеют одинаковое хэш-значение. ```py >>> 5 == 5.0 == 5 + 0j True >>> hash(5) == hash(5.0) == hash(5 + 0j) True ``` - **Примечание:** Обратное не обязательно верно: Объекты с одинаковыми хэш-значениями сами могут быть неравными. (Это вызывает так называемую [хэш-коллизию](https://en.wikipedia.org/wiki/Collision_(computer_science)) и ухудшает производительность постоянного времени, которую обычно обеспечивает хэширование). + **Примечание:** Обратное не обязательно верно: Объекты с одинаковыми хэш-значениями сами могут быть неравными. (Это вызывает так называемую [хэш-коллизию](https://en.wikipedia.org/wiki/Collision_(computer_science)) и ухудшает производительность постоянного времени, которую обычно обеспечивает хеширование). --- @@ -604,14 +670,14 @@ class WTF: False >>> WTF() is WTF() # идентификаторы также различаются False ->>> hash(WTF()) == hash(WTF()) # хэши тоже должны отличаться +>>> hash(WTF()) == hash(WTF()) # хеши тоже должны отличаться True >>> id(WTF()) == id(WTF()) True ``` #### 💡 Объяснение: -* При вызове `id` Python создал объект класса `WTF` и передал его функции `id`. Функция `id` забирает свой `id` (местоположение в памяти) и выбрасывает объект. Объект уничтожается. +* При вызове `id` Python создал объект класса `WTF` и передал его функции `id`. Функция `id` забирает свой `id` (расположение в памяти) и выбрасывает объект. Объект уничтожается. * Когда мы делаем это дважды подряд, Python выделяет ту же самую область памяти и для второго объекта. Поскольку (в CPython) `id` использует участок памяти в качестве идентификатора объекта, идентификатор двух объектов одинаков. * Таким образом, id объекта уникален только во время жизни объекта. После уничтожения объекта или до его создания, другой объект может иметь такой же id. * Но почему выражение с оператором `is` равно `False`? Давайте посмотрим с помощью этого фрагмента. @@ -641,7 +707,7 @@ True --- -### ▶ Беспорядок внутри порядка * +### ▶ Беспорядок внутри порядка * ```py from collections import OrderedDict @@ -657,13 +723,13 @@ another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; class DictWithHash(dict): """ - A dict that also implements __hash__ magic. + Словарь с реализованным методом __hash__. """ __hash__ = lambda self: 0 class OrderedDictWithHash(OrderedDict): """ - An OrderedDict that also implements __hash__ magic. + OrderedDict с реализованным методом __hash__. """ __hash__ = lambda self: 0 ``` @@ -677,7 +743,7 @@ True >>> ordered_dict == another_ordered_dict # почему же c != a ?? False -# Мы все знаем, что множество состоит только из уникальных элементов, +# Мы все знаем, что множество состоит из уникальных элементов, # давайте попробуем составить множество из этих словарей и посмотрим, что получится... >>> len({dictionary, ordered_dict, another_ordered_dict}) @@ -695,7 +761,7 @@ TypeError: unhashable type: 'dict' >>> another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; >>> len({dictionary, ordered_dict, another_ordered_dict}) 1 ->>> len({ordered_dict, another_ordered_dict, dictionary}) # changing the order +>>> len({ordered_dict, another_ordered_dict, dictionary}) # изменим порядок элементов 2 ``` @@ -703,7 +769,7 @@ TypeError: unhashable type: 'dict' #### 💡 Объяснение: -- Переходное (интрантизивное) равенство между `dictionary`, `ordered_dict` и `another_ordered_dict` не выполняется из-за реализации магического метода `__eq__` в классе `OrderedDict`. Перевод цитаты из [документации](https://docs.python.org/3/library/collections.html#ordereddict-objects) +- Переходное (интранзитивное) равенство между `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` и другими объектами Mapping нечувствительны к порядку, как обычные словари. - Причина такого поведения равенства в том, что оно позволяет напрямую подставлять объекты `OrderedDict` везде, где используется обычный словарь. @@ -794,7 +860,7 @@ Iteration 0 #### 💡 Объяснение: -- Когда один из операторов `return`, `break` или `continue` выполняется в блоке `try` оператора "try...finally", на выходе также выполняется пункт `finally`. +- Когда один из операторов `return`, `break` или `continue` выполняется в блоке `try` оператора "try...finally", на выходе также выполняется блок `finally`. - Возвращаемое значение функции определяется последним выполненным оператором `return`. Поскольку блок `finally` выполняется всегда, оператор `return`, выполненный в блоке `finally`, всегда будет последним. - Предостережение - если в блоке `finally` выполняется оператор `return` или `break`, то временно сохраненное исключение отбрасывается. @@ -966,7 +1032,7 @@ board = [row] * 3 [['X', '', ''], ['X', '', ''], ['X', '', '']] ``` -Мы же не назначили три `"Х"`? +Мы же не назначали три `"Х"`? #### 💡 Объяснение: @@ -1006,7 +1072,7 @@ for x in range(7): funcs_results = [func() for func in funcs] ``` -**Вывод (Python version):** +**Вывод:** ```py >>> results [0, 1, 2, 3, 4, 5, 6] @@ -1039,7 +1105,7 @@ ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) [42, 42, 42, 42, 42, 42, 42] ``` -* Чтобы получить желаемое поведение, вы можете передать переменную цикла как именованную переменную в функцию. **Почему это работает?** Потому что это определит переменную *внутри* области видимости функции. Она больше не будет обращаться к глобальной области видимости для поиска значения переменной, а создаст локальную переменную, которая будет хранить значение `x` в данный момент времени. +* Чтобы получить желаемое поведение, вы можете передать переменную цикла как именованную аргумент в функцию. **Почему это работает?** Потому что это определит переменную *внутри* области видимости функции. Она больше не будет обращаться к глобальной области видимости для поиска значения переменной, а создаст локальную переменную, которая будет хранить значение `x` в данный момент времени. ```py funcs = [] @@ -1079,7 +1145,7 @@ True True ``` -Так какой же базовый класс является "окончательным"? Кстати, это еще не все, +Так какой же базовый класс является "родительским"? Кстати, это еще не все, 2\. @@ -1137,12 +1203,11 @@ False * Отношения подклассов не обязательно являются транзитивными в Python. Можно переопределить магический метод `__subclasscheck__` в метаклассе. * Когда вызывается `issubclass(cls, Hashable)`, он просто ищет не-фальшивый метод "`__hash__`" в `cls` или во всем, от чего он наследуется. -* Поскольку `object` является хэшируемым, а `list` - нехэшируемым, это нарушает отношение транзитивности. -* Более подробное объяснение можно найти [здесь] (https://www.naftaliharris.com/blog/python-subclass-intransitivity/). +* Поскольку `object` является хэшируемым, а `list` - нет, это нарушает отношение транзитивности. +* Более подробное объяснение можно найти [здесь](https://www.naftaliharris.com/blog/python-subclass-intransitivity/). --- - ### ▶ Равенство и тождество методов @@ -1202,7 +1267,7 @@ True #### 💡 Объяснение * Функции являются [дескрипторами](https://docs.python.org/3/howto/descriptor.html). Всякий раз, когда к функции обращаются как к -атрибута, вызывается дескриптор, создавая объект метода, который "связывает" функцию с объектом, владеющим атрибутом. При вызове метод вызывает функцию, неявно передавая связанный объект в качестве первого аргумента +атрибуту, вызывается дескриптор, создавая объект метода, который "связывает" функцию с объектом, владеющим атрибутом. При вызове метод вызывает функцию, неявно передавая связанный объект в качестве первого аргумента (именно так мы получаем `self` в качестве первого аргумента, несмотря на то, что не передаем его явно). ```py >>> o1.method @@ -1338,7 +1403,7 @@ True #### 💡 Объяснение -- В обычной строке обратная слэш используется для экранирования символов, которые могут иметь специальное значение (например, одинарная кавычка, двойная кавычка и сам обратный слэш). +- В обычной строке обратный слэш используется для экранирования символов, которые могут иметь специальное значение (например, одинарная кавычка, двойная кавычка и сам обратный слэш). ```py >>> "wt\"f" 'wt"f' @@ -1355,12 +1420,12 @@ True >>> print(r"\\n") '\\n' ``` -- Это означает, что когда синтаксический анализатор встречает обратный слэш в необработанной строке, он ожидает, что за ней последует другой символ. А в нашем случае (`print(r"\")`) обратная слэш экранирует двойную кавычку, оставив парсер без завершающей кавычки (отсюда `SyntaxError`). Вот почему обратный слеш не работает в конце необработанной строки. +- Это означает, что когда синтаксический анализатор встречает обратный слэш в необработанной строке, он ожидает, что за ней последует другой символ. А в нашем случае (`print(r"\")`) обратный слэш экранирует двойную кавычку, оставив синтаксический анализатор без завершающей кавычки (отсюда `SyntaxError`). Вот почему обратный слэш не работает в конце необработанной строки. --- +--- -### ▶ Не узел! (eng. not knot!) +### ▶ Не узел! (англ. not knot!) ```py x = True @@ -1383,12 +1448,12 @@ SyntaxError: invalid syntax * Старшинство операторов влияет на выполнение выражения, и оператор `==` имеет более высокий приоритет, чем оператор `not` в Python. * Поэтому `not x == y` эквивалентно `not (x == y)`, что эквивалентно `not (True == False)`, в итоге равное `True`. * Но `x == not y` вызывает `SyntaxError`, потому что его можно считать эквивалентным `(x == not) y`, а не `x == (not y)`, что можно было бы ожидать на первый взгляд. -* Парсер ожидал, что ключевое слово `not` будет частью оператора `not in` (потому что оба оператора `==` и `not in` имеют одинаковый приоритет), но после того, как он не смог найти ключевое слово `in`, следующее за `not`, он выдает `SyntaxError`. +* Синтаксический анализатор (англ. parser) ожидал, что ключевое слово `not` будет частью оператора `not in` (потому что оба оператора `==` и `not in` имеют одинаковый приоритет), но после того, как он не смог найти ключевое слово `in`, следующее за `not`, он выдает `SyntaxError`. --- -### ▶ Строки наполовину в тройных кавычках +### ▶ Строки, наполовину обернутые в тройные кавычки **Вывод:** ```py @@ -1503,7 +1568,7 @@ I have lost faith in truth! * Изначально в Python не было типа `bool` (использовали 0 для false и ненулевое значение 1 для true). В версиях 2.x были добавлены `True`, `False` и тип `bool`, но для обратной совместимости `True` и `False` нельзя было сделать константами. Они просто были встроенными переменными, и их можно было переназначить. -* Python 3 был несовместим с предыдущими версиями, эту проблему наконец-то исправили, и поэтому последний фрагмент не будет работать с Python 3.x! +* Python 3 несовместим с предыдущими версиями, эту проблему наконец-то исправили, и поэтому последний фрагмент не будет работать с Python 3.x! --- @@ -1651,7 +1716,7 @@ def some_func(x): [] ``` -То же самое, это тоже не сработало. Что происходит? +Опять не сработало. Что происходит? #### 💡 Объяснение: @@ -1659,7 +1724,7 @@ def some_func(x): > "... `return expr` в генераторе вызывает исключение `StopIteration(expr)` при выходе из генератора." -+ В случае `some_func(3)` `StopIteration` возникает в начале из-за оператора `return`. Исключение `StopIteration` автоматически перехватывается внутри обертки `list(...)` и цикла `for`. Поэтому два вышеприведенных фрагмента приводят к пустому списку. ++ В случае `some_func(3)` `StopIteration` возникает в начале из-за оператора `return`. Исключение `StopIteration` автоматически перехватывается внутри обертки `list(...)` и цикла `for`. Поэтому два вышеприведенных фрагмента возвращают пустой список. + Чтобы получить `["wtf"]` из генератора `some_func`, нужно перехватить исключение `StopIteration`. @@ -1721,7 +1786,7 @@ nan ```py >>> x = float('nan') >>> y = x / x ->>> y is y # идендичность сохраняется +>>> y is y # идентичность сохраняется True >>> y == y # сравнение ложно для y False @@ -1733,7 +1798,7 @@ True - `'inf'` и `'nan'` - это специальные строки (без учета регистра), которые при явном приведении к типу `float` используются для представления математической "бесконечности" и "не число" соответственно. -- Согласно стандартам IEEE `NaN != NaN`, но соблюдение этого правила нарушает предположение о рефлексивности элемента коллекции в Python, то есть если `x` является частью коллекции, такой как `list`, реализации, методы сравнения предполагают, что `x == x`. Поэтому при сравнении элементов сначала сравниваются их идентификаторы (так как это быстрее), а значения сравниваются только при несовпадении идентификаторов. Следующий фрагмент сделает вещи более ясными: +- Согласно стандартам IEEE, `NaN != NaN`, но соблюдение этого правила нарушает предположение о рефлексивности элемента коллекции в Python, то есть если `x` является частью коллекции, такой как `list`, реализации методов сравнения предполагают, что `x == x`. Поэтому при сравнении элементов сначала сравниваются их идентификаторы (так как это быстрее), а значения сравниваются только при несовпадении идентификаторов. Следующий фрагмент сделает вещи более ясными: ```py >>> x = float('nan') @@ -1753,7 +1818,7 @@ True --- -### ▶ Мутируем немутируемое! +### ▶ Изменяем неизменяемое! @@ -1783,8 +1848,7 @@ TypeError: 'tuple' object does not support item assignment * Перевод цитаты из [документации](https://docs.python.org/3/reference/datamodel.html) - > Неизменяемые последовательности - Объект неизменяемого типа последовательности не может измениться после создания. (Если объект содержит ссылки на другие объекты, эти объекты могут быть изменяемыми и могут быть изменены; однако набор объектов, на которые непосредственно ссылается неизменяемый объект, не может изменяться.) + > Объект неизменяемого типа последовательности не может измениться после создания. (Если объект содержит ссылки на другие объекты, эти объекты могут быть изменяемыми и могут быть изменены; однако набор объектов, на которые непосредственно ссылается неизменяемый объект, не может изменяться.) * Оператор `+=` изменяет список на месте. Присваивание элемента не работает, но когда возникает исключение, элемент уже был изменен на месте. * Также есть объяснение в официальном [Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works). @@ -1836,30 +1900,30 @@ NameError: name 'e' is not defined del N ``` -Это означает, что исключению должно быть присвоено другое имя, чтобы на него можно было ссылаться после завершения блока `except`. Исключения очищаются, потому что с прикрепленным к ним трейсбэком они образуют цикл ссылок со стеком вызовов, сохраняя все локальные объекты в этой стэке до следующей сборки мусора. +Это означает, что исключению должно быть присвоено другое имя, чтобы на него можно было ссылаться после завершения блока `except`. Исключения очищаются, потому что с прикрепленным к ним трейсбэком они образуют цикл ссылок со стэком вызовов, сохраняя все локальные объекты в этой стэке до следующей сборки мусора. * В Python clauses не имеют области видимости. В примере все объекты в одной области видимости, а переменная `e` была удалена из-за выполнения блока `except`. Этого нельзя сказать о функциях, которые имеют отдельные внутренние области видимости. Пример ниже иллюстрирует это: -```py - def f(x): - del(x) - print(x) - - 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 + def f(x): + del(x) + print(x) + + 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] + ``` * В Python 2.x, имя переменной `e` назначается на экземпляр `Exception()`, и при попытки вывести значение `e` ничего не выводится. @@ -1954,13 +2018,9 @@ a, b = a[b] = {}, 5 > Оператор присваивания исполняет список выражений (помните, что это может быть одно выражение или список, разделенный запятыми, в последнем случае получается кортеж) и присваивает единственный результирующий объект каждому из целевых списков, слева направо. * `+` в `(target_list "=")+` означает, что может быть **один или более** целевых списков. В данном случае целевыми списками являются `a, b` и `a[b]` (обратите внимание, что список выражений ровно один, в нашем случае это `{}, 5`). - * После исполнения списка выражений его значение распаковывается в целевые списки **слева направо**. Так, в нашем случае сначала кортеж `{}, 5` распаковывается в `a, b`, и теперь у нас есть `a = {}` и `b = 5`. - * Теперь `a` имеет значение `{}`, которое является изменяемым объектом. - * Вторым целевым списком является `a[b]` (вы можете ожидать, что это вызовет ошибку, поскольку `a` и `b` не были определены в предыдущих утверждениях. Но помните, мы только что присвоили `a` значение `{}` и `b` - `5`). - * Теперь мы устанавливаем ключ `5` в словаре в кортеж `({}, 5)`, создавая круговую ссылку (`{...}` в выводе ссылается на тот же объект, на который уже ссылается `a`). Другим более простым примером круговой ссылки может быть ```py @@ -2010,7 +2070,7 @@ ValueError: Exceeds the limit (4300) for integer string conversion: #### 💡 Объяснение: Этот вызов `int()` прекрасно работает в Python 3.10.6 и вызывает ошибку `ValueError` в Python 3.10.8, 3.11. Обратите внимание, что Python все еще может работать с большими целыми числами. Ошибка возникает только при преобразовании между целыми числами и строками. К счастью, вы можете увеличить предел допустимого количества цифр. Для этого можно воспользоваться одним из следующих способов: -- `-X int_max_str_digits` - флаг командной строкиcommand-line flag +- `-X int_max_str_digits` - флаг командной строки - `set_int_max_str_digits()` - функция из модуля `sys` - `PYTHONINTMAXSTRDIGITS` - переменная окружения @@ -2230,7 +2290,7 @@ for idx, item in enumerate(list_4): >>> some_list = [1, 2, 3, 4] >>> id(some_list) 139798789457608 - >>> id(some_list[:]) # Notice that python creates new object for sliced list. + >>> id(some_list[:]) # Обратите внимание, создается новый объект из среза списка 139798779601192 ``` @@ -2239,7 +2299,7 @@ for idx, item in enumerate(list_4): * `remove` удаляет первое подходящее значение, а не конкретный индекс, вызывает `ValueError`, если значение не найдено. * `pop` удаляет элемент по определенному индексу и возвращает его, вызывает `IndexError`, если указан неверный индекс. -**Почему на выходе получается `[2, 4]`? +**Почему на выходе получается `[2, 4]`?** - Проход по списку выполняется индекс за индексом, и когда мы удаляем `1` из `list_2` или `list_4`, содержимое списков становится `[2, 3, 4]`. Оставшиеся элементы сдвинуты вниз, то есть `2` находится на индексе 0, а `3` - на индексе 1. Поскольку на следующей итерации будет просматриваться индекс 1 (который и есть `3`), `2` будет пропущен полностью. Аналогичное произойдет с каждым альтернативным элементом в последовательности списка. * Объяснение примера можно найти на [StackOverflow](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it). @@ -2354,7 +2414,7 @@ print(x, ': x in global') #### 💡 Объяснение: -- В Python циклы for используют область видимости, в которой они существуют, и оставляют свою определенную переменную цикла после завершения. Это также относится к случаям, когда мы явно определили переменную цикла for в глобальном пространстве имен. В этом случае будет произведена перепривязка существующей переменной. +- В Python циклы for используют область видимости, в которой они существуют, и оставляют свою определенную переменную цикла после завершения. Это также относится к случаям, когда мы явно определили переменную цикла for в глобальном пространстве имен. В этом случае будет произведена повторная привязка существующей переменной. - Различия в выводе интерпретаторов Python 2.x и Python 3.x для примера с пониманием списков можно объяснить следующим изменением, задокументированным в журнале изменений [What's New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html): @@ -2386,7 +2446,7 @@ def some_func(default_arg=[]): #### 💡 Объяснение: -- Изменяемые аргументы функций по умолчанию в Python на самом деле не инициализируются каждый раз, когда вы вызываете функцию. Вместо этого в качестве значения по умолчанию используется недавно присвоенное им значение. Когда мы явно передали `[]` в `some_func в качестве аргумента, значение по умолчанию переменной `default_arg` не было использовано, поэтому функция вернулась, как и ожидалось. +- Изменяемые аргументы функций по умолчанию в Python на самом деле не инициализируются каждый раз, когда вы вызываете функцию. Вместо этого в качестве значения по умолчанию используется недавно присвоенное им значение. Когда мы явно передали `[]` в `some_func` в качестве аргумента, значение по умолчанию переменной `default_arg` не было использовано, поэтому функция вернулась, как и ожидалось. ```py def some_func(default_arg=[]): @@ -2396,7 +2456,7 @@ def some_func(default_arg=[]): **Результат:** ```py - >>> some_func.__defaults__ # Выражение выведет значения стандартных аргументов фукнции + >>> some_func.__defaults__ # Выражение выведет значения стандартных аргументов функции ([],) >>> some_func() >>> some_func.__defaults__ @@ -2580,7 +2640,7 @@ class SomeClass: #### 💡 Объяснение - Области видимости, вложенные внутрь определения класса, игнорируют имена, связанные на уровне класса. - Выражение-генератор имеет свою собственную область видимости. -- Начиная с версии Python 3.X, списковые вычисления также имеют свою собственную область видимости. +- Начиная с версии Python 3.X, списковые выражения (list comprehensions) также имеют свою собственную область видимости. --- @@ -2716,7 +2776,7 @@ b = "javascript" **Результат:** ```py -# assert выражение с сообщением об ошиб +# assert выражение с сообщением об ошибке >>> assert(a == b, "Both languages are different") # Исключение AssertionError не возникло ``` @@ -2939,7 +2999,7 @@ False (tuple, list) ``` -- В отличие от метода `sorted, метод `reversed` возвращает итератор. Почему? Потому что сортировка требует, чтобы итератор либо изменялся на месте, либо использовал дополнительный контейнер (список), в то время как реверсирование может работать просто путем итерации от последнего индекса к первому. +- В отличие от метода `sorted`, метод `reversed` возвращает итератор. Почему? Потому что сортировка требует, чтобы итератор либо изменялся на месте, либо использовал дополнительный контейнер (список), в то время как реверсирование может работать просто путем итерации от последнего индекса к первому. - Поэтому при сравнении `sorted(y) == sorted(y)` первый вызов `sorted()` будет потреблять итератор `y`, а следующий вызов просто вернет пустой список. @@ -2992,7 +3052,7 @@ if noon_time: Секция содержит менее известные интересные нюансы работы Python, которые неизвестны большинству новичков. -### ▶ Python, можешь ли ты помочь взлелеть? +### ▶ Python, можешь ли ты помочь взлететь? Что ж, поехали @@ -3007,7 +3067,7 @@ Sshh... It's a super-secret. + Модуль `antigravity` - одно из немногих пасхальных яиц, выпущенных разработчиками Python. + `import antigravity` открывает веб-браузер, указывающий на [классический комикс XKCD](https://xkcd.com/353/) о Python. -+ Это еще не все. Внутри пасхального яйца находится **еще одно пасхальное яйцо**. Если вы посмотрите на [код](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), там определена функция, которая якобы реализует [алгоритм геохашинга XKCD](https://xkcd.com/426/). ++ Это еще не все. Внутри пасхального яйца находится **еще одно пасхальное яйцо**. Если вы посмотрите на [код](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17), там определена функция, которая якобы реализует алгоритм [XKCD](https://xkcd.com/426/). --- @@ -3164,7 +3224,7 @@ True ### ▶ Да, оно существует! -**Ключевое слово `else` в связвке с циклом `for`.** Один из стандартных примеров: +**Ключевое слово `else` в связке с циклом `for`.** Один из стандартных примеров: ```py def does_exists_num(l, to_find): @@ -3239,7 +3299,7 @@ Ellipsis - Многоточие может использоваться в нескольких случаях, + В качестве заполнителя для кода, который еще не написан (аналогично оператору `pass`) + В синтаксисе срезов (slices) для представления полных срезов в оставшемся направлении - ``py + ```py >>> import numpy as np >>> three_dimensional_array = np.arange(8).reshape(2, 2, 2) array([ @@ -3264,7 +3324,7 @@ Ellipsis [5, 7]]) ``` Примечание: это будет работать для любого количества измерений. Можно даже выбрать срез в первом и последнем измерении и игнорировать средние (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`) - + В [подсказках типов](https://docs.python.org/3/library/typing.html) для указания только части типа (например, `(Callable[..., int]` или `Tuple[str, ...]`)) + + В [подсказках типов](https://docs.python.org/3/library/typing.html) для указания только части типа (например, `Callable[..., int]` или `Tuple[str, ...]`) + Вы также можете использовать `Ellipsis` в качестве аргумента функции по умолчанию (в случаях, когда вы хотите провести различие между сценариями "аргумент не передан" и "значение не передано"). --- @@ -3483,7 +3543,7 @@ def square(x): ## Секция: Разное -### ▶ `+=` быстрее +### ▶ `+=` быстрее `+` ```py @@ -3587,7 +3647,7 @@ def convert_list_to_string(l, iters): >>> %timeit -n100 add_string_with_plus(1000) 388 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) - >>> %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time + >>> %timeit -n100 add_string_with_plus(10000) # Квадратичное увеличение времени выполнения 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` @@ -3627,7 +3687,7 @@ KeyError: 1 #### 💡 Объяснение: + В CPython есть общая функция поиска по словарю, которая работает со всеми типами ключей (`str`, `int`, любой объект ...), и специализированная для распространенного случая словарей, состоящих только из `str`-ключей. -+ Специализированная функция (названная `lookdict_unicode` в [исходный код CPython](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) знает, что все существующие ключи (включая искомый ключ) являются строками, и использует более быстрое и простое сравнение строк для сравнения ключей, вместо вызова метода `__eq__`. ++ Специализированная функция (названная `lookdict_unicode` в [CPython](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) знает, что все существующие ключи (включая искомый ключ) являются строками, и использует более быстрое и простое сравнение строк для сравнения ключей, вместо вызова метода `__eq__`. + При первом обращении к экземпляру `dict` с ключом, не являющимся `str`, он модифицируется, чтобы в дальнейшем для поиска использовалась общая функция. + Этот процесс не обратим для конкретного экземпляра `dict`, и ключ даже не обязательно должен существовать в словаре. Поэтому попытка неудачного поиска имеет тот же эффект. @@ -3706,7 +3766,7 @@ def dict_size(o): * Несколько странных, но семантически правильных утверждений: + `[] = ()` - семантически корректное утверждение (распаковка пустого `кортежа` в пустой `список`) - + `'a'[0][0][0][0][0]` также является семантически корректным утверждением, поскольку в Python строки являются [последовательностями](https://docs.python.org/3/glossary.html#term-sequence)(итерируемыми объектами, поддерживающими доступ к элементам с использованием целочисленных индексов). + + `'a'[0][0][0][0][0]` также является семантически корректным утверждением, поскольку в Python строки являются [последовательностями](https://docs.python.org/3/glossary.html#term-sequence) (итерируемыми объектами, поддерживающими доступ к элементам с использованием целочисленных индексов). + `3 --0-- 5 == 8` и `--5 == 5` - оба семантически корректные утверждения и имеют значение `True`. * Учитывая, что `a` - это число, `++a` и `--a` являются корректными утверждениями Python, но ведут себя не так, как аналогичные утверждения в таких языках, как C, C++ или Java. From 9687de2a67cda2fcd16e7cca56523ea3ce919278 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 29 Apr 2024 06:36:44 +0300 Subject: [PATCH 139/210] Translate CONTRIBUTING guide --- CONTRIBUTING.md | 70 ++++++++++++++++++++++++------------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dd9049d4..a5428149 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,63 +1,63 @@ -All kinds of patches are welcome. Feel free to even suggest some catchy and funny titles for the existing Examples. The goal is to make this collection as interesting to read as possible. Here are a few ways through which you can contribute, +Приветствуются все виды изменений. Не стесняйтесь предлагать броские и смешные названия для существующих примеров. Цель - сделать эту коллекцию как можно более интересной для чтения. Вот несколько способов, с помощью которых вы можете внести свой вклад, -- If you are interested in translating the project to another language (some people have done that in the past), please feel free to open up an issue, and let me know if you need any kind of help. -- If the changes you suggest are significant, filing an issue before submitting the actual patch will be appreciated. If you'd like to work on the issue (highly encouraged), you can mention that you're interested in working on it while creating the issue and get assigned to it. -- If you're adding a new example, it is highly recommended to create an issue to discuss it before submitting a patch. You can use the following template for adding a new example: +- Если вы заинтересованы в переводе проекта на другой язык (некоторые люди уже делали это в прошлом), пожалуйста, не стесняйтесь открыть тему и дайте мне знать, если вам нужна какая-либо помощь. +- Если изменения, которые вы предлагаете, значительны, то создание issue перед внесением изменений будет оценено по достоинству. Если вы хотите поработать над issue (это очень рекомендуется), выразите свою заинтересованность и вы будете назначены исполнителем. +- Если вы добавляете новый пример, настоятельно рекомендуется создать issue, чтобы обсудить ее перед отправкой изменений. Для добавления нового примера вы можете использовать следующий шаблон:
-### ▶ Some fancy Title *
-The asterisk at the end of the title indicates the example was not present in the first release and has been recently added.
+### ▶ Какое-то причудливое название. *
+* в конце названия означает, что пример был добавлен недавно.
 
 ```py
-# Setting up the code.
-# Preparation for the magic...
+# Подготовка кода.
+# Подготовка к волшебству...
 ```
 
-**Output (Python version):**
+**Вывод (версия Python):**
 ```py
 >>> triggering_statement
-Probably unexpected output
+Вероятно, неожиданный вывод
+
 ```
-(Optional): One line describing the unexpected output.
+(Необязательно): Одна строка, описывающая неожиданный вывод.
 
-#### 💡 Explanation:
-* Brief explanation of what's happening and why is it happening.
+#### 💡 Объяснение:
+* Краткое объяснение того, что происходит и почему это происходит.
   ```py
-  Setting up examples for clarification (if necessary)
+  Подготовка примеров для пояснения (при необходимости)
   ```
-  **Output:**
+
+  **Вывод:**
   ```py
-  >>> trigger # some example that makes it easy to unveil the magic
-  # some justified output
+  >>> trigger # пример, облегчающий понимание магии
+  # обоснованный вывод
   ```
-```
 
+Несколько моментов, которые стоит учитывать при написании примера, -Few things that you can consider while writing an example, - -- If you are choosing to submit a new example without creating an issue and discussing, please check the project to make sure there aren't similar examples already. -- Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's no strictly enforced scheme in the project as such, but you can take a glance at other examples to get a gist. -- Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write. -- Also, feel free to add your name to the [contributors list](/CONTRIBUTORS.md). +- Если вы решили отправить новый пример без создания issue и обсуждения, пожалуйста, проверьте проект, чтобы убедиться, что в нем уже нет похожих примеров. +- Старайтесь быть последовательными в именах и значениях, которые вы используете для переменных. Например, большинство имен переменных в проекте имеют вид `some_string`, `some_list`, `some_dict` и т.д. Вы увидите много `x` для однобуквенных имен переменных, и `"wtf"` в качестве значений для строк. В проекте нет строгой схемы, как таковой, но вы можете взглянуть на другие примеры, чтобы понять суть. +- Старайтесь быть как можно более креативными, чтобы добавить элемент "сюрприза" во время подготовки примеров. Иногда это может означать написание фрагмента, который здравомыслящий программист никогда бы не написал. +- Также не стесняйтесь добавлять свое имя в список [контрибьюторов](/CONTRIBUTORS.md). -**Some FAQs** +**Некоторые часто задаваемые вопросы** - What is is this after every snippet title (###) in the README: ? Should it be added manually or can it be ignored when creating new snippets? + Что это такое после каждого заголовка сниппета (###) в README: ? Нужно ли его добавлять вручную или можно игнорировать при создании новых сниппетов? -That's a random UUID, it is used to keep identify the examples across multiple translations of the project. As a contributor, you don't have to worry about behind the scenes of how it is used, you just have to add a new random UUID to new examples in that format. +Это случайный UUID, он используется для идентификации примеров в нескольких переводах проекта. Как контрибьютор, вы не должны беспокоиться о том, как он используется, вы просто должны добавлять новый случайный UUID к новым примерам в этом формате. - Where should new snippets be added? Top/bottom of the section, doesn't ? + Куда следует добавлять новые сниппеты? В начало/в конец раздела? -There are multiple things that are considered to decide the order (the dependency on the other examples, difficulty level, category, etc). I'd suggest simply adding the new example at the bottom of a section you find more fitting (or just add it to the Miscellaneous section). Its order will be taken care of in future revisions. +При определении порядка учитывается множество факторов (зависимость от других примеров, уровень сложности, категория и т.д.). Я бы предложил просто добавить новый пример в конец раздела, который вы считаете более подходящим (или просто добавить его в раздел "Разное"). О его порядке можно будет позаботиться в будущих редакциях. - What's the difference between the sections (the first two feel very similar)? + В чем разница между разделами (первые два очень похожи)? -The section "Strain your brain" contains more contrived examples that you may not really encounter in real life, whereas the section "Slippery Slopes" contains examples that have the potential to be encountered more frequently while programming. +Раздел "Напрягите мозг" содержит более надуманные примеры, с которыми вы не столкнетесь в реальной жизни, в то время как раздел "Скользкие склоны" содержит примеры, с которыми можно чаще сталкиваться при программировании. - Before the table of contents it says that markdown-toc -i README.md --maxdepth 3 was used to create it. The pip package markdown-toc does not contain either -i or --maxdepth flags. Which package is meant, or what version of that package? - Should the new table of contents entry for the snippet be created with the above command or created manually (in case the above command does more than only add the entry)? + Перед оглавлением написано, что для его создания использовался markdown-toc -i README.md --maxdepth 3. Пакет pip markdown-toc не содержит ни флагов -i, ни --maxdepth. Какой пакет имеется в виду, или какая версия этого пакета? + Должна ли новая запись в оглавлении для фрагмента быть создана с помощью вышеуказанной команды или вручную (в случае, если вышеуказанная команда делает больше, чем просто добавляет запись)? -We use the [markdown-toc](https://www.npmjs.com/package/markdown-toc) npm package to generate ToC. It has some issues with special characters though (I'm not sure if it's fixed yet). More often than not, I just end up inserting the toc link manually at the right place. The tool is handy when I have to big reordering, otherwise just updating toc manually is more convenient imo. +Мы используем пакет [markdown-toc](https://www.npmjs.com/package/markdown-toc) npm для создания ToC (содержание). Однако у него есть некоторые проблемы со специальными символами (не уверен, что они уже исправлены). Чаще всего я просто вставляю ссылку toc вручную в нужное место. Инструмент удобен, когда мне нужно сделать большую перестановку, в остальных случаях просто обновлять toc вручную удобнее. -If you have any questions feel free to ask on [this issue](https://github.com/satwikkansal/wtfpython/issues/269) (thanks to [@LiquidFun](https://github.com/LiquidFun) for starting it). +Если у вас есть вопросы, не стесняйтесь спрашивать в [issue](https://github.com/satwikkansal/wtfpython/issues/269) (спасибо [@LiquidFun](https://github.com/LiquidFun) за ее создание). From fcb70ba7b909b50d4bfa7c51d27a7b46a037d562 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 29 Apr 2024 06:43:47 +0300 Subject: [PATCH 140/210] Change translation for word "section" --- translations/README-ru.md | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/translations/README-ru.md b/translations/README-ru.md index 9cde0244..21dc0570 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -21,7 +21,7 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - [Структура примера](#структура-примера) - [Применение](#применение) - [👀 Примеры](#-примеры) - - [Секция: Напряги мозги!](#секция-напряги-мозги) + - [Раздел: Напряги мозги!](#раздел-напряги-мозги) - [▶ Первым делом!](#-первым-делом) - [💡 Обьяснение](#-обьяснение) - [▶ Строки иногда ведут себя непредсказуемо](#-строки-иногда-ведут-себя-непредсказуемо) @@ -83,7 +83,7 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - [💡 Объяснение:](#-объяснение-28) - [▶ Превышение предела целочисленного преобразования строк](#-превышение-предела-целочисленного-преобразования-строк) - [💡 Объяснение:](#-объяснение-29) - - [Секция: Скользкие склоны](#секция-скользкие-склоны) + - [Раздел: Скользкие склоны](#раздел-скользкие-склоны) - [▶ Изменение словаря во время прохода по нему](#-изменение-словаря-во-время-прохода-по-нему) - [💡 Объяснение:](#-объяснение-30) - [▶ Упрямая операция `del`](#-упрямая-операция-del) @@ -116,7 +116,7 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - [💡 Объяснение:](#-объяснение-44) - [▶ Полночи не существует?](#-полночи-не-существует) - [💡 Объяснение:](#-объяснение-45) - - [Секция: Скрытые сокровища!](#секция-скрытые-сокровища) + - [Раздел: Скрытые сокровища!](#раздел-скрытые-сокровища) - [▶ Python, можешь ли ты помочь взлететь?](#-python-можешь-ли-ты-помочь-взлететь) - [💡 Объяснение:](#-объяснение-46) - [▶ `goto`, но почему?](#-goto-но-почему) @@ -135,14 +135,14 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - [💡 Объяснение:](#-объяснение-53) - [▶ Давайте искажать](#-давайте-искажать) - [💡 Объяснение:](#-объяснение-54) - - [Секция: Внешность обманчива!](#секция-внешность-обманчива) + - [Раздел: Внешность обманчива!](#раздел-внешность-обманчива) - [▶ Пропускаем строки?](#-пропускаем-строки) - [💡 Объяснение](#-объяснение-55) - [▶ Телепортация](#-телепортация) - [💡 Объяснение:](#-объяснение-56) - [▶ Что-то не так...](#-что-то-не-так) - [💡 Объяснение](#-объяснение-57) - - [Секция: Разное](#секция-разное) + - [Раздел: Разное](#раздел-разное) - [▶ `+=` быстрее `+`](#--быстрее-) - [💡 Объяснение:](#-объяснение-58) - [▶ Сделаем гигантскую строку!](#-сделаем-гигантскую-строку) @@ -218,7 +218,7 @@ wtfpython # 👀 Примеры -## Секция: Напряги мозги! +## Раздел: Напряги мозги! ### ▶ Первым делом! @@ -2079,7 +2079,7 @@ ValueError: Exceeds the limit (4300) for integer string conversion: --- -## Секция: Скользкие склоны +## Раздел: Скользкие склоны ### ▶ Изменение словаря во время прохода по нему @@ -3046,11 +3046,9 @@ if noon_time: --- --- +## Раздел: Скрытые сокровища! - -## Секция: Скрытые сокровища! - -Секция содержит менее известные интересные нюансы работы Python, которые неизвестны большинству новичков. +Раздел содержит менее известные интересные нюансы работы Python, которые неизвестны большинству новичков. ### ▶ Python, можешь ли ты помочь взлететь? @@ -3426,7 +3424,7 @@ AttributeError: 'A' object has no attribute '__variable' --- --- -## Секция: Внешность обманчива! +## Раздел: Внешность обманчива! ### ▶ Пропускаем строки? @@ -3540,7 +3538,7 @@ def square(x): --- --- -## Секция: Разное +## Раздел: Разное ### ▶ `+=` быстрее `+` From a2c5a17ca8346d6285e62b10dd6137cb1f3eb557 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 29 Apr 2024 06:50:59 +0300 Subject: [PATCH 141/210] Remove extra level of headings from Table of Content --- translations/README-ru.md | 64 --------------------------------------- 1 file changed, 64 deletions(-) diff --git a/translations/README-ru.md b/translations/README-ru.md index 21dc0570..402b26aa 100644 --- a/translations/README-ru.md +++ b/translations/README-ru.md @@ -23,138 +23,74 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - [👀 Примеры](#-примеры) - [Раздел: Напряги мозги!](#раздел-напряги-мозги) - [▶ Первым делом!](#-первым-делом) - - [💡 Обьяснение](#-обьяснение) - [▶ Строки иногда ведут себя непредсказуемо](#-строки-иногда-ведут-себя-непредсказуемо) - - [💡 Объяснение](#-объяснение) - [▶ Осторожнее с цепочкой операций](#-осторожнее-с-цепочкой-операций) - - [💡 Объяснение:](#-объяснение-1) - [▶ Как не надо использовать оператор `is`](#-как-не-надо-использовать-оператор-is) - - [💡 Объяснение:](#-объяснение-2) - [▶ Мистическое хеширование](#-мистическое-хеширование) - - [💡 Объяснение](#-объяснение-3) - [▶ В глубине души мы все одинаковы.](#-в-глубине-души-мы-все-одинаковы) - - [💡 Объяснение:](#-объяснение-4) - [▶ Беспорядок внутри порядка \*](#-беспорядок-внутри-порядка-) - - [💡 Объяснение:](#-объяснение-5) - [▶ Продолжай пытаться... \*](#-продолжай-пытаться-) - - [💡 Объяснение:](#-объяснение-6) - [▶ Для чего?](#-для-чего) - - [💡 Объяснение:](#-объяснение-7) - [▶ Расхождение во времени исполнения](#-расхождение-во-времени-исполнения) - - [💡 Объяснение](#-объяснение-8) - [▶ `is not ...` не является `is (not ...)`](#-is-not--не-является-is-not-) - - [💡 Объяснение](#-объяснение-9) - [▶ Крестики-нолики, где X побеждает с первой попытки!](#-крестики-нолики-где-x-побеждает-с-первой-попытки) - - [💡 Объяснение:](#-объяснение-10) - [▶ Переменная Шредингера \*](#-переменная-шредингера-) - - [💡 Объяснение:](#-объяснение-11) - [▶ Проблема курицы и яйца \*](#-проблема-курицы-и-яйца-) - - [💡 Объяснение](#-объяснение-12) - [▶ Отношения между подклассами](#-отношения-между-подклассами) - - [💡 Объяснение](#-объяснение-13) - [▶ Равенство и тождество методов](#-равенство-и-тождество-методов) - - [💡 Объяснение](#-объяснение-14) - [▶ All-true-ation (непереводимая игра слов) \*](#-all-true-ation-непереводимая-игра-слов-) - - [💡 Объяснение:](#-объяснение-15) - - [💡 Объяснение:](#-объяснение-16) - [▶ Строки и обратные слэши](#-строки-и-обратные-слэши) - - [💡 Объяснение](#-объяснение-17) - [▶ Не узел! (англ. not knot!)](#-не-узел-англ-not-knot) - - [💡 Объяснение](#-объяснение-18) - [▶ Строки, наполовину обернутые в тройные кавычки](#-строки-наполовину-обернутые-в-тройные-кавычки) - - [💡 Объяснение:](#-объяснение-19) - [▶ Что не так с логическими значениями?](#-что-не-так-с-логическими-значениями) - - [💡 Объяснение:](#-объяснение-20) - [▶ Атрибуты класса и экземпляра](#-атрибуты-класса-и-экземпляра) - - [💡 Объяснение:](#-объяснение-21) - [▶ Возврат None из генератора](#-возврат-none-из-генератора) - - [💡 Объяснение:](#-объяснение-22) - [▶ Yield from возвращает... \*](#-yield-from-возвращает-) - - [💡 Объяснение:](#-объяснение-23) - [▶ Nan-рефлексивность \*](#-nan-рефлексивность-) - - [💡 Объяснение:](#-объяснение-24) - [▶ Изменяем неизменяемое!](#-изменяем-неизменяемое) - - [💡 Объяснение:](#-объяснение-25) - [▶ Исчезающая переменная из внешней области видимости](#-исчезающая-переменная-из-внешней-области-видимости) - - [💡 Объяснение:](#-объяснение-26) - [▶ Загадочное преобразование типов ключей](#-загадочное-преобразование-типов-ключей) - - [💡 Объяснение:](#-объяснение-27) - [▶ Посмотрим, сможете ли вы угадать что здесь?](#-посмотрим-сможете-ли-вы-угадать-что-здесь) - - [💡 Объяснение:](#-объяснение-28) - [▶ Превышение предела целочисленного преобразования строк](#-превышение-предела-целочисленного-преобразования-строк) - - [💡 Объяснение:](#-объяснение-29) - [Раздел: Скользкие склоны](#раздел-скользкие-склоны) - [▶ Изменение словаря во время прохода по нему](#-изменение-словаря-во-время-прохода-по-нему) - - [💡 Объяснение:](#-объяснение-30) - [▶ Упрямая операция `del`](#-упрямая-операция-del) - - [💡 Объяснение:](#-объяснение-31) - [▶ Переменная за пределами видимости](#-переменная-за-пределами-видимости) - - [💡 Объяснение:](#-объяснение-32) - [▶ Удаление элемента списка во время прохода по списку](#-удаление-элемента-списка-во-время-прохода-по-списку) - - [💡 Объяснение:](#-объяснение-33) - [▶ Сжатие итераторов с потерями \*](#-сжатие-итераторов-с-потерями-) - - [💡 Объяснение:](#-объяснение-34) - [▶ Утечка переменных внутри цикла](#-утечка-переменных-внутри-цикла) - - [💡 Объяснение:](#-объяснение-35) - [▶ Остерегайтесь изменяемых аргументов по умолчанию!](#-остерегайтесь-изменяемых-аргументов-по-умолчанию) - - [💡 Объяснение:](#-объяснение-36) - [▶ Ловля исключений](#-ловля-исключений) - - [💡 Объяснение](#-объяснение-37) - [▶ Одни и те же операнды, разная история!](#-одни-и-те-же-операнды-разная-история) - - [💡 Объяснение:](#-объяснение-38) - [▶ Разрешение имен игнорирует область видимости класса](#-разрешение-имен-игнорирует-область-видимости-класса) - - [💡 Объяснение](#-объяснение-39) - [▶ Округляясь как банкир \*](#-округляясь-как-банкир-) - - [💡 Объяснение:](#-объяснение-40) - [▶ Иголки в стоге сена \*](#-иголки-в-стоге-сена-) - - [💡 Объяснение:](#-объяснение-41) - [▶ Сплиты (splitsies) \*](#-сплиты-splitsies-) - - [💡 Объяснение](#-объяснение-42) - [▶ Подстановочное импортирование (wild imports) \*](#-подстановочное-импортирование-wild-imports-) - - [💡 Объяснение:](#-объяснение-43) - [▶ Все ли отсортировано? \*](#-все-ли-отсортировано-) - - [💡 Объяснение:](#-объяснение-44) - [▶ Полночи не существует?](#-полночи-не-существует) - - [💡 Объяснение:](#-объяснение-45) - [Раздел: Скрытые сокровища!](#раздел-скрытые-сокровища) - [▶ Python, можешь ли ты помочь взлететь?](#-python-можешь-ли-ты-помочь-взлететь) - - [💡 Объяснение:](#-объяснение-46) - [▶ `goto`, но почему?](#-goto-но-почему) - - [💡 Объяснение:](#-объяснение-47) - [▶ Держитесь!](#-держитесь) - - [💡 Объяснение:](#-объяснение-48) - [▶ Давайте познакомимся с дружелюбным Дядей Барри](#-давайте-познакомимся-с-дружелюбным-дядей-барри) - - [💡 Объяснение:](#-объяснение-49) - [▶ Даже Python понимает, что любовь - это сложно.](#-даже-python-понимает-что-любовь---это-сложно) - - [💡 Объяснение:](#-объяснение-50) - [▶ Да, оно существует!](#-да-оно-существует) - - [💡 Объяснение:](#-объяснение-51) - [▶ Многоточие \*](#-многоточие-) - - [💡 Объяснение](#-объяснение-52) - [▶ Писконечность (Inpinity)](#-писконечность-inpinity) - - [💡 Объяснение:](#-объяснение-53) - [▶ Давайте искажать](#-давайте-искажать) - - [💡 Объяснение:](#-объяснение-54) - [Раздел: Внешность обманчива!](#раздел-внешность-обманчива) - [▶ Пропускаем строки?](#-пропускаем-строки) - - [💡 Объяснение](#-объяснение-55) - [▶ Телепортация](#-телепортация) - - [💡 Объяснение:](#-объяснение-56) - [▶ Что-то не так...](#-что-то-не-так) - - [💡 Объяснение](#-объяснение-57) - [Раздел: Разное](#раздел-разное) - [▶ `+=` быстрее `+`](#--быстрее-) - - [💡 Объяснение:](#-объяснение-58) - [▶ Сделаем гигантскую строку!](#-сделаем-гигантскую-строку) - - [💡 Объяснение](#-объяснение-59) - [▶ Замедляем поиск по `dict` \*](#-замедляем-поиск-по-dict-) - - [💡 Объяснение:](#-объяснение-60) - [▶ Раздуваем экземпляры словарей \*](#-раздуваем-экземпляры-словарей-) - - [💡 Объяснение:](#-объяснение-61) - [▶ Минорное \*](#-минорное-) - [Вклад в проект](#вклад-в-проект) - [Благодарности](#благодарности) - - [Несколько хороших ссылок!](#несколько-хороших-ссылок) - [🎓 Лицензия](#-лицензия) - [Удиви своих друзей!](#удиви-своих-друзей) - [Нужна PDF версия?](#нужна-pdf-версия) From 6f35f0046194bcb907403a8c008b0ffe6cc1cc4c Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 3 May 2024 09:38:55 +0300 Subject: [PATCH 142/210] Translate Code of Conduct --- code-of-conduct.md | 106 ++++++++++++++++++++++----------------------- 1 file changed, 51 insertions(+), 55 deletions(-) diff --git a/code-of-conduct.md b/code-of-conduct.md index 558af4a6..2aa521fc 100644 --- a/code-of-conduct.md +++ b/code-of-conduct.md @@ -1,74 +1,70 @@ -# Contributor Covenant Code of Conduct +# Кодекс Поведения участника -## Our Pledge +## Наши обязательства -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -education, socio-economic status, nationality, personal appearance, race, -religion, or sexual identity and orientation. +Мы, как участники, авторы и лидеры обязуемся сделать участие в сообществе +свободным от притеснений для всех, независимо от возраста, телосложения, +видимых или невидимых ограничений способности, этнической принадлежности, +половых признаков, гендерной идентичности и выражения, уровня опыта, +образования, социально-экономического статуса, национальности, внешности, +расы, религии, или сексуальной идентичности и ориентации. -## Our Standards +Мы обещаем действовать и взаимодействовать таким образом, чтобы вносить вклад в открытое, +дружелюбное, многообразное, инклюзивное и здоровое сообщество. -Examples of behavior that contributes to creating a positive environment -include: +## Наши стандарты -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members +Примеры поведения, создающие условия для благоприятных взаимоотношений включают в себя: -Examples of unacceptable behavior by participants include: +* Проявление доброты и эмпатии к другим участникам проекта +* Уважение к чужой точке зрения и опыту +* Конструктивная критика и принятие конструктивной критики +* Принятие ответственности, принесение извинений тем, кто пострадал от наших ошибок + и извлечение уроков из опыта +* Ориентирование на то, что лучше подходит для сообщества, а не только для нас лично -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting +Примеры неприемлемого поведения участников включают в себя: -## Our Responsibilities +* Использование выражений или изображений сексуального характера и нежелательное сексуальное внимание или домогательство в любой форме +* Троллинг, оскорбительные или уничижительные комментарии, переход на личности или затрагивание политических убеждений +* Публичное или приватное домогательство +* Публикация личной информации других лиц, например, физического или электронного адреса, без явного разрешения +* Иное поведение, которое обоснованно считать неуместным в профессиональной обстановке -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. +## Обязанности -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. +Лидеры сообщества отвечают за разъяснение и применение наших стандартов приемлемого +поведения и будут предпринимать соответствующие и честные меры по исправлению положения +в ответ на любое поведение, которое они сочтут неприемлемым, угрожающим, оскорбительным или вредным. -## Scope +Лидеры сообщества обладают правом и обязанностью удалять, редактировать или отклонять +комментарии, коммиты, код, изменения в вики, вопросы и другой вклад, который не совпадает +с Кодексом Поведения, и предоставят причины принятого решения, когда сочтут нужным. -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. +## Область применения -## Enforcement +Данный Кодекс Поведения применим во всех публичных физических и цифровых пространства сообщества, +а также когда человек официально представляет сообщество в публичных местах. +Примеры представления проекта или сообщества включают использование официальной электронной почты, +публикации в официальном аккаунте в социальных сетях, +или упоминания как представителя в онлайн или офлайн мероприятии. -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at [INSERT EMAIL ADDRESS]. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. +## Приведение в исполнение -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. +О случаях домогательства, а так же оскорбительного или иного другого неприемлемого +поведения можно сообщить ответственным лидерам сообщества с помощью email. +Все жалобы будут рассмотрены и расследованы оперативно и беспристрастно. -## Attribution +Все лидеры сообщества обязаны уважать неприкосновенность частной жизни и личную +неприкосновенность автора сообщения. -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html +## Атрибуция -[homepage]: https://www.contributor-covenant.org +Данный Кодекс Поведения основан на [Кодекс Поведения участника][homepage], +версии 2.0, доступной по адресу +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Принципы Воздействия в Сообществе были вдохновлены [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). +[homepage]: https://www.contributor-covenant.org From b1684aaf39a5277e607c28f1c90b6c7cacc602eb Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sat, 4 May 2024 18:58:57 +0300 Subject: [PATCH 143/210] Move translated files to translations/ru-russian --- CONTRIBUTING.md | 70 ++++++------ CONTRIBUTORS.md | 12 +- code-of-conduct.md | 105 +++++++++--------- translations/ru-russian/CONTIRBUTING.md | 63 +++++++++++ translations/ru-russian/CONTRIBUTORS.md | 42 +++++++ .../{README-ru.md => ru-russian/README.md} | 0 translations/ru-russian/code-of-conduct.md | 70 ++++++++++++ 7 files changed, 270 insertions(+), 92 deletions(-) create mode 100644 translations/ru-russian/CONTIRBUTING.md create mode 100644 translations/ru-russian/CONTRIBUTORS.md rename translations/{README-ru.md => ru-russian/README.md} (100%) create mode 100644 translations/ru-russian/code-of-conduct.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a5428149..e6863e3d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,63 +1,63 @@ -Приветствуются все виды изменений. Не стесняйтесь предлагать броские и смешные названия для существующих примеров. Цель - сделать эту коллекцию как можно более интересной для чтения. Вот несколько способов, с помощью которых вы можете внести свой вклад, +All kinds of patches are welcome. Feel free to even suggest some catchy and funny titles for the existing Examples. The goal is to make this collection as interesting to read as possible. Here are a few ways through which you can contribute, -- Если вы заинтересованы в переводе проекта на другой язык (некоторые люди уже делали это в прошлом), пожалуйста, не стесняйтесь открыть тему и дайте мне знать, если вам нужна какая-либо помощь. -- Если изменения, которые вы предлагаете, значительны, то создание issue перед внесением изменений будет оценено по достоинству. Если вы хотите поработать над issue (это очень рекомендуется), выразите свою заинтересованность и вы будете назначены исполнителем. -- Если вы добавляете новый пример, настоятельно рекомендуется создать issue, чтобы обсудить ее перед отправкой изменений. Для добавления нового примера вы можете использовать следующий шаблон: +- If you are interested in translating the project to another language (some people have done that in the past), please feel free to open up an issue, and let me know if you need any kind of help. +- If the changes you suggest are significant, filing an issue before submitting the actual patch will be appreciated. If you'd like to work on the issue (highly encouraged), you can mention that you're interested in working on it while creating the issue and get assigned to it. +- If you're adding a new example, it is highly recommended to create an issue to discuss it before submitting a patch. You can use the following template for adding a new example:
-### ▶ Какое-то причудливое название. *
-* в конце названия означает, что пример был добавлен недавно.
+### ▶ Some fancy Title *
+The asterisk at the end of the title indicates the example was not present in the first release and has been recently added.
 
 ```py
-# Подготовка кода.
-# Подготовка к волшебству...
+# Setting up the code.
+# Preparation for the magic...
 ```
 
-**Вывод (версия Python):**
+**Output (Python version):**
 ```py
 >>> triggering_statement
-Вероятно, неожиданный вывод
-
+Probably unexpected output
 ```
-(Необязательно): Одна строка, описывающая неожиданный вывод.
+(Optional): One line describing the unexpected output.
 
-#### 💡 Объяснение:
-* Краткое объяснение того, что происходит и почему это происходит.
+#### 💡 Explanation:
+* Brief explanation of what's happening and why is it happening.
   ```py
-  Подготовка примеров для пояснения (при необходимости)
+  Setting up examples for clarification (if necessary)
   ```
-
-  **Вывод:**
+  **Output:**
   ```py
-  >>> trigger # пример, облегчающий понимание магии
-  # обоснованный вывод
+  >>> trigger # some example that makes it easy to unveil the magic
+  # some justified output
   ```
+```
 
-Несколько моментов, которые стоит учитывать при написании примера, -- Если вы решили отправить новый пример без создания issue и обсуждения, пожалуйста, проверьте проект, чтобы убедиться, что в нем уже нет похожих примеров. -- Старайтесь быть последовательными в именах и значениях, которые вы используете для переменных. Например, большинство имен переменных в проекте имеют вид `some_string`, `some_list`, `some_dict` и т.д. Вы увидите много `x` для однобуквенных имен переменных, и `"wtf"` в качестве значений для строк. В проекте нет строгой схемы, как таковой, но вы можете взглянуть на другие примеры, чтобы понять суть. -- Старайтесь быть как можно более креативными, чтобы добавить элемент "сюрприза" во время подготовки примеров. Иногда это может означать написание фрагмента, который здравомыслящий программист никогда бы не написал. -- Также не стесняйтесь добавлять свое имя в список [контрибьюторов](/CONTRIBUTORS.md). +Few things that you can consider while writing an example, + +- If you are choosing to submit a new example without creating an issue and discussing, please check the project to make sure there aren't similar examples already. +- Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's no strictly enforced scheme in the project as such, but you can take a glance at other examples to get a gist. +- Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write. +- Also, feel free to add your name to the [contributors list](/CONTRIBUTORS.md). -**Некоторые часто задаваемые вопросы** +**Some FAQs** - Что это такое после каждого заголовка сниппета (###) в README: ? Нужно ли его добавлять вручную или можно игнорировать при создании новых сниппетов? + What is is this after every snippet title (###) in the README: ? Should it be added manually or can it be ignored when creating new snippets? -Это случайный UUID, он используется для идентификации примеров в нескольких переводах проекта. Как контрибьютор, вы не должны беспокоиться о том, как он используется, вы просто должны добавлять новый случайный UUID к новым примерам в этом формате. +That's a random UUID, it is used to keep identify the examples across multiple translations of the project. As a contributor, you don't have to worry about behind the scenes of how it is used, you just have to add a new random UUID to new examples in that format. - Куда следует добавлять новые сниппеты? В начало/в конец раздела? + Where should new snippets be added? Top/bottom of the section, doesn't ? -При определении порядка учитывается множество факторов (зависимость от других примеров, уровень сложности, категория и т.д.). Я бы предложил просто добавить новый пример в конец раздела, который вы считаете более подходящим (или просто добавить его в раздел "Разное"). О его порядке можно будет позаботиться в будущих редакциях. +There are multiple things that are considered to decide the order (the dependency on the other examples, difficulty level, category, etc). I'd suggest simply adding the new example at the bottom of a section you find more fitting (or just add it to the Miscellaneous section). Its order will be taken care of in future revisions. - В чем разница между разделами (первые два очень похожи)? + What's the difference between the sections (the first two feel very similar)? -Раздел "Напрягите мозг" содержит более надуманные примеры, с которыми вы не столкнетесь в реальной жизни, в то время как раздел "Скользкие склоны" содержит примеры, с которыми можно чаще сталкиваться при программировании. +The section "Strain your brain" contains more contrived examples that you may not really encounter in real life, whereas the section "Slippery Slopes" contains examples that have the potential to be encountered more frequently while programming. - Перед оглавлением написано, что для его создания использовался markdown-toc -i README.md --maxdepth 3. Пакет pip markdown-toc не содержит ни флагов -i, ни --maxdepth. Какой пакет имеется в виду, или какая версия этого пакета? - Должна ли новая запись в оглавлении для фрагмента быть создана с помощью вышеуказанной команды или вручную (в случае, если вышеуказанная команда делает больше, чем просто добавляет запись)? + Before the table of contents it says that markdown-toc -i README.md --maxdepth 3 was used to create it. The pip package markdown-toc does not contain either -i or --maxdepth flags. Which package is meant, or what version of that package? + Should the new table of contents entry for the snippet be created with the above command or created manually (in case the above command does more than only add the entry)? -Мы используем пакет [markdown-toc](https://www.npmjs.com/package/markdown-toc) npm для создания ToC (содержание). Однако у него есть некоторые проблемы со специальными символами (не уверен, что они уже исправлены). Чаще всего я просто вставляю ссылку toc вручную в нужное место. Инструмент удобен, когда мне нужно сделать большую перестановку, в остальных случаях просто обновлять toc вручную удобнее. +We use the [markdown-toc](https://www.npmjs.com/package/markdown-toc) npm package to generate ToC. It has some issues with special characters though (I'm not sure if it's fixed yet). More often than not, I just end up inserting the toc link manually at the right place. The tool is handy when I have to big reordering, otherwise just updating toc manually is more convenient imo. -Если у вас есть вопросы, не стесняйтесь спрашивать в [issue](https://github.com/satwikkansal/wtfpython/issues/269) (спасибо [@LiquidFun](https://github.com/LiquidFun) за ее создание). +If you have any questions feel free to ask on [this issue](https://github.com/satwikkansal/wtfpython/issues/269) (thanks to [@LiquidFun](https://github.com/LiquidFun) for starting it). \ No newline at end of file diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 8a22a49b..eb624967 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1,6 +1,6 @@ -Ниже перечислены (без определенного порядка) замечательные люди, которые внесли вклад в развитие wtfpython. +Following are the wonderful people (in no specific order) who have contributed their examples to wtfpython. -| Автор | Github | Issues | +| Contributor | Github | Issues | |-------------|--------|--------| | Lucas-C | [Lucas-C](https://github.com/Lucas-C) | [#36](https://github.com/satwikkansal/wtfpython/issues/36) | | MittalAshok | [MittalAshok](https://github.com/MittalAshok) | [#23](https://github.com/satwikkansal/wtfpython/issues/23) | @@ -28,15 +28,15 @@ --- -**Переводчики** +**Translations** -| Переводчик | Github | Язык | +| Translator | Github | Language | |-------------|--------|--------| | leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [Chinese](https://github.com/leisurelicht/wtfpython-cn) | | vuduclyunitn | [vuduclyunitn](https://github.com/vuduclyunitn) | [Vietnamese](https://github.com/vuduclyunitn/wtfptyhon-vi) | | José De Freitas | [JoseDeFreitas](https://github.com/JoseDeFreitas) | [Spanish](https://github.com/JoseDeFreitas/wtfpython-es) | | Vadim Nifadev | [nifadyev](https://github.com/nifadyev) | [Russian](https://github.com/satwikkansal/wtfpython/tree/main/translations/README-ru.md) | -Спасибо всем за ваше время и за то, что делаете wtfpython еще более потрясающим! :smile: +Thank you all for your time and making wtfpython more awesome! :smile: -PS: Этот список обновляется после каждого крупного релиза, если я забыл добавить сюда ваш вклад, пожалуйста, не стесняйтесь сделать Pull request. +PS: This list is updated after every major release, if I forgot to add your contribution here, please feel free to raise a Pull request. \ No newline at end of file diff --git a/code-of-conduct.md b/code-of-conduct.md index 2aa521fc..45904feb 100644 --- a/code-of-conduct.md +++ b/code-of-conduct.md @@ -1,70 +1,73 @@ -# Кодекс Поведения участника +# Contributor Covenant Code of Conduct -## Наши обязательства +## Our Pledge -Мы, как участники, авторы и лидеры обязуемся сделать участие в сообществе -свободным от притеснений для всех, независимо от возраста, телосложения, -видимых или невидимых ограничений способности, этнической принадлежности, -половых признаков, гендерной идентичности и выражения, уровня опыта, -образования, социально-экономического статуса, национальности, внешности, -расы, религии, или сексуальной идентичности и ориентации. +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +education, socio-economic status, nationality, personal appearance, race, +religion, or sexual identity and orientation. -Мы обещаем действовать и взаимодействовать таким образом, чтобы вносить вклад в открытое, -дружелюбное, многообразное, инклюзивное и здоровое сообщество. +## Our Standards -## Наши стандарты +Examples of behavior that contributes to creating a positive environment +include: -Примеры поведения, создающие условия для благоприятных взаимоотношений включают в себя: +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members -* Проявление доброты и эмпатии к другим участникам проекта -* Уважение к чужой точке зрения и опыту -* Конструктивная критика и принятие конструктивной критики -* Принятие ответственности, принесение извинений тем, кто пострадал от наших ошибок - и извлечение уроков из опыта -* Ориентирование на то, что лучше подходит для сообщества, а не только для нас лично +Examples of unacceptable behavior by participants include: -Примеры неприемлемого поведения участников включают в себя: +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting -* Использование выражений или изображений сексуального характера и нежелательное сексуальное внимание или домогательство в любой форме -* Троллинг, оскорбительные или уничижительные комментарии, переход на личности или затрагивание политических убеждений -* Публичное или приватное домогательство -* Публикация личной информации других лиц, например, физического или электронного адреса, без явного разрешения -* Иное поведение, которое обоснованно считать неуместным в профессиональной обстановке +## Our Responsibilities -## Обязанности +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. -Лидеры сообщества отвечают за разъяснение и применение наших стандартов приемлемого -поведения и будут предпринимать соответствующие и честные меры по исправлению положения -в ответ на любое поведение, которое они сочтут неприемлемым, угрожающим, оскорбительным или вредным. +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. -Лидеры сообщества обладают правом и обязанностью удалять, редактировать или отклонять -комментарии, коммиты, код, изменения в вики, вопросы и другой вклад, который не совпадает -с Кодексом Поведения, и предоставят причины принятого решения, когда сочтут нужным. +## Scope -## Область применения +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. -Данный Кодекс Поведения применим во всех публичных физических и цифровых пространства сообщества, -а также когда человек официально представляет сообщество в публичных местах. -Примеры представления проекта или сообщества включают использование официальной электронной почты, -публикации в официальном аккаунте в социальных сетях, -или упоминания как представителя в онлайн или офлайн мероприятии. +## Enforcement -## Приведение в исполнение +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at [INSERT EMAIL ADDRESS]. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. -О случаях домогательства, а так же оскорбительного или иного другого неприемлемого -поведения можно сообщить ответственным лидерам сообщества с помощью email. -Все жалобы будут рассмотрены и расследованы оперативно и беспристрастно. +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. -Все лидеры сообщества обязаны уважать неприкосновенность частной жизни и личную -неприкосновенность автора сообщения. +## Attribution -## Атрибуция - -Данный Кодекс Поведения основан на [Кодекс Поведения участника][homepage], -версии 2.0, доступной по адресу -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Принципы Воздействия в Сообществе были вдохновлены [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org diff --git a/translations/ru-russian/CONTIRBUTING.md b/translations/ru-russian/CONTIRBUTING.md new file mode 100644 index 00000000..a5428149 --- /dev/null +++ b/translations/ru-russian/CONTIRBUTING.md @@ -0,0 +1,63 @@ +Приветствуются все виды изменений. Не стесняйтесь предлагать броские и смешные названия для существующих примеров. Цель - сделать эту коллекцию как можно более интересной для чтения. Вот несколько способов, с помощью которых вы можете внести свой вклад, + +- Если вы заинтересованы в переводе проекта на другой язык (некоторые люди уже делали это в прошлом), пожалуйста, не стесняйтесь открыть тему и дайте мне знать, если вам нужна какая-либо помощь. +- Если изменения, которые вы предлагаете, значительны, то создание issue перед внесением изменений будет оценено по достоинству. Если вы хотите поработать над issue (это очень рекомендуется), выразите свою заинтересованность и вы будете назначены исполнителем. +- Если вы добавляете новый пример, настоятельно рекомендуется создать issue, чтобы обсудить ее перед отправкой изменений. Для добавления нового примера вы можете использовать следующий шаблон: + +
+### ▶ Какое-то причудливое название. *
+* в конце названия означает, что пример был добавлен недавно.
+
+```py
+# Подготовка кода.
+# Подготовка к волшебству...
+```
+
+**Вывод (версия Python):**
+```py
+>>> triggering_statement
+Вероятно, неожиданный вывод
+
+```
+(Необязательно): Одна строка, описывающая неожиданный вывод.
+
+#### 💡 Объяснение:
+* Краткое объяснение того, что происходит и почему это происходит.
+  ```py
+  Подготовка примеров для пояснения (при необходимости)
+  ```
+
+  **Вывод:**
+  ```py
+  >>> trigger # пример, облегчающий понимание магии
+  # обоснованный вывод
+  ```
+
+ +Несколько моментов, которые стоит учитывать при написании примера, + +- Если вы решили отправить новый пример без создания issue и обсуждения, пожалуйста, проверьте проект, чтобы убедиться, что в нем уже нет похожих примеров. +- Старайтесь быть последовательными в именах и значениях, которые вы используете для переменных. Например, большинство имен переменных в проекте имеют вид `some_string`, `some_list`, `some_dict` и т.д. Вы увидите много `x` для однобуквенных имен переменных, и `"wtf"` в качестве значений для строк. В проекте нет строгой схемы, как таковой, но вы можете взглянуть на другие примеры, чтобы понять суть. +- Старайтесь быть как можно более креативными, чтобы добавить элемент "сюрприза" во время подготовки примеров. Иногда это может означать написание фрагмента, который здравомыслящий программист никогда бы не написал. +- Также не стесняйтесь добавлять свое имя в список [контрибьюторов](/CONTRIBUTORS.md). + +**Некоторые часто задаваемые вопросы** + + Что это такое после каждого заголовка сниппета (###) в README: ? Нужно ли его добавлять вручную или можно игнорировать при создании новых сниппетов? + +Это случайный UUID, он используется для идентификации примеров в нескольких переводах проекта. Как контрибьютор, вы не должны беспокоиться о том, как он используется, вы просто должны добавлять новый случайный UUID к новым примерам в этом формате. + + Куда следует добавлять новые сниппеты? В начало/в конец раздела? + +При определении порядка учитывается множество факторов (зависимость от других примеров, уровень сложности, категория и т.д.). Я бы предложил просто добавить новый пример в конец раздела, который вы считаете более подходящим (или просто добавить его в раздел "Разное"). О его порядке можно будет позаботиться в будущих редакциях. + + В чем разница между разделами (первые два очень похожи)? + +Раздел "Напрягите мозг" содержит более надуманные примеры, с которыми вы не столкнетесь в реальной жизни, в то время как раздел "Скользкие склоны" содержит примеры, с которыми можно чаще сталкиваться при программировании. + + Перед оглавлением написано, что для его создания использовался markdown-toc -i README.md --maxdepth 3. Пакет pip markdown-toc не содержит ни флагов -i, ни --maxdepth. Какой пакет имеется в виду, или какая версия этого пакета? + Должна ли новая запись в оглавлении для фрагмента быть создана с помощью вышеуказанной команды или вручную (в случае, если вышеуказанная команда делает больше, чем просто добавляет запись)? + +Мы используем пакет [markdown-toc](https://www.npmjs.com/package/markdown-toc) npm для создания ToC (содержание). Однако у него есть некоторые проблемы со специальными символами (не уверен, что они уже исправлены). Чаще всего я просто вставляю ссылку toc вручную в нужное место. Инструмент удобен, когда мне нужно сделать большую перестановку, в остальных случаях просто обновлять toc вручную удобнее. + +Если у вас есть вопросы, не стесняйтесь спрашивать в [issue](https://github.com/satwikkansal/wtfpython/issues/269) (спасибо [@LiquidFun](https://github.com/LiquidFun) за ее создание). diff --git a/translations/ru-russian/CONTRIBUTORS.md b/translations/ru-russian/CONTRIBUTORS.md new file mode 100644 index 00000000..8a22a49b --- /dev/null +++ b/translations/ru-russian/CONTRIBUTORS.md @@ -0,0 +1,42 @@ +Ниже перечислены (без определенного порядка) замечательные люди, которые внесли вклад в развитие wtfpython. + +| Автор | Github | Issues | +|-------------|--------|--------| +| Lucas-C | [Lucas-C](https://github.com/Lucas-C) | [#36](https://github.com/satwikkansal/wtfpython/issues/36) | +| MittalAshok | [MittalAshok](https://github.com/MittalAshok) | [#23](https://github.com/satwikkansal/wtfpython/issues/23) | +| asottile | [asottile](https://github.com/asottile) | [#40](https://github.com/satwikkansal/wtfpython/issues/40) | +| MostAwesomeDude | [MostAwesomeDude](https://github.com/MostAwesomeDude) | [#1](https://github.com/satwikkansal/wtfpython/issues/1) | +| tukkek | [tukkek](https://github.com/tukkek) | [#11](https://github.com/satwikkansal/wtfpython/issues/11), [#26](https://github.com/satwikkansal/wtfpython/issues/26) | +| PiaFraus | [PiaFraus](https://github.com/PiaFraus) | [#9](https://github.com/satwikkansal/wtfpython/issues/9) | +| chris-rands | [chris-rands](https://github.com/chris-rands) | [#32](https://github.com/satwikkansal/wtfpython/issues/32) | +| sohaibfarooqi | [sohaibfarooqi](https://github.com/sohaibfarooqi) | [#63](https://github.com/satwikkansal/wtfpython/issues/63) | +| ipid | [ipid](https://github.com/ipid) | [#145](https://github.com/satwikkansal/wtfpython/issues/145) | +| roshnet | [roshnet](https://github.com/roshnet) | [#140](https://github.com/satwikkansal/wtfpython/issues/140) | +| daidai21 | [daidai21](https://github.com/daidai21) | [#137](https://github.com/satwikkansal/wtfpython/issues/137) | +| scidam | [scidam](https://github.com/scidam) | [#136](https://github.com/satwikkansal/wtfpython/issues/136) | +| pmjpawelec | [pmjpawelec](https://github.com/pmjpawelec) | [#121](https://github.com/satwikkansal/wtfpython/issues/121) | +| leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [#112](https://github.com/satwikkansal/wtfpython/issues/112) | +| mishaturnbull | [mishaturnbull](https://github.com/mishaturnbull) | [#108](https://github.com/satwikkansal/wtfpython/issues/108) | +| MuseBoy | [MuseBoy](https://github.com/MuseBoy) | [#101](https://github.com/satwikkansal/wtfpython/issues/101) | +| Ghost account | N/A | [#96](https://github.com/satwikkansal/wtfpython/issues/96) | +| koddo | [koddo](https://github.com/koddo) | [#80](https://github.com/satwikkansal/wtfpython/issues/80), [#73](https://github.com/satwikkansal/wtfpython/issues/73) | +| jab | [jab](https://github.com/jab) | [#77](https://github.com/satwikkansal/wtfpython/issues/77) | +| Jongy | [Jongy](https://github.com/Jongy) | [#208](https://github.com/satwikkansal/wtfpython/issues/208), [#210](https://github.com/satwikkansal/wtfpython/issues/210), [#233](https://github.com/satwikkansal/wtfpython/issues/233) | +| Diptangsu Goswami | [diptangsu](https://github.com/diptangsu) | [#193](https://github.com/satwikkansal/wtfpython/issues/193) | +| Charles | [charles-l](https://github.com/charles-l) | [#245](https://github.com/satwikkansal/wtfpython/issues/245) | +| LiquidFun | [LiquidFun](https://github.com/LiquidFun) | [#267](https://github.com/satwikkansal/wtfpython/issues/267) | + +--- + +**Переводчики** + +| Переводчик | Github | Язык | +|-------------|--------|--------| +| leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [Chinese](https://github.com/leisurelicht/wtfpython-cn) | +| vuduclyunitn | [vuduclyunitn](https://github.com/vuduclyunitn) | [Vietnamese](https://github.com/vuduclyunitn/wtfptyhon-vi) | +| José De Freitas | [JoseDeFreitas](https://github.com/JoseDeFreitas) | [Spanish](https://github.com/JoseDeFreitas/wtfpython-es) | +| Vadim Nifadev | [nifadyev](https://github.com/nifadyev) | [Russian](https://github.com/satwikkansal/wtfpython/tree/main/translations/README-ru.md) | + +Спасибо всем за ваше время и за то, что делаете wtfpython еще более потрясающим! :smile: + +PS: Этот список обновляется после каждого крупного релиза, если я забыл добавить сюда ваш вклад, пожалуйста, не стесняйтесь сделать Pull request. diff --git a/translations/README-ru.md b/translations/ru-russian/README.md similarity index 100% rename from translations/README-ru.md rename to translations/ru-russian/README.md diff --git a/translations/ru-russian/code-of-conduct.md b/translations/ru-russian/code-of-conduct.md new file mode 100644 index 00000000..2aa521fc --- /dev/null +++ b/translations/ru-russian/code-of-conduct.md @@ -0,0 +1,70 @@ +# Кодекс Поведения участника + +## Наши обязательства + +Мы, как участники, авторы и лидеры обязуемся сделать участие в сообществе +свободным от притеснений для всех, независимо от возраста, телосложения, +видимых или невидимых ограничений способности, этнической принадлежности, +половых признаков, гендерной идентичности и выражения, уровня опыта, +образования, социально-экономического статуса, национальности, внешности, +расы, религии, или сексуальной идентичности и ориентации. + +Мы обещаем действовать и взаимодействовать таким образом, чтобы вносить вклад в открытое, +дружелюбное, многообразное, инклюзивное и здоровое сообщество. + +## Наши стандарты + +Примеры поведения, создающие условия для благоприятных взаимоотношений включают в себя: + +* Проявление доброты и эмпатии к другим участникам проекта +* Уважение к чужой точке зрения и опыту +* Конструктивная критика и принятие конструктивной критики +* Принятие ответственности, принесение извинений тем, кто пострадал от наших ошибок + и извлечение уроков из опыта +* Ориентирование на то, что лучше подходит для сообщества, а не только для нас лично + +Примеры неприемлемого поведения участников включают в себя: + +* Использование выражений или изображений сексуального характера и нежелательное сексуальное внимание или домогательство в любой форме +* Троллинг, оскорбительные или уничижительные комментарии, переход на личности или затрагивание политических убеждений +* Публичное или приватное домогательство +* Публикация личной информации других лиц, например, физического или электронного адреса, без явного разрешения +* Иное поведение, которое обоснованно считать неуместным в профессиональной обстановке + +## Обязанности + +Лидеры сообщества отвечают за разъяснение и применение наших стандартов приемлемого +поведения и будут предпринимать соответствующие и честные меры по исправлению положения +в ответ на любое поведение, которое они сочтут неприемлемым, угрожающим, оскорбительным или вредным. + +Лидеры сообщества обладают правом и обязанностью удалять, редактировать или отклонять +комментарии, коммиты, код, изменения в вики, вопросы и другой вклад, который не совпадает +с Кодексом Поведения, и предоставят причины принятого решения, когда сочтут нужным. + +## Область применения + +Данный Кодекс Поведения применим во всех публичных физических и цифровых пространства сообщества, +а также когда человек официально представляет сообщество в публичных местах. +Примеры представления проекта или сообщества включают использование официальной электронной почты, +публикации в официальном аккаунте в социальных сетях, +или упоминания как представителя в онлайн или офлайн мероприятии. + +## Приведение в исполнение + +О случаях домогательства, а так же оскорбительного или иного другого неприемлемого +поведения можно сообщить ответственным лидерам сообщества с помощью email. +Все жалобы будут рассмотрены и расследованы оперативно и беспристрастно. + +Все лидеры сообщества обязаны уважать неприкосновенность частной жизни и личную +неприкосновенность автора сообщения. + +## Атрибуция + +Данный Кодекс Поведения основан на [Кодекс Поведения участника][homepage], +версии 2.0, доступной по адресу +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Принципы Воздействия в Сообществе были вдохновлены [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org From 16628ba0711a686c45a9d59b3c3a67bb30edab8c Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sat, 4 May 2024 19:05:24 +0300 Subject: [PATCH 144/210] Minor changes --- CONTRIBUTING.md | 2 +- CONTRIBUTORS.md | 2 +- code-of-conduct.md | 1 + translations/ru-russian/{CONTIRBUTING.md => CONTRIBUTING.md} | 0 4 files changed, 3 insertions(+), 2 deletions(-) mode change 100644 => 100755 CONTRIBUTING.md mode change 100644 => 100755 code-of-conduct.md rename translations/ru-russian/{CONTIRBUTING.md => CONTRIBUTING.md} (100%) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md old mode 100644 new mode 100755 index e6863e3d..dd9049d4 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -60,4 +60,4 @@ The section "Strain your brain" contains more contrived examples that you may no We use the [markdown-toc](https://www.npmjs.com/package/markdown-toc) npm package to generate ToC. It has some issues with special characters though (I'm not sure if it's fixed yet). More often than not, I just end up inserting the toc link manually at the right place. The tool is handy when I have to big reordering, otherwise just updating toc manually is more convenient imo. -If you have any questions feel free to ask on [this issue](https://github.com/satwikkansal/wtfpython/issues/269) (thanks to [@LiquidFun](https://github.com/LiquidFun) for starting it). \ No newline at end of file +If you have any questions feel free to ask on [this issue](https://github.com/satwikkansal/wtfpython/issues/269) (thanks to [@LiquidFun](https://github.com/LiquidFun) for starting it). diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index eb624967..68d51766 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -39,4 +39,4 @@ Following are the wonderful people (in no specific order) who have contributed t Thank you all for your time and making wtfpython more awesome! :smile: -PS: This list is updated after every major release, if I forgot to add your contribution here, please feel free to raise a Pull request. \ No newline at end of file +PS: This list is updated after every major release, if I forgot to add your contribution here, please feel free to raise a Pull request. diff --git a/code-of-conduct.md b/code-of-conduct.md old mode 100644 new mode 100755 index 45904feb..558af4a6 --- a/code-of-conduct.md +++ b/code-of-conduct.md @@ -71,3 +71,4 @@ This Code of Conduct is adapted from the [Contributor Covenant][homepage], versi available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org + diff --git a/translations/ru-russian/CONTIRBUTING.md b/translations/ru-russian/CONTRIBUTING.md similarity index 100% rename from translations/ru-russian/CONTIRBUTING.md rename to translations/ru-russian/CONTRIBUTING.md From 19fba3855684a21f93af9f85b0db71bf5ccea102 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sat, 4 May 2024 19:58:02 +0300 Subject: [PATCH 145/210] Fix links to Russian translation --- README.md | 209 +++++++++++++++++++----------- translations/ru-russian/README.md | 66 +++++++++- 2 files changed, 201 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index bb3100fc..0d3fd480 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) @@ -24,84 +24,147 @@ So, here we go... +- [Table of Contents](#table-of-contents) - [Structure of the Examples](#structure-of-the-examples) - + [▶ Some fancy Title](#-some-fancy-title) - [Usage](#usage) - [👀 Examples](#-examples) - * [Section: Strain your brain!](#section-strain-your-brain) - + [▶ First things first! *](#-first-things-first-) - + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) - + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - + [▶ How not to use `is` operator](#-how-not-to-use-is-operator) - + [▶ Hash brownies](#-hash-brownies) - + [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) - + [▶ Disorder within order *](#-disorder-within-order-) - + [▶ Keep trying... *](#-keep-trying-) - + [▶ For what?](#-for-what) - + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - + [▶ `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-) - + [▶ Subclass relationships](#-subclass-relationships) - + [▶ Methods equality and identity](#-methods-equality-and-identity) - + [▶ All-true-ation *](#-all-true-ation-) - + [▶ The surprising comma](#-the-surprising-comma) - + [▶ Strings and the backslashes](#-strings-and-the-backslashes) - + [▶ not knot!](#-not-knot) - + [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - + [▶ yielding None](#-yielding-none) - + [▶ 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) - + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) - + [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) - * [Section: Slippery Slopes](#section-slippery-slopes) - + [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) - + [▶ Stubborn `del` operation](#-stubborn-del-operation) - + [▶ The out of scope variable](#-the-out-of-scope-variable) - + [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - + [▶ Lossy zip of iterators *](#-lossy-zip-of-iterators-) - + [▶ Loop variables leaking out!](#-loop-variables-leaking-out) - + [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - + [▶ Catching the Exceptions](#-catching-the-exceptions) - + [▶ Same operands, different story!](#-same-operands-different-story) - + [▶ 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-) - + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - * [Section: The Hidden treasures!](#section-the-hidden-treasures) - + [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) - + [▶ `goto`, but why?](#-goto-but-why) - + [▶ Brace yourself!](#-brace-yourself) - + [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) - + [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) - + [▶ Yes, it exists!](#-yes-it-exists) - + [▶ Ellipsis *](#-ellipsis-) - + [▶ Inpinity](#-inpinity) - + [▶ Let's mangle](#-lets-mangle) - * [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - + [▶ Skipping lines?](#-skipping-lines) - + [▶ Teleportation](#-teleportation) - + [▶ Well, something is fishy...](#-well-something-is-fishy) - * [Section: Miscellaneous](#section-miscellaneous) - + [▶ `+=` is faster](#--is-faster) - + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups-) - + [▶ Bloating instance `dict`s *](#-bloating-instance-dicts-) - + [▶ Minor Ones *](#-minor-ones-) + - [Section: Strain your brain!](#section-strain-your-brain) + - [▶ First things first! \*](#-first-things-first-) + - [💡 Explanation](#-explanation) + - [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) + - [💡 Explanation:](#-explanation-1) + - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + - [💡 Explanation:](#-explanation-2) + - [▶ How not to use `is` operator](#-how-not-to-use-is-operator) + - [💡 Explanation:](#-explanation-3) + - [▶ Hash brownies](#-hash-brownies) + - [💡 Explanation](#-explanation-4) + - [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) + - [💡 Explanation:](#-explanation-5) + - [▶ Disorder within order \*](#-disorder-within-order-) + - [💡 Explanation:](#-explanation-6) + - [▶ Keep trying... \*](#-keep-trying-) + - [💡 Explanation:](#-explanation-7) + - [▶ For what?](#-for-what) + - [💡 Explanation:](#-explanation-8) + - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) + - [💡 Explanation](#-explanation-9) + - [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) + - [💡 Explanation](#-explanation-10) + - [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + - [💡 Explanation:](#-explanation-11) + - [▶ Schrödinger's variable \*](#-schrödingers-variable-) + - [💡 Explanation:](#-explanation-12) + - [▶ The chicken-egg problem \*](#-the-chicken-egg-problem-) + - [💡 Explanation](#-explanation-13) + - [▶ Subclass relationships](#-subclass-relationships) + - [💡 Explanation:](#-explanation-14) + - [▶ Methods equality and identity](#-methods-equality-and-identity) + - [💡 Explanation](#-explanation-15) + - [▶ All-true-ation \*](#-all-true-ation-) + - [💡 Explanation:](#-explanation-16) + - [💡 Explanation:](#-explanation-17) + - [▶ Strings and the backslashes](#-strings-and-the-backslashes) + - [💡 Explanation](#-explanation-18) + - [▶ not knot!](#-not-knot) + - [💡 Explanation:](#-explanation-19) + - [▶ Half triple-quoted strings](#-half-triple-quoted-strings) + - [💡 Explanation:](#-explanation-20) + - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) + - [💡 Explanation:](#-explanation-21) + - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) + - [💡 Explanation:](#-explanation-22) + - [▶ yielding None](#-yielding-none) + - [💡 Explanation:](#-explanation-23) + - [▶ Yielding from... return! \*](#-yielding-from-return-) + - [💡 Explanation:](#-explanation-24) + - [▶ Nan-reflexivity \*](#-nan-reflexivity-) + - [💡 Explanation:](#-explanation-25) + - [▶ Mutating the immutable!](#-mutating-the-immutable) + - [💡 Explanation:](#-explanation-26) + - [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) + - [💡 Explanation:](#-explanation-27) + - [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) + - [💡 Explanation:](#-explanation-28) + - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + - [💡 Explanation:](#-explanation-29) + - [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) + - [💡 Explanation:](#-explanation-30) + - [Section: Slippery Slopes](#section-slippery-slopes) + - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + - [💡 Explanation:](#-explanation-31) + - [▶ Stubborn `del` operation](#-stubborn-del-operation) + - [💡 Explanation:](#-explanation-32) + - [▶ The out of scope variable](#-the-out-of-scope-variable) + - [💡 Explanation:](#-explanation-33) + - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) + - [💡 Explanation:](#-explanation-34) + - [▶ Lossy zip of iterators \*](#-lossy-zip-of-iterators-) + - [💡 Explanation:](#-explanation-35) + - [▶ Loop variables leaking out!](#-loop-variables-leaking-out) + - [💡 Explanation:](#-explanation-36) + - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) + - [💡 Explanation:](#-explanation-37) + - [▶ Catching the Exceptions](#-catching-the-exceptions) + - [💡 Explanation](#-explanation-38) + - [▶ Same operands, different story!](#-same-operands-different-story) + - [💡 Explanation:](#-explanation-39) + - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) + - [💡 Explanation](#-explanation-40) + - [▶ Rounding like a banker \*](#-rounding-like-a-banker-) + - [💡 Explanation:](#-explanation-41) + - [▶ Needles in a Haystack \*](#-needles-in-a-haystack-) + - [💡 Explanation:](#-explanation-42) + - [▶ Splitsies \*](#-splitsies-) + - [💡 Explanation:](#-explanation-43) + - [▶ Wild imports \*](#-wild-imports-) + - [💡 Explanation:](#-explanation-44) + - [▶ All sorted? \*](#-all-sorted-) + - [💡 Explanation:](#-explanation-45) + - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) + - [💡 Explanation:](#-explanation-46) + - [Section: The Hidden treasures!](#section-the-hidden-treasures) + - [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) + - [💡 Explanation:](#-explanation-47) + - [▶ `goto`, but why?](#-goto-but-why) + - [💡 Explanation:](#-explanation-48) + - [▶ Brace yourself!](#-brace-yourself) + - [💡 Explanation:](#-explanation-49) + - [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) + - [💡 Explanation:](#-explanation-50) + - [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) + - [💡 Explanation:](#-explanation-51) + - [▶ Yes, it exists!](#-yes-it-exists) + - [💡 Explanation:](#-explanation-52) + - [▶ Ellipsis \*](#-ellipsis-) + - [💡 Explanation](#-explanation-53) + - [▶ Inpinity](#-inpinity) + - [💡 Explanation:](#-explanation-54) + - [▶ Let's mangle](#-lets-mangle) + - [💡 Explanation:](#-explanation-55) + - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) + - [▶ Skipping lines?](#-skipping-lines) + - [💡 Explanation](#-explanation-56) + - [▶ Teleportation](#-teleportation) + - [💡 Explanation:](#-explanation-57) + - [▶ Well, something is fishy...](#-well-something-is-fishy) + - [💡 Explanation](#-explanation-58) + - [Section: Miscellaneous](#section-miscellaneous) + - [▶ `+=` is faster](#--is-faster) + - [💡 Explanation:](#-explanation-59) + - [▶ Let's make a giant string!](#-lets-make-a-giant-string) + - [💡 Explanation](#-explanation-60) + - [▶ Slowing down `dict` lookups \*](#-slowing-down-dict-lookups-) + - [💡 Explanation:](#-explanation-61) + - [▶ Bloating instance `dict`s \*](#-bloating-instance-dicts-) + - [💡 Explanation:](#-explanation-62) + - [▶ Minor Ones \*](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) + - [Some nice Links!](#some-nice-links) - [🎓 License](#-license) - * [Surprise your friends as well!](#surprise-your-friends-as-well) - * [More content like this?](#more-content-like-this) + - [Surprise your friends as well!](#surprise-your-friends-as-well) + - [Need a pdf version?](#need-a-pdf-version) diff --git a/translations/ru-russian/README.md b/translations/ru-russian/README.md index 402b26aa..d8dff4aa 100644 --- a/translations/ru-russian/README.md +++ b/translations/ru-russian/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Изучение и понимание Python с помощью удивительных примеров поведения.

-Переводы: [English Original](https://github.com/satwikkansal/wtfpython) [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/main/translations/README-ru.md) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Переводы: [English Original](https://github.com/satwikkansal/wtfpython) [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Альтернативные способы: [Интерактивный сайт](https://wtfpython-interactive.vercel.app) | [Интерактивный Jupiter notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) @@ -23,74 +23,138 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - [👀 Примеры](#-примеры) - [Раздел: Напряги мозги!](#раздел-напряги-мозги) - [▶ Первым делом!](#-первым-делом) + - [💡 Обьяснение](#-обьяснение) - [▶ Строки иногда ведут себя непредсказуемо](#-строки-иногда-ведут-себя-непредсказуемо) + - [💡 Объяснение](#-объяснение) - [▶ Осторожнее с цепочкой операций](#-осторожнее-с-цепочкой-операций) + - [💡 Объяснение:](#-объяснение-1) - [▶ Как не надо использовать оператор `is`](#-как-не-надо-использовать-оператор-is) + - [💡 Объяснение:](#-объяснение-2) - [▶ Мистическое хеширование](#-мистическое-хеширование) + - [💡 Объяснение](#-объяснение-3) - [▶ В глубине души мы все одинаковы.](#-в-глубине-души-мы-все-одинаковы) + - [💡 Объяснение:](#-объяснение-4) - [▶ Беспорядок внутри порядка \*](#-беспорядок-внутри-порядка-) + - [💡 Объяснение:](#-объяснение-5) - [▶ Продолжай пытаться... \*](#-продолжай-пытаться-) + - [💡 Объяснение:](#-объяснение-6) - [▶ Для чего?](#-для-чего) + - [💡 Объяснение:](#-объяснение-7) - [▶ Расхождение во времени исполнения](#-расхождение-во-времени-исполнения) + - [💡 Объяснение](#-объяснение-8) - [▶ `is not ...` не является `is (not ...)`](#-is-not--не-является-is-not-) + - [💡 Объяснение](#-объяснение-9) - [▶ Крестики-нолики, где X побеждает с первой попытки!](#-крестики-нолики-где-x-побеждает-с-первой-попытки) + - [💡 Объяснение:](#-объяснение-10) - [▶ Переменная Шредингера \*](#-переменная-шредингера-) + - [💡 Объяснение:](#-объяснение-11) - [▶ Проблема курицы и яйца \*](#-проблема-курицы-и-яйца-) + - [💡 Объяснение](#-объяснение-12) - [▶ Отношения между подклассами](#-отношения-между-подклассами) + - [💡 Объяснение](#-объяснение-13) - [▶ Равенство и тождество методов](#-равенство-и-тождество-методов) + - [💡 Объяснение](#-объяснение-14) - [▶ All-true-ation (непереводимая игра слов) \*](#-all-true-ation-непереводимая-игра-слов-) + - [💡 Объяснение:](#-объяснение-15) + - [💡 Объяснение:](#-объяснение-16) - [▶ Строки и обратные слэши](#-строки-и-обратные-слэши) + - [💡 Объяснение](#-объяснение-17) - [▶ Не узел! (англ. not knot!)](#-не-узел-англ-not-knot) + - [💡 Объяснение](#-объяснение-18) - [▶ Строки, наполовину обернутые в тройные кавычки](#-строки-наполовину-обернутые-в-тройные-кавычки) + - [💡 Объяснение:](#-объяснение-19) - [▶ Что не так с логическими значениями?](#-что-не-так-с-логическими-значениями) + - [💡 Объяснение:](#-объяснение-20) - [▶ Атрибуты класса и экземпляра](#-атрибуты-класса-и-экземпляра) + - [💡 Объяснение:](#-объяснение-21) - [▶ Возврат None из генератора](#-возврат-none-из-генератора) + - [💡 Объяснение:](#-объяснение-22) - [▶ Yield from возвращает... \*](#-yield-from-возвращает-) + - [💡 Объяснение:](#-объяснение-23) - [▶ Nan-рефлексивность \*](#-nan-рефлексивность-) + - [💡 Объяснение:](#-объяснение-24) - [▶ Изменяем неизменяемое!](#-изменяем-неизменяемое) + - [💡 Объяснение:](#-объяснение-25) - [▶ Исчезающая переменная из внешней области видимости](#-исчезающая-переменная-из-внешней-области-видимости) + - [💡 Объяснение:](#-объяснение-26) - [▶ Загадочное преобразование типов ключей](#-загадочное-преобразование-типов-ключей) + - [💡 Объяснение:](#-объяснение-27) - [▶ Посмотрим, сможете ли вы угадать что здесь?](#-посмотрим-сможете-ли-вы-угадать-что-здесь) + - [💡 Объяснение:](#-объяснение-28) - [▶ Превышение предела целочисленного преобразования строк](#-превышение-предела-целочисленного-преобразования-строк) + - [💡 Объяснение:](#-объяснение-29) - [Раздел: Скользкие склоны](#раздел-скользкие-склоны) - [▶ Изменение словаря во время прохода по нему](#-изменение-словаря-во-время-прохода-по-нему) + - [💡 Объяснение:](#-объяснение-30) - [▶ Упрямая операция `del`](#-упрямая-операция-del) + - [💡 Объяснение:](#-объяснение-31) - [▶ Переменная за пределами видимости](#-переменная-за-пределами-видимости) + - [💡 Объяснение:](#-объяснение-32) - [▶ Удаление элемента списка во время прохода по списку](#-удаление-элемента-списка-во-время-прохода-по-списку) + - [💡 Объяснение:](#-объяснение-33) - [▶ Сжатие итераторов с потерями \*](#-сжатие-итераторов-с-потерями-) + - [💡 Объяснение:](#-объяснение-34) - [▶ Утечка переменных внутри цикла](#-утечка-переменных-внутри-цикла) + - [💡 Объяснение:](#-объяснение-35) - [▶ Остерегайтесь изменяемых аргументов по умолчанию!](#-остерегайтесь-изменяемых-аргументов-по-умолчанию) + - [💡 Объяснение:](#-объяснение-36) - [▶ Ловля исключений](#-ловля-исключений) + - [💡 Объяснение](#-объяснение-37) - [▶ Одни и те же операнды, разная история!](#-одни-и-те-же-операнды-разная-история) + - [💡 Объяснение:](#-объяснение-38) - [▶ Разрешение имен игнорирует область видимости класса](#-разрешение-имен-игнорирует-область-видимости-класса) + - [💡 Объяснение](#-объяснение-39) - [▶ Округляясь как банкир \*](#-округляясь-как-банкир-) + - [💡 Объяснение:](#-объяснение-40) - [▶ Иголки в стоге сена \*](#-иголки-в-стоге-сена-) + - [💡 Объяснение:](#-объяснение-41) - [▶ Сплиты (splitsies) \*](#-сплиты-splitsies-) + - [💡 Объяснение](#-объяснение-42) - [▶ Подстановочное импортирование (wild imports) \*](#-подстановочное-импортирование-wild-imports-) + - [💡 Объяснение:](#-объяснение-43) - [▶ Все ли отсортировано? \*](#-все-ли-отсортировано-) + - [💡 Объяснение:](#-объяснение-44) - [▶ Полночи не существует?](#-полночи-не-существует) + - [💡 Объяснение:](#-объяснение-45) - [Раздел: Скрытые сокровища!](#раздел-скрытые-сокровища) - [▶ Python, можешь ли ты помочь взлететь?](#-python-можешь-ли-ты-помочь-взлететь) + - [💡 Объяснение:](#-объяснение-46) - [▶ `goto`, но почему?](#-goto-но-почему) + - [💡 Объяснение:](#-объяснение-47) - [▶ Держитесь!](#-держитесь) + - [💡 Объяснение:](#-объяснение-48) - [▶ Давайте познакомимся с дружелюбным Дядей Барри](#-давайте-познакомимся-с-дружелюбным-дядей-барри) + - [💡 Объяснение:](#-объяснение-49) - [▶ Даже Python понимает, что любовь - это сложно.](#-даже-python-понимает-что-любовь---это-сложно) + - [💡 Объяснение:](#-объяснение-50) - [▶ Да, оно существует!](#-да-оно-существует) + - [💡 Объяснение:](#-объяснение-51) - [▶ Многоточие \*](#-многоточие-) + - [💡 Объяснение](#-объяснение-52) - [▶ Писконечность (Inpinity)](#-писконечность-inpinity) + - [💡 Объяснение:](#-объяснение-53) - [▶ Давайте искажать](#-давайте-искажать) + - [💡 Объяснение:](#-объяснение-54) - [Раздел: Внешность обманчива!](#раздел-внешность-обманчива) - [▶ Пропускаем строки?](#-пропускаем-строки) + - [💡 Объяснение](#-объяснение-55) - [▶ Телепортация](#-телепортация) + - [💡 Объяснение:](#-объяснение-56) - [▶ Что-то не так...](#-что-то-не-так) + - [💡 Объяснение](#-объяснение-57) - [Раздел: Разное](#раздел-разное) - [▶ `+=` быстрее `+`](#--быстрее-) + - [💡 Объяснение:](#-объяснение-58) - [▶ Сделаем гигантскую строку!](#-сделаем-гигантскую-строку) + - [💡 Объяснение](#-объяснение-59) - [▶ Замедляем поиск по `dict` \*](#-замедляем-поиск-по-dict-) + - [💡 Объяснение:](#-объяснение-60) - [▶ Раздуваем экземпляры словарей \*](#-раздуваем-экземпляры-словарей-) + - [💡 Объяснение:](#-объяснение-61) - [▶ Минорное \*](#-минорное-) - [Вклад в проект](#вклад-в-проект) - [Благодарности](#благодарности) + - [Несколько хороших ссылок!](#несколько-хороших-ссылок) - [🎓 Лицензия](#-лицензия) - [Удиви своих друзей!](#удиви-своих-друзей) - [Нужна PDF версия?](#нужна-pdf-версия) From 0ec593971346c2575b605442cb9ce9dba0a9abfe Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sat, 4 May 2024 19:58:56 +0300 Subject: [PATCH 146/210] Revert CONTRIBUTING.md --- CONTRIBUTING.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md old mode 100755 new mode 100644 From b6fd12efa2fb58d1984460ac3fe5abca94da39ba Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sat, 4 May 2024 20:01:51 +0300 Subject: [PATCH 147/210] Revert code-of-conduct.md --- code-of-conduct.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 code-of-conduct.md diff --git a/code-of-conduct.md b/code-of-conduct.md old mode 100755 new mode 100644 From 39595fc35f5538040c825f28f191926707a84fa9 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sat, 4 May 2024 20:03:28 +0300 Subject: [PATCH 148/210] Revert README.md --- README.md | 209 +++++++++++++++++++----------------------------------- 1 file changed, 73 insertions(+), 136 deletions(-) diff --git a/README.md b/README.md index 0d3fd480..bb3100fc 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) @@ -24,147 +24,84 @@ So, here we go... -- [Table of Contents](#table-of-contents) - [Structure of the Examples](#structure-of-the-examples) + + [▶ Some fancy Title](#-some-fancy-title) - [Usage](#usage) - [👀 Examples](#-examples) - - [Section: Strain your brain!](#section-strain-your-brain) - - [▶ First things first! \*](#-first-things-first-) - - [💡 Explanation](#-explanation) - - [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) - - [💡 Explanation:](#-explanation-1) - - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - - [💡 Explanation:](#-explanation-2) - - [▶ How not to use `is` operator](#-how-not-to-use-is-operator) - - [💡 Explanation:](#-explanation-3) - - [▶ Hash brownies](#-hash-brownies) - - [💡 Explanation](#-explanation-4) - - [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) - - [💡 Explanation:](#-explanation-5) - - [▶ Disorder within order \*](#-disorder-within-order-) - - [💡 Explanation:](#-explanation-6) - - [▶ Keep trying... \*](#-keep-trying-) - - [💡 Explanation:](#-explanation-7) - - [▶ For what?](#-for-what) - - [💡 Explanation:](#-explanation-8) - - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - - [💡 Explanation](#-explanation-9) - - [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) - - [💡 Explanation](#-explanation-10) - - [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - - [💡 Explanation:](#-explanation-11) - - [▶ Schrödinger's variable \*](#-schrödingers-variable-) - - [💡 Explanation:](#-explanation-12) - - [▶ The chicken-egg problem \*](#-the-chicken-egg-problem-) - - [💡 Explanation](#-explanation-13) - - [▶ Subclass relationships](#-subclass-relationships) - - [💡 Explanation:](#-explanation-14) - - [▶ Methods equality and identity](#-methods-equality-and-identity) - - [💡 Explanation](#-explanation-15) - - [▶ All-true-ation \*](#-all-true-ation-) - - [💡 Explanation:](#-explanation-16) - - [💡 Explanation:](#-explanation-17) - - [▶ Strings and the backslashes](#-strings-and-the-backslashes) - - [💡 Explanation](#-explanation-18) - - [▶ not knot!](#-not-knot) - - [💡 Explanation:](#-explanation-19) - - [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - - [💡 Explanation:](#-explanation-20) - - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - - [💡 Explanation:](#-explanation-21) - - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - - [💡 Explanation:](#-explanation-22) - - [▶ yielding None](#-yielding-none) - - [💡 Explanation:](#-explanation-23) - - [▶ Yielding from... return! \*](#-yielding-from-return-) - - [💡 Explanation:](#-explanation-24) - - [▶ Nan-reflexivity \*](#-nan-reflexivity-) - - [💡 Explanation:](#-explanation-25) - - [▶ Mutating the immutable!](#-mutating-the-immutable) - - [💡 Explanation:](#-explanation-26) - - [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) - - [💡 Explanation:](#-explanation-27) - - [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) - - [💡 Explanation:](#-explanation-28) - - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) - - [💡 Explanation:](#-explanation-29) - - [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) - - [💡 Explanation:](#-explanation-30) - - [Section: Slippery Slopes](#section-slippery-slopes) - - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) - - [💡 Explanation:](#-explanation-31) - - [▶ Stubborn `del` operation](#-stubborn-del-operation) - - [💡 Explanation:](#-explanation-32) - - [▶ The out of scope variable](#-the-out-of-scope-variable) - - [💡 Explanation:](#-explanation-33) - - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - - [💡 Explanation:](#-explanation-34) - - [▶ Lossy zip of iterators \*](#-lossy-zip-of-iterators-) - - [💡 Explanation:](#-explanation-35) - - [▶ Loop variables leaking out!](#-loop-variables-leaking-out) - - [💡 Explanation:](#-explanation-36) - - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - - [💡 Explanation:](#-explanation-37) - - [▶ Catching the Exceptions](#-catching-the-exceptions) - - [💡 Explanation](#-explanation-38) - - [▶ Same operands, different story!](#-same-operands-different-story) - - [💡 Explanation:](#-explanation-39) - - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - - [💡 Explanation](#-explanation-40) - - [▶ Rounding like a banker \*](#-rounding-like-a-banker-) - - [💡 Explanation:](#-explanation-41) - - [▶ Needles in a Haystack \*](#-needles-in-a-haystack-) - - [💡 Explanation:](#-explanation-42) - - [▶ Splitsies \*](#-splitsies-) - - [💡 Explanation:](#-explanation-43) - - [▶ Wild imports \*](#-wild-imports-) - - [💡 Explanation:](#-explanation-44) - - [▶ All sorted? \*](#-all-sorted-) - - [💡 Explanation:](#-explanation-45) - - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - - [💡 Explanation:](#-explanation-46) - - [Section: The Hidden treasures!](#section-the-hidden-treasures) - - [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) - - [💡 Explanation:](#-explanation-47) - - [▶ `goto`, but why?](#-goto-but-why) - - [💡 Explanation:](#-explanation-48) - - [▶ Brace yourself!](#-brace-yourself) - - [💡 Explanation:](#-explanation-49) - - [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) - - [💡 Explanation:](#-explanation-50) - - [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) - - [💡 Explanation:](#-explanation-51) - - [▶ Yes, it exists!](#-yes-it-exists) - - [💡 Explanation:](#-explanation-52) - - [▶ Ellipsis \*](#-ellipsis-) - - [💡 Explanation](#-explanation-53) - - [▶ Inpinity](#-inpinity) - - [💡 Explanation:](#-explanation-54) - - [▶ Let's mangle](#-lets-mangle) - - [💡 Explanation:](#-explanation-55) - - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - - [▶ Skipping lines?](#-skipping-lines) - - [💡 Explanation](#-explanation-56) - - [▶ Teleportation](#-teleportation) - - [💡 Explanation:](#-explanation-57) - - [▶ Well, something is fishy...](#-well-something-is-fishy) - - [💡 Explanation](#-explanation-58) - - [Section: Miscellaneous](#section-miscellaneous) - - [▶ `+=` is faster](#--is-faster) - - [💡 Explanation:](#-explanation-59) - - [▶ Let's make a giant string!](#-lets-make-a-giant-string) - - [💡 Explanation](#-explanation-60) - - [▶ Slowing down `dict` lookups \*](#-slowing-down-dict-lookups-) - - [💡 Explanation:](#-explanation-61) - - [▶ Bloating instance `dict`s \*](#-bloating-instance-dicts-) - - [💡 Explanation:](#-explanation-62) - - [▶ Minor Ones \*](#-minor-ones-) + * [Section: Strain your brain!](#section-strain-your-brain) + + [▶ First things first! *](#-first-things-first-) + + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) + + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + + [▶ How not to use `is` operator](#-how-not-to-use-is-operator) + + [▶ Hash brownies](#-hash-brownies) + + [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) + + [▶ Disorder within order *](#-disorder-within-order-) + + [▶ Keep trying... *](#-keep-trying-) + + [▶ For what?](#-for-what) + + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) + + [▶ `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-) + + [▶ Subclass relationships](#-subclass-relationships) + + [▶ Methods equality and identity](#-methods-equality-and-identity) + + [▶ All-true-ation *](#-all-true-ation-) + + [▶ The surprising comma](#-the-surprising-comma) + + [▶ Strings and the backslashes](#-strings-and-the-backslashes) + + [▶ not knot!](#-not-knot) + + [▶ Half triple-quoted strings](#-half-triple-quoted-strings) + + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) + + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) + + [▶ yielding None](#-yielding-none) + + [▶ 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) + + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + + [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) + * [Section: Slippery Slopes](#section-slippery-slopes) + + [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + + [▶ Stubborn `del` operation](#-stubborn-del-operation) + + [▶ The out of scope variable](#-the-out-of-scope-variable) + + [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) + + [▶ Lossy zip of iterators *](#-lossy-zip-of-iterators-) + + [▶ Loop variables leaking out!](#-loop-variables-leaking-out) + + [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) + + [▶ Catching the Exceptions](#-catching-the-exceptions) + + [▶ Same operands, different story!](#-same-operands-different-story) + + [▶ 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-) + + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) + * [Section: The Hidden treasures!](#section-the-hidden-treasures) + + [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) + + [▶ `goto`, but why?](#-goto-but-why) + + [▶ Brace yourself!](#-brace-yourself) + + [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) + + [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) + + [▶ Yes, it exists!](#-yes-it-exists) + + [▶ Ellipsis *](#-ellipsis-) + + [▶ Inpinity](#-inpinity) + + [▶ Let's mangle](#-lets-mangle) + * [Section: Appearances are deceptive!](#section-appearances-are-deceptive) + + [▶ Skipping lines?](#-skipping-lines) + + [▶ Teleportation](#-teleportation) + + [▶ Well, something is fishy...](#-well-something-is-fishy) + * [Section: Miscellaneous](#section-miscellaneous) + + [▶ `+=` is faster](#--is-faster) + + [▶ Let's make a giant string!](#-lets-make-a-giant-string) + + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups-) + + [▶ Bloating instance `dict`s *](#-bloating-instance-dicts-) + + [▶ Minor Ones *](#-minor-ones-) - [Contributing](#contributing) - [Acknowledgements](#acknowledgements) - - [Some nice Links!](#some-nice-links) - [🎓 License](#-license) - - [Surprise your friends as well!](#surprise-your-friends-as-well) - - [Need a pdf version?](#need-a-pdf-version) + * [Surprise your friends as well!](#surprise-your-friends-as-well) + * [More content like this?](#more-content-like-this) From 8db7d48ad67179b43027cfa104c3cbe61f5fca9e Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sat, 4 May 2024 20:04:21 +0300 Subject: [PATCH 149/210] Add new link to Russian translation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bb3100fc..9311af68 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From d70bf71cb67fd918603d992f3aaae85305d22708 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sat, 4 May 2024 20:06:24 +0300 Subject: [PATCH 150/210] Fix link to Russian translation --- CONTRIBUTORS.md | 2 +- translations/ru-russian/CONTRIBUTORS.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 68d51766..40526d90 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -35,7 +35,7 @@ Following are the wonderful people (in no specific order) who have contributed t | leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [Chinese](https://github.com/leisurelicht/wtfpython-cn) | | vuduclyunitn | [vuduclyunitn](https://github.com/vuduclyunitn) | [Vietnamese](https://github.com/vuduclyunitn/wtfptyhon-vi) | | José De Freitas | [JoseDeFreitas](https://github.com/JoseDeFreitas) | [Spanish](https://github.com/JoseDeFreitas/wtfpython-es) | -| Vadim Nifadev | [nifadyev](https://github.com/nifadyev) | [Russian](https://github.com/satwikkansal/wtfpython/tree/main/translations/README-ru.md) | +| Vadim Nifadev | [nifadyev](https://github.com/nifadyev) | [Russian](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | Thank you all for your time and making wtfpython more awesome! :smile: diff --git a/translations/ru-russian/CONTRIBUTORS.md b/translations/ru-russian/CONTRIBUTORS.md index 8a22a49b..2599f8ab 100644 --- a/translations/ru-russian/CONTRIBUTORS.md +++ b/translations/ru-russian/CONTRIBUTORS.md @@ -35,7 +35,7 @@ | leisurelicht | [leisurelicht](https://github.com/leisurelicht) | [Chinese](https://github.com/leisurelicht/wtfpython-cn) | | vuduclyunitn | [vuduclyunitn](https://github.com/vuduclyunitn) | [Vietnamese](https://github.com/vuduclyunitn/wtfptyhon-vi) | | José De Freitas | [JoseDeFreitas](https://github.com/JoseDeFreitas) | [Spanish](https://github.com/JoseDeFreitas/wtfpython-es) | -| Vadim Nifadev | [nifadyev](https://github.com/nifadyev) | [Russian](https://github.com/satwikkansal/wtfpython/tree/main/translations/README-ru.md) | +| Vadim Nifadev | [nifadyev](https://github.com/nifadyev) | [Russian](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | Спасибо всем за ваше время и за то, что делаете wtfpython еще более потрясающим! :smile: From c7f3849c1acaf204d094d9e44b7022ca27f5be18 Mon Sep 17 00:00:00 2001 From: Jeremy Cheng Date: Thu, 9 May 2024 17:16:15 +0900 Subject: [PATCH 151/210] doc: fix links and typos --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index bb3100fc..922730d4 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) @@ -2596,7 +2596,7 @@ It seems as though Python rounded 2.5 to 2. #### 💡 Explanation: -- This is not a float precision error, in fact, this behavior is intentional. Since Python 3.0, `round()` uses [banker's rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even) where .5 fractions are rounded to the nearest **even** number: +- This is not a float precision error, in fact, this behavior is intentional. Since Python 3.0, `round()` uses [banker's rounding](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even) where .5 fractions are rounded to the nearest **even** number: ```py >>> round(0.5) @@ -3647,7 +3647,7 @@ What makes those dictionaries become bloated? And why are newly created objects + CPython is able to reuse the same "keys" object in multiple dictionaries. This was added in [PEP 412](https://www.python.org/dev/peps/pep-0412/) with the motivation to reduce memory usage, specifically in dictionaries of instances - where keys (instance attributes) tend to be common to all instances. + This optimization is entirely seamless for instance dictionaries, but it is disabled if certain assumptions are broken. + Key-sharing dictionaries do not support deletion; if an instance attribute is deleted, the dictionary is "unshared", and key-sharing is disabled for all future instances of the same class. -+ Additionaly, if the dictionary keys have 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__`! @@ -3822,7 +3822,6 @@ The idea and design for this collection were initially inspired by Denys Dovhan' * https://stackoverflow.com/questions/1011431/common-pitfalls-in-python * https://www.python.org/doc/humor/ * https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator -* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 * https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues * WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). From be4811aeb7f68f308851964f408070e00649454f Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Mon, 13 May 2024 09:59:32 +0300 Subject: [PATCH 152/210] Change link to Russian translation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 688e8060..e7491373 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/frontdevops/wtfpython) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) From f07d547dc75fae25c8bb16c15e00257896cd01d7 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 14:54:03 +0300 Subject: [PATCH 153/210] Replace string interning image to SVG, add image for dark theme --- images/string-intern/string_intern.png | Bin 9731 -> 0 bytes .../string_interning_dark_theme.svg | 4 ++++ images/string-intern/string_interrning.svg | 4 ++++ 3 files changed, 8 insertions(+) delete mode 100644 images/string-intern/string_intern.png create mode 100755 images/string-intern/string_interning_dark_theme.svg create mode 100755 images/string-intern/string_interrning.svg diff --git a/images/string-intern/string_intern.png b/images/string-intern/string_intern.png deleted file mode 100644 index 6511978ae5ce2ec78ea208d9824a552138d2a1a8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9731 zcmcJVcQl)A{P6F@-dcnjQC&(=S`;SXN2t+gd!Cy z4^=HSio}Q@RkUIgl+s_G-+9k@&pZD3op_rBUT*f4M_SMv065!w=jL^*u*ns=f!~Es9ne|5ha8>wYnOqbaO>h% z8CcMvVo>>8jsfA|5b~W@NDhbb%Gr-4r=$noVP(z-pXW&eImr|wc7stb@6sP+`e^4Z zFM{|VmMToh`_wsEACmMq*G)mgyYf;yOA|Zp$F}0 zBe~I+CKN=Q_$s1(BbBnC`ulIeoGKs_@)EJf*&?A>{8AR9?TV+h*ymn!eYK%d;ydv_ z&P_1Q-u9??#lt6LsNx=**z8W!(K|QF-BcGj_X%&+w`0grpSe>4zL~kAL{Hj5v7)Rf zfj^x>G~>h@f~gIA^m<+yH>BMdCmxQm3=hj4<*bd;oxikIl&uv<5KR23{W*n|r-`RE zj5m=mN@L#l8_a$BeEOOW@SL0~w2z70czuH3YM{JWTsz_IX1Lp4E(GL<;v`1t(wf>t_@_V&82KwF=t5$dF${Pka22kg zILcWQg{)C~P&)6=e|qFp!%GEsyM)f|pr!kLk>7Hu8mwzCVW~7QwKS|6)4z63kstYQ znyxEm%AU}M_IutpuA|6a{3f&%Vjr~rKZm6>KjiEw5UmwDON|MEMI$HK^;5?0}21f4A8 zl^}Z8qxR+T-uTsvkxeCcm@HPpiqt{hLtgc9td>AOEFqdx1(q<^u=Z!&>bGAQ@=71y zY7Hu{t`1c$yLIUn+ z@}mC=&HkXUv0^EDg>;BgSsWzpM1CQSmv8UqB}suyA%JDX@+wv24c4~9Q4w*?8MSFZaf5wh-raGmI7RJofn>pgl?YWCcEavN%*K1bW z?i?&ND&$0a*VVQodghz-)UaPztGvj?`5HY1!;tm%D+Qvl{idTcxJ*AiP=`2Z!PDg8 zC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!mzL3g0KHEuYg z_(ljI^^EnA_!|jg>a`ATVCK|001!?jlh_pHohl%Ryn-O4uzZs^LFfcituG6jt!8|I zcR=3OzL^Tw0jWAmc!O>;0sGP~)b+L~us7z6w`4VyVznx%&bEhBiv;IbLq}o38ku-mpS5EwY?`tc4~LRrV(Ks zZ5fUifZ4}7n!CYYv4|b(GHA77l3Fd!ZRPlL7k`B8@hI^c0IT=okAVvQP>hyM>X5&x zwV+9;Dm2?KbZc^R10dg~+mtZGhXZEo-PZN8!p9wxCAtu@!oe*v02*gWMQgz+LyMx$ zdC{VgI7c(7n;`7v;NFR;txDIMdBg0d4(PZj`b%ck_CnMzyOc#{L2K`Grw1vNt|$5e)gL4?EAA% z5FfKwuK09Cew8!t*Y)omt&P9GngamoQE#Pm(n-IASmB5b_OnAc%OLjNE=nLt5Mvkq zjWsgNw)*T0#@0_J8bXu{?)RREI0ccg;Fg=xTnq!1TVbUJuRCeRa40B z^P0_YwaW*Uf!U)ab`DOw-w9BwT61bK;wLT%L01VaDLBgC8<;9+U2sj~d z*q_M7&cgn|WUDzUo$&v2ODg7G-?|-FU$U|XN>?1fs-Y|nzrZD=<*U?L4qR2ECK8d$ zHEr_%xvni?>)rEpZSTquAIHQu7>YGzPy~@fl6V7PEuX;L-hvV;4o+zr*u*I%RxIMn z*v}G_zXAYm4+u#$crY?|wO-vSsRDDX5Slt9PWy|<1L)k+c)zR%{|6(HU{O6{@@CC5 zLK$ogEd&6yN$~-@mZSdh&1XJI1CrYi^+9{{#K-Y%u@; diff --git a/images/string-intern/string_interning_dark_theme.svg b/images/string-intern/string_interning_dark_theme.svg new file mode 100755 index 00000000..dec5f3f1 --- /dev/null +++ b/images/string-intern/string_interning_dark_theme.svg @@ -0,0 +1,4 @@ + + + +
PyStringObject
PyStringObject
"wtf!"
"wtf!"
a
a
PyStringObject
PyStringObject
"wtf!"
"wtf!"
b
b
PyStringObject
PyStringObject
"wtf!"
"wtf!"
a
a
b
b
Text is not SVG - cannot display
diff --git a/images/string-intern/string_interrning.svg b/images/string-intern/string_interrning.svg new file mode 100755 index 00000000..0572a9e3 --- /dev/null +++ b/images/string-intern/string_interrning.svg @@ -0,0 +1,4 @@ + + + +
PyStringObject
PyStringObject
"wtf!"
"wtf!"
a
a
PyStringObject
PyStringObject
"wtf!"
"wtf!"
b
b
PyStringObject
PyStringObject
"wtf!"
"wtf!"
a
a
b
b
Text is not SVG - cannot display
From 9315d0144d99bdc2164940e83608a1c621668298 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 14:54:22 +0300 Subject: [PATCH 154/210] Add venv and vscode config folders to .gitignore --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index 057dcb0c..998895f3 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,8 @@ irrelevant/.ipynb_checkpoints/ irrelevant/.python-version .idea/ +.vscode/ + +# Virtual envitonments +venv/ +.venv/ From e0411b68fbf6a5db9459d9e9ec17de14cf2d9ada Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 14:55:12 +0300 Subject: [PATCH 155/210] Use new theme specific logic for images --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 17851d02..cd0d72e8 100644 --- a/README.md +++ b/README.md @@ -352,7 +352,12 @@ Makes sense, right? * All length 0 and length 1 strings are interned. * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) - ![image](/images/string-intern/string_intern.png) + + + + Shows a string interning process. + + + 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. From b471c9fa14695e34d1a97d02e95e7a7fb7c3b9e5 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 15:05:34 +0300 Subject: [PATCH 156/210] Fix image name, remove extra rectangles from dark theme image --- .../{string_interrning.svg => string_interning.svg} | 0 images/string-intern/string_interning_dark_theme.svg | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename images/string-intern/{string_interrning.svg => string_interning.svg} (100%) diff --git a/images/string-intern/string_interrning.svg b/images/string-intern/string_interning.svg similarity index 100% rename from images/string-intern/string_interrning.svg rename to images/string-intern/string_interning.svg diff --git a/images/string-intern/string_interning_dark_theme.svg b/images/string-intern/string_interning_dark_theme.svg index dec5f3f1..69c32e40 100755 --- a/images/string-intern/string_interning_dark_theme.svg +++ b/images/string-intern/string_interning_dark_theme.svg @@ -1,4 +1,4 @@ -
PyStringObject
PyStringObject
"wtf!"
"wtf!"
a
a
PyStringObject
PyStringObject
"wtf!"
"wtf!"
b
b
PyStringObject
PyStringObject
"wtf!"
"wtf!"
a
a
b
b
Text is not SVG - cannot display
+
PyStringObject
PyStringObject
"wtf!"
"wtf!"
a
a
PyStringObject
PyStringObject
"wtf!"
"wtf!"
b
b
PyStringObject
PyStringObject
"wtf!"
"wtf!"
a
a
b
b
Text is not SVG - cannot display
From daf7ccd2ce3b21b7f4800e50a6d4a474dfff120d Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 15:51:43 +0300 Subject: [PATCH 157/210] Use new theme specific logic for images --- README.md | 36 +++++++++++++---- images/logo-dark.png | Bin 13052 -> 0 bytes images/logo.png | Bin 8317 -> 0 bytes images/logo.svg | 38 ++++++++++++++++++ images/logo_dark_theme.svg | 38 ++++++++++++++++++ .../tic-tac-toe/after_board_initialized.png | Bin 162385 -> 0 bytes .../tic-tac-toe/after_board_initialized.svg | 4 ++ .../after_board_initialized_dark_theme.svg | 4 ++ images/tic-tac-toe/after_row_initialized.png | Bin 51686 -> 0 bytes images/tic-tac-toe/after_row_initialized.svg | 4 ++ .../after_row_initialized_dark_theme.svg | 4 ++ 11 files changed, 120 insertions(+), 8 deletions(-) delete mode 100644 images/logo-dark.png delete mode 100644 images/logo.png create mode 100755 images/logo.svg create mode 100755 images/logo_dark_theme.svg delete mode 100644 images/tic-tac-toe/after_board_initialized.png create mode 100755 images/tic-tac-toe/after_board_initialized.svg create mode 100755 images/tic-tac-toe/after_board_initialized_dark_theme.svg delete mode 100644 images/tic-tac-toe/after_row_initialized.png create mode 100755 images/tic-tac-toe/after_row_initialized.svg create mode 100755 images/tic-tac-toe/after_row_initialized_dark_theme.svg diff --git a/README.md b/README.md index cd0d72e8..69053137 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,10 @@ -

+

+ + + + Shows a wtfpython logo. + +

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

@@ -352,11 +358,13 @@ Makes sense, right? * All length 0 and length 1 strings are interned. * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned) * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) - - - - Shows a string interning process. - +

+ + + + Shows a string interning process. + +

+ 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` @@ -980,11 +988,23 @@ We didn't assign three `"X"`s, did we? When we initialize `row` variable, this visualization explains what happens in the memory -![image](/images/tic-tac-toe/after_row_initialized.png) +

+ + + + Shows a memory segment after row is initialized. + +

And when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`) -![image](/images/tic-tac-toe/after_board_initialized.png) +

+ + + + Shows a memory segment after board is initialized. + +

We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue). diff --git a/images/logo-dark.png b/images/logo-dark.png deleted file mode 100644 index 9d7791f3a30ae76158b3f33d84cdf0f31de2e3c2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13052 zcmbWe1z4QR(jbhxyJxTjcNqrv!5sz<4DK>mfZ!Se6Eq>X6A13^5)w2C!8K@Lf+Rq& z9nQV??C!T`cmIERnC6}Cdb^~ns=KO-1YK=aLOeP=6ciLfHL#LC3JNM5`QgFALiQ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-G-CkMZ3E9A8AZL#Jx;05K+ob!Q~DGG13u~wES9f`ltfiG42nx3 zIqz#6e_`-z`_RcMv(#GW+PR}9ld<$ZPMiCz;>#eVEP---Uk}k;le?Vp$!;gjE`#10 zx7nw*zGJL5NnoaMzge0xlglMlqW(6QeV3Xday>Zcj-9&5{^o5a=M@$^e4jId0Ne@)t~ppw%|R4tuW9tRK=lDt)r4%<}ERv8lMk;c3**lT!cZ$2p1P_;d;oW4cz^ zeOwfDb;Et>s34CiwSqKb^vxwS_T8kLV1IJV%t4=!=0nnom!89@&v%a$V$;kBHd`Rc z15wZ%tG3eZN~cuYi|mHF<>n|J&8FS`gI?vkc*&i%otLb({>%uodFTm2ikn+CEuDQ7 zoTr(&khz8qgSFV|22u}KTHY#j%RYxj&L-lzh(j@ZIp11a*qnRuB~X5dQc)sh`$D@q zmcU^B!8!eZ-ZZxuzN!2$E!0gA`y1vbO0f~-VM3I+0pkKydQKkW$Z?2LKkn zOj?HJ;nK~BfNthIx=~(9rwOzEI7<-lLCTOc&vs?6hn*G-;O#f%aNW1G0JwVjf5AG@ zG+@9d_Z=edoOl`nEZ?aZebUEA01yGMPX_h#$pIfi@TS?Vs1+ob1c^i660z__i52?c zLYQt_1%Dv|pgU*`Byp>+CrX)G6gsd%Ms5Q(ohkO2|F3B7^aM9|jn_?CO_xSx{(k^X MRXr7y((}mw2cnT^J^%m! diff --git a/images/logo.svg b/images/logo.svg new file mode 100755 index 00000000..6ec5edab --- /dev/null +++ b/images/logo.svg @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/images/logo_dark_theme.svg b/images/logo_dark_theme.svg new file mode 100755 index 00000000..f89e7970 --- /dev/null +++ b/images/logo_dark_theme.svg @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/images/tic-tac-toe/after_board_initialized.png b/images/tic-tac-toe/after_board_initialized.png deleted file mode 100644 index 616747fba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RoLWR>ZS7t$9mUU%1=LS~U$n6BDx z9AW-FD$Lm^c5d4n)S6(oiSrz1TjYg{qEIh#4k*t2CFAw&FF4!Gl-`VJG|Hj}k0SFk zNr8v7?pU>;?o`iqwhzyVn0N0v)VYsiHW}K;laz(rgWL&Lcw}>u@b%&hzqy~0->2G`$8{bbseUBub>9eobd9}XC!_BE zg2JCo4GAY2bNe1jn+G_sz_mjvlEHC-EfByN4^DhtI6H{-SeZIYCog_MP=NU8kq~c0 zWkMiEH@Hb<-j&_7N6ld`a%m|=wz0+;Lo)<@{4HXB8j^iv#SeUGYtnUhG^a8b>+g9DuHFClahqGCpARzx-vLnefJ@gs ztxHC&?kfF4`8#19Fp?x7j~eYk(7BSX<6+}E@Vvid+%pOQ|Ld*tRFX|7Jf13iM^7c$ zdICLU=Kwse@Yh{6wxwlBQDD+9tNUI@?04|N2V> vzBC_2Qdado45Uo{oiQoCcxD6i-=&{SrOhm#-cJB}XOJP<4ArRPlKlSw-=jeR diff --git a/images/tic-tac-toe/after_board_initialized.svg b/images/tic-tac-toe/after_board_initialized.svg new file mode 100755 index 00000000..02b1dad0 --- /dev/null +++ b/images/tic-tac-toe/after_board_initialized.svg @@ -0,0 +1,4 @@ + + + +
" "
" "
" "
" "
" "
" "
row
row
board[0]
board[0]
board[1]
board[1]
board[2]
board[2]
Text is not SVG - cannot display
\ No newline at end of file diff --git a/images/tic-tac-toe/after_board_initialized_dark_theme.svg b/images/tic-tac-toe/after_board_initialized_dark_theme.svg new file mode 100755 index 00000000..3218ad06 --- /dev/null +++ b/images/tic-tac-toe/after_board_initialized_dark_theme.svg @@ -0,0 +1,4 @@ + + + +
" "
" "
" "
" "
" "
" "
row
row
board[0]
board[0]
board[1]
board[1]
board[2]
board[2]
Text is not SVG - cannot display
\ No newline at end of file diff --git a/images/tic-tac-toe/after_row_initialized.png b/images/tic-tac-toe/after_row_initialized.png deleted file mode 100644 index 520d7007d5b10cac03389effdb970af65ac8066e..0000000000000000000000000000000000000000 GIT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_CqwkbY^dG`fk-4CESYqO`n1h2Fpt(3;A!Ga4vG`#wGuVKSjxwDIN(&=2 zCVdUt2g;jPJ$3TDyOD)`H17pH+#>uVk%BK>MJD-jf3w%rs@I@#xTUR}OMd%zQOh#r z1HynlLPVkI_Nm0&mIsE5meU=Q^sJ}n1z+xr)T*D-zWl47SZ`~IAoq(BN#2V=Ic&8m zJTCH=(c2^aeVj2=;k3$f(H50H9}O=~31tRgSZq4Hm1ce{B09X(@1rlSX$6Mtg=C+z!^AP_E*|2*&e&M$a+ zxp1Ua)H5j^XyR3L5rzeoT6S5gIb@dJym_vjH7mP6jF{-6kQ=1!x{0;KBq z8aN2V2a*G7*T6LTx}zrRMvhncyC(nJgFPE%nG>(7;0LeLI8$X0!Kg`hO*LU?-2@|Dq2-B46HX z;lLJX@Lu+Q-?}j=g7>-R?AMInf}I*6bBU)Xoqx{>L(zhKHtm9Es-Zx?M675yT6H4q z+_r5GZA3oUz63H|E6F9fFP(V_BswEES$r0^oz71|IHfi9L+AE2oVerLI)-09?uVKF zbmJ&hz}C7)BMZq`Q~7hl-jqoM43G|NiwEDX@8HP(|1=a>Sp2WW-v4iJ|9{VT!UG;U zc)*_Q%>DlaiU4*0jdpuUCtFAteg!)Wc47oztLgR?#-IS!O^wjRB=Y$<2nEU>?T+`2Vj)IiU|M!VDms|f>Dy#&vsdF x?asZ!TnYdH0|i18j1}G`r3Iih0RUi#{C}zMG`T;>rR)Fz002ovPDHLkV1h|}v|s=L diff --git a/images/tic-tac-toe/after_row_initialized.svg b/images/tic-tac-toe/after_row_initialized.svg new file mode 100755 index 00000000..92eb02cd --- /dev/null +++ b/images/tic-tac-toe/after_row_initialized.svg @@ -0,0 +1,4 @@ + + + +
" "
" "
" "
" "
" "
" "
row
row
Text is not SVG - cannot display
\ No newline at end of file diff --git a/images/tic-tac-toe/after_row_initialized_dark_theme.svg b/images/tic-tac-toe/after_row_initialized_dark_theme.svg new file mode 100755 index 00000000..24049580 --- /dev/null +++ b/images/tic-tac-toe/after_row_initialized_dark_theme.svg @@ -0,0 +1,4 @@ + + + +
" "
" "
" "
" "
" "
" "
row
row
Text is not SVG - cannot display
\ No newline at end of file From d8734aa6ace3d631e1e15eba8c655c6acef298f0 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 15:54:26 +0300 Subject: [PATCH 158/210] Fix invalid image path --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 69053137..2c6b0439 100644 --- a/README.md +++ b/README.md @@ -990,8 +990,8 @@ When we initialize `row` variable, this visualization explains what happens in t

- - + + Shows a memory segment after row is initialized.

From 0bba8d932cbba97936d395a3b213cf2713520e37 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 15:54:40 +0300 Subject: [PATCH 159/210] Delete unused images --- images/expanding-brain-meme.jpg | Bin 115494 -> 0 bytes images/tic-tac-toe.png | Bin 7515 -> 0 bytes 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 images/expanding-brain-meme.jpg delete mode 100644 images/tic-tac-toe.png diff --git a/images/expanding-brain-meme.jpg b/images/expanding-brain-meme.jpg deleted file mode 100644 index 9437c2f9c3308f07b1b662d4fe9fc774b83b938e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 115494 zcmb@tbyOV9w=O({;O-FI-Q9yb1b26r!7U-UyIXK~f=h58Jjfuy-7RSD6AtNH8A|W84V4$F)p`&AnDS1iAWu8UFMGFyP;HL)}6{VF2D?KtW?b{TT!hL(2Ic`fqXnJG_U1g?k4L z4}}0pCWNFwQvWmk9rSxB$Q^%H0m#r$fOqK7=n#nGg#XU|PlQqibbg8IH4nN>(mztG zvSfGAwha#m7us!re_-kEjB=>+sGl9~psh>3=0pcOXc}tVAx=-NrgM!5A0GHwBKffW z8!slG+j1Z{S8$+vrI2U3DXb%rHa}44+%O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/README.md | 32 +++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/translations/ru-russian/README.md b/translations/ru-russian/README.md index d8dff4aa..1936149a 100644 --- a/translations/ru-russian/README.md +++ b/translations/ru-russian/README.md @@ -1,4 +1,10 @@ -

+

+ + + + Логотип wtfpython + +

What the f*ck Python! 😱

Изучение и понимание Python с помощью удивительных примеров поведения.

@@ -408,7 +414,13 @@ False - Все строки длиной 0 или 1 символа интернируются. - Строки интернируются во время компиляции (`'wtf'` будет интернирована, но `''.join(['w'', 't', 'f'])` - нет) - Строки, не состоящие из букв ASCII, цифр или знаков подчеркивания, не интернируются. В примере выше `'wtf!'` не интернируется из-за `!`. Реализацию этого правила в CPython можно найти [здесь](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) - ![image](/images/string-intern/string_intern.png) +

+ + + + Процесс интернирования строк. + +

- Когда переменные `a` и `b` принимают значение `"wtf!"` в одной строке, интерпретатор Python создает новый объект, а затем одновременно ссылается на вторую переменную. Если это выполняется в отдельных строках, он не "знает", что уже существует `"wtf!"` как объект (потому что `"wtf!"` не является неявно интернированным в соответствии с фактами, упомянутыми выше). Это оптимизация во время компиляции, не применяется к версиям CPython 3.7.x (более подробное обсуждение смотрите [здесь](https://github.com/satwikkansal/wtfpython/issues/100)). - Единица компиляции в интерактивной среде IPython состоит из одного оператора, тогда как в случае модулей она состоит из всего модуля. `a, b = "wtf!", "wtf!"` - это одно утверждение, тогда как `a = "wtf!"; b = "wtf!"` - это два утверждения в одной строке. Это объясняет, почему тождества различны в `a = "wtf!"; b = "wtf!"`, но одинаковы при вызове в модуле. - Резкое изменение в выводе четвертого фрагмента связано с [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) техникой, известной как складывание констант (англ. Constant folding). Это означает, что выражение `'a'*20` заменяется на `'aaaaaaaaaaaaaaaaaaaa'` во время компиляции, чтобы сэкономить несколько тактов во время выполнения. Складывание констант происходит только для строк длиной менее 21. (Почему? Представьте себе размер файла `.pyc`, созданного в результате выполнения выражения `'a'*10**10`). [Вот](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) исходный текст реализации для этого. @@ -1038,11 +1050,23 @@ board = [row] * 3 Когда мы инициализируем переменную `row`, эта визуализация объясняет, что происходит в памяти -![image](/images/tic-tac-toe/after_row_initialized.png) +

+ + + + Ячейка памяти после того, как переменная row инициализирована. + +

А когда переменная `board` инициализируется путем умножения `row`, вот что происходит в памяти (каждый из элементов `board[0]`, `board[1]` и `board[2]` является ссылкой на тот же список, на который ссылается `row`) -![image](/images/tic-tac-toe/after_board_initialized.png) +

+ + + + Ячейка памяти после того, как переменная board инициализирована. + +

Мы можем избежать этого сценария, не используя переменную `row` для генерации `board`. (Подробнее в [issue](https://github.com/satwikkansal/wtfpython/issues/68)). From 4b3818a667fee6c30c0321810fb250176ed84d88 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 17:06:52 +0300 Subject: [PATCH 161/210] Replace images in notebook --- irrelevant/wtf.ipynb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb index a3147e19..a4e6c748 100644 --- a/irrelevant/wtf.ipynb +++ b/irrelevant/wtf.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "

\"\"

\n", + "

\"wtfpython

\n", "

What the f*ck Python! \ud83d\ude31

\n", "

Exploring and understanding Python through surprising snippets.

\n", "\n", @@ -355,7 +355,7 @@ " * All length 0 and length 1 strings are interned.\n", " * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned)\n", " * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", - " ![image](/images/string-intern/string_intern.png)\n", + " ![String interning process](https://raw.githubusercontent.com/nifadyev/wtfpython/refs/heads/feature/%2374/add-dark-theme-and-alt-support-for-images/images/string-intern/string_interning.svg)\n", "+ When `a` and `b` are set to `\"wtf!\"` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't \"know\" that there's already `\"wtf!\"` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, and also explain why they are same when invoked in `some_file.py`\n", "+ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 21. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same.\n", @@ -13475,4 +13475,4 @@ "metadata": {}, "nbformat": 4, "nbformat_minor": 2 -} \ No newline at end of file +} From c3e7cc9bed8b3a8b76509f4e8e9175990b1e5588 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 17:25:56 +0300 Subject: [PATCH 162/210] Change images source in notebook --- irrelevant/wtf.ipynb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb index a4e6c748..c0370321 100644 --- a/irrelevant/wtf.ipynb +++ b/irrelevant/wtf.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "

\"wtfpython

\n", + "\"wtfpython\n", "

What the f*ck Python! \ud83d\ude31

\n", "

Exploring and understanding Python through surprising snippets.

\n", "\n", @@ -2947,11 +2947,11 @@ "\n", "When we initialize `row` variable, this visualization explains what happens in the memory\n", "\n", - "![image](/images/tic-tac-toe/after_row_initialized.png)\n", + "\"Shows\n", "\n", "And when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`)\n", "\n", - "![image](/images/tic-tac-toe/after_board_initialized.png)\n", + "\"Shows\n", "\n", "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", "\n" From 6702c788683c7ac40a3ccbf1e4af3bca3734e75a Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 15 Oct 2024 17:42:15 +0300 Subject: [PATCH 163/210] Fix images source in notebook --- irrelevant/wtf.ipynb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb index c0370321..809c17f0 100644 --- a/irrelevant/wtf.ipynb +++ b/irrelevant/wtf.ipynb @@ -355,7 +355,7 @@ " * All length 0 and length 1 strings are interned.\n", " * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned)\n", " * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)\n", - " ![String interning process](https://raw.githubusercontent.com/nifadyev/wtfpython/refs/heads/feature/%2374/add-dark-theme-and-alt-support-for-images/images/string-intern/string_interning.svg)\n", + "\"Shows\n", "+ When `a` and `b` are set to `\"wtf!\"` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't \"know\" that there's already `\"wtf!\"` as an object (because `\"wtf!\"` is not implicitly interned as per the facts mentioned above). It's a compile-time optimization. This optimization doesn't apply to 3.7.x versions of CPython (check this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for more discussion).\n", "+ A compile unit in an interactive environment like IPython consists of a single statement, whereas it consists of the entire module in case of modules. `a, b = \"wtf!\", \"wtf!\"` is single statement, whereas `a = \"wtf!\"; b = \"wtf!\"` are two statements in a single line. This explains why the identities are different in `a = \"wtf!\"; b = \"wtf!\"`, and also explain why they are same when invoked in `some_file.py`\n", "+ The abrupt change in the output of the fourth snippet is due to a [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) technique known as Constant folding. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to save a few clock cycles during runtime. Constant folding only occurs for strings having a length of less than 21. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same.\n", @@ -2947,11 +2947,11 @@ "\n", "When we initialize `row` variable, this visualization explains what happens in the memory\n", "\n", - "\"Shows\n", + "\"Shows\n", "\n", "And when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`)\n", "\n", - "\"Shows\n", + "\"Shows\n", "\n", "We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue).\n", "\n" From 578c82094c00dd6c2ed3a92fab60b5fac511df07 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 16 Oct 2024 09:36:51 +0300 Subject: [PATCH 164/210] Fix image source url in notebook --- irrelevant/wtf.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb index 809c17f0..4ea23336 100644 --- a/irrelevant/wtf.ipynb +++ b/irrelevant/wtf.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "\"wtfpython\n", + "\"wtfpython\n", "

What the f*ck Python! \ud83d\ude31

\n", "

Exploring and understanding Python through surprising snippets.

\n", "\n", From b10e2cbc31b729d63710f6b1b9b14ad63a531064 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 17 Oct 2024 15:10:47 +0300 Subject: [PATCH 165/210] Delete cli package because it is not convinient to use --- .gitignore | 3 - README.md | 7 +- irrelevant/wtf.ipynb | 11 +- translations/ru-russian/README.md | 9 +- wtfpython-pypi/content.md | 2386 ------------------------- wtfpython-pypi/setup.py | 41 - wtfpython-pypi/wtf_python/__init__.py | 0 wtfpython-pypi/wtf_python/main.py | 42 - wtfpython-pypi/wtfpython | 8 - 9 files changed, 3 insertions(+), 2504 deletions(-) delete mode 100644 wtfpython-pypi/content.md delete mode 100644 wtfpython-pypi/setup.py delete mode 100644 wtfpython-pypi/wtf_python/__init__.py delete mode 100644 wtfpython-pypi/wtf_python/main.py delete mode 100644 wtfpython-pypi/wtfpython diff --git a/.gitignore b/.gitignore index 998895f3..7a88626b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,9 +2,6 @@ node_modules npm-debug.log -wtfpython-pypi/build/ -wtfpython-pypi/dist/ -wtfpython-pypi/wtfpython.egg-info # Python-specific byte-compiled files should be ignored __pycache__/ diff --git a/README.md b/README.md index 2c6b0439..35a9cf59 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) -Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) +Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) Python, being a beautifully designed high-level and interpreter-based programming language, provides us with many features for the programmer's comfort. But sometimes, the outcomes of a Python snippet may not seem obvious at first sight. @@ -158,11 +158,6 @@ A nice way to get the most out of these examples, in my opinion, is to read them - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfpython/issues/new)). - If yes, give a gentle pat on your back, and you may skip to the next example. -PS: You can also read WTFPython at the command line using the [pypi package](https://pypi.python.org/pypi/wtfpython), -```sh -$ pip install wtfpython -U -$ wtfpython -``` --- # 👀 Examples diff --git a/irrelevant/wtf.ipynb b/irrelevant/wtf.ipynb index 4ea23336..c0f3d669 100644 --- a/irrelevant/wtf.ipynb +++ b/irrelevant/wtf.ipynb @@ -10,7 +10,7 @@ "\n", "Translations: [Chinese \u4e2d\u6587](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Ti\u1ebfng Vi\u1ec7t](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].)\n", "\n", - "Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython)\n", + "Other modes: [Interactive](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb)\n", "\n", "Python, being a beautifully designed high-level and interpreter-based programming language, provides us with many features for the programmer's comfort. But sometimes, the outcomes of a Python snippet may not seem obvious at first sight.\n", "\n", @@ -71,15 +71,6 @@ " - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfpython/issues/new)).\n", " - If yes, give a gentle pat on your back, and you may skip to the next example.\n", "\n", - "PS: You can also read WTFPython at the command line using the [pypi package](https://pypi.python.org/pypi/wtfpython),\n", - "```sh\n", - "$ pip install wtfpython -U\n", - "$ wtfpython\n", - "```\n", - "---\n", - "\n", - "# \ud83d\udc40 Examples\n", - "\n", "\n\n## Hosted notebook instructions\n\nThis is just an experimental attempt of browsing wtfpython through jupyter notebooks. Some examples are read-only because, \n- they either require a version of Python that's not supported in the hosted runtime.\n- or they can't be reproduced in the notebook envrinonment.\n\nThe expected outputs are already present in collapsed cells following the code cells. The Google colab provides Python2 (2.7) and Python3 (3.6, default) runtimes. You can switch among these for Python2 specific examples. For examples specific to other minor versions, you can simply refer to collapsed outputs (it's not possible to control the minor version in hosted notebooks as of now). You can check the active version using\n\n```py\n>>> import sys\n>>> sys.version\n# Prints out Python version here.\n```\n\nThat being said, most of the examples do work as expected. If you face any trouble, feel free to consult the original content on wtfpython and create an issue in the repo. Have fun!\n\n---\n" ] }, diff --git a/translations/ru-russian/README.md b/translations/ru-russian/README.md index 1936149a..c80fe2a4 100644 --- a/translations/ru-russian/README.md +++ b/translations/ru-russian/README.md @@ -10,7 +10,7 @@ Переводы: [English Original](https://github.com/satwikkansal/wtfpython) [Chinese 中文](https://github.com/robertparley/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) -Альтернативные способы: [Интерактивный сайт](https://wtfpython-interactive.vercel.app) | [Интерактивный Jupiter notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) | [CLI](https://pypi.python.org/pypi/wtfpython) +Альтернативные способы: [Интерактивный сайт](https://wtfpython-interactive.vercel.app) | [Интерактивный Jupiter notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) Python, будучи прекрасно спроектированным высокоуровневым языком программирования, предоставляет множество возможностей для удобства программиста. Но иногда поведение Python кода могут показаться запутывающим на первый взгляд. @@ -215,13 +215,6 @@ PS: Если вы уже читали **wtfpython** раньше, с измен - Если ответ отрицательный (что совершенно нормально), сделать глубокий вдох и прочитать объяснение (а если пример все еще непонятен, и создайте [issue](https://github.com/satwikkansal/wtfpython/issues/new)). - Если "да", ощутите мощь своих познаний в Python и переходите к следующему примеру. -PS: Вы также можете читать WTFPython в командной строке, используя [pypi package](https://pypi.python.org/pypi/wtfpython), - -```sh -pip install wtfpython -U -wtfpython -``` - # 👀 Примеры ## Раздел: Напряги мозги! diff --git a/wtfpython-pypi/content.md b/wtfpython-pypi/content.md deleted file mode 100644 index 0d246693..00000000 --- a/wtfpython-pypi/content.md +++ /dev/null @@ -1,2386 +0,0 @@ -

-

What the f*ck Python! 🐍

-

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

- -[![WTFPL 2.0][license-image]][license-url] - -Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) - -Python, being a beautifully designed high-level and interpreter-based programming language, provides us with many features for the programmer's comfort. But sometimes, the outcomes of a Python snippet may not seem obvious to a regular user at first sight. - -Here is a fun project to collect such tricky & counter-intuitive examples and lesser-known features in Python, attempting to discuss what exactly is happening under the hood! - -While some of the examples you see below may not be WTFs in the truest sense, but they'll reveal some of the interesting parts of Python that you might be unaware of. I find it a nice way to learn the internals of a programming language, and I think you'll find them interesting as well! - -If you're an experienced Python programmer, you can take it as a challenge to get most of them right in first attempt. You may be already familiar with some of these examples, and I might be able to revive sweet old memories of yours being bitten by these gotchas :sweat_smile: - -PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/). - -So, here we go... - -# Table of Contents - - - - - -- [Structure of the Examples](#structure-of-the-examples) -- [Usage](#usage) -- [👀 Examples](#-examples) - - [Section: Strain your brain!](#section-strain-your-brain) - - [▶ Strings can be tricky sometimes *](#-strings-can-be-tricky-sometimes-) - - [▶ Time for some hash brownies!](#-time-for-some-hash-brownies) - - [▶ Return return everywhere!](#-return-return-everywhere) - - [▶ Deep down, we're all the same. *](#-deep-down-were-all-the-same-) - - [▶ For what?](#-for-what) - - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - - [▶ `is` is not what it is!](#-is-is-not-what-it-is) - - [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - - [▶ The sticky output function](#-the-sticky-output-function) - - [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) - - [▶ The surprising comma](#-the-surprising-comma) - - [▶ Backslashes at the end of string](#-backslashes-at-the-end-of-string) - - [▶ not knot!](#-not-knot) - - [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - - [▶ yielding None](#-yielding-none) - - [▶ Mutating the immutable!](#-mutating-the-immutable) - - [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) - - [▶ When True is actually False](#-when-true-is-actually-false) - - [▶ From filled to None in one instruction...](#-from-filled-to-none-in-one-instruction) - - [▶ Subclass relationships *](#-subclass-relationships-) - - [▶ The mysterious key type conversion *](#-the-mysterious-key-type-conversion-) - - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) - - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - - [▶ Skipping lines?](#-skipping-lines) - - [▶ Teleportation *](#-teleportation-) - - [▶ Well, something is fishy...](#-well-something-is-fishy) - - [Section: Watch out for the landmines!](#section-watch-out-for-the-landmines) - - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) - - [▶ Stubborn `del` operator *](#-stubborn-del-operator-) - - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - - [▶ Loop variables leaking out!](#-loop-variables-leaking-out) - - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - - [▶ Catching the Exceptions](#-catching-the-exceptions) - - [▶ Same operands, different story!](#-same-operands-different-story) - - [▶ The out of scope variable](#-the-out-of-scope-variable) - - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - - [▶ Needle in a Haystack](#-needle-in-a-haystack) - - [Section: The Hidden treasures!](#section-the-hidden-treasures) - - [▶ Okay Python, Can you make me fly? *](#-okay-python-can-you-make-me-fly-) - - [▶ `goto`, but why? *](#-goto-but-why-) - - [▶ Brace yourself! *](#-brace-yourself-) - - [▶ Let's meet Friendly Language Uncle For Life *](#-lets-meet-friendly-language-uncle-for-life-) - - [▶ Even Python understands that love is complicated *](#-even-python-understands-that-love-is-complicated-) - - [▶ Yes, it exists!](#-yes-it-exists) - - [▶ Inpinity *](#-inpinity-) - - [▶ Mangling time! *](#-mangling-time-) - - [Section: Miscellaneous](#section-miscellaneous) - - [▶ `+=` is faster](#--is-faster) - - [▶ Let's make a giant string!](#-lets-make-a-giant-string) - - [▶ Explicit typecast of strings](#-explicit-typecast-of-strings) - - [▶ Minor Ones](#-minor-ones) -- [Contributing](#contributing) -- [Acknowledgements](#acknowledgements) -- [🎓 License](#-license) - - [Help](#help) - - [Want to share wtfpython with friends?](#want-to-share-wtfpython-with-friends) - - [Need a pdf version?](#need-a-pdf-version) - - - -# Structure of the Examples - -All the examples are structured like below: - -> ### ▶ Some fancy Title * -> The asterisk at the end of the title indicates the example was not present in the first release and has been recently added. -> -> ```py -> # Setting up the code. -> # Preparation for the magic... -> ``` -> -> **Output (Python version):** -> ```py -> >>> triggering_statement -> Probably unexpected output -> ``` -> (Optional): One line describing the unexpected output. -> -> -> #### 💡 Explanation: -> -> * Brief explanation of what's happening and why is it happening. -> ```py -> Setting up examples for clarification (if necessary) -> ``` -> **Output:** -> ```py -> >>> trigger # some example that makes it easy to unveil the magic -> # some justified output -> ``` - -**Note:** All the examples are tested on Python 3.5.2 interactive interpreter, and they should work for all the Python versions unless explicitly specified in the description. - -# Usage - -A nice way to get the most out of these examples, in my opinion, will be just to read the examples chronologically, and for every example: -- Carefully read the initial code for setting up the example. If you're an experienced Python programmer, most of the times you will successfully anticipate what's going to happen next. -- Read the output snippets and, - + Check if the outputs are the same as you'd expect. - + Make sure if you know the exact reason behind the output being the way it is. - - If no, take a deep breath, and read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfPython)). - - If yes, give a gentle pat on your back, and you may skip to the next example. - -PS: You can also read WTFpython at the command line. There's a pypi package and an npm package (supports colored formatting) for the same. - -To install the npm package [`wtfpython`](https://www.npmjs.com/package/wtfpython) -```sh -$ npm install -g wtfpython -``` - -Alternatively, to install the pypi package [`wtfpython`](https://pypi.python.org/pypi/wtfpython) -```sh -$ pip install wtfpython -U -``` - -Now, just run `wtfpython` at the command line which will open this collection in your selected `$PAGER`. - ---- - -# 👀 Examples - - -## Section: Strain your brain! - -### ▶ Strings can be tricky sometimes * - -1\. -```py ->>> a = "some_string" ->>> id(a) -140420665652016 ->>> id("some" + "_" + "string") # Notice that both the ids are same. -140420665652016 -``` - -2\. -```py ->>> a = "wtf" ->>> b = "wtf" ->>> a is b -True - ->>> a = "wtf!" ->>> b = "wtf!" ->>> a is b -False - ->>> a, b = "wtf!", "wtf!" ->>> a is b -True -``` - -3\. -```py ->>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' -True ->>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' -False -``` - -Makes sense, right? - -#### 💡 Explanation: -+ Such behavior is due to CPython optimization (called string interning) that tries to use existing immutable objects in some cases rather than creating a new object every time. -+ After being interned, many variables may point to the same string object in memory (thereby saving memory). -+ In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation dependent. There are some facts that can be used to guess if a string will be interned or not: - * All length 0 and length 1 strings are interned. - * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f']` will not be interned) - * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. Cpython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) - -+ When `a` and `b` are set to `"wtf!"` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already `wtf!` as an object (because `"wtf!"` is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment. -+ Constant folding is a technique for [peephole optimization](https://en.wikipedia.org/wiki/Peephole_optimization) in Python. This means the expression `'a'*20` is replaced by `'aaaaaaaaaaaaaaaaaaaa'` during compilation to reduce few clock cycles during runtime. Constant folding only occurs for strings having length less than 20. (Why? Imagine the size of `.pyc` file generated as a result of the expression `'a'*10**10`). [Here's](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) the implementation source for the same. - - ---- - -### ▶ Time for some hash brownies! - -1\. -```py -some_dict = {} -some_dict[5.5] = "Ruby" -some_dict[5.0] = "JavaScript" -some_dict[5] = "Python" -``` - -**Output:** -```py ->>> some_dict[5.5] -"Ruby" ->>> some_dict[5.0] -"Python" ->>> some_dict[5] -"Python" -``` - -"Python" destroyed the existence of "JavaScript"? - -#### 💡 Explanation - -* Python dictionaries check for equality and compare the hash value to determine if two keys are the same. -* Immutable objects with same value always have the same hash in Python. - ```py - >>> 5 == 5.0 - True - >>> hash(5) == hash(5.0) - True - ``` - **Note:** Objects with different values may also have same hash (known as hash collision). -* When the statement `some_dict[5] = "Python"` is executed, the existing value "JavaScript" is overwritten with "Python" because Python recognizes `5` and `5.0` as the same keys of the dictionary `some_dict`. -* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains beautifully the rationale behind it. - ---- - -### ▶ Return return everywhere! - -```py -def some_func(): - try: - return 'from_try' - finally: - return 'from_finally' -``` - -**Output:** -```py ->>> some_func() -'from_finally' -``` - -#### 💡 Explanation: - -- When a `return`, `break` or `continue` statement is executed in the `try` suite of a "try…finally" statement, the `finally` clause is also executed ‘on the way out. -- The return value of a function is determined by the last `return` statement executed. Since the `finally` clause always executes, a `return` statement executed in the `finally` clause will always be the last one executed. - ---- - -### ▶ Deep down, we're all the same. * - -```py -class WTF: - pass -``` - -**Output:** -```py ->>> WTF() == WTF() # two different instances can't be equal -False ->>> WTF() is WTF() # identities are also different -False ->>> hash(WTF()) == hash(WTF()) # hashes _should_ be different as well -True ->>> id(WTF()) == id(WTF()) -True -``` - -#### 💡 Explanation: - -* When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed. -* When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same. -* So, object's id is unique only for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id. -* But why did the `is` operator evaluated to `False`? Let's see with this snippet. - ```py - class WTF(object): - def __init__(self): print("I") - def __del__(self): print("D") - ``` - - **Output:** - ```py - >>> WTF() is WTF() - I - I - D - D - False - >>> id(WTF()) == id(WTF()) - I - D - I - D - True - ``` - As you may observe, the order in which the objects are destroyed is what made all the difference here. - ---- - -### ▶ For what? - -```py -some_string = "wtf" -some_dict = {} -for i, some_dict[i] in enumerate(some_string): - pass -``` - -**Output:** -```py ->>> some_dict # An indexed dict is created. -{0: 'w', 1: 't', 2: 'f'} -``` - -#### 💡 Explanation: - -* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as: - ``` - for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] - ``` - Where `exprlist` is the assignment target. This means that the equivalent of `{exprlist} = {next_value}` is **executed for each item** in the iterable. - An interesting example that illustrates this: - ```py - for i in range(4): - print(i) - i = 10 - ``` - - **Output:** - ``` - 0 - 1 - 2 - 3 - ``` - - Did you expect the loop to run just once? - - **💡 Explanation:** - - - The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(4)` this case) is unpacked and assigned the target list variables (`i` in this case). - -* The `enumerate(some_string)` function yields a new value `i` (A counter going up) and a character from the `some_string` in each iteration. It then sets the (just assigned) `i` key of the dictionary `some_dict` to that character. The unrolling of the loop can be simplified as: - ```py - >>> i, some_dict[i] = (0, 'w') - >>> i, some_dict[i] = (1, 't') - >>> i, some_dict[i] = (2, 'f') - >>> some_dict - ``` - ---- - -### ▶ Evaluation time discrepancy - -1\. -```py -array = [1, 8, 15] -g = (x for x in array if array.count(x) > 0) -array = [2, 8, 22] -``` - -**Output:** -```py ->>> print(list(g)) -[8] -``` - -2\. - -```py -array_1 = [1,2,3,4] -g1 = (x for x in array_1) -array_1 = [1,2,3,4,5] - -array_2 = [1,2,3,4] -g2 = (x for x in array_2) -array_2[:] = [1,2,3,4,5] -``` - -**Output:** -```py ->>> print(list(g1)) -[1,2,3,4] - ->>> print(list(g2)) -[1,2,3,4,5] -``` - -#### 💡 Explanation - -- In a [generator](https://wiki.python.org/moin/Generators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at runtime. -- So before runtime, `array` is re-assigned to the list `[2, 8, 22]`, and since out of `1`, `8` and `15`, only the count of `8` is greater than `0`, the generator only yields `8`. -- The differences in the output of `g1` and `g2` in the second part is due the way variables `array_1` and `array_2` are re-assigned values. -- In the first case, `array_1` is binded to the new object `[1,2,3,4,5]` and since the `in` clause is evaluated at the declaration time it still refers to the old object `[1,2,3,4]` (which is not destroyed). -- In the 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]`). - ---- - -### ▶ `is` is not what it is! - -The following is a very famous example present all over the internet. - -```py ->>> a = 256 ->>> b = 256 ->>> a is b -True - ->>> a = 257 ->>> b = 257 ->>> a is b -False - ->>> a = 257; b = 257 ->>> a is b -True -``` - -#### 💡 Explanation: - -**The difference between `is` and `==`** - -* `is` operator checks if both the operands refer to the same object (i.e., it checks if the identity of the operands matches or not). -* `==` operator compares the values of both the operands and checks if they are the same. -* So `is` is for reference equality and `==` is for value equality. An example to clear things up, - ```py - >>> [] == [] - True - >>> [] is [] # These are two empty lists at two different memory locations. - False - ``` - -**`256` is an existing object but `257` isn't** - -When you start up python the numbers from `-5` to `256` will be allocated. These numbers are used a lot, so it makes sense just to have them ready. - -Quoting from https://docs.python.org/3/c-api/long.html -> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behavior of Python, in this case, is undefined. :-) - -```py ->>> id(256) -10922528 ->>> a = 256 ->>> b = 256 ->>> id(a) -10922528 ->>> id(b) -10922528 ->>> id(257) -140084850247312 ->>> x = 257 ->>> y = 257 ->>> id(x) -140084850247440 ->>> id(y) -140084850247344 -``` - -Here the interpreter isn't smart enough while executing `y = 257` to recognize that we've already created an integer of the value `257,` and so it goes on to create another object in the memory. - -**Both `a` and `b` refer to the same object when initialized with same value in the same line.** - -```py ->>> a, b = 257, 257 ->>> id(a) -140640774013296 ->>> id(b) -140640774013296 ->>> a = 257 ->>> b = 257 ->>> id(a) -140640774013392 ->>> id(b) -140640774013488 -``` - -* When a and b are set to `257` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already `257` as an object. -* It's a compiler optimization and specifically applies to the interactive environment. When you enter two lines in a live interpreter, they're compiled separately, therefore optimized separately. If you were to try this example in a `.py` file, you would not see the same behavior, because the file is compiled all at once. - ---- - -### ▶ A tic-tac-toe where X wins in the first attempt! - -```py -# Let's initialize a row -row = [""]*3 #row i['', '', ''] -# Let's make a board -board = [row]*3 -``` - -**Output:** -```py ->>> board -[['', '', ''], ['', '', ''], ['', '', '']] ->>> board[0] -['', '', ''] ->>> board[0][0] -'' ->>> board[0][0] = "X" ->>> board -[['X', '', ''], ['X', '', ''], ['X', '', '']] -``` - -We didn't assign 3 "X"s or did we? - -#### 💡 Explanation: - -When we initialize `row` variable, this visualization explains what happens in the memory - -![image](/images/tic-tac-toe/after_row_initialized.png) - -And when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`) - -![image](/images/tic-tac-toe/after_board_initialized.png) - -We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue). - -```py ->>> board = [['']*3 for _ in range(3)] ->>> board[0][0] = "X" ->>> board -[['X', '', ''], ['', '', ''], ['', '', '']] -``` - ---- - -### ▶ The sticky output function - -```py -funcs = [] -results = [] -for x in range(7): - def some_func(): - return x - funcs.append(some_func) - results.append(some_func()) # note the function call here - -funcs_results = [func() for func in funcs] -``` - -**Output:** -```py ->>> results -[0, 1, 2, 3, 4, 5, 6] ->>> funcs_results -[6, 6, 6, 6, 6, 6, 6] -``` -Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6. - -//OR - -```py ->>> powers_of_x = [lambda x: x**i for i in range(10)] ->>> [f(2) for f in powers_of_x] -[512, 512, 512, 512, 512, 512, 512, 512, 512, 512] -``` - -#### 💡 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. So all of the functions use the latest value assigned to the variable for computation. - -- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope. - - ```py - funcs = [] - for x in range(7): - def some_func(x=x): - return x - funcs.append(some_func) - ``` - - **Output:** - ```py - >>> funcs_results = [func() for func in funcs] - >>> funcs_results - [0, 1, 2, 3, 4, 5, 6] - ``` - ---- - -### ▶ `is not ...` is not `is (not ...)` - -```py ->>> 'something' is not None -True ->>> 'something' is (not None) -False -``` - -#### 💡 Explanation - -- `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. -- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. - ---- - -### ▶ The surprising comma - -**Output:** -```py ->>> def f(x, y,): -... print(x, y) -... ->>> def g(x=4, y=5,): -... print(x, y) -... ->>> def h(x, **kwargs,): - File "", line 1 - def h(x, **kwargs,): - ^ -SyntaxError: invalid syntax ->>> def h(*args,): - File "", line 1 - def h(*args,): - ^ -SyntaxError: invalid syntax -``` - -#### 💡 Explanation: - -- Trailing comma is not always legal in formal parameters list of a Python function. -- In Python, the argument list is defined partially with leading commas and partially with trailing commas. This conflict causes situations where a comma is trapped in the middle, and no rule accepts it. -- **Note:** The trailing comma problem is [fixed in Python 3.6](https://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python. - ---- - -### ▶ Backslashes at the end of string - -**Output:** -``` ->>> print("\\ C:\\") -\ C:\ ->>> print(r"\ C:") -\ C: ->>> print(r"\ C:\") - - File "", line 1 - print(r"\ C:\") - ^ -SyntaxError: EOL while scanning string literal -``` - -#### 💡 Explanation - -- In a raw string literal, as indicated by the prefix `r`, the backslash doesn't have the special meaning. - ```py - >>> print(repr(r"wt\"f")) - 'wt\\"f' - ``` -- What the interpreter actually does, though, is simply change the behavior of backslashes, so they pass themselves and the following character through. That's why backslashes don't work at the end of a raw string. - ---- - -### ▶ not knot! - -```py -x = True -y = False -``` - -**Output:** -```py ->>> not x == y -True ->>> x == not y - File "", line 1 - x == not y - ^ -SyntaxError: invalid syntax -``` - -#### 💡 Explanation: - -* Operator precedence affects how an expression is evaluated, and `==` operator has higher precedence than `not` operator in Python. -* So `not x == y` is equivalent to `not (x == y)` which is equivalent to `not (True == False)` finally evaluating to `True`. -* But `x == not y` raises a `SyntaxError` because it can be thought of being equivalent to `(x == not) y` and not `x == (not y)` which you might have expected at first sight. -* The parser expected the `not` token to be a part of the `not in` operator (because both `==` and `not in` operators have the same precedence), but after not being able to find an `in` token following the `not` token, it raises a `SyntaxError`. - ---- - -### ▶ Half triple-quoted strings - -**Output:** -```py ->>> print('wtfpython''') -wtfpython ->>> print("wtfpython""") -wtfpython ->>> # The following statements raise `SyntaxError` ->>> # print('''wtfpython') ->>> # print("""wtfpython") -``` - -#### 💡 Explanation: -+ Python supports implicit [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation), Example, - ``` - >>> print("wtf" "python") - wtfpython - >>> 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. - ---- - -### ▶ Midnight time doesn't exist? - -```py -from datetime import datetime - -midnight = datetime(2018, 1, 1, 0, 0) -midnight_time = midnight.time() - -noon = datetime(2018, 1, 1, 12, 0) -noon_time = noon.time() - -if midnight_time: - print("Time at midnight is", midnight_time) - -if noon_time: - print("Time at noon is", noon_time) -``` - -**Output:** -```sh -('Time at noon is', datetime.time(12, 0)) -``` -The midnight time is not printed. - -#### 💡 Explanation: - -Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of "empty." - ---- - -### ▶ What's wrong with booleans? - -1\. -```py -# A simple example to count the number of boolean and -# integers in an iterable of mixed data types. -mixed_list = [False, 1.0, "some_string", 3, True, [], False] -integers_found_so_far = 0 -booleans_found_so_far = 0 - -for item in mixed_list: - if isinstance(item, int): - integers_found_so_far += 1 - elif isinstance(item, bool): - booleans_found_so_far += 1 -``` - -**Output:** -```py ->>> integers_found_so_far -4 ->>> booleans_found_so_far -0 -``` - -2\. -```py -another_dict = {} -another_dict[True] = "JavaScript" -another_dict[1] = "Ruby" -another_dict[1.0] = "Python" -``` - -**Output:** -```py ->>> another_dict[True] -"Python" -``` - -3\. -```py ->>> some_bool = True ->>> "wtf"*some_bool -'wtf' ->>> some_bool = False ->>> "wtf"*some_bool -'' -``` - -#### 💡 Explanation: - -* Booleans are a subclass of `int` - ```py - >>> isinstance(True, int) - True - >>> isinstance(False, int) - True - ``` - -* The integer value of `True` is `1` and that of `False` is `0`. - ```py - >>> True == 1 == 1.0 and False == 0 == 0.0 - True - ``` - -* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for the rationale behind it. - ---- - -### ▶ Class attributes and instance attributes - -1\. -```py -class A: - x = 1 - -class B(A): - pass - -class C(A): - pass -``` - -**Output:** -```py ->>> A.x, B.x, C.x -(1, 1, 1) ->>> B.x = 2 ->>> A.x, B.x, C.x -(1, 2, 1) ->>> A.x = 3 ->>> A.x, B.x, C.x -(3, 2, 3) ->>> a = A() ->>> a.x, A.x -(3, 3) ->>> a.x += 1 ->>> a.x, A.x -(4, 3) -``` - -2\. -```py -class SomeClass: - some_var = 15 - some_list = [5] - another_list = [5] - def __init__(self, x): - self.some_var = x + 1 - self.some_list = self.some_list + [x] - self.another_list += [x] -``` - -**Output:** - -```py ->>> some_obj = SomeClass(420) ->>> some_obj.some_list -[5, 420] ->>> some_obj.another_list -[5, 420] ->>> another_obj = SomeClass(111) ->>> another_obj.some_list -[5, 111] ->>> another_obj.another_list -[5, 420, 111] ->>> another_obj.another_list is SomeClass.another_list -True ->>> another_obj.another_list is some_obj.another_list -True -``` - -#### 💡 Explanation: - -* Class variables and variables in class instances are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of the current class, the parent classes are searched for it. -* The `+=` operator modifies the mutable object in-place without creating a new object. So changing the attribute of one instance affects the other instances and the class attribute as well. - ---- - -### ▶ yielding None - -```py -some_iterable = ('a', 'b') - -def some_func(val): - return "something" -``` - -**Output:** -```py ->>> [x for x in some_iterable] -['a', 'b'] ->>> [(yield x) for x in some_iterable] - at 0x7f70b0a4ad58> ->>> list([(yield x) for x in some_iterable]) -['a', 'b'] ->>> list((yield x) for x in some_iterable) -['a', None, 'b', None] ->>> list(some_func((yield x)) for x in some_iterable) -['a', 'something', 'b', 'something'] -``` - -#### 💡 Explanation: -- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions -- Related bug report: http://bugs.python.org/issue10544 - ---- - -### ▶ Mutating the immutable! - -```py -some_tuple = ("A", "tuple", "with", "values") -another_tuple = ([1, 2], [3, 4], [5, 6]) -``` - -**Output:** -```py ->>> some_tuple[2] = "change this" -TypeError: 'tuple' object does not support item assignment ->>> another_tuple[2].append(1000) #This throws no error ->>> another_tuple -([1, 2], [3, 4], [5, 6, 1000]) ->>> another_tuple[2] += [99, 999] -TypeError: 'tuple' object does not support item assignment ->>> another_tuple -([1, 2], [3, 4], [5, 6, 1000, 99, 999]) -``` - -But I thought tuples were immutable... - -#### 💡 Explanation: - -* Quoting from https://docs.python.org/2/reference/datamodel.html - - > Immutable sequences - An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.) - -* `+=` 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. - ---- - -### ▶ The disappearing variable from outer scope - -```py -e = 7 -try: - raise Exception() -except Exception as e: - pass -``` - -**Output (Python 2.x):** -```py ->>> print(e) -# prints nothing -``` - -**Output (Python 3.x):** -```py ->>> print(e) -NameError: name 'e' is not defined -``` - -#### 💡 Explanation: - -* Source: https://docs.python.org/3/reference/compound_stmts.html#except - - When an exception has been assigned using `as` target, it is cleared at the end of the except clause. This is as if - - ```py - except E as N: - foo - ``` - - was translated into - - ```py - except E as N: - try: - foo - finally: - del N - ``` - - This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because, with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs. - -* The clauses are not scoped in Python. Everything in the example is present in the same scope, and the variable `e` got removed due to the execution of the `except` clause. The same is not the case with functions which have their separate inner-scopes. The example below illustrates this: - - ```py - def f(x): - del(x) - print(x) - - x = 5 - y = [5, 4, 3] - ``` - - **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] - ``` - -* In Python 2.x the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing. - - **Output (Python 2.x):** - ```py - >>> e - Exception() - >>> print e - # Nothing is printed! - ``` - ---- - -### ▶ When True is actually False - -```py -True = False -if True == False: - print("I've lost faith in truth!") -``` - -**Output:** -``` -I've lost faith in truth! -``` - -#### 💡 Explanation: - -- Initially, Python used to have no `bool` type (people used 0 for false and non-zero value like 1 for true). Then they added `True`, `False`, and a `bool` type, but, for backward compatibility, they couldn't make `True` and `False` constants- they just were built-in variables. -- Python 3 was backward-incompatible, so it was now finally possible to fix that, and so this example won't work with Python 3.x! - ---- - -### ▶ From filled to None in one instruction... - -```py -some_list = [1, 2, 3] -some_dict = { - "key_1": 1, - "key_2": 2, - "key_3": 3 -} - -some_list = some_list.append(4) -some_dict = some_dict.update({"key_4": 4}) -``` - -**Output:** -```py ->>> print(some_list) -None ->>> print(some_dict) -None -``` - -#### 💡 Explanation - -Most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](http://docs.python.org/2/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)) - ---- - -### ▶ Subclass relationships * - -**Output:** -```py ->>> from collections import Hashable ->>> issubclass(list, object) -True ->>> issubclass(object, Hashable) -True ->>> issubclass(list, Hashable) -False -``` - -The Subclass relationships were expected to be transitive, right? (i.e., if `A` is a subclass of `B`, and `B` is a subclass of `C`, the `A` _should_ a subclass of `C`) - -#### 💡 Explanation: - -* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass. -* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey "`__hash__`" method in `cls` or anything it inherits from. -* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation. -* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/). - ---- - -### ▶ The mysterious key type conversion * - -```py -class SomeClass(str): - pass - -some_dict = {'s':42} -``` - -**Output:** -```py ->>> type(list(some_dict.keys())[0]) -str ->>> s = SomeClass('s') ->>> some_dict[s] = 40 ->>> some_dict # expected: Two different keys-value pairs -{'s': 40} ->>> type(list(some_dict.keys())[0]) -str -``` - -#### 💡 Explanation: - -* Both the object `s` and the string `"s"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class. -* `SomeClass("s") == "s"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class. -* Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary. -* For the desired behavior, we can redefine the `__eq__` method in `SomeClass` - ```py - class SomeClass(str): - def __eq__(self, other): - return ( - type(self) is SomeClass - and type(other) is SomeClass - and super().__eq__(other) - ) - - # When we define a custom __eq__, Python stops automatically inheriting the - # __hash__ method, so we need to define it as well - __hash__ = str.__hash__ - - some_dict = {'s':42} - ``` - - **Output:** - ```py - >>> s = SomeClass('s') - >>> some_dict[s] = 40 - >>> some_dict - {'s': 40, 's': 42} - >>> keys = list(some_dict.keys()) - >>> type(keys[0]), type(keys[1]) - (__main__.SomeClass, str) - ``` - ---- - -### ▶ Let's see if you can guess this? - -```py -a, b = a[b] = {}, 5 -``` - -**Output:** -```py ->>> a -{5: ({...}, 5)} -``` - -#### 💡 Explanation: - -* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form - ``` - (target_list "=")+ (expression_list | yield_expression) - ``` - and - > An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. - -* The `+` in `(target_list "=")+` means there can be **one or more** target lists. In this case, target lists are `a, b` and `a[b]` (note the expression list is exactly one, which in our case is `{}, 5`). - -* After the expression list is evaluated, it's value is unpacked to the target lists from **left to right**. So, in our case, first the `{}, 5` tuple is unpacked to `a, b` and we now have `a = {}` and `b = 5`. - -* `a` is now assigned to `{}` which is a mutable object. - -* The second target list is `a[b]` (you may expect this to throw an error because both `a` and `b` have not been defined in the statements before. But remember, we just assigned `a` to `{}` and `b` to `5`). - -* Now, we are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference (the `{...}` in the output refers to the same object that `a` is already referencing). Another simpler example of circular reference could be - ```py - >>> some_list = some_list[0] = [0] - >>> some_list - [[...]] - >>> some_list[0] - [[...]] - >>> some_list is some_list[0] - True - >>> some_list[0][0][0][0][0][0] == some_list - True - ``` - Similar is the case in our example (`a[b][0]` is the same object as `a`) - -* So to sum it up, you can break the example down to - ```py - a, b = {}, 5 - a[b] = a, b - ``` - And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a` - ```py - >>> a[b][0] is a - True - ``` - ---- - ---- - -## Section: Appearances are deceptive! - -### ▶ Skipping lines? - -**Output:** -```py ->>> value = 11 ->>> valuе = 32 ->>> value -11 -``` - -Wut? - -**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell. - -#### 💡 Explanation - -Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter. - -```py ->>> ord('е') # cyrillic 'e' (Ye) -1077 ->>> ord('e') # latin 'e', as used in English and typed using standard keyboard -101 ->>> 'е' == 'e' -False - ->>> value = 42 # latin e ->>> valuе = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here ->>> value -42 -``` - -The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example. - ---- - -### ▶ Teleportation * - -```py -import numpy as np - -def energy_send(x): - # Initializing a numpy array - np.array([float(x)]) - -def energy_receive(): - # Return an empty numpy array - return np.empty((), dtype=np.float).tolist() -``` - -**Output:** -```py ->>> energy_send(123.456) ->>> energy_receive() -123.456 -``` - -Where's the Nobel Prize? - -#### 💡 Explanation: - -* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate. -* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always). - ---- - -### ▶ Well, something is fishy... - -```py -def square(x): - """ - A simple function to calculate the square of a number by addition. - """ - sum_so_far = 0 - for counter in range(x): - sum_so_far = sum_so_far + x - return sum_so_far -``` - -**Output (Python 2.x):** - -```py ->>> square(10) -10 -``` - -Shouldn't that be 100? - -**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell. - -#### 💡 Explanation - -* **Don't mix tabs and spaces!** The character just preceding return is a "tab", and the code is indented by multiple of "4 spaces" elsewhere in the example. -* This is how Python handles tabs: - > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...> -* So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. -* Python 3 is kind enough to throw an error for such cases automatically. - - **Output (Python 3.x):** - ```py - TabError: inconsistent use of tabs and spaces in indentation - ``` - ---- - ---- - -## Section: Watch out for the landmines! - - -### ▶ Modifying a dictionary while iterating over it - -```py -x = {0: None} - -for i in x: - del x[i] - x[i+1] = None - print(i) -``` - -**Output (Python 2.7- Python 3.5):** - -``` -0 -1 -2 -3 -4 -5 -6 -7 -``` - -Yes, it runs for exactly **eight** times and stops. - -#### 💡 Explanation: - -* Iteration over a dictionary that you edit at the same time is not supported. -* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. -* How deleted keys are handled and when the resize occurs might be different for different Python implementations. -* For more information, you may refer to this StackOverflow [thread](https://stackoverflow.com/questions/44763802/bug-in-python-dict) explaining a similar example in detail. - ---- - -### ▶ Stubborn `del` operator * - -```py -class SomeClass: - def __del__(self): - print("Deleted!") -``` - -**Output:** -1\. -```py ->>> x = SomeClass() ->>> y = x ->>> del x # this should print "Deleted!" ->>> del y -Deleted! -``` - -Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twist to the example. - -2\. -```py ->>> x = SomeClass() ->>> y = x ->>> del x ->>> y # check if y exists -<__main__.SomeClass instance at 0x7f98a1a67fc8> ->>> del y # Like previously, this should print "Deleted!" ->>> globals() # oh, it didn't. Let's check all our global variables and confirm -Deleted! -{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None} -``` - -Okay, now it's deleted :confused: - -#### 💡 Explanation: -+ `del x` doesn’t directly call `x.__del__()`. -+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero. -+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count to reach zero when `del y` was encountered. -+ Calling `globals` caused the existing reference to be destroyed and hence we can see "Deleted!" being printed (finally!). - ---- - -### ▶ Deleting a list item while iterating - -```py -list_1 = [1, 2, 3, 4] -list_2 = [1, 2, 3, 4] -list_3 = [1, 2, 3, 4] -list_4 = [1, 2, 3, 4] - -for idx, item in enumerate(list_1): - del item - -for idx, item in enumerate(list_2): - list_2.remove(item) - -for idx, item in enumerate(list_3[:]): - list_3.remove(item) - -for idx, item in enumerate(list_4): - list_4.pop(idx) -``` - -**Output:** -```py ->>> list_1 -[1, 2, 3, 4] ->>> list_2 -[2, 4] ->>> list_3 -[] ->>> list_4 -[2, 4] -``` - -Can you guess why the output is `[2, 4]`? - -#### 💡 Explanation: - -* 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 - ``` - -**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. - -**Why the output is `[2, 4]`?** -- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence. - -* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example -* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python. - ---- - -### ▶ Loop variables leaking out! - -1\. -```py -for x in range(7): - if x == 6: - print(x, ': for x inside loop') -print(x, ': x in global') -``` - -**Output:** -```py -6 : for x inside loop -6 : x in global -``` - -But `x` was never defined outside the scope of for loop... - -2\. -```py -# This time let's initialize x first -x = -1 -for x in range(7): - if x == 6: - print(x, ': for x inside loop') -print(x, ': x in global') -``` - -**Output:** -```py -6 : for x inside loop -6 : x in global -``` - -3\. -``` -x = 1 -print([x for x in range(5)]) -print(x, ': x in global') -``` - -**Output (on Python 2.x):** -``` -[0, 1, 2, 3, 4] -(4, ': x in global') -``` - -**Output (on Python 3.x):** -``` -[0, 1, 2, 3, 4] -1 : x in global -``` - -#### 💡 Explanation: - -- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable. - -- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) documentation: - - > "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 -def some_func(default_arg=[]): - default_arg.append("some_string") - return default_arg -``` - -**Output:** -```py ->>> some_func() -['some_string'] ->>> some_func() -['some_string', 'some_string'] ->>> some_func([]) -['some_string'] ->>> some_func() -['some_string', 'some_string', 'some_string'] -``` - -#### 💡 Explanation: - -- 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 - ``` - - **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'],) - ``` - -- 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 not default_arg: - default_arg = [] - default_arg.append("some_string") - return default_arg - ``` - ---- - -### ▶ Catching the Exceptions - -```py -some_list = [1, 2, 3] -try: - # This should raise an ``IndexError`` - print(some_list[4]) -except IndexError, ValueError: - print("Caught!") - -try: - # This should raise a ``ValueError`` - some_list.remove(4) -except IndexError, ValueError: - print("Caught again!") -``` - -**Output (Python 2.x):** -```py -Caught! - -ValueError: list.remove(x): x not in list -``` - -**Output (Python 3.x):** -```py - File "", line 3 - except IndexError, ValueError: - ^ -SyntaxError: invalid syntax -``` - -#### 💡 Explanation - -* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example, - ```py - some_list = [1, 2, 3] - try: - # This should raise a ``ValueError`` - some_list.remove(4) - except (IndexError, ValueError), e: - print("Caught again!") - print(e) - ``` - **Output (Python 2.x):** - ``` - Caught again! - list.remove(x): x not in list - ``` - **Output (Python 3.x):** - ```py - File "", line 4 - except (IndexError, ValueError), e: - ^ - IndentationError: unindent does not match any outer indentation level - ``` - -* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example, - ```py - some_list = [1, 2, 3] - try: - some_list.remove(4) - - except (IndexError, ValueError) as e: - print("Caught again!") - print(e) - ``` - **Output:** - ``` - Caught again! - list.remove(x): x not in list - ``` - ---- - -### ▶ Same operands, different story! - -1\. -```py -a = [1, 2, 3, 4] -b = a -a = a + [5, 6, 7, 8] -``` - -**Output:** -```py ->>> a -[1, 2, 3, 4, 5, 6, 7, 8] ->>> b -[1, 2, 3, 4] -``` - -2\. -```py -a = [1, 2, 3, 4] -b = a -a += [5, 6, 7, 8] -``` - -**Output:** -```py ->>> a -[1, 2, 3, 4, 5, 6, 7, 8] ->>> b -[1, 2, 3, 4, 5, 6, 7, 8] -``` - -#### 💡 Explanation: - -* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this. - -* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged. - -* The expression `a += [5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. - ---- - -### ▶ The out of scope variable - -```py -a = 1 -def some_func(): - return a - -def another_func(): - a += 1 - return a -``` - -**Output:** -```py ->>> some_func() -1 ->>> another_func() -UnboundLocalError: local variable 'a' referenced before assignment -``` - -#### 💡 Explanation: -* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope which throws an error. -* Read [this](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python. -* To modify the outer scope variable `a` in `another_func`, use `global` keyword. - ```py - def another_func() - global a - a += 1 - return a - ``` - - **Output:** - ```py - >>> another_func() - 2 - ``` - ---- - -### ▶ Be careful with chained operations - -```py ->>> (False == False) in [False] # makes sense -False ->>> False == (False in [False]) # makes sense -False ->>> False == False in [False] # now what? -True - ->>> True is False == False -False ->>> False is False is False -True - ->>> 1 > 0 < 1 -True ->>> (1 > 0) < 1 -False ->>> 1 > (0 < 1) -False -``` - -#### 💡 Explanation: - -As per https://docs.python.org/2/reference/expressions.html#not-in - -> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once. - -While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. - -* `False is False is False` is equivalent to `(False is False) and (False is False)` -* `True is False == False` is equivalent to `True is False and False == False` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. -* `1 > 0 < 1` is equivalent to `1 > 0 and 0 < 1` which evaluates to `True`. -* The expression `(1 > 0) < 1` is equivalent to `True < 1` and - ```py - >>> int(True) - 1 - >>> True + 1 #not relevant for this example, but just for fun - 2 - ``` - So, `1 < 1` evaluates to `False` - ---- - -### ▶ Name resolution ignoring class scope - -1\. -```py -x = 5 -class SomeClass: - x = 17 - y = (x for i in range(10)) -``` - -**Output:** -```py ->>> list(SomeClass.y)[0] -5 -``` - -2\. -```py -x = 5 -class SomeClass: - x = 17 - y = [x for i in range(10)] -``` - -**Output (Python 2.x):** -```py ->>> SomeClass.y[0] -17 -``` - -**Output (Python 3.x):** -```py ->>> SomeClass.y[0] -5 -``` - -#### 💡 Explanation -- Scopes nested inside class definition ignore names bound at the class level. -- A generator expression has its own scope. -- Starting from Python 3.X, list comprehensions also have their own scope. - ---- - -### ▶ Needle in a Haystack - -1\. -```py -x, y = (0, 1) if True else None, None -``` - -**Output:** -``` ->>> x, y # expected (0, 1) -((0, 1), None) -``` - -Almost every Python programmer has faced a similar situation. - -2\. -```py -t = ('one', 'two') -for i in t: - print(i) - -t = ('one') -for i in t: - print(i) - -t = () -print(t) -``` - -**Output:** -```py -one -two -o -n -e -tuple() -``` - -#### 💡 Explanation: -* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. -* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. -* `()` is a special token and denotes empty `tuple`. - ---- - ---- - - -## Section: The Hidden treasures! - -This section contains few of the lesser-known interesting things about Python that most beginners like me are unaware of (well, not anymore). - -### ▶ Okay Python, Can you make me fly? * - -Well, here you go - -```py -import antigravity -``` - -**Output:** -Sshh.. It's a super secret. - -#### 💡 Explanation: -+ `antigravity` module is one of the few easter eggs released by Python developers. -+ `import antigravity` opens up a web browser pointing to the [classic XKCD comic](http://xkcd.com/353/) about Python. -+ Well, there's more to it. There's **another easter egg inside the easter egg**. If 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/). - ---- - -### ▶ `goto`, but why? * - -```py -from goto import goto, label -for i in range(9): - for j in range(9): - for k in range(9): - print("I'm trapped, please rescue!") - if k == 2: - goto .breakout # breaking out from a deeply nested loop -label .breakout -print("Freedom!") -``` - -**Output (Python 2.3):** -```py -I'm trapped, please rescue! -I'm trapped, please rescue! -Freedom! -``` - -#### 💡 Explanation: -- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004. -- Current versions of Python do not have this module. -- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python. - ---- - -### ▶ 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 -from __future__ import braces -``` - -**Output:** -```py - File "some_file.py", line 1 - from __future__ import braces -SyntaxError: not a chance -``` - -Braces? No way! If you think that's disappointing, use Java. - -#### 💡 Explanation: -+ The `__future__` module is normally used to provide features from future versions of Python. The "future" here is however ironic. -+ This is an easter egg concerned with the community's feelings on this issue. - ---- - -### ▶ Let's meet Friendly Language Uncle For Life * - -**Output (Python 3.x)** -```py ->>> from __future__ import barry_as_FLUFL ->>> "Ruby" != "Python" # there's no doubt about it - File "some_file.py", line 1 - "Ruby" != "Python" - ^ -SyntaxError: invalid syntax - ->>> "Ruby" <> "Python" -True -``` - -There we go. - -#### 💡 Explanation: -- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means). -- Quoting from the PEP-401 - > Recognized that the != inequality operator in Python 3.0 was a horrible, finger pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. -- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/). - ---- - -### ▶ Even Python understands that love is complicated * - -```py -import this -``` - -Wait, what's **this**? `this` is love :heart: - -**Output:** -``` -The Zen of Python, by Tim Peters - -Beautiful is better than ugly. -Explicit is better than implicit. -Simple is better than complex. -Complex is better than complicated. -Flat is better than nested. -Sparse is better than dense. -Readability counts. -Special cases aren't special enough to break the rules. -Although practicality beats purity. -Errors should never pass silently. -Unless explicitly silenced. -In the face of ambiguity, refuse the temptation to guess. -There should be one-- and preferably only one --obvious way to do it. -Although that way may not be obvious at first unless you're Dutch. -Now is better than never. -Although never is often better than *right* now. -If the implementation is hard to explain, it's a bad idea. -If the implementation is easy to explain, it may be a good idea. -Namespaces are one honking great idea -- let's do more of those! -``` - -It's the Zen of Python! - -```py ->>> love = this ->>> this is love -True ->>> love is True -False ->>> love is False -False ->>> love is not True or False -True ->>> love is not True or False; love is love # Love is complicated -True -``` - -#### 💡 Explanation: - -* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)). -* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, the code for the Zen violates itself (and that's probably the only place where this happens). -* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory. - ---- - -### ▶ Yes, it exists! - -**The `else` clause for loops.** One typical example might be: - -```py - def does_exists_num(l, to_find): - for num in l: - if num == to_find: - print("Exists!") - break - else: - print("Does not exist") -``` - -**Output:** -```py ->>> some_list = [1, 2, 3, 4, 5] ->>> does_exists_num(some_list, 4) -Exists! ->>> does_exists_num(some_list, -1) -Does not exist -``` - -**The `else` clause in exception handling.** An example, - -```py -try: - pass -except: - print("Exception occurred!!!") -else: - print("Try block executed successfully...") -``` - -**Output:** -```py -Try block executed successfully... -``` - -#### 💡 Explanation: -- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. -- `else` clause after try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. - ---- - -### ▶ Inpinity * - -The spelling is intended. Please, don't submit a patch for this. - -**Output (Python 3.x):** -```py ->>> infinity = float('infinity') ->>> hash(infinity) -314159 ->>> hash(float('-inf')) --314159 -``` - -#### 💡 Explanation: -- Hash of infinity is 10⁵ x π. -- Interestingly, the hash of `float('-inf')` is "-10⁵ x π" in Python 3, whereas "-10⁵ x e" in Python 2. - ---- - -### ▶ Mangling time! * - -```py -class Yo(object): - def __init__(self): - self.__honey = True - self.bitch = True -``` - -**Output:** -```py ->>> Yo().bitch -True ->>> Yo().__honey -AttributeError: 'Yo' object has no attribute '__honey' ->>> Yo()._Yo__honey -True -``` - -Why did `Yo()._Yo__honey` work? Only Indian readers would understand. - -#### 💡 Explanation: - -* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces. -* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore) and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. -* So, to access `__honey` attribute, we are required to append `_Yo` to the front which would prevent conflicts with the same name attribute defined in any other class. - ---- - ---- - -## Section: Miscellaneous - - -### ▶ `+=` is faster - -```py -# using "+", three strings: ->>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) -0.25748300552368164 -# using "+=", three strings: ->>> timeit.timeit("s1 += s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) -0.012188911437988281 -``` - -#### 💡 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 = "" - for i in range(iters): - s += "xyz" - assert len(s) == 3*iters - -def add_bytes_with_plus(iters): - s = b"" - for i in range(iters): - s += b"xyz" - assert len(s) == 3*iters - -def add_string_with_format(iters): - fs = "{}"*iters - s = fs.format(*(["xyz"]*iters)) - assert len(s) == 3*iters - -def add_string_with_join(iters): - l = [] - for i in range(iters): - l.append("xyz") - s = "".join(l) - assert len(s) == 3*iters - -def convert_list_to_string(l, iters): - s = "".join(l) - assert len(s) == 3*iters -``` - -**Output:** -```py ->>> timeit(add_string_with_plus(10000)) -1000 loops, best of 3: 972 µs per loop ->>> timeit(add_bytes_with_plus(10000)) -1000 loops, best of 3: 815 µs per loop ->>> timeit(add_string_with_format(10000)) -1000 loops, best of 3: 508 µs per loop ->>> timeit(add_string_with_join(10000)) -1000 loops, best of 3: 878 µs per loop ->>> l = ["xyz"]*10000 ->>> timeit(convert_list_to_string(l, 10000)) -10000 loops, best of 3: 80 µs per loop -``` - -Let's increase the number of iterations by a factor of 10. - -```py ->>> timeit(add_string_with_plus(100000)) # Linear increase in execution time -100 loops, best of 3: 9.75 ms per loop ->>> timeit(add_bytes_with_plus(100000)) # Quadratic increase -1000 loops, best of 3: 974 ms per loop ->>> timeit(add_string_with_format(100000)) # Linear increase -100 loops, best of 3: 5.25 ms per loop ->>> timeit(add_string_with_join(100000)) # Linear increase -100 loops, best of 3: 9.85 ms per loop ->>> l = ["xyz"]*100000 ->>> timeit(convert_list_to_string(l, 100000)) # Linear increase -1000 loops, best of 3: 723 µs per loop -``` - -#### 💡 Explanation -- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) from here. It is generally used to measure the execution time of snippets. -- Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function) -- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for short strings). -- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster. -- `add_string_with_plus` didn't show a quadratic increase in execution time unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example. Had the statement been `s = s + "x" + "y" + "z"` instead of `s += "xyz"`, the increase would have been quadratic. - ```py - def add_string_with_plus(iters): - s = "" - for i in range(iters): - s = s + "x" + "y" + "z" - assert len(s) == 3*iters - - >>> timeit(add_string_with_plus(10000)) - 100 loops, best of 3: 9.87 ms per loop - >>> timeit(add_string_with_plus(100000)) # Quadratic increase in execution time - 1 loops, best of 3: 1.09 s per loop - ``` - ---- - -### ▶ Explicit typecast of strings - -```py -a = float('inf') -b = float('nan') -c = float('-iNf') #These strings are case-insensitive -d = float('nan') -``` - -**Output:** -```py ->>> a -inf ->>> b -nan ->>> c --inf ->>> float('some_other_string') -ValueError: could not convert string to float: some_other_string ->>> a == -c #inf==inf -True ->>> None == None # None==None -True ->>> b == d #but nan!=nan -False ->>> 50/a -0.0 ->>> a/a -nan ->>> 23 + b -nan -``` - -#### 💡 Explanation: - -`'inf'` and `'nan'` are special strings (case-insensitive), which when explicitly typecasted to `float` type, are used to represent mathematical "infinity" and "not a number" respectively. - ---- - -### ▶ 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 a semantically correct statement as strings are [sequences](https://docs.python.org/3/glossary.html#term-sequence)(iterables supporting element access using integer indices) in Python. - + `3 --0-- 5 == 8` and `--5 == 5` are both semantically correct statements and evaluate to `True`. - -* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++ or Java. - ```py - >>> a = 5 - >>> a - 5 - >>> ++a - 5 - >>> --a - 5 - ``` - - **💡 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. - -* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!): - ```py - import dis - exec(""" - def f(): - """ + """ - """.join(["X"+str(x)+"=" + str(x) for x in range(65539)])) - - f() - - print(dis.dis(f)) - ``` - -* Multiple Python threads won't run your *Python code* concurrently (yes you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module. - -* List slicing with out of the bounds indices throws no errors - ```py - >>> some_list = [1, 2, 3, 4, 5] - >>> some_list[111:] - [] - ``` - -* `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](http://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python. - -* `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear - ```py - def count(s, sub): - result = 0 - for i in range(len(s) + 1 - len(sub)): - result += (s[i:i + len(sub)] == sub) - return result - ``` - The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string. - ---- - -# Contributing - -All patches are Welcome! Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for further details. - -For discussions, you can either create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) or ping on the Gitter [channel](https://gitter.im/wtfpython/Lobby) - -# Acknowledgements - -The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by the community gave it the shape it is in right now. - -#### 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 -* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines -* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python -* https://www.python.org/doc/humor/ -* https://www.codementor.io/satwikkansal/python-practices-for-efficient-code-performance-memory-and-usability-aze6oiq65 - -# 🎓 License - -[![CC 4.0][license-image]][license-url] - -© [Satwik Kansal](https://satwikkansal.xyz) - -[license-url]: http://www.wtfpl.net -[license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square - -## Help - -If you have any wtfs, ideas or suggestions, please share. - -## Surprise your geeky pythonist friends? - -You can use these quick links to recommend wtfpython to your friends, - -[Twitter](https://twitter.com/intent/tweet?url=https://github.com/satwikkansal/wtfpython&hastags=python,wtfpython) - | [Linkedin](https://www.linkedin.com/shareArticle?url=https://github.com/satwikkansal&title=What%20the%20f*ck%20Python!&summary=An%20interesting%20collection%20of%20subtle%20and%20tricky%20Python%20snippets.) - -## Need a pdf version? - -I've received a few requests for the pdf version of wtfpython. You can add your details [here](https://satwikkansal.xyz/wtfpython-pdf/) to get the pdf as soon as it is finished. diff --git a/wtfpython-pypi/setup.py b/wtfpython-pypi/setup.py deleted file mode 100644 index 030c6a2d..00000000 --- a/wtfpython-pypi/setup.py +++ /dev/null @@ -1,41 +0,0 @@ -from setuptools import setup, find_packages - -if __name__ == "__main__": - setup(name='wtfpython', - version='0.2', - description='What the f*ck Python!', - author="Satwik Kansal", - maintainer="Satwik Kansal", - maintainer_email='satwikkansal@gmail.com', - url='https://github.com/satwikkansal/wtfpython', - platforms='any', - license="WTFPL 2.0", - long_description="An interesting collection of subtle & tricky Python Snippets" - " and features.", - keywords="wtfpython gotchas snippets tricky", - packages=find_packages(), - entry_points = { - 'console_scripts': ['wtfpython = wtf_python.main:load_and_read'] - }, - classifiers=[ - 'Development Status :: 4 - Beta', - - 'Environment :: Console', - 'Environment :: MacOS X', - 'Environment :: Win32 (MS Windows)', - - 'Intended Audience :: Science/Research', - 'Intended Audience :: Developers', - 'Intended Audience :: Education', - 'Intended Audience :: End Users/Desktop', - - 'Operating System :: OS Independent', - - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 2', - - 'Topic :: Documentation', - 'Topic :: Education', - 'Topic :: Scientific/Engineering', - 'Topic :: Software Development'], - ) diff --git a/wtfpython-pypi/wtf_python/__init__.py b/wtfpython-pypi/wtf_python/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/wtfpython-pypi/wtf_python/main.py b/wtfpython-pypi/wtf_python/main.py deleted file mode 100644 index 0c41d0cc..00000000 --- a/wtfpython-pypi/wtf_python/main.py +++ /dev/null @@ -1,42 +0,0 @@ -from os.path import dirname, join, realpath - -import pydoc -try: - from urllib.request import urlretrieve -except ImportError: - from urllib import urlretrieve - -url = ("http://raw.githubusercontent.com/satwikkansal/" - "wtfpython/master/README.md") - -file_path = join(dirname(dirname(realpath(__file__))), "content.md") - - -def fetch_updated_doc(): - """ - Fetch the latest version of the file at `url` and save it to `file_path`. - If anything goes wrong, do nothing. - """ - try: - print("Fetching the latest version...") - urlretrieve(url, file_path) - print("Done!") - except Exception as e: - print(e) - print("Uh oh, failed to check for the latest version, " - "using the local version for now.") - - -def render_doc(): - with open(file_path, 'r', encoding="utf-8") as f: - content = f.read() - pydoc.pager(content) - - -def load_and_read(): - fetch_updated_doc() - render_doc() - - -if __name__== "__main__": - load_and_read() diff --git a/wtfpython-pypi/wtfpython b/wtfpython-pypi/wtfpython deleted file mode 100644 index d20a5e09..00000000 --- a/wtfpython-pypi/wtfpython +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env python3 - -import sys - -from wtf_python.main import load_and_read - -if __name__ == "__main__": - sys.exit(load_and_read()) From a999ed789f61b21f28bd8960074d6410cf817ce3 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 23 Oct 2024 08:54:18 +0300 Subject: [PATCH 166/210] Add markdownlint-cli2 as Github Action and pre-commit hook --- .github/workflows/pr.yaml | 17 +++++++++++++++++ .pre-commit-config.yaml | 7 +++++++ 2 files changed, 24 insertions(+) create mode 100644 .github/workflows/pr.yaml create mode 100644 .pre-commit-config.yaml diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml new file mode 100644 index 00000000..4da1774b --- /dev/null +++ b/.github/workflows/pr.yaml @@ -0,0 +1,17 @@ +on: [pull_request] + +permissions: + contents: read + pull-requests: read + checks: write + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: DavidAnson/markdownlint-cli2-action@v17 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..8813a02d --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,7 @@ +default_language_version: + python: python3.12 +repos: +- repo: https://github.com/DavidAnson/markdownlint-cli2 + rev: v0.14.0 + hooks: + - id: markdownlint-cli2 From c0217f29f34f3c0a83b23a46a967991c0af8523c Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Wed, 23 Oct 2024 10:21:52 +0300 Subject: [PATCH 167/210] Gix Github Action file extension --- .github/workflows/{pr.yaml => pr.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{pr.yaml => pr.yml} (100%) diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yml similarity index 100% rename from .github/workflows/pr.yaml rename to .github/workflows/pr.yml From f25156107bf55321de5e9c2c490ae39ee613b62a Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 24 Oct 2024 07:53:10 +0300 Subject: [PATCH 168/210] Configure Nox and basic Poetry support - Use new structure for code blocks in README --- README.md | 55 +++++-------- noxfile.py | 13 +++ poetry.lock | 155 +++++++++++++++++++++++++++++++++++ pyproject.toml | 16 ++++ snippets/2_tricky_strings.py | 19 +++++ snippets/__init__.py | 0 6 files changed, 223 insertions(+), 35 deletions(-) create mode 100644 noxfile.py create mode 100644 poetry.lock create mode 100644 pyproject.toml create mode 100644 snippets/2_tricky_strings.py create mode 100644 snippets/__init__.py diff --git a/README.md b/README.md index 2c6b0439..be31b2be 100644 --- a/README.md +++ b/README.md @@ -293,52 +293,37 @@ This saved one line of code, and implicitly prevented invoking `some_func` twice ### ▶ Strings can be tricky sometimes -1\. - -```py ->>> a = "some_string" ->>> id(a) -140420665652016 ->>> id("some" + "_" + "string") # Notice that both the ids are same. -140420665652016 -``` -2\. -```py ->>> a = "wtf" ->>> b = "wtf" ->>> a is b -True - ->>> a = "wtf!" ->>> b = "wtf!" ->>> a is b -False +1\. Notice that both the ids are same. +```python:snippets/2_tricky_strings.py -s 2 -e 3 +assert id("some_string") == id("some" + "_" + "string") +assert id("some_string") == id("some_string") ``` -3\. +2\. `True` because it is invoked in script. Might be `False` in `python shell` or `ipython` -```py ->>> a, b = "wtf!", "wtf!" ->>> a is b # All versions except 3.7.x -True +```python:snippets/2_tricky_strings.py -s 6 -e 12 +a = "wtf" +b = "wtf" +assert a is b ->>> a = "wtf!"; b = "wtf!" ->>> a is b # This will print True or False depending on where you're invoking it (python shell / ipython / as a script) -False -``` - -```py -# This time in file some_file.py a = "wtf!" b = "wtf!" -print(a is b) +assert a is b +``` + +3\. `True` because it is invoked in script. Might be `False` in `python shell` or `ipython` + +```python:snippets/2_tricky_strings.py -s 15 -e 19 +a, b = "wtf!", "wtf!" +assert a is b -# prints True when the module is invoked! +a = "wtf!"; b = "wtf!" +assert a is b ``` -4\. +4\. __Disclaimer - snippet is not relavant in modern Python versions__ **Output (< Python3.7 )** diff --git a/noxfile.py b/noxfile.py new file mode 100644 index 00000000..f693b854 --- /dev/null +++ b/noxfile.py @@ -0,0 +1,13 @@ +from typing import TYPE_CHECKING + +import nox + + +if TYPE_CHECKING: + from nox.sessions import Session + +python_versions = ["3.9", "3.10", "3.11", "3.12", "3.13"] + +@nox.session(python=python_versions, reuse_venv=True) +def tests(session: "Session") -> None: + _ = session.run("python", "snippets/2_tricky_strings.py") diff --git a/poetry.lock b/poetry.lock new file mode 100644 index 00000000..47b34986 --- /dev/null +++ b/poetry.lock @@ -0,0 +1,155 @@ +# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand. + +[[package]] +name = "argcomplete" +version = "3.5.1" +description = "Bash tab completion for argparse" +optional = false +python-versions = ">=3.8" +files = [ + {file = "argcomplete-3.5.1-py3-none-any.whl", hash = "sha256:1a1d148bdaa3e3b93454900163403df41448a248af01b6e849edc5ac08e6c363"}, + {file = "argcomplete-3.5.1.tar.gz", hash = "sha256:eb1ee355aa2557bd3d0145de7b06b2a45b0ce461e1e7813f5d066039ab4177b4"}, +] + +[package.extras] +test = ["coverage", "mypy", "pexpect", "ruff", "wheel"] + +[[package]] +name = "colorama" +version = "0.4.6" +description = "Cross-platform colored terminal text." +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +files = [ + {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, + {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, +] + +[[package]] +name = "colorlog" +version = "6.8.2" +description = "Add colours to the output of Python's logging module." +optional = false +python-versions = ">=3.6" +files = [ + {file = "colorlog-6.8.2-py3-none-any.whl", hash = "sha256:4dcbb62368e2800cb3c5abd348da7e53f6c362dda502ec27c560b2e58a66bd33"}, + {file = "colorlog-6.8.2.tar.gz", hash = "sha256:3e3e079a41feb5a1b64f978b5ea4f46040a94f11f0e8bbb8261e3dbbeca64d44"}, +] + +[package.dependencies] +colorama = {version = "*", markers = "sys_platform == \"win32\""} + +[package.extras] +development = ["black", "flake8", "mypy", "pytest", "types-colorama"] + +[[package]] +name = "distlib" +version = "0.3.9" +description = "Distribution utilities" +optional = false +python-versions = "*" +files = [ + {file = "distlib-0.3.9-py2.py3-none-any.whl", hash = "sha256:47f8c22fd27c27e25a65601af709b38e4f0a45ea4fc2e710f65755fa8caaaf87"}, + {file = "distlib-0.3.9.tar.gz", hash = "sha256:a60f20dea646b8a33f3e7772f74dc0b2d0772d2837ee1342a00645c81edf9403"}, +] + +[[package]] +name = "filelock" +version = "3.16.1" +description = "A platform independent file lock." +optional = false +python-versions = ">=3.8" +files = [ + {file = "filelock-3.16.1-py3-none-any.whl", hash = "sha256:2082e5703d51fbf98ea75855d9d5527e33d8ff23099bec374a134febee6946b0"}, + {file = "filelock-3.16.1.tar.gz", hash = "sha256:c249fbfcd5db47e5e2d6d62198e565475ee65e4831e2561c8e313fa7eb961435"}, +] + +[package.extras] +docs = ["furo (>=2024.8.6)", "sphinx (>=8.0.2)", "sphinx-autodoc-typehints (>=2.4.1)"] +testing = ["covdefaults (>=2.3)", "coverage (>=7.6.1)", "diff-cover (>=9.2)", "pytest (>=8.3.3)", "pytest-asyncio (>=0.24)", "pytest-cov (>=5)", "pytest-mock (>=3.14)", "pytest-timeout (>=2.3.1)", "virtualenv (>=20.26.4)"] +typing = ["typing-extensions (>=4.12.2)"] + +[[package]] +name = "nox" +version = "2024.10.9" +description = "Flexible test automation." +optional = false +python-versions = ">=3.8" +files = [ + {file = "nox-2024.10.9-py3-none-any.whl", hash = "sha256:1d36f309a0a2a853e9bccb76bbef6bb118ba92fa92674d15604ca99adeb29eab"}, + {file = "nox-2024.10.9.tar.gz", hash = "sha256:7aa9dc8d1c27e9f45ab046ffd1c3b2c4f7c91755304769df231308849ebded95"}, +] + +[package.dependencies] +argcomplete = ">=1.9.4,<4" +colorlog = ">=2.6.1,<7" +packaging = ">=20.9" +tomli = {version = ">=1", markers = "python_version < \"3.11\""} +virtualenv = ">=20.14.1" + +[package.extras] +tox-to-nox = ["jinja2", "tox"] +uv = ["uv (>=0.1.6)"] + +[[package]] +name = "packaging" +version = "24.1" +description = "Core utilities for Python packages" +optional = false +python-versions = ">=3.8" +files = [ + {file = "packaging-24.1-py3-none-any.whl", hash = "sha256:5b8f2217dbdbd2f7f384c41c628544e6d52f2d0f53c6d0c3ea61aa5d1d7ff124"}, + {file = "packaging-24.1.tar.gz", hash = "sha256:026ed72c8ed3fcce5bf8950572258698927fd1dbda10a5e981cdf0ac37f4f002"}, +] + +[[package]] +name = "platformdirs" +version = "4.3.6" +description = "A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`." +optional = false +python-versions = ">=3.8" +files = [ + {file = "platformdirs-4.3.6-py3-none-any.whl", hash = "sha256:73e575e1408ab8103900836b97580d5307456908a03e92031bab39e4554cc3fb"}, + {file = "platformdirs-4.3.6.tar.gz", hash = "sha256:357fb2acbc885b0419afd3ce3ed34564c13c9b95c89360cd9563f73aa5e2b907"}, +] + +[package.extras] +docs = ["furo (>=2024.8.6)", "proselint (>=0.14)", "sphinx (>=8.0.2)", "sphinx-autodoc-typehints (>=2.4)"] +test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=8.3.2)", "pytest-cov (>=5)", "pytest-mock (>=3.14)"] +type = ["mypy (>=1.11.2)"] + +[[package]] +name = "tomli" +version = "2.0.2" +description = "A lil' TOML parser" +optional = false +python-versions = ">=3.8" +files = [ + {file = "tomli-2.0.2-py3-none-any.whl", hash = "sha256:2ebe24485c53d303f690b0ec092806a085f07af5a5aa1464f3931eec36caaa38"}, + {file = "tomli-2.0.2.tar.gz", hash = "sha256:d46d457a85337051c36524bc5349dd91b1877838e2979ac5ced3e710ed8a60ed"}, +] + +[[package]] +name = "virtualenv" +version = "20.27.0" +description = "Virtual Python Environment builder" +optional = false +python-versions = ">=3.8" +files = [ + {file = "virtualenv-20.27.0-py3-none-any.whl", hash = "sha256:44a72c29cceb0ee08f300b314848c86e57bf8d1f13107a5e671fb9274138d655"}, + {file = "virtualenv-20.27.0.tar.gz", hash = "sha256:2ca56a68ed615b8fe4326d11a0dca5dfbe8fd68510fb6c6349163bed3c15f2b2"}, +] + +[package.dependencies] +distlib = ">=0.3.7,<1" +filelock = ">=3.12.2,<4" +platformdirs = ">=3.9.1,<5" + +[package.extras] +docs = ["furo (>=2023.7.26)", "proselint (>=0.13)", "sphinx (>=7.1.2,!=7.3)", "sphinx-argparse (>=0.4)", "sphinxcontrib-towncrier (>=0.2.1a0)", "towncrier (>=23.6)"] +test = ["covdefaults (>=2.3)", "coverage (>=7.2.7)", "coverage-enable-subprocess (>=1)", "flaky (>=3.7)", "packaging (>=23.1)", "pytest (>=7.4)", "pytest-env (>=0.8.2)", "pytest-freezer (>=0.4.8)", "pytest-mock (>=3.11.1)", "pytest-randomly (>=3.12)", "pytest-timeout (>=2.1)", "setuptools (>=68)", "time-machine (>=2.10)"] + +[metadata] +lock-version = "2.0" +python-versions = "^3.9" +content-hash = "af91619c8e62e649ee538e51a248ef2fc1e4f4495e7748b3b551685aa47b404e" diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..a048fafe --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,16 @@ +[tool.poetry] +name = "wtfpython" +version = "3.0.0" +description = "What the f*ck Python!" +authors = ["Satwik Kansal "] +license = "WTFPL 2.0" +readme = "README.md" + +[tool.poetry.dependencies] +python = "^3.9" +nox = "^2024.10.9" + + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/snippets/2_tricky_strings.py b/snippets/2_tricky_strings.py new file mode 100644 index 00000000..25320f27 --- /dev/null +++ b/snippets/2_tricky_strings.py @@ -0,0 +1,19 @@ +# 1 +assert id("some_string") == id("some" + "_" + "string") +assert id("some_string") == id("some_string") + +# 2 +a = "wtf" +b = "wtf" +assert a is b + +a = "wtf!" +b = "wtf!" +assert a is b + +# 3 +a, b = "wtf!", "wtf!" +assert a is b + +a = "wtf!"; b = "wtf!" +assert a is b diff --git a/snippets/__init__.py b/snippets/__init__.py new file mode 100644 index 00000000..e69de29b From 8987d66adbdbe41d015ca1039f01eba6af610f4e Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 31 Oct 2024 15:53:24 +0300 Subject: [PATCH 169/210] Add Markdownlintcli config --- .markdownlint.yaml | 15 +++++++++++++++ README.md | 1 + 2 files changed, 16 insertions(+) create mode 100644 .markdownlint.yaml diff --git a/.markdownlint.yaml b/.markdownlint.yaml new file mode 100644 index 00000000..7ebffd8d --- /dev/null +++ b/.markdownlint.yaml @@ -0,0 +1,15 @@ +# MD013/line-length +MD013: + line_length: 120 + +# no-duplicate-heading - Multiple headings with the same content (Ignore multiple `Explanation` headings) +MD024: false + +# no-trailing-punctuation - Trailing punctuation in heading (Ignore exclamation marks in headings) +MD026: false + +# no-inline-html : Inline HTML (HTML is used for centered and theme specific images) +MD033: false + +# no-inline-html : Bare URL used (site should be attributed transparently, because otherwise we have to un-necesarily explain where the link directs) +MD034: false diff --git a/README.md b/README.md index 35a9cf59..f9a72778 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@

Exploring and understanding Python through surprising snippets.

+ Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) From 77c978b0f86be9d00720e0e0849ff9035c3e57e4 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Thu, 31 Oct 2024 15:54:06 +0300 Subject: [PATCH 170/210] Fix Markdown syntax in README using Markdownlintcli autofix --- README.md | 766 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 457 insertions(+), 309 deletions(-) diff --git a/README.md b/README.md index f9a72778..d026d5f1 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,6 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

- - Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) @@ -22,7 +20,7 @@ While some of the examples you see below may not be WTFs in the truest sense, bu If you're an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt. You may have already experienced some of them before, and I might be able to revive sweet old memories of yours! :sweat_smile: -PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) (the examples marked with asterisk are the ones added in the latest major revision). +PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) (the examples marked with asterisk are the ones added in the latest major revision). So, here we go... @@ -33,83 +31,83 @@ So, here we go... - [Structure of the Examples](#structure-of-the-examples) - + [▶ Some fancy Title](#-some-fancy-title) + - [▶ Some fancy Title](#-some-fancy-title) - [Usage](#usage) - [👀 Examples](#-examples) - * [Section: Strain your brain!](#section-strain-your-brain) - + [▶ First things first! *](#-first-things-first-) - + [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) - + [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - + [▶ How not to use `is` operator](#-how-not-to-use-is-operator) - + [▶ Hash brownies](#-hash-brownies) - + [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) - + [▶ Disorder within order *](#-disorder-within-order-) - + [▶ Keep trying... *](#-keep-trying-) - + [▶ For what?](#-for-what) - + [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - + [▶ `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-) - + [▶ Subclass relationships](#-subclass-relationships) - + [▶ Methods equality and identity](#-methods-equality-and-identity) - + [▶ All-true-ation *](#-all-true-ation-) - + [▶ The surprising comma](#-the-surprising-comma) - + [▶ Strings and the backslashes](#-strings-and-the-backslashes) - + [▶ not knot!](#-not-knot) - + [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - + [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - + [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - + [▶ yielding None](#-yielding-none) - + [▶ 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) - + [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) - + [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) - * [Section: Slippery Slopes](#section-slippery-slopes) - + [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) - + [▶ Stubborn `del` operation](#-stubborn-del-operation) - + [▶ The out of scope variable](#-the-out-of-scope-variable) - + [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - + [▶ Lossy zip of iterators *](#-lossy-zip-of-iterators-) - + [▶ Loop variables leaking out!](#-loop-variables-leaking-out) - + [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - + [▶ Catching the Exceptions](#-catching-the-exceptions) - + [▶ Same operands, different story!](#-same-operands-different-story) - + [▶ 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-) - + [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - * [Section: The Hidden treasures!](#section-the-hidden-treasures) - + [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) - + [▶ `goto`, but why?](#-goto-but-why) - + [▶ Brace yourself!](#-brace-yourself) - + [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) - + [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) - + [▶ Yes, it exists!](#-yes-it-exists) - + [▶ Ellipsis *](#-ellipsis-) - + [▶ Inpinity](#-inpinity) - + [▶ Let's mangle](#-lets-mangle) - * [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - + [▶ Skipping lines?](#-skipping-lines) - + [▶ Teleportation](#-teleportation) - + [▶ Well, something is fishy...](#-well-something-is-fishy) - * [Section: Miscellaneous](#section-miscellaneous) - + [▶ `+=` is faster](#--is-faster) - + [▶ Let's make a giant string!](#-lets-make-a-giant-string) - + [▶ Slowing down `dict` lookups *](#-slowing-down-dict-lookups-) - + [▶ Bloating instance `dict`s *](#-bloating-instance-dicts-) - + [▶ Minor Ones *](#-minor-ones-) + - [Section: Strain your brain!](#section-strain-your-brain) + - [▶ First things first! *](#-first-things-first-) + - [▶ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes) + - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + - [▶ How not to use `is` operator](#-how-not-to-use-is-operator) + - [▶ Hash brownies](#-hash-brownies) + - [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) + - [▶ Disorder within order *](#-disorder-within-order-) + - [▶ Keep trying... *](#-keep-trying-) + - [▶ For what?](#-for-what) + - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) + - [▶ `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-) + - [▶ Subclass relationships](#-subclass-relationships) + - [▶ Methods equality and identity](#-methods-equality-and-identity) + - [▶ All-true-ation *](#-all-true-ation-) + - [▶ The surprising comma](#-the-surprising-comma) + - [▶ Strings and the backslashes](#-strings-and-the-backslashes) + - [▶ not knot!](#-not-knot) + - [▶ Half triple-quoted strings](#-half-triple-quoted-strings) + - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) + - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) + - [▶ yielding None](#-yielding-none) + - [▶ 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) + - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + - [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) + - [Section: Slippery Slopes](#section-slippery-slopes) + - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + - [▶ Stubborn `del` operation](#-stubborn-del-operation) + - [▶ The out of scope variable](#-the-out-of-scope-variable) + - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) + - [▶ Lossy zip of iterators *](#-lossy-zip-of-iterators-) + - [▶ Loop variables leaking out!](#-loop-variables-leaking-out) + - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) + - [▶ Catching the Exceptions](#-catching-the-exceptions) + - [▶ Same operands, different story!](#-same-operands-different-story) + - [▶ 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-) + - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) + - [Section: The Hidden treasures!](#section-the-hidden-treasures) + - [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) + - [▶ `goto`, but why?](#-goto-but-why) + - [▶ Brace yourself!](#-brace-yourself) + - [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) + - [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) + - [▶ Yes, it exists!](#-yes-it-exists) + - [▶ Ellipsis *](#-ellipsis-) + - [▶ Inpinity](#-inpinity) + - [▶ Let's mangle](#-lets-mangle) + - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) + - [▶ Skipping lines?](#-skipping-lines) + - [▶ Teleportation](#-teleportation) + - [▶ Well, something is fishy...](#-well-something-is-fishy) + - [Section: Miscellaneous](#section-miscellaneous) + - [▶ `+=` is faster](#--is-faster) + - [▶ Let's make a giant string!](#-lets-make-a-giant-string) + - [▶ 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) - * [Surprise your friends as well!](#surprise-your-friends-as-well) - * [More content like this?](#more-content-like-this) + - [Surprise your friends as well!](#surprise-your-friends-as-well) + - [More content like this?](#more-content-like-this) @@ -130,16 +128,19 @@ All the examples are structured like below: > >>> triggering_statement > Some unexpected output > ``` +> > (Optional): One line describing the unexpected output. > > > #### 💡 Explanation: > -> * Brief explanation of what's happening and why is it happening. +> - Brief explanation of what's happening and why is it happening. +> > ```py > # Set up code > # More examples for further clarification (if necessary) > ``` +> > **Output (Python version(s)):** > > ```py @@ -152,10 +153,11 @@ All the examples are structured like below: # Usage A nice way to get the most out of these examples, in my opinion, is to read them in sequential order, and for every example: + - Carefully read the initial code for setting up the example. If you're an experienced Python programmer, you'll successfully anticipate what's going to happen next most of the time. - Read the output snippets and, - + Check if the outputs are the same as you'd expect. - + Make sure if you know the exact reason behind the output being the way it is. + - Check if the outputs are the same as you'd expect. + - Make sure if you know the exact reason behind the output being the way it is. - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfpython/issues/new)). - If yes, give a gentle pat on your back, and you may skip to the next example. @@ -226,8 +228,6 @@ SyntaxError: invalid syntax 16 ``` - - #### 💡 Explanation **Quick walrus operator refresher** @@ -266,11 +266,11 @@ 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`. -- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. +- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. -- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, +- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, - - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6') + - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9)` (where `a`'s value is 6') ```py >>> (a := 6, 9) == ((a := 6), 9) @@ -282,7 +282,7 @@ This saved one line of code, and implicitly prevented invoking `some_func` twice True ``` - - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. + - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. --- @@ -300,6 +300,7 @@ This saved one line of code, and implicitly prevented invoking `some_func` twice ``` 2\. + ```py >>> a = "wtf" >>> b = "wtf" @@ -348,12 +349,13 @@ 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: - * All length 0 and length 1 strings are interned. - * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned) - * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) +- The behavior in first and second snippets is due to a CPython optimization (called string interning) that tries to use existing immutable objects in some cases rather than creating a new object every time. +- After being "interned," many variables may reference the same string object in memory (saving memory thereby). +- In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is implementation-dependent. There are some rules that can be used to guess if a string will be interned or not: + - All length 0 and length 1 strings are interned. + - Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned) + - Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) +

@@ -362,14 +364,13 @@ 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. -+ 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). +- 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. +- 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 @@ -401,16 +402,18 @@ As per https://docs.python.org/3/reference/expressions.html#comparisons While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. -* `False is False is False` is equivalent to `(False is False) and (False is False)` -* `True is False == False` is equivalent to `(True is False) and (False == False)` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. -* `1 > 0 < 1` is equivalent to `(1 > 0) and (0 < 1)` which evaluates to `True`. -* The expression `(1 > 0) < 1` is equivalent to `True < 1` and +- `False is False is False` is equivalent to `(False is False) and (False is False)` +- `True is False == False` is equivalent to `(True is False) and (False == False)` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. +- `1 > 0 < 1` is equivalent to `(1 > 0) and (0 < 1)` which evaluates to `True`. +- The expression `(1 > 0) < 1` is equivalent to `True < 1` and + ```py >>> int(True) 1 >>> True + 1 #not relevant for this example, but just for fun 2 ``` + So, `1 < 1` evaluates to `False` --- @@ -468,9 +471,10 @@ False **The difference between `is` and `==`** -* `is` operator checks if both the operands refer to the same object (i.e., it checks if the identity of the operands matches or not). -* `==` operator compares the values of both the operands and checks if they are the same. -* So `is` is for reference equality and `==` is for value equality. An example to clear things up, +- `is` operator checks if both the operands refer to the same object (i.e., it checks if the identity of the operands matches or not). +- `==` operator compares the values of both the operands and checks if they are the same. +- So `is` is for reference equality and `==` is for value equality. An example to clear things up, + ```py >>> class A: pass >>> A() is A() # These are two empty objects at two different memory locations. @@ -505,7 +509,7 @@ Quoting from https://docs.python.org/3/c-api/long.html Here the interpreter isn't smart enough while executing `y = 257` to recognize that we've already created an integer of the value `257,` and so it goes on to create another object in the memory. -Similar optimization applies to other **immutable** objects like empty tuples as well. Since lists are mutable, that's why `[] is []` will return `False` and `() is ()` will return `True`. This explains our second snippet. Let's move on to the third one, +Similar optimization applies to other **immutable** objects like empty tuples as well. Since lists are mutable, that's why `[] is []` will return `False` and `() is ()` will return `True`. This explains our second snippet. Let's move on to the third one, **Both `a` and `b` refer to the same object when initialized with same value in the same line.** @@ -525,9 +529,9 @@ Similar optimization applies to other **immutable** objects like empty tuples as 140640774013488 ``` -* When a and b are set to `257` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already `257` as an object. +- When a and b are set to `257` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already `257` as an object. -* It's a compiler optimization and specifically applies to the interactive environment. When you enter two lines in a live interpreter, they're compiled separately, therefore optimized separately. If you were to try this example in a `.py` file, you would not see the same behavior, because the file is compiled all at once. This optimization is not limited to integers, it works for other immutable data types like strings (check the "Strings are tricky example") and floats as well, +- It's a compiler optimization and specifically applies to the interactive environment. When you enter two lines in a live interpreter, they're compiled separately, therefore optimized separately. If you were to try this example in a `.py` file, you would not see the same behavior, because the file is compiled all at once. This optimization is not limited to integers, it works for other immutable data types like strings (check the "Strings are tricky example") and floats as well, ```py >>> a, b = 257.0, 257.0 @@ -535,14 +539,14 @@ Similar optimization applies to other **immutable** objects like empty tuples as True ``` -* Why didn't this work for Python 3.7? The abstract reason is because such compiler optimizations are implementation specific (i.e. may change with version, OS, etc). I'm still figuring out what exact implementation change cause the issue, you can check out this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for updates. +- Why didn't this work for Python 3.7? The abstract reason is because such compiler optimizations are implementation specific (i.e. may change with version, OS, etc). I'm still figuring out what exact implementation change cause the issue, you can check out this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for updates. --- - ### ▶ Hash brownies 1\. + ```py some_dict = {} some_dict[5.5] = "JavaScript" @@ -569,10 +573,10 @@ complex 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 True @@ -585,7 +589,8 @@ 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. +- This applies when setting an item as well. So when you do `some_dict[5] = "Python"`, Python finds the existing item with equivalent key `5.0 -> "Ruby"`, overwrites its value in place, and leaves the original key alone. + ```py >>> some_dict {5.0: 'Ruby'} @@ -593,15 +598,17 @@ 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. +- 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. -* How did Python find `5` in a dictionary containing `5.0`? Python does this in constant time without having to scan through every item by using hash functions. When Python looks up a key `foo` in a dict, it first computes `hash(foo)` (which runs in constant-time). Since in Python it is required that objects that compare equal also have the same hash value ([docs](https://docs.python.org/3/reference/datamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value. ```py >>> 5 == 5.0 == 5 + 0j True >>> hash(5) == hash(5.0) == hash(5 + 0j) 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.) --- @@ -614,6 +621,7 @@ class WTF: ``` **Output:** + ```py >>> WTF() == WTF() # two different instances can't be equal False @@ -627,10 +635,11 @@ True #### 💡 Explanation: -* When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed. -* When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same. -* So, the object's id is unique only for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id. -* But why did the `is` operator evaluate to `False`? Let's see with this snippet. +- When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed. +- When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same. +- So, the object's id is unique only for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id. +- But why did the `is` operator evaluate to `False`? Let's see with this snippet. + ```py class WTF(object): def __init__(self): print("I") @@ -638,6 +647,7 @@ True ``` **Output:** + ```py >>> WTF() is WTF() I @@ -652,6 +662,7 @@ True D True ``` + As you may observe, the order in which the objects are destroyed is what made all the difference here. --- @@ -684,6 +695,7 @@ class OrderedDictWithHash(OrderedDict): ``` **Output** + ```py >>> dictionary == ordered_dict # If a == b True @@ -723,6 +735,7 @@ What is going on here? > Equality tests between OrderedDict objects are order-sensitive and are implemented as `list(od1.items())==list(od2.items())`. Equality tests between `OrderedDict` objects and other Mapping objects are order-insensitive like regular dictionaries. - The reason for this equality 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 @@ -750,6 +763,7 @@ What is going on here? >>> len(another_set) 2 ``` + So the inconsistency is due to `another_ordered_dict in another_set` being `False` because `ordered_dict` was already present in `another_set` and as observed before, `ordered_dict == another_ordered_dict` is `False`. --- @@ -814,7 +828,6 @@ Iteration 0 --- - ### ▶ For what? ```py @@ -825,19 +838,23 @@ for i, some_dict[i] in enumerate(some_string): ``` **Output:** + ```py >>> some_dict # An indexed dict appears. {0: 'w', 1: 't', 2: 'f'} ``` -#### 💡 Explanation: +#### 💡 Explanation: + +- A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as: -* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as: ``` for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] ``` + Where `exprlist` is the assignment target. This means that the equivalent of `{exprlist} = {next_value}` is **executed for each item** in the iterable. An interesting example that illustrates this: + ```py for i in range(4): print(i) @@ -845,6 +862,7 @@ for i, some_dict[i] in enumerate(some_string): ``` **Output:** + ``` 0 1 @@ -858,7 +876,8 @@ for i, some_dict[i] in enumerate(some_string): - The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(4)` in this case) is unpacked and assigned the target list variables (`i` in this case). -* The `enumerate(some_string)` function yields a new value `i` (a counter going up) and a character from the `some_string` in each iteration. It then sets the (just assigned) `i` key of the dictionary `some_dict` to that character. The unrolling of the loop can be simplified as: +- The `enumerate(some_string)` function yields a new value `i` (a counter going up) and a character from the `some_string` in each iteration. It then sets the (just assigned) `i` key of the dictionary `some_dict` to that character. The unrolling of the loop can be simplified as: + ```py >>> i, some_dict[i] = (0, 'w') >>> i, some_dict[i] = (1, 't') @@ -871,6 +890,7 @@ for i, some_dict[i] in enumerate(some_string): ### ▶ Evaluation time discrepancy 1\. + ```py array = [1, 8, 15] # A typical generator expression @@ -898,6 +918,7 @@ array_2[:] = [1,2,3,4,5] ``` **Output:** + ```py >>> print(list(gen_1)) [1, 2, 3, 4] @@ -918,6 +939,7 @@ array_4 = [400, 500, 600] ``` **Output:** + ```py >>> print(list(gen)) [401, 501, 601, 402, 502, 602, 403, 503, 603] @@ -936,7 +958,6 @@ array_4 = [400, 500, 600] --- - ### ▶ `is not ...` is not `is (not ...)` ```py @@ -949,7 +970,7 @@ False #### 💡 Explanation - `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. -- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. +- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. - In the example, `(not None)` evaluates to `True` since the value `None` is `False` in a boolean context, so the expression becomes `'something' is True`. --- @@ -1016,7 +1037,6 @@ We can avoid this scenario here by not using `row` variable to generate `board`. ### ▶ Schrödinger's variable * - ```py funcs = [] results = [] @@ -1030,6 +1050,7 @@ funcs_results = [func() for func in funcs] ``` **Output (Python version):** + ```py >>> results [0, 1, 2, 3, 4, 5, 6] @@ -1048,12 +1069,14 @@ 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 >>> inspect.getclosurevars(funcs[0]) ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) ``` + Since `x` is a global value, we can change the value that the `funcs` will lookup and return by updating `x`: ```py @@ -1062,7 +1085,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 = [] @@ -1092,6 +1115,7 @@ ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) ### ▶ The chicken-egg problem * 1\. + ```py >>> isinstance(3, int) True @@ -1103,7 +1127,7 @@ True So which is the "ultimate" base class? There's more to the confusion by the way, -2\. +2\. ```py >>> class A: pass @@ -1126,15 +1150,14 @@ True False ``` - #### 💡 Explanation - `type` is a [metaclass](https://realpython.com/python-metaclasses/) in Python. - **Everything** is an `object` in Python, which includes classes as well as their objects (instances). - class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`. - There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking about these relationships (`issubclass` and `isinstance`) in terms of Python classes. The relationship between `object` and `type` can't be reproduced in pure python. To be more precise the following relationships can't be reproduced in pure Python, - + class A is an instance of class B, and class B is an instance of class A. - + class A is an instance of itself. + - class A is an instance of class B, and class B is an instance of class A. + - class A is an instance of itself. - These relationships between `object` and `type` (both being instances of each other as well as themselves) exist in Python because of "cheating" at the implementation level. --- @@ -1142,6 +1165,7 @@ False ### ▶ Subclass relationships **Output:** + ```py >>> from collections.abc import Hashable >>> issubclass(list, object) @@ -1152,14 +1176,14 @@ 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: -* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass. -* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey "`__hash__`" method in `cls` or anything it inherits from. -* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation. -* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/). +- Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass. +- When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey "`__hash__`" method in `cls` or anything it inherits from. +- Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation. +- More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/). --- @@ -1167,6 +1191,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` 1. + ```py class SomeClass: def method(self): @@ -1182,6 +1207,7 @@ class SomeClass: ``` **Output:** + ```py >>> print(SomeClass.method is SomeClass.method) True @@ -1197,12 +1223,14 @@ Accessing `classm` twice, we get an equal object, but not the *same* one? Let's with instances of `SomeClass`: 2. + ```py o1 = SomeClass() o2 = SomeClass() ``` **Output:** + ```py >>> print(o1.method == o2.method) False @@ -1221,44 +1249,49 @@ True Accessing `classm` or `method` twice, creates equal but not *same* objects for the same instance of `SomeClass`. #### 💡 Explanation -* Functions are [descriptors](https://docs.python.org/3/howto/descriptor.html). Whenever a function is accessed as an +- 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). + ```py >>> o1.method > ``` -* Accessing the attribute multiple times creates a method object every time! Therefore `o1.method is o1.method` is +- Accessing the attribute multiple times creates a method object every time! Therefore `o1.method is o1.method` is never truthy. Accessing functions as class attributes (as opposed to instance) does not create methods, however; so `SomeClass.method is SomeClass.method` is truthy. + ```py >>> SomeClass.method ``` -* `classmethod` transforms functions into class methods. Class methods are descriptors that, when accessed, create +- `classmethod` transforms functions into class methods. Class methods are descriptors that, when accessed, create a method object which binds the *class* (type) of the object, instead of the object itself. + ```py >>> o1.classm > ``` -* Unlike functions, `classmethod`s will create a method also when accessed as class attributes (in which case they +- Unlike functions, `classmethod`s will create a method also when accessed as class attributes (in which case they bind the class, not to the type of it). So `SomeClass.classm is SomeClass.classm` is falsy. + ```py >>> SomeClass.classm > ``` -* A method object compares equal when both the functions are equal, and the bound objects are the same. So +- A method object compares equal when both the functions are equal, and the bound objects are the same. So `o1.method == o1.method` is truthy, although not the same object in memory. -* `staticmethod` transforms functions into a "no-op" descriptor, which returns the function as-is. No method +- `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. + ```py >>> o1.staticm >>> SomeClass.staticm ``` -* Having to create new "method" objects every time Python calls instance methods and having to modify the arguments +- 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 @@ -1296,7 +1329,7 @@ Why's this True-False alteration? return True ``` -- `all([])` returns `True` since the iterable is empty. +- `all([])` returns `True` since the iterable is empty. - `all([[]])` returns `False` because the passed array has one element, `[]`, and in python, an empty list is falsy. - `all([[[]]])` and higher recursive variants are always `True`. This is because the passed array's single element (`[[...]]`) is no longer empty, and lists with values are truthy. @@ -1329,14 +1362,15 @@ SyntaxError: invalid syntax #### 💡 Explanation: - Trailing comma is not always legal in formal parameters list of a Python function. -- In Python, the argument list is defined partially with leading commas and partially with trailing commas. This conflict causes situations where a comma is trapped in the middle, and no rule accepts it. -- **Note:** The trailing comma problem is [fixed in Python 3.6](https://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python. +- In Python, the argument list is defined partially with leading commas and partially with trailing commas. This conflict causes situations where a comma is trapped in the middle, and no rule accepts it. +- **Note:** The trailing comma problem is [fixed in Python 3.6](https://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python. --- ### ▶ Strings and the backslashes **Output:** + ```py >>> print("\"") " @@ -1357,11 +1391,14 @@ True #### 💡 Explanation - 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' ``` + - 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 @@ -1373,6 +1410,7 @@ True >>> 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. --- @@ -1385,6 +1423,7 @@ y = False ``` **Output:** + ```py >>> not x == y True @@ -1397,16 +1436,17 @@ SyntaxError: invalid syntax #### 💡 Explanation: -* Operator precedence affects how an expression is evaluated, and `==` operator has higher precedence than `not` operator in Python. -* So `not x == y` is equivalent to `not (x == y)` which is equivalent to `not (True == False)` finally evaluating to `True`. -* But `x == not y` raises a `SyntaxError` because it can be thought of being equivalent to `(x == not) y` and not `x == (not y)` which you might have expected at first sight. -* The parser expected the `not` token to be a part of the `not in` operator (because both `==` and `not in` operators have the same precedence), but after not being able to find an `in` token following the `not` token, it raises a `SyntaxError`. +- Operator precedence affects how an expression is evaluated, and `==` operator has higher precedence than `not` operator in Python. +- So `not x == y` is equivalent to `not (x == y)` which is equivalent to `not (True == False)` finally evaluating to `True`. +- But `x == not y` raises a `SyntaxError` because it can be thought of being equivalent to `(x == not) y` and not `x == (not y)` which you might have expected at first sight. +- The parser expected the `not` token to be a part of the `not in` operator (because both `==` and `not in` operators have the same precedence), but after not being able to find an `in` token following the `not` token, it raises a `SyntaxError`. --- ### ▶ Half triple-quoted strings **Output:** + ```py >>> print('wtfpython''') wtfpython @@ -1422,14 +1462,15 @@ 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, +- Python supports implicit [string literal concatenation](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation), Example, + ``` >>> print("wtf" "python") wtfpython >>> 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. +- `'''` 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. --- @@ -1452,6 +1493,7 @@ for item in mixed_list: ``` **Output:** + ```py >>> integers_found_so_far 4 @@ -1459,8 +1501,8 @@ for item in mixed_list: 0 ``` - 2\. + ```py >>> some_bool = True >>> "wtf" * some_bool @@ -1486,20 +1528,19 @@ def tell_truth(): I have lost faith in truth! ``` - - #### 💡 Explanation: -* `bool` is a subclass of `int` in Python - +- `bool` is a subclass of `int` in Python + ```py >>> issubclass(bool, int) True >>> issubclass(int, bool) False ``` - -* And thus, `True` and `False` are instances of `int` + +- And thus, `True` and `False` are instances of `int` + ```py >>> isinstance(True, int) True @@ -1507,7 +1548,8 @@ I have lost faith in truth! True ``` -* The integer value of `True` is `1` and that of `False` is `0`. +- The integer value of `True` is `1` and that of `False` is `0`. + ```py >>> int(True) 1 @@ -1515,17 +1557,18 @@ I have lost faith in truth! 0 ``` -* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for the rationale behind it. +- 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! +- 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 class A: x = 1 @@ -1538,6 +1581,7 @@ class C(A): ``` **Output:** + ```py >>> A.x, B.x, C.x (1, 1, 1) @@ -1556,6 +1600,7 @@ class C(A): ``` 2\. + ```py class SomeClass: some_var = 15 @@ -1588,8 +1633,8 @@ True #### 💡 Explanation: -* Class variables and variables in class instances are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of the current class, the parent classes are searched for it. -* The `+=` operator modifies the mutable object in-place without creating a new object. So changing the attribute of one instance affects the other instances and the class attribute as well. +- Class variables and variables in class instances are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of the current class, the parent classes are searched for it. +- The `+=` operator modifies the mutable object in-place without creating a new object. So changing the attribute of one instance affects the other instances and the class attribute as well. --- @@ -1618,6 +1663,7 @@ def some_func(val): ``` #### 💡 Explanation: + - This is a bug in CPython's handling of `yield` in generators and comprehensions. - Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions - Related bug report: https://bugs.python.org/issue10544 @@ -1625,7 +1671,6 @@ def some_func(val): --- - ### ▶ Yielding from... return! * 1\. @@ -1669,13 +1714,13 @@ The same result, this didn't work either. #### 💡 Explanation: -+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that, +- From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that, > "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." -+ In the case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically caught inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. +- In the case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically caught inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. -+ To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, +- To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, ```py try: @@ -1742,13 +1787,11 @@ False True ``` - - #### 💡 Explanation: - `'inf'` and `'nan'` are special strings (case-insensitive), which, when explicitly typecast-ed to `float` type, are used to represent mathematical "infinity" and "not a number" respectively. -- Since according to 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') @@ -1779,6 +1822,7 @@ another_tuple = ([1, 2], [3, 4], [5, 6]) ``` **Output:** + ```py >>> some_tuple[2] = "change this" TypeError: 'tuple' object does not support item assignment @@ -1795,13 +1839,13 @@ But I thought tuples were immutable... #### 💡 Explanation: -* Quoting from https://docs.python.org/3/reference/datamodel.html +- Quoting from https://docs.python.org/3/reference/datamodel.html > Immutable sequences An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.) -* `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place. -* There's also an explanation in [official Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works). +- `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place. +- There's also an explanation in [official Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works). --- @@ -1817,12 +1861,14 @@ except Exception as e: ``` **Output (Python 2.x):** + ```py >>> print(e) # prints nothing ``` **Output (Python 3.x):** + ```py >>> print(e) NameError: name 'e' is not defined @@ -1830,7 +1876,7 @@ NameError: name 'e' is not defined #### 💡 Explanation: -* Source: https://docs.python.org/3/reference/compound_stmts.html#except +- Source: https://docs.python.org/3/reference/compound_stmts.html#except When an exception has been assigned using `as` target, it is cleared at the end of the `except` clause. This is as if @@ -1851,7 +1897,7 @@ NameError: name 'e' is not defined This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because, with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs. -* The clauses are not scoped in Python. Everything in the example is present in the same scope, and the variable `e` got removed due to the execution of the `except` clause. The same is not the case with functions that have their separate inner-scopes. The example below illustrates this: +- The clauses are not scoped in Python. Everything in the example is present in the same scope, and the variable `e` got removed due to the execution of the `except` clause. The same is not the case with functions that have their separate inner-scopes. The example below illustrates this: ```py def f(x): @@ -1863,6 +1909,7 @@ NameError: name 'e' is not defined ``` **Output:** + ```py >>> f(x) UnboundLocalError: local variable 'x' referenced before assignment @@ -1874,9 +1921,10 @@ NameError: name 'e' is not defined [5, 4, 3] ``` -* In Python 2.x, the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing. +- In Python 2.x, the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing. **Output (Python 2.x):** + ```py >>> e Exception() @@ -1886,7 +1934,6 @@ NameError: name 'e' is not defined --- - ### ▶ The mysterious key type conversion ```py @@ -1897,6 +1944,7 @@ some_dict = {'s': 42} ``` **Output:** + ```py >>> type(list(some_dict.keys())[0]) str @@ -1910,10 +1958,11 @@ str #### 💡 Explanation: -* Both the object `s` and the string `"s"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class. -* `SomeClass("s") == "s"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class. -* Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary. -* For the desired behavior, we can redefine the `__eq__` method in `SomeClass` +- Both the object `s` and the string `"s"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class. +- `SomeClass("s") == "s"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class. +- Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary. +- For the desired behavior, we can redefine the `__eq__` method in `SomeClass` + ```py class SomeClass(str): def __eq__(self, other): @@ -1931,6 +1980,7 @@ str ``` **Output:** + ```py >>> s = SomeClass('s') >>> some_dict[s] = 40 @@ -1950,6 +2000,7 @@ a, b = a[b] = {}, 5 ``` **Output:** + ```py >>> a {5: ({...}, 5)} @@ -1957,23 +2008,26 @@ a, b = a[b] = {}, 5 #### 💡 Explanation: -* According to [Python language reference](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), assignment statements have the form +- According to [Python language reference](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), assignment statements have the form + ``` (target_list "=")+ (expression_list | yield_expression) ``` + 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`). +- The `+` in `(target_list "=")+` means there can be **one or more** target lists. In this case, target lists are `a, b` and `a[b]` (note the expression list is exactly one, which in our case is `{}, 5`). -* After the expression list is evaluated, its value is unpacked to the target lists from **left to right**. So, in our case, first the `{}, 5` tuple is unpacked to `a, b` and we now have `a = {}` and `b = 5`. +- After the expression list is evaluated, its value is unpacked to the target lists from **left to right**. So, in our case, first the `{}, 5` tuple is unpacked to `a, b` and we now have `a = {}` and `b = 5`. -* `a` is now assigned to `{}`, which is a mutable object. +- `a` is now assigned to `{}`, which is a mutable object. -* The second target list is `a[b]` (you may expect this to throw an error because both `a` and `b` have not been defined in the statements before. But remember, we just assigned `a` to `{}` and `b` to `5`). +- The second target list is `a[b]` (you may expect this to throw an error because both `a` and `b` have not been defined in the statements before. But remember, we just assigned `a` to `{}` and `b` to `5`). + +- Now, we are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference (the `{...}` in the output refers to the same object that `a` is already referencing). Another simpler example of circular reference could be -* Now, we are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference (the `{...}` in the output refers to the same object that `a` is already referencing). Another simpler example of circular reference could be ```py >>> some_list = some_list[0] = [0] >>> some_list @@ -1985,23 +2039,27 @@ a, b = a[b] = {}, 5 >>> some_list[0][0][0][0][0][0] == some_list True ``` + Similar is the case in our example (`a[b][0]` is the same object as `a`) -* So to sum it up, you can break the example down to +- So to sum it up, you can break the example down to + ```py a, b = {}, 5 a[b] = a, b ``` + And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a` + ```py >>> a[b][0] is a True ``` - --- ### ▶ Exceeds the limit for integer string conversion + ```py >>> # Python 3.10.6 >>> int("2" * 5432) @@ -2011,6 +2069,7 @@ a, b = a[b] = {}, 5 ``` **Output:** + ```py >>> # Python 3.10.6 222222222222222222222222222222222222222222222222222222222222222... @@ -2024,19 +2083,19 @@ ValueError: Exceeds the limit (4300) for integer string conversion: ``` #### 💡 Explanation: + This call to `int()` works fine in Python 3.10.6 and raises a ValueError in Python 3.10.8. Note that Python can still work with large integers. The error is only raised when converting between integers and strings. Fortunately, you can increase the limit for the allowed number of digits when you expect an operation to exceed it. To do this, you can use one of the following: + - The -X int_max_str_digits command-line flag - The set_int_max_str_digits() function from the sys module - The PYTHONINTMAXSTRDIGITS environment variable [Check the documentation](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) for more details on changing the default limit if you expect your code to exceed this value. - --- - ## Section: Slippery Slopes ### ▶ Modifying a dictionary while iterating over it @@ -2067,11 +2126,11 @@ Yes, it runs for exactly **eight** times and stops. #### 💡 Explanation: -* Iteration over a dictionary that you edit at the same time is not supported. -* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. -* How deleted keys are handled and when the resize occurs might be different for different Python implementations. -* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. -* Python 3.7.6 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. +- Iteration over a dictionary that you edit at the same time is not supported. +- It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. +- How deleted keys are handled and when the resize occurs might be different for different Python implementations. +- So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. +- Python 3.7.6 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. --- @@ -2087,6 +2146,7 @@ class SomeClass: **Output:** 1\. + ```py >>> x = SomeClass() >>> y = x @@ -2098,6 +2158,7 @@ Deleted! Phew, deleted at last. You might have guessed what saved `__del__` from being called in our first attempt to delete `x`. Let's add more twists to the example. 2\. + ```py >>> x = SomeClass() >>> y = x @@ -2113,10 +2174,10 @@ 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. -+ Calling `globals` (or really, executing anything that will have a non `None` result) caused `_` to reference the new result, dropping the existing reference. Now the reference count reached 0 and we can see "Deleted!" being printed (finally!). +- `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. +- Calling `globals` (or really, executing anything that will have a non `None` result) caused `_` to reference the new result, dropping the existing reference. Now the reference count reached 0 and we can see "Deleted!" being printed (finally!). --- @@ -2124,6 +2185,7 @@ Okay, now it's deleted :confused: 1\. + ```py a = 1 def some_func(): @@ -2135,6 +2197,7 @@ def another_func(): ``` 2\. + ```py def some_closure_func(): a = 1 @@ -2151,6 +2214,7 @@ def another_closure_func(): ``` **Output:** + ```py >>> some_func() 1 @@ -2164,8 +2228,9 @@ 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. +- 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. + ```py def another_func() global a @@ -2174,12 +2239,14 @@ UnboundLocalError: local variable 'a' referenced before assignment ``` **Output:** + ```py >>> 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. +- In `another_closure_func`, `a` becomes local to the scope of `another_inner_func`, but it has not been initialized previously in the same scope, which is why it throws an error. +- To modify the outer scope variable `a` in `another_inner_func`, use the `nonlocal` keyword. The nonlocal statement is used to refer to variables defined in the nearest outer (excluding the global) scope. + ```py def another_func(): a = 1 @@ -2191,12 +2258,13 @@ UnboundLocalError: local variable 'a' referenced before assignment ``` **Output:** + ```py >>> 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. +- 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. --- @@ -2222,6 +2290,7 @@ for idx, item in enumerate(list_4): ``` **Output:** + ```py >>> list_1 [1, 2, 3, 4] @@ -2237,7 +2306,7 @@ Can you guess why the output is `[2, 4]`? #### 💡 Explanation: -* 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. +- 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] @@ -2248,19 +2317,19 @@ Can you guess why the output is `[2, 4]`? ``` **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. +- `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. **Why the output is `[2, 4]`?** + - The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence. -* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example -* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python. +- Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example +- See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python. --- - ### ▶ Lossy zip of iterators * @@ -2278,11 +2347,13 @@ Can you guess why the output is `[2, 4]`? >>> list(zip(numbers_iter, remaining)) [(4, 3), (5, 4), (6, 5)] ``` + Where did element `3` go from the `numbers` list? #### 💡 Explanation: - From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function, + ```py def zip(*iterables): sentinel = object() @@ -2295,9 +2366,11 @@ Where did element `3` go from the `numbers` list? 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. + +- 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) @@ -2306,6 +2379,7 @@ Where did element `3` go from the `numbers` list? >>> 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. --- @@ -2313,6 +2387,7 @@ Where did element `3` go from the `numbers` list? ### ▶ Loop variables leaking out! 1\. + ```py for x in range(7): if x == 6: @@ -2321,6 +2396,7 @@ print(x, ': x in global') ``` **Output:** + ```py 6 : for x inside loop 6 : x in global @@ -2329,6 +2405,7 @@ print(x, ': x in global') But `x` was never defined outside the scope of for loop... 2\. + ```py # This time let's initialize x first x = -1 @@ -2339,6 +2416,7 @@ print(x, ': x in global') ``` **Output:** + ```py 6 : for x inside loop 6 : x in global @@ -2347,6 +2425,7 @@ print(x, ': x in global') 3\. **Output (Python 2.x):** + ```py >>> x = 1 >>> print([x for x in range(5)]) @@ -2356,6 +2435,7 @@ print(x, ': x in global') ``` **Output (Python 3.x):** + ```py >>> x = 1 >>> print([x for x in range(5)]) @@ -2384,6 +2464,7 @@ def some_func(default_arg=[]): ``` **Output:** + ```py >>> some_func() ['some_string'] @@ -2406,6 +2487,7 @@ def some_func(default_arg=[]): ``` **Output:** + ```py >>> some_func.__defaults__ #This will show the default argument values for the function ([],) @@ -2450,6 +2532,7 @@ except IndexError, ValueError: ``` **Output (Python 2.x):** + ```py Caught! @@ -2457,6 +2540,7 @@ ValueError: list.remove(x): x not in list ``` **Output (Python 3.x):** + ```py File "", line 3 except IndexError, ValueError: @@ -2466,7 +2550,8 @@ SyntaxError: invalid syntax #### 💡 Explanation -* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example, +- To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example, + ```py some_list = [1, 2, 3] try: @@ -2476,12 +2561,16 @@ SyntaxError: invalid syntax print("Caught again!") print(e) ``` + **Output (Python 2.x):** + ``` Caught again! list.remove(x): x not in list ``` + **Output (Python 3.x):** + ```py File "", line 4 except (IndexError, ValueError), e: @@ -2489,7 +2578,8 @@ SyntaxError: invalid syntax IndentationError: unindent does not match any outer indentation level ``` -* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example, +- Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example, + ```py some_list = [1, 2, 3] try: @@ -2499,7 +2589,9 @@ SyntaxError: invalid syntax print("Caught again!") print(e) ``` + **Output:** + ``` Caught again! list.remove(x): x not in list @@ -2510,6 +2602,7 @@ SyntaxError: invalid syntax ### ▶ Same operands, different story! 1\. + ```py a = [1, 2, 3, 4] b = a @@ -2517,6 +2610,7 @@ a = a + [5, 6, 7, 8] ``` **Output:** + ```py >>> a [1, 2, 3, 4, 5, 6, 7, 8] @@ -2525,6 +2619,7 @@ a = a + [5, 6, 7, 8] ``` 2\. + ```py a = [1, 2, 3, 4] b = a @@ -2532,6 +2627,7 @@ a += [5, 6, 7, 8] ``` **Output:** + ```py >>> a [1, 2, 3, 4, 5, 6, 7, 8] @@ -2541,17 +2637,18 @@ 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. +- The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged. -* The expression `a += [5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. +- The expression `a += [5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. --- ### ▶ Name resolution ignoring class scope 1\. + ```py x = 5 class SomeClass: @@ -2560,12 +2657,14 @@ class SomeClass: ``` **Output:** + ```py >>> list(SomeClass.y)[0] 5 ``` 2\. + ```py x = 5 class SomeClass: @@ -2574,18 +2673,21 @@ class SomeClass: ``` **Output (Python 2.x):** + ```py >>> SomeClass.y[0] 17 ``` **Output (Python 3.x):** + ```py >>> SomeClass.y[0] 5 ``` #### 💡 Explanation + - Scopes nested inside class definition ignore names bound at the class level. - A generator expression has its own scope. - Starting from Python 3.X, list comprehensions also have their own scope. @@ -2595,6 +2697,7 @@ class SomeClass: ### ▶ Rounding like a banker * Let's implement a naive function to get the middle element of a list: + ```py def get_middle(some_list): mid_index = round(len(some_list) / 2) @@ -2602,6 +2705,7 @@ def get_middle(some_list): ``` **Python 3.x:** + ```py >>> get_middle([1]) # looks good 1 @@ -2614,6 +2718,7 @@ def get_middle(some_list): >>> round(len([1,2,3,4,5]) / 2) # why? 2 ``` + It seems as though Python rounded 2.5 to 2. #### 💡 Explanation: @@ -2636,7 +2741,7 @@ It seems as though Python rounded 2.5 to 2. 2.0 ``` -- This is the recommended way to round .5 fractions as described in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules). However, the other way (round away from zero) is taught in school most of the time, so banker's rounding is likely not that well known. Furthermore, some of the most popular programming languages (for example: JavaScript, Java, C/C++, Ruby, Rust) do not use banker's rounding either. Therefore, this is still quite special to Python and may result in confusion when rounding fractions. +- This is the recommended way to round .5 fractions as described in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules). However, the other way (round away from zero) is taught in school most of the time, so banker's rounding is likely not that well known. Furthermore, some of the most popular programming languages (for example: JavaScript, Java, C/C++, Ruby, Rust) do not use banker's rounding either. Therefore, this is still quite special to Python and may result in confusion when rounding fractions. - See the [round() docs](https://docs.python.org/3/library/functions.html#round) or [this stackoverflow thread](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) for more information. - Note that `get_middle([1])` only returned 1 because the index was `round(0.5) - 1 = 0 - 1 = -1`, returning the last element in the list. @@ -2778,20 +2883,20 @@ def similar_recursive_func(a): #### 💡 Explanation: -* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. +- For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. -* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. +- For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. -* `()` is a special token and denotes empty `tuple`. +- `()` is a special token and denotes empty `tuple`. -* In 3, as you might have already figured out, there's a missing comma after 5th element (`"that"`) in the list. So by implicit string literal concatenation, +- In 3, as you might have already figured out, there's a missing comma after 5th element (`"that"`) in the list. So by implicit string literal concatenation, ```py >>> ten_words_list ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] ``` -* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up, +- No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up, ```py >>> a = "python" @@ -2810,15 +2915,14 @@ def similar_recursive_func(a): AssertionError: Values are not equal ``` -* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). +- As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). -* Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignment of an immutable (`a -= 1`) is not an alteration of the value. +- Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignment of an immutable (`a -= 1`) is not an alteration of the value. -* Being aware of these nitpicks can save you hours of debugging effort in the long run. +- Being aware of these nitpicks can save you hours of debugging effort in the long run. --- - ### ▶ Splitsies * ```py @@ -2841,9 +2945,10 @@ 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 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', ''] @@ -2886,12 +2991,15 @@ 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! ``` + - 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'] @@ -2901,6 +3009,7 @@ NameError: name '_another_weird_name_func' is not defined def _another_weird_name_func(): print("works!") ``` + **Output** ```py @@ -2932,7 +3041,7 @@ False #### 💡 Explanation: -- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. +- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. - ```py >>> [] == tuple() @@ -2978,6 +3087,7 @@ if noon_time: ```py ('Time at noon is', datetime.time(12, 0)) ``` + The midnight time is not printed. #### 💡 Explanation: @@ -2987,8 +3097,6 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t --- --- - - ## Section: The Hidden treasures! This section contains a few lesser-known and interesting things about Python that most beginners like me are unaware of (well, not anymore). @@ -3005,9 +3113,9 @@ 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/). +- `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/). --- @@ -3027,6 +3135,7 @@ print("Freedom!") ``` **Output (Python 2.3):** + ```py I am trapped, please rescue! I am trapped, please rescue! @@ -3034,6 +3143,7 @@ Freedom! ``` #### 💡 Explanation: + - A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004. - Current versions of Python do not have this module. - Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python. @@ -3049,6 +3159,7 @@ from __future__ import braces ``` **Output:** + ```py File "some_file.py", line 1 from __future__ import braces @@ -3058,16 +3169,17 @@ 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. -+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement. +- The `__future__` module is normally used to provide features from future versions of Python. The "future" in this specific context is however, ironic. +- This is an easter egg concerned with the community's feelings on this issue. +- The code is actually present [here](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) in `future.c` file. +- When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement. --- ### ▶ Let's meet Friendly Language Uncle For Life **Output (Python 3.x)** + ```py >>> from __future__ import barry_as_FLUFL >>> "Ruby" != "Python" # there's no doubt about it @@ -3083,12 +3195,14 @@ True There we go. #### 💡 Explanation: + - This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means). - Quoting from the PEP-401 > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. - There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/). - 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"')) @@ -3105,6 +3219,7 @@ import this Wait, what's **this**? `this` is love :heart: **Output:** + ``` The Zen of Python, by Tim Peters @@ -3147,9 +3262,9 @@ True #### 💡 Explanation: -* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)). -* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens). -* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators). +- `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)). +- And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens). +- Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators). --- @@ -3168,6 +3283,7 @@ True ``` **Output:** + ```py >>> some_list = [1, 2, 3, 4, 5] >>> does_exists_num(some_list, 4) @@ -3188,15 +3304,18 @@ else: ``` **Output:** + ```py Try block executed successfully... ``` #### 💡 Explanation: + - The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a "nobreak" clause. - `else` clause after a try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. --- + ### ▶ Ellipsis * ```py @@ -3205,6 +3324,7 @@ def some_func(): ``` **Output** + ```py >>> some_func() # No output, No Error @@ -3219,14 +3339,18 @@ Ellipsis ``` #### 💡 Explanation + - In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`. + ```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 + - As a placeholder for code that hasn't been written yet (just like `pass` statement) + - In slicing syntax to represent the full slices in remaining direction + ```py >>> import numpy as np >>> three_dimensional_array = np.arange(8).reshape(2, 2, 2) @@ -3242,7 +3366,9 @@ Ellipsis ] ]) ``` + So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions + ```py >>> three_dimensional_array[:,:,1] array([[1, 3], @@ -3251,9 +3377,10 @@ Ellipsis array([[1, 3], [5, 7]]) ``` + Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`) - + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`)) - + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the "no argument passed" and "None value passed" scenarios). + - 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). --- @@ -3262,6 +3389,7 @@ Ellipsis The spelling is intended. Please, don't submit a patch for this. **Output (Python 3.x):** + ```py >>> infinity = float('infinity') >>> hash(infinity) @@ -3271,6 +3399,7 @@ The spelling is intended. Please, don't submit a patch for this. ``` #### 💡 Explanation: + - Hash of infinity is 10⁵ x π. - Interestingly, the hash of `float('-inf')` is "-10⁵ x π" in Python 3, whereas "-10⁵ x e" in Python 2. @@ -3279,6 +3408,7 @@ The spelling is intended. Please, don't submit a patch for this. ### ▶ Let's mangle 1\. + ```py class Yo(object): def __init__(self): @@ -3287,6 +3417,7 @@ class Yo(object): ``` **Output:** + ```py >>> Yo().bro True @@ -3297,6 +3428,7 @@ True ``` 2\. + ```py class Yo(object): def __init__(self): @@ -3306,6 +3438,7 @@ class Yo(object): ``` **Output:** + ```py >>> Yo().bro True @@ -3329,6 +3462,7 @@ class A(object): ``` **Output:** + ```py >>> A().__variable Traceback (most recent call last): @@ -3339,15 +3473,14 @@ AttributeError: 'A' object has no attribute '__variable' 'Some value' ``` - #### 💡 Explanation: -* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces. -* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a "dunder") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. -* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class. -* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores. -* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope. -* Also, if the mangled name is longer than 255 characters, truncation will happen. +- [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces. +- In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a "dunder") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. +- So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class. +- But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores. +- The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope. +- Also, if the mangled name is longer than 255 characters, truncation will happen. --- --- @@ -3357,6 +3490,7 @@ AttributeError: 'A' object has no attribute '__variable' ### ▶ Skipping lines? **Output:** + ```py >>> value = 11 >>> valuе = 32 @@ -3408,6 +3542,7 @@ def energy_receive(): ``` **Output:** + ```py >>> energy_send(123.456) >>> energy_receive() @@ -3418,8 +3553,8 @@ Where's the Nobel Prize? #### 💡 Explanation: -* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate. -* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always). +- Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate. +- `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always). --- @@ -3449,14 +3584,15 @@ 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. -* This is how Python handles tabs: +- **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. +- So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. +- Python 3 is kind enough to throw an error for such cases automatically. **Output (Python 3.x):** + ```py TabError: inconsistent use of tabs and spaces in indentation ``` @@ -3466,7 +3602,6 @@ Shouldn't that be 100? ## Section: Miscellaneous - ### ▶ `+=` is faster @@ -3480,7 +3615,7 @@ 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. +- `+=` 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. --- @@ -3555,11 +3690,13 @@ Let's increase the number of iterations by a factor of 10. ``` #### 💡 Explanation + - You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces. - Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function) - Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings). - Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster. - Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + "x" + "y" + "z"` instead of `s += "xyz"`, the increase would have been quadratic. + ```py def add_string_with_plus(iters): s = "" @@ -3572,6 +3709,7 @@ Let's increase the number of iterations by a factor of 10. >>> %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` + - So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which, > There should be one-- and preferably only one --obvious way to do it. @@ -3586,6 +3724,7 @@ another_dict = {str(i): 1 for i in range(1_000_000)} ``` **Output:** + ```py >>> %timeit some_dict['5'] 28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) @@ -3602,14 +3741,14 @@ KeyError: 1 >>> %timeit another_dict['5'] 38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) ``` + Why are same lookups becoming slower? #### 💡 Explanation: -+ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys. -+ The specialized function (named `lookdict_unicode` in CPython's [source](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method. -+ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function. -+ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary. That's why attempting a failed lookup has the same effect. - +- 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 * @@ -3630,6 +3769,7 @@ def dict_size(o): ``` **Output:** (Python 3.8, other Python 3 versions may vary a little) + ```py >>> o1 = SomeClass() >>> o2 = SomeClass() @@ -3666,25 +3806,25 @@ 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. -+ 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__`! - +- 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. +- A small tip, if you aim to lower your program's memory footprint: don't delete instance attributes, and make sure to initialize all attributes in your `__init__`! ### ▶ Minor Ones * -* `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) +- `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`. +- 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`. + +- Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java. -* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java. ```py >>> a = 5 >>> a @@ -3696,27 +3836,31 @@ 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. + - 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 >>> a -=- 1 >>> a 43 ``` + It is used as an alternative incrementation operator, together with another one + ```py >>> a +=+ 1 >>> a >>> 44 ``` + **💡 Explanation:** This prank comes from [Raymond Hettinger's 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. - +- Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. + ```py >>> False ** False == True True @@ -3729,8 +3873,8 @@ What makes those dictionaries become bloated? And why are newly created objects ``` **💡 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). + +- 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 @@ -3740,15 +3884,16 @@ What makes those dictionaries become bloated? And why are newly created objects **💡 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, +- 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'" - ``` + ``` + +- 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!): -* 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(""" @@ -3760,10 +3905,10 @@ What makes those dictionaries become bloated? And why are newly created objects print(dis.dis(f)) ``` - -* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) module. -* Sometimes, the `print` method might not print values immediately. For example, +- 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 @@ -3775,14 +3920,16 @@ What makes those dictionaries become bloated? And why are newly created objects 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 +- List slicing with out of the bounds indices throws no errors + ```py >>> some_list = [1, 2, 3, 4, 5] >>> some_list[111:] [] ``` -* Slicing an iterable not always creates a new object. For example, +- 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'] @@ -3792,9 +3939,9 @@ What makes those dictionaries become bloated? And why are newly created objects True ``` -* `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python. +- `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python. -* You can separate numeric literals with underscores (for better readability) from Python 3 onwards. +- You can separate numeric literals with underscores (for better readability) from Python 3 onwards. ```py >>> six_million = 6_000_000 @@ -3805,7 +3952,8 @@ What makes those dictionaries become bloated? And why are newly created objects 4027435774 ``` -* `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear +- `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear + ```py def count(s, sub): result = 0 @@ -3813,6 +3961,7 @@ What makes those dictionaries become bloated? And why are newly created objects result += (s[i:i + len(sub)] == sub) return result ``` + The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string. --- @@ -3837,15 +3986,15 @@ 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 -* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines -* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python -* https://www.python.org/doc/humor/ -* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator -* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues -* WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). +- 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 +- https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines +- https://stackoverflow.com/questions/1011431/common-pitfalls-in-python +- https://www.python.org/doc/humor/ +- https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator +- https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues +- WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). # 🎓 License @@ -3866,5 +4015,4 @@ If you like wtfpython, you can use these quick links to share it with your frien I've received a few requests for the pdf (and epub) version of wtfpython. You can add your details [here](https://form.jotform.com/221593245656057) to get them as soon as they are finished. - **That's all folks!** For upcoming content like this, you can add your email [here](https://form.jotform.com/221593598380062). From cc704cebb4ca8f31c1ccbaf9b229a6be47de3c1a Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Sun, 24 Nov 2024 15:01:40 +0300 Subject: [PATCH 171/210] #269: Update CONTRIBUTING guidelines, add PR and issue templates - Add issue templates for bugs, translations and new snippets - Add PR templates for general purpose, new snippets and translations --- .github/ISSUE_TEMPLATE/bug.md | 25 ++++++++++ .github/ISSUE_TEMPLATE/new_snippet.md | 23 +++++++++ .github/ISSUE_TEMPLATE/translation.md | 13 +++++ .github/PULL_REQUEST_TEMPLATE/new_snippet.md | 15 ++++++ .../pull_request_template.md | 13 +++++ .github/PULL_REQUEST_TEMPLATE/translation.md | 13 +++++ CONTRIBUTING.md | 48 ++++++++++--------- 7 files changed, 127 insertions(+), 23 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug.md create mode 100644 .github/ISSUE_TEMPLATE/new_snippet.md create mode 100644 .github/ISSUE_TEMPLATE/translation.md create mode 100644 .github/PULL_REQUEST_TEMPLATE/new_snippet.md create mode 100644 .github/PULL_REQUEST_TEMPLATE/pull_request_template.md create mode 100644 .github/PULL_REQUEST_TEMPLATE/translation.md diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md new file mode 100644 index 00000000..0e7241e6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -0,0 +1,25 @@ +--- +name: Bug report +about: Bug template +title: 'Fix ...' +labels: 'bug' + +--- + + +## What's wrong + + + +## How it should work? + + + +## Checklist before calling for maintainers + +* [ ] Have you checked to ensure there aren't other open [Issues](../../../issues) for the same problem? + diff --git a/.github/ISSUE_TEMPLATE/new_snippet.md b/.github/ISSUE_TEMPLATE/new_snippet.md new file mode 100644 index 00000000..09b045a2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/new_snippet.md @@ -0,0 +1,23 @@ +--- +name: New snippet +about: New snippet template +title: 'New snippet: ...' +labels: 'new snippets' +--- + + +## Description + +## Snippet preview + +## Checklist before calling for maintainers + +* [ ] Have you checked to ensure there aren't other open [Issues](../../../issues) for the same update/change? +* [ ] Have you checked that this snippet is not similar to any of the existing snippets? + +* [ ] Have you added an `Explanation` section? It shall include the reasons of changes and why you'd like us to include them + diff --git a/.github/ISSUE_TEMPLATE/translation.md b/.github/ISSUE_TEMPLATE/translation.md new file mode 100644 index 00000000..788bc4c7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/translation.md @@ -0,0 +1,13 @@ +--- +name: Translation +about: New translation template +title: 'Tranlate to ...' +labels: 'translations' + +--- + + +## Checklist before calling for maintainers + +* [ ] Have you checked to ensure there aren't other open [Issues](../../../issues) for the same tranlation? +* [ ] Do you wish to make a translation by yourself? diff --git a/.github/PULL_REQUEST_TEMPLATE/new_snippet.md b/.github/PULL_REQUEST_TEMPLATE/new_snippet.md new file mode 100644 index 00000000..5d10e7fa --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/new_snippet.md @@ -0,0 +1,15 @@ +## #(issue number): Summarize your changes + + + +Closes # (issue number) + +## Checklist before requesting a review + +- [ ] Have you written simple and understandable explanation? +- [ ] Have you added new snippet into `snippets/` with suitable name and number? +- [ ] Have you updated Table of content? (later will be done by pre-commit) +- [ ] Have you followed the guidelines in [CONTRIBUTING.md](../../CONTRIBUTING.md)? +- [ ] Have you performed a self-review? +- [ ] Have you added yourself into [CONTRIBUTORS.md](../../CONTRIBUTORS.md)? diff --git a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md new file mode 100644 index 00000000..155780d4 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md @@ -0,0 +1,13 @@ +## #(issue number): Summarize your changes + + + +Closes # (issue number) + +## Checklist before requesting a review + +- [ ] Have you followed the guidelines in [CONTRIBUTING.md](../../CONTRIBUTING.md)? +- [ ] Have you performed a self-review? +- [ ] Have you added yourself into [CONTRIBUTORS.md](../../CONTRIBUTORS.md)? + diff --git a/.github/PULL_REQUEST_TEMPLATE/translation.md b/.github/PULL_REQUEST_TEMPLATE/translation.md new file mode 100644 index 00000000..990a389d --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/translation.md @@ -0,0 +1,13 @@ +## #(issue number): Translate to ... + + + +Closes # (issue number) + +## Checklist before requesting a review + +- [ ] Have you fetched the latest `master` branch? +- [ ] Have you translated all snippets? +- [ ] Have you followed the guidelines in [CONTRIBUTING.md](../../CONTRIBUTING.md)? +- [ ] Have you performed a self-review? +- [ ] Have you added yourself into [CONTRIBUTORS.md](../../CONTRIBUTORS.md)? diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dd9049d4..771ece8a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,19 @@ +# Contributing + +## Getting Started + +Contributions are made to this repo via Issues and Pull Requests (PRs). A few general guidelines that cover both: + +- Search for existing Issues and PRs before creating your own. +- We work hard to makes sure issues are handled in a timely manner but, depending on the impact, it could take a while to investigate the root cause. A friendly ping in the comment thread to the submitter or a contributor can help draw attention if your issue is blocking. + +## Issues + All kinds of patches are welcome. Feel free to even suggest some catchy and funny titles for the existing Examples. The goal is to make this collection as interesting to read as possible. Here are a few ways through which you can contribute, -- If you are interested in translating the project to another language (some people have done that in the past), please feel free to open up an issue, and let me know if you need any kind of help. +- If you are interested in translating the project to another language, please feel free to open up an issue using `translation` template, and let me know if you need any kind of help. - If the changes you suggest are significant, filing an issue before submitting the actual patch will be appreciated. If you'd like to work on the issue (highly encouraged), you can mention that you're interested in working on it while creating the issue and get assigned to it. -- If you're adding a new example, it is highly recommended to create an issue to discuss it before submitting a patch. You can use the following template for adding a new example: +- If you're adding a new example, it is highly recommended to create an issue using `new_snippet` template to discuss it before submitting a patch. You can use the following template for adding a new example:
 ### ▶ Some fancy Title *
@@ -33,31 +44,22 @@ Probably unexpected output
 ```
 
+## Pull requests -Few things that you can consider while writing an example, - -- If you are choosing to submit a new example without creating an issue and discussing, please check the project to make sure there aren't similar examples already. - Try to be consistent with the namings and the values you use with the variables. For instance, most variable names in the project are along the lines of `some_string`, `some_list`, `some_dict`, etc. You'd see a lot of `x`s for single letter variable names, and `"wtf"` as values for strings. There's no strictly enforced scheme in the project as such, but you can take a glance at other examples to get a gist. - Try to be as creative as possible to add that element of "surprise" in the setting up part of an example. Sometimes this may mean writing a snippet a sane programmer would never write. - Also, feel free to add your name to the [contributors list](/CONTRIBUTORS.md). -**Some FAQs** - - What is is this after every snippet title (###) in the README: ? Should it be added manually or can it be ignored when creating new snippets? - -That's a random UUID, it is used to keep identify the examples across multiple translations of the project. As a contributor, you don't have to worry about behind the scenes of how it is used, you just have to add a new random UUID to new examples in that format. - - Where should new snippets be added? Top/bottom of the section, doesn't ? - -There are multiple things that are considered to decide the order (the dependency on the other examples, difficulty level, category, etc). I'd suggest simply adding the new example at the bottom of a section you find more fitting (or just add it to the Miscellaneous section). Its order will be taken care of in future revisions. - - What's the difference between the sections (the first two feel very similar)? - -The section "Strain your brain" contains more contrived examples that you may not really encounter in real life, whereas the section "Slippery Slopes" contains examples that have the potential to be encountered more frequently while programming. - - Before the table of contents it says that markdown-toc -i README.md --maxdepth 3 was used to create it. The pip package markdown-toc does not contain either -i or --maxdepth flags. Which package is meant, or what version of that package? - Should the new table of contents entry for the snippet be created with the above command or created manually (in case the above command does more than only add the entry)? - -We use the [markdown-toc](https://www.npmjs.com/package/markdown-toc) npm package to generate ToC. It has some issues with special characters though (I'm not sure if it's fixed yet). More often than not, I just end up inserting the toc link manually at the right place. The tool is handy when I have to big reordering, otherwise just updating toc manually is more convenient imo. +## Common questions + +- What is is this after every snippet title (###) in the README: ? Should it be added manually or can it be ignored when creating new snippets? + - That's a random UUID, it is used to keep identify the examples across multiple translations of the project. As a contributor, you don't have to worry about behind the scenes of how it is used, you just have to add a new random UUID to new examples in that format. +- Where should new snippets be added? Top/bottom of the section, doesn't ? +- There are multiple things that are considered to decide the order (the dependency on the other examples, difficulty level, category, etc). I'd suggest simply adding the new example at the bottom of a section you find more fitting (or just add it to the Miscellaneous section). Its order will be taken care of in future revisions. +- What's the difference between the sections (the first two feel very similar)? + - The section "Strain your brain" contains more contrived examples that you may not really encounter in real life, whereas the section "Slippery Slopes" contains examples that have the potential to be encountered more frequently while programming. +- Before the table of contents it says that `markdown-toc -i README.md --maxdepth 3` was used to create it. The pip package `markdown-toc` does not contain neither `-i` nor `--maxdepth` flags. Which package is meant, or what version of that package? Should the new table of contents entry for the snippet be created with the above command or created manually (in case the above command does more than only add the entry)? + - `markdown-toc` will be replaced in the near future, follow the [issue](https://github.com/satwikkansal/wtfpython/issues/351) to check the progress. + - We use the [markdown-toc](https://www.npmjs.com/package/markdown-toc) npm package to generate ToC. It has some issues with special characters though (I'm not sure if it's fixed yet). More often than not, I just end up inserting the toc link manually at the right place. The tool is handy when I have to big reordering, otherwise just updating toc manually is more convenient imo. If you have any questions feel free to ask on [this issue](https://github.com/satwikkansal/wtfpython/issues/269) (thanks to [@LiquidFun](https://github.com/LiquidFun) for starting it). From 84e757692b54ae805656652438670c4c54ba9c81 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 26 Nov 2024 09:10:27 +0300 Subject: [PATCH 172/210] #269: Change issues link and fix typos in Github issue templates --- .github/ISSUE_TEMPLATE/bug.md | 4 ++-- .github/ISSUE_TEMPLATE/new_snippet.md | 8 ++++---- .github/ISSUE_TEMPLATE/translation.md | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md index 0e7241e6..2162d315 100644 --- a/.github/ISSUE_TEMPLATE/bug.md +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -1,6 +1,6 @@ --- name: Bug report -about: Bug template +about: Report a problem and provide necessary context title: 'Fix ...' labels: 'bug' @@ -21,5 +21,5 @@ But, we will need some information about what's wrong to help you. ## Checklist before calling for maintainers -* [ ] Have you checked to ensure there aren't other open [Issues](../../../issues) for the same problem? +* [ ] Have you checked to ensure there aren't other open [Issues](../../issues) for the same problem? diff --git a/.github/ISSUE_TEMPLATE/new_snippet.md b/.github/ISSUE_TEMPLATE/new_snippet.md index 09b045a2..47fc83c1 100644 --- a/.github/ISSUE_TEMPLATE/new_snippet.md +++ b/.github/ISSUE_TEMPLATE/new_snippet.md @@ -1,6 +1,6 @@ --- name: New snippet -about: New snippet template +about: Suggest new gotcha and try to explain it title: 'New snippet: ...' labels: 'new snippets' --- @@ -16,8 +16,8 @@ But, we will need some information and (optionally) explanation to accept it. ## Checklist before calling for maintainers -* [ ] Have you checked to ensure there aren't other open [Issues](../../../issues) for the same update/change? +* [ ] Have you checked to ensure there aren't other open [Issues](../../issues) for the same update/change? * [ ] Have you checked that this snippet is not similar to any of the existing snippets? - -* [ ] Have you added an `Explanation` section? It shall include the reasons of changes and why you'd like us to include them + +* [ ] Have you added an `Explanation` section? It shall include the reasons for changes and why you'd like us to include them diff --git a/.github/ISSUE_TEMPLATE/translation.md b/.github/ISSUE_TEMPLATE/translation.md index 788bc4c7..e80b7310 100644 --- a/.github/ISSUE_TEMPLATE/translation.md +++ b/.github/ISSUE_TEMPLATE/translation.md @@ -1,7 +1,7 @@ --- name: Translation -about: New translation template -title: 'Tranlate to ...' +about: Request a new traslation and start working on it (if possible) +title: 'Translate to ...' labels: 'translations' --- @@ -9,5 +9,5 @@ labels: 'translations' ## Checklist before calling for maintainers -* [ ] Have you checked to ensure there aren't other open [Issues](../../../issues) for the same tranlation? +* [ ] Have you checked to ensure there aren't other open [Issues](../../issues) for the same translation? * [ ] Do you wish to make a translation by yourself? From 684650beec732dd1024cbcb105a4a9b3b73add3c Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 26 Nov 2024 16:05:18 +0300 Subject: [PATCH 173/210] Rename common PR template, fix links in PR and issue templates --- .github/ISSUE_TEMPLATE/bug.md | 2 +- .github/ISSUE_TEMPLATE/new_snippet.md | 2 +- .github/ISSUE_TEMPLATE/translation.md | 2 +- .../{pull_request_template.md => common.md} | 4 ++-- .github/PULL_REQUEST_TEMPLATE/new_snippet.md | 4 ++-- .github/PULL_REQUEST_TEMPLATE/translation.md | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) rename .github/PULL_REQUEST_TEMPLATE/{pull_request_template.md => common.md} (69%) diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md index 2162d315..2cfa7778 100644 --- a/.github/ISSUE_TEMPLATE/bug.md +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -21,5 +21,5 @@ But, we will need some information about what's wrong to help you. ## Checklist before calling for maintainers -* [ ] Have you checked to ensure there aren't other open [Issues](../../issues) for the same problem? +* [ ] Have you checked to ensure there aren't other open [Issues](../issues) for the same problem? diff --git a/.github/ISSUE_TEMPLATE/new_snippet.md b/.github/ISSUE_TEMPLATE/new_snippet.md index 47fc83c1..6bb19dc9 100644 --- a/.github/ISSUE_TEMPLATE/new_snippet.md +++ b/.github/ISSUE_TEMPLATE/new_snippet.md @@ -16,7 +16,7 @@ But, we will need some information and (optionally) explanation to accept it. ## Checklist before calling for maintainers -* [ ] Have you checked to ensure there aren't other open [Issues](../../issues) for the same update/change? +* [ ] Have you checked to ensure there aren't other open [Issues](../issues) for the same update/change? * [ ] Have you checked that this snippet is not similar to any of the existing snippets? * [ ] Have you added an `Explanation` section? It shall include the reasons for changes and why you'd like us to include them diff --git a/.github/ISSUE_TEMPLATE/translation.md b/.github/ISSUE_TEMPLATE/translation.md index e80b7310..37ea4c3a 100644 --- a/.github/ISSUE_TEMPLATE/translation.md +++ b/.github/ISSUE_TEMPLATE/translation.md @@ -9,5 +9,5 @@ labels: 'translations' ## Checklist before calling for maintainers -* [ ] Have you checked to ensure there aren't other open [Issues](../../issues) for the same translation? +* [ ] Have you checked to ensure there aren't other open [Issues](../issues) for the same translation? * [ ] Do you wish to make a translation by yourself? diff --git a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/common.md similarity index 69% rename from .github/PULL_REQUEST_TEMPLATE/pull_request_template.md rename to .github/PULL_REQUEST_TEMPLATE/common.md index 155780d4..ab9f34ad 100644 --- a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md +++ b/.github/PULL_REQUEST_TEMPLATE/common.md @@ -7,7 +7,7 @@ Closes # (issue number) ## Checklist before requesting a review -- [ ] Have you followed the guidelines in [CONTRIBUTING.md](../../CONTRIBUTING.md)? +- [ ] Have you followed the guidelines in [CONTRIBUTING.md](../CONTRIBUTING.md)? - [ ] Have you performed a self-review? -- [ ] Have you added yourself into [CONTRIBUTORS.md](../../CONTRIBUTORS.md)? +- [ ] Have you added yourself into [CONTRIBUTORS.md](../CONTRIBUTORS.md)? diff --git a/.github/PULL_REQUEST_TEMPLATE/new_snippet.md b/.github/PULL_REQUEST_TEMPLATE/new_snippet.md index 5d10e7fa..dab5816f 100644 --- a/.github/PULL_REQUEST_TEMPLATE/new_snippet.md +++ b/.github/PULL_REQUEST_TEMPLATE/new_snippet.md @@ -10,6 +10,6 @@ Closes # (issue number) - [ ] Have you written simple and understandable explanation? - [ ] Have you added new snippet into `snippets/` with suitable name and number? - [ ] Have you updated Table of content? (later will be done by pre-commit) -- [ ] Have you followed the guidelines in [CONTRIBUTING.md](../../CONTRIBUTING.md)? +- [ ] Have you followed the guidelines in [CONTRIBUTING.md](../CONTRIBUTING.md)? - [ ] Have you performed a self-review? -- [ ] Have you added yourself into [CONTRIBUTORS.md](../../CONTRIBUTORS.md)? +- [ ] Have you added yourself into [CONTRIBUTORS.md](../CONTRIBUTORS.md)? diff --git a/.github/PULL_REQUEST_TEMPLATE/translation.md b/.github/PULL_REQUEST_TEMPLATE/translation.md index 990a389d..74f88005 100644 --- a/.github/PULL_REQUEST_TEMPLATE/translation.md +++ b/.github/PULL_REQUEST_TEMPLATE/translation.md @@ -8,6 +8,6 @@ Closes # (issue number) - [ ] Have you fetched the latest `master` branch? - [ ] Have you translated all snippets? -- [ ] Have you followed the guidelines in [CONTRIBUTING.md](../../CONTRIBUTING.md)? +- [ ] Have you followed the guidelines in [CONTRIBUTING.md](../CONTRIBUTING.md)? - [ ] Have you performed a self-review? -- [ ] Have you added yourself into [CONTRIBUTORS.md](../../CONTRIBUTORS.md)? +- [ ] Have you added yourself into [CONTRIBUTORS.md](../CONTRIBUTORS.md)? From de24d18af5fb96960ed7220a6f673bb17b732b0a Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 14 Jan 2025 11:54:28 +0300 Subject: [PATCH 174/210] Fix logical typo in section How not to use operator, Russian translation --- translations/ru-russian/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/translations/ru-russian/README.md b/translations/ru-russian/README.md index c80fe2a4..03fc771c 100644 --- a/translations/ru-russian/README.md +++ b/translations/ru-russian/README.md @@ -559,7 +559,7 @@ False Интерпретатор не понимает, что до выполнения выражения `y = 257` целое число со значением `257` уже создано, и поэтому он продолжает создавать другой объект в памяти. -Подобная оптимизация применима и к другим **изменяемым** объектам, таким как пустые кортежи. Поскольку списки являются изменяемыми, поэтому `[] is []` вернет `False`, а `() is ()` вернет `True`. Это объясняет наш второй фрагмент. Перейдем к третьему, +Подобная оптимизация применима и к другим **неизменяемым** объектам, таким как пустые кортежи. Поскольку списки являются изменяемыми, поэтому `[] is []` вернет `False`, а `() is ()` вернет `True`. Это объясняет наш второй фрагмент. Перейдем к третьему, **И `a`, и `b` ссылаются на один и тот же объект при инициализации одним и тем же значением в одной и той же строке**. From b7184bc2113ce1f4de5bbfc0bff042d242948b89 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Thu, 27 Feb 2025 11:20:10 +0100 Subject: [PATCH 175/210] Add persian translations boilerplate --- translations/fa-farsi/README.md | 3932 +++++++++++++++++++++++++++++++ 1 file changed, 3932 insertions(+) create mode 100644 translations/fa-farsi/README.md diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md new file mode 100644 index 00000000..6d89f3bb --- /dev/null +++ b/translations/fa-farsi/README.md @@ -0,0 +1,3932 @@ +

+ + + + Shows a wtfpython logo. + +

+

What the f*ck Python! 😱

+

کاوش و درک پایتون از طریق تکه‌های کد شگفت‌انگیز.

+ + +ترجمه‌ها: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) + +Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) + +Python, being a beautifully designed high-level and interpreter-based programming language, provides us with many features for the programmer's comfort. But sometimes, the outcomes of a Python snippet may not seem obvious at first sight. + +Here's a fun project attempting to explain what exactly is happening under the hood for some counter-intuitive snippets and lesser-known features in Python. + +While some of the examples you see below may not be WTFs in the truest sense, but they'll reveal some of the interesting parts of Python that you might be unaware of. I find it a nice way to learn the internals of a programming language, and I believe that you'll find it interesting too! + +If you're an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt. You may have already experienced some of them before, and I might be able to revive sweet old memories of yours! :sweat_smile: + +PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) (the examples marked with asterisk are the ones added in the latest major revision). + +So, here we go... + +# Table of Contents + + + + + +- [Table of Contents](#table-of-contents) +- [Structure of the Examples](#structure-of-the-examples) +- [Usage](#usage) +- [👀 Examples](#-examples) + - [Section: Strain your brain!](#section-strain-your-brain) + - [▶ First things first! \*](#-first-things-first-) + - [💡 Explanation](#-explanation) + - [▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند](#-بعضی-وقتها-رشتهها-میتوانند-دردسرساز-شوند) + - [💡 Explanation:](#-explanation-1) + - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) + - [💡 Explanation:](#-explanation-2) + - [▶ How not to use `is` operator](#-how-not-to-use-is-operator) + - [💡 Explanation:](#-explanation-3) + - [▶ Hash brownies](#-hash-brownies) + - [💡 Explanation](#-explanation-4) + - [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) + - [💡 Explanation:](#-explanation-5) + - [▶ Disorder within order \*](#-disorder-within-order-) + - [💡 Explanation:](#-explanation-6) + - [▶ Keep trying... \*](#-keep-trying-) + - [💡 Explanation:](#-explanation-7) + - [▶ For what?](#-for-what) + - [💡 Explanation:](#-explanation-8) + - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) + - [💡 Explanation](#-explanation-9) + - [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) + - [💡 Explanation](#-explanation-10) + - [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) + - [💡 Explanation:](#-explanation-11) + - [▶ Schrödinger's variable \*](#-schrödingers-variable-) + - [💡 Explanation:](#-explanation-12) + - [▶ The chicken-egg problem \*](#-the-chicken-egg-problem-) + - [💡 Explanation](#-explanation-13) + - [▶ Subclass relationships](#-subclass-relationships) + - [💡 Explanation:](#-explanation-14) + - [▶ Methods equality and identity](#-methods-equality-and-identity) + - [💡 Explanation](#-explanation-15) + - [▶ All-true-ation \*](#-all-true-ation-) + - [💡 Explanation:](#-explanation-16) + - [💡 Explanation:](#-explanation-17) + - [▶ Strings and the backslashes](#-strings-and-the-backslashes) + - [💡 Explanation](#-explanation-18) + - [▶ not knot!](#-not-knot) + - [💡 Explanation:](#-explanation-19) + - [▶ Half triple-quoted strings](#-half-triple-quoted-strings) + - [💡 Explanation:](#-explanation-20) + - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) + - [💡 Explanation:](#-explanation-21) + - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) + - [💡 Explanation:](#-explanation-22) + - [▶ yielding None](#-yielding-none) + - [💡 Explanation:](#-explanation-23) + - [▶ Yielding from... return! \*](#-yielding-from-return-) + - [💡 Explanation:](#-explanation-24) + - [▶ Nan-reflexivity \*](#-nan-reflexivity-) + - [💡 Explanation:](#-explanation-25) + - [▶ Mutating the immutable!](#-mutating-the-immutable) + - [💡 Explanation:](#-explanation-26) + - [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) + - [💡 Explanation:](#-explanation-27) + - [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) + - [💡 Explanation:](#-explanation-28) + - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) + - [💡 Explanation:](#-explanation-29) + - [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) + - [💡 Explanation:](#-explanation-30) + - [Section: Slippery Slopes](#section-slippery-slopes) + - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + - [💡 Explanation:](#-explanation-31) + - [▶ Stubborn `del` operation](#-stubborn-del-operation) + - [💡 Explanation:](#-explanation-32) + - [▶ The out of scope variable](#-the-out-of-scope-variable) + - [💡 Explanation:](#-explanation-33) + - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) + - [💡 Explanation:](#-explanation-34) + - [▶ Lossy zip of iterators \*](#-lossy-zip-of-iterators-) + - [💡 Explanation:](#-explanation-35) + - [▶ Loop variables leaking out!](#-loop-variables-leaking-out) + - [💡 Explanation:](#-explanation-36) + - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) + - [💡 Explanation:](#-explanation-37) + - [▶ Catching the Exceptions](#-catching-the-exceptions) + - [💡 Explanation](#-explanation-38) + - [▶ Same operands, different story!](#-same-operands-different-story) + - [💡 Explanation:](#-explanation-39) + - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) + - [💡 Explanation](#-explanation-40) + - [▶ Rounding like a banker \*](#-rounding-like-a-banker-) + - [💡 Explanation:](#-explanation-41) + - [▶ Needles in a Haystack \*](#-needles-in-a-haystack-) + - [💡 Explanation:](#-explanation-42) + - [▶ Splitsies \*](#-splitsies-) + - [💡 Explanation:](#-explanation-43) + - [▶ Wild imports \*](#-wild-imports-) + - [💡 Explanation:](#-explanation-44) + - [▶ All sorted? \*](#-all-sorted-) + - [💡 Explanation:](#-explanation-45) + - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) + - [💡 Explanation:](#-explanation-46) + - [Section: The Hidden treasures!](#section-the-hidden-treasures) + - [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) + - [💡 Explanation:](#-explanation-47) + - [▶ `goto`, but why?](#-goto-but-why) + - [💡 Explanation:](#-explanation-48) + - [▶ Brace yourself!](#-brace-yourself) + - [💡 Explanation:](#-explanation-49) + - [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) + - [💡 Explanation:](#-explanation-50) + - [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) + - [💡 Explanation:](#-explanation-51) + - [▶ Yes, it exists!](#-yes-it-exists) + - [💡 Explanation:](#-explanation-52) + - [▶ Ellipsis \*](#-ellipsis-) + - [💡 Explanation](#-explanation-53) + - [▶ Inpinity](#-inpinity) + - [💡 Explanation:](#-explanation-54) + - [▶ Let's mangle](#-lets-mangle) + - [💡 Explanation:](#-explanation-55) + - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) + - [▶ Skipping lines?](#-skipping-lines) + - [💡 Explanation](#-explanation-56) + - [▶ Teleportation](#-teleportation) + - [💡 Explanation:](#-explanation-57) + - [▶ Well, something is fishy...](#-well-something-is-fishy) + - [💡 Explanation](#-explanation-58) + - [Section: Miscellaneous](#section-miscellaneous) + - [▶ `+=` is faster](#--is-faster) + - [💡 Explanation:](#-explanation-59) + - [▶ Let's make a giant string!](#-lets-make-a-giant-string) + - [💡 Explanation](#-explanation-60) + - [▶ Slowing down `dict` lookups \*](#-slowing-down-dict-lookups-) + - [💡 Explanation:](#-explanation-61) + - [▶ Bloating instance `dict`s \*](#-bloating-instance-dicts-) + - [💡 Explanation:](#-explanation-62) + - [▶ Minor Ones \*](#-minor-ones-) +- [Contributing](#contributing) +- [Acknowledgements](#acknowledgements) + - [Some nice Links!](#some-nice-links) +- [🎓 License](#-license) + - [Surprise your friends as well!](#surprise-your-friends-as-well) + - [Need a pdf version?](#need-a-pdf-version) + + + +# Structure of the Examples + +All the examples are structured like below: + +> ### ▶ Some fancy Title +> +> ```py +> # Set up the code. +> # Preparation for the magic... +> ``` +> +> **Output (Python version(s)):** +> +> ```py +> >>> triggering_statement +> Some unexpected output +> ``` +> (Optional): One line describing the unexpected output. +> +> +> #### 💡 Explanation: +> +> * Brief explanation of what's happening and why is it happening. +> ```py +> # Set up code +> # More examples for further clarification (if necessary) +> ``` +> **Output (Python version(s)):** +> +> ```py +> >>> trigger # some example that makes it easy to unveil the magic +> # some justified output +> ``` + +**Note:** All the examples are tested on Python 3.5.2 interactive interpreter, and they should work for all the Python versions unless explicitly specified before the output. + +# Usage + +A nice way to get the most out of these examples, in my opinion, is to read them in sequential order, and for every example: +- Carefully read the initial code for setting up the example. If you're an experienced Python programmer, you'll successfully anticipate what's going to happen next most of the time. +- Read the output snippets and, + + Check if the outputs are the same as you'd expect. + + Make sure if you know the exact reason behind the output being the way it is. + - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfpython/issues/new)). + - If yes, give a gentle pat on your back, and you may skip to the next example. + +--- + +# 👀 Examples + +## Section: Strain your brain! + +### ▶ First things first! * + + + + +For some reason, the Python 3.8's "Walrus" operator (`:=`) has become quite popular. Let's check it out, + +1\. + +```py +# Python version 3.8+ + +>>> a = "wtf_walrus" +>>> a +'wtf_walrus' + +>>> a := "wtf_walrus" +File "", line 1 + a := "wtf_walrus" + ^ +SyntaxError: invalid syntax + +>>> (a := "wtf_walrus") # This works though +'wtf_walrus' +>>> a +'wtf_walrus' +``` + +2 \. + +```py +# Python version 3.8+ + +>>> a = 6, 9 +>>> a +(6, 9) + +>>> (a := 6, 9) +(6, 9) +>>> a +6 + +>>> a, b = 6, 9 # Typical unpacking +>>> a, b +(6, 9) +>>> (a, b = 16, 19) # Oops + File "", line 1 + (a, b = 16, 19) + ^ +SyntaxError: invalid syntax + +>>> (a, b := 16, 19) # This prints out a weird 3-tuple +(6, 16, 19) + +>>> a # a is still unchanged? +6 + +>>> b +16 +``` + + + +#### 💡 Explanation + +**Quick walrus operator refresher** + +The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression. + +```py +def some_func(): + # Assume some expensive computation here + # time.sleep(1000) + return 5 + +# So instead of, +if some_func(): + print(some_func()) # Which is bad practice since computation is happening twice + +# or +a = some_func() +if a: + print(a) + +# Now you can concisely write +if a := some_func(): + print(a) +``` + +**Output (> 3.8):** + +```py +5 +5 +5 +``` + +This 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`. + +- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. + +- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, + + - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6') + + ```py + >>> (a := 6, 9) == ((a := 6), 9) + True + >>> x = (a := 696, 9) + >>> x + (696, 9) + >>> x[0] is a # Both reference same memory location + True + ``` + + - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. + +--- + +### ▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند + + +1\. + +```py +>>> a = "some_string" +>>> id(a) +140420665652016 +>>> id("some" + "_" + "string") # دقت کنید که هردو ID یکی هستند. +140420665652016 +``` + +2\. +```py +>>> a = "wtf" +>>> b = "wtf" +>>> a is b +True + +>>> a = "wtf!" +>>> b = "wtf!" +>>> a is b +False + +``` + +3\. + +```py +>>> a, b = "wtf!", "wtf!" +>>> a is b # همه‌ی نسخه‌ها به جز 3.7.x +True + +>>> a = "wtf!"; b = "wtf!" +>>> a is b # ممکن است True یا False باشد بسته به جایی که آن را اجرا می‌کنید (python shell / ipython / به‌صورت اسکریپت) +False +``` + +```py +# این بار در فایل some_file.py +a = "wtf!" +b = "wtf!" +print(a is b) + +# موقع اجرای ماژول، True را چاپ می‌کند! +``` + +4\. + +**خروجی (< Python3.7 )** + +```py +>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' +True +>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' +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: + * All length 0 and length 1 strings are interned. + * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned) + * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) +

+ + + + Shows a string interning process. + +

+ ++ 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. ++ 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 +>>> False == (False in [False]) # makes sense +False +>>> False == False in [False] # now what? +True + +>>> True is False == False +False +>>> False is False is False +True + +>>> 1 > 0 < 1 +True +>>> (1 > 0) < 1 +False +>>> 1 > (0 < 1) +False +``` + +#### 💡 Explanation: + +As per https://docs.python.org/3/reference/expressions.html#comparisons + +> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once. + +While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. + +* `False is False is False` is equivalent to `(False is False) and (False is False)` +* `True is False == False` is equivalent to `(True is False) and (False == False)` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. +* `1 > 0 < 1` is equivalent to `(1 > 0) and (0 < 1)` which evaluates to `True`. +* The expression `(1 > 0) < 1` is equivalent to `True < 1` and + ```py + >>> int(True) + 1 + >>> True + 1 #not relevant for this example, but just for fun + 2 + ``` + So, `1 < 1` evaluates to `False` + +--- + +### ▶ How not to use `is` operator + +The following is a very famous example present all over the internet. + +1\. + +```py +>>> a = 256 +>>> b = 256 +>>> a is b +True + +>>> a = 257 +>>> b = 257 +>>> a is b +False +``` + +2\. + +```py +>>> a = [] +>>> b = [] +>>> a is b +False + +>>> a = tuple() +>>> b = tuple() +>>> a is b +True +``` + +3\. +**Output** + +```py +>>> a, b = 257, 257 +>>> a is b +True +``` + +**Output (Python 3.7.x specifically)** + +```py +>>> a, b = 257, 257 +>>> a is b +False +``` + +#### 💡 Explanation: + +**The difference between `is` and `==`** + +* `is` operator checks if both the operands refer to the same object (i.e., it checks if the identity of the operands matches or not). +* `==` operator compares the values of both the operands and checks if they are the same. +* So `is` is for reference equality and `==` is for value equality. An example to clear things up, + ```py + >>> class A: pass + >>> A() is A() # These are two empty objects at two different memory locations. + False + ``` + +**`256` is an existing object but `257` isn't** + +When you start up python the numbers from `-5` to `256` will be allocated. These numbers are used a lot, so it makes sense just to have them ready. + +Quoting from https://docs.python.org/3/c-api/long.html +> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behavior of Python, in this case, is undefined. :-) + +```py +>>> id(256) +10922528 +>>> a = 256 +>>> b = 256 +>>> id(a) +10922528 +>>> id(b) +10922528 +>>> id(257) +140084850247312 +>>> x = 257 +>>> y = 257 +>>> id(x) +140084850247440 +>>> id(y) +140084850247344 +``` + +Here the interpreter isn't smart enough while executing `y = 257` to recognize that we've already created an integer of the value `257,` and so it goes on to create another object in the memory. + +Similar optimization applies to other **immutable** objects like empty tuples as well. Since lists are mutable, that's why `[] is []` will return `False` and `() is ()` will return `True`. This explains our second snippet. Let's move on to the third one, + +**Both `a` and `b` refer to the same object when initialized with same value in the same line.** + +**Output** + +```py +>>> a, b = 257, 257 +>>> id(a) +140640774013296 +>>> id(b) +140640774013296 +>>> a = 257 +>>> b = 257 +>>> id(a) +140640774013392 +>>> id(b) +140640774013488 +``` + +* When a and b are set to `257` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already `257` as an object. + +* It's a compiler optimization and specifically applies to the interactive environment. When you enter two lines in a live interpreter, they're compiled separately, therefore optimized separately. If you were to try this example in a `.py` file, you would not see the same behavior, because the file is compiled all at once. This optimization is not limited to integers, it works for other immutable data types like strings (check the "Strings are tricky example") and floats as well, + + ```py + >>> a, b = 257.0, 257.0 + >>> a is b + True + ``` + +* Why didn't this work for Python 3.7? The abstract reason is because such compiler optimizations are implementation specific (i.e. may change with version, OS, etc). I'm still figuring out what exact implementation change cause the issue, you can check out this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for updates. + +--- + + +### ▶ Hash brownies + +1\. +```py +some_dict = {} +some_dict[5.5] = "JavaScript" +some_dict[5.0] = "Ruby" +some_dict[5] = "Python" +``` + +**Output:** + +```py +>>> some_dict[5.5] +"JavaScript" +>>> some_dict[5.0] # "Python" destroyed the existence of "Ruby"? +"Python" +>>> some_dict[5] +"Python" + +>>> complex_five = 5 + 0j +>>> type(complex_five) +complex +>>> some_dict[complex_five] +"Python" +``` + +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`): + ```py + >>> 5 == 5.0 == 5 + 0j + True + >>> 5 is not 5.0 is not 5 + 0j + True + >>> some_dict = {} + >>> some_dict[5.0] = "Ruby" + >>> 5.0 in some_dict + True + >>> (5 in some_dict) and (5 + 0j in some_dict) + True + ``` +* This applies when setting an item as well. So when you do `some_dict[5] = "Python"`, Python finds the existing item with equivalent key `5.0 -> "Ruby"`, overwrites its value in place, and leaves the original key alone. + ```py + >>> some_dict + {5.0: 'Ruby'} + >>> some_dict[5] = "Python" + >>> some_dict + {5.0: 'Python'} + ``` +* So how can we update the key to `5` (instead of `5.0`)? We can't actually do this update in place, but what we can do is first delete the key (`del some_dict[5.0]`), and then set it (`some_dict[5]`) to get the integer `5` as the key instead of floating `5.0`, though this should be needed in rare cases. + +* How did Python find `5` in a dictionary containing `5.0`? Python does this in constant time without having to scan through every item by using hash functions. When Python looks up a key `foo` in a dict, it first computes `hash(foo)` (which runs in constant-time). Since in Python it is required that objects that compare equal also have the same hash value ([docs](https://docs.python.org/3/reference/datamodel.html#object.__hash__) here), `5`, `5.0`, and `5 + 0j` have the same hash value. + ```py + >>> 5 == 5.0 == 5 + 0j + True + >>> hash(5) == hash(5.0) == hash(5 + 0j) + 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.) + +--- + +### ▶ Deep down, we're all the same. + +```py +class WTF: + pass +``` + +**Output:** +```py +>>> WTF() == WTF() # two different instances can't be equal +False +>>> WTF() is WTF() # identities are also different +False +>>> hash(WTF()) == hash(WTF()) # hashes _should_ be different as well +True +>>> id(WTF()) == id(WTF()) +True +``` + +#### 💡 Explanation: + +* When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed. +* When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same. +* So, the object's id is unique only for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id. +* But why did the `is` operator evaluate to `False`? Let's see with this snippet. + ```py + class WTF(object): + def __init__(self): print("I") + def __del__(self): print("D") + ``` + + **Output:** + ```py + >>> WTF() is WTF() + I + I + D + D + False + >>> id(WTF()) == id(WTF()) + I + D + I + D + True + ``` + As you may observe, the order in which the objects are destroyed is what made all the difference here. + +--- + +### ▶ Disorder within order * + +```py +from collections import OrderedDict + +dictionary = dict() +dictionary[1] = 'a'; dictionary[2] = 'b'; + +ordered_dict = OrderedDict() +ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; + +another_ordered_dict = OrderedDict() +another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; + +class DictWithHash(dict): + """ + A dict that also implements __hash__ magic. + """ + __hash__ = lambda self: 0 + +class OrderedDictWithHash(OrderedDict): + """ + An OrderedDict that also implements __hash__ magic. + """ + __hash__ = lambda self: 0 +``` + +**Output** +```py +>>> dictionary == ordered_dict # If a == b +True +>>> dictionary == another_ordered_dict # and b == c +True +>>> ordered_dict == another_ordered_dict # then why isn't c == a ?? +False + +# We all know that a set consists of only unique elements, +# let's try making a set of these dictionaries and see what happens... + +>>> len({dictionary, ordered_dict, another_ordered_dict}) +Traceback (most recent call last): + File "", line 1, in +TypeError: unhashable type: 'dict' + +# Makes sense since dict don't have __hash__ implemented, let's use +# our wrapper classes. +>>> dictionary = DictWithHash() +>>> dictionary[1] = 'a'; dictionary[2] = 'b'; +>>> ordered_dict = OrderedDictWithHash() +>>> ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; +>>> another_ordered_dict = OrderedDictWithHash() +>>> another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; +>>> len({dictionary, ordered_dict, another_ordered_dict}) +1 +>>> len({ordered_dict, another_ordered_dict, dictionary}) # changing the order +2 +``` + +What is going on here? + +#### 💡 Explanation: + +- The reason why intransitive equality didn't hold among `dictionary`, `ordered_dict` and `another_ordered_dict` is because of the way `__eq__` method is implemented in `OrderedDict` class. From the [docs](https://docs.python.org/3/library/collections.html#ordereddict-objects) + + > Equality tests between OrderedDict objects are order-sensitive and are implemented as `list(od1.items())==list(od2.items())`. Equality tests between `OrderedDict` objects and other Mapping objects are order-insensitive like regular dictionaries. +- The reason for this equality 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 + + >>> another_set = set() + >>> another_set.add(ordered_dict) + >>> another_ordered_dict in another_set + False + >>> another_set.add(another_ordered_dict) + >>> len(another_set) + 2 + >>> dictionary in another_set + True + >>> another_set.add(another_ordered_dict) + >>> len(another_set) + 2 + ``` + So the inconsistency is due to `another_ordered_dict in another_set` being `False` because `ordered_dict` was already present in `another_set` and as observed before, `ordered_dict == another_ordered_dict` is `False`. + +--- + +### ▶ Keep trying... * + +```py +def some_func(): + try: + return 'from_try' + finally: + return 'from_finally' + +def another_func(): + for _ in range(3): + try: + continue + finally: + print("Finally!") + +def one_more_func(): # A gotcha! + try: + for i in range(3): + try: + 1 / i + except ZeroDivisionError: + # Let's throw it here and handle it outside for loop + raise ZeroDivisionError("A trivial divide by zero error") + finally: + print("Iteration", i) + break + except ZeroDivisionError as e: + print("Zero division error occurred", e) +``` + +**Output:** + +```py +>>> some_func() +'from_finally' + +>>> another_func() +Finally! +Finally! +Finally! + +>>> 1 / 0 +Traceback (most recent call last): + File "", line 1, in +ZeroDivisionError: division by zero + +>>> one_more_func() +Iteration 0 + +``` + +#### 💡 Explanation: + +- When a `return`, `break` or `continue` statement is executed in the `try` suite of a "try…finally" statement, the `finally` clause is also executed on the way out. +- The return value of a function is determined by the last `return` statement executed. Since the `finally` clause always executes, a `return` statement executed in the `finally` clause will always be the last one executed. +- The caveat here is, if the finally clause executes a `return` or `break` statement, the temporarily saved exception is discarded. + +--- + + +### ▶ For what? + +```py +some_string = "wtf" +some_dict = {} +for i, some_dict[i] in enumerate(some_string): + i = 10 +``` + +**Output:** +```py +>>> some_dict # An indexed dict appears. +{0: 'w', 1: 't', 2: 'f'} +``` + +#### 💡 Explanation: + +* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as: + ``` + for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] + ``` + Where `exprlist` is the assignment target. This means that the equivalent of `{exprlist} = {next_value}` is **executed for each item** in the iterable. + An interesting example that illustrates this: + ```py + for i in range(4): + print(i) + i = 10 + ``` + + **Output:** + ``` + 0 + 1 + 2 + 3 + ``` + + Did you expect the loop to run just once? + + **💡 Explanation:** + + - The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(4)` in this case) is unpacked and assigned the target list variables (`i` in this case). + +* The `enumerate(some_string)` function yields a new value `i` (a counter going up) and a character from the `some_string` in each iteration. It then sets the (just assigned) `i` key of the dictionary `some_dict` to that character. The unrolling of the loop can be simplified as: + ```py + >>> i, some_dict[i] = (0, 'w') + >>> i, some_dict[i] = (1, 't') + >>> i, some_dict[i] = (2, 'f') + >>> some_dict + ``` + +--- + +### ▶ Evaluation time discrepancy + +1\. +```py +array = [1, 8, 15] +# A typical generator expression +gen = (x for x in array if array.count(x) > 0) +array = [2, 8, 22] +``` + +**Output:** + +```py +>>> print(list(gen)) # Where did the other values go? +[8] +``` + +2\. + +```py +array_1 = [1,2,3,4] +gen_1 = (x for x in array_1) +array_1 = [1,2,3,4,5] + +array_2 = [1,2,3,4] +gen_2 = (x for x in array_2) +array_2[:] = [1,2,3,4,5] +``` + +**Output:** +```py +>>> print(list(gen_1)) +[1, 2, 3, 4] + +>>> print(list(gen_2)) +[1, 2, 3, 4, 5] +``` + +3\. + +```py +array_3 = [1, 2, 3] +array_4 = [10, 20, 30] +gen = (i + j for i in array_3 for j in array_4) + +array_3 = [4, 5, 6] +array_4 = [400, 500, 600] +``` + +**Output:** +```py +>>> print(list(gen)) +[401, 501, 601, 402, 502, 602, 403, 503, 603] +``` + +#### 💡 Explanation + +- In a [generator](https://wiki.python.org/moin/Generators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at runtime. +- So before runtime, `array` is re-assigned to the list `[2, 8, 22]`, and since out of `1`, `8` and `15`, only the count of `8` is greater than `0`, the generator only yields `8`. +- The differences in the output of `g1` and `g2` in the second part is due the way variables `array_1` and `array_2` are re-assigned values. +- In the first case, `array_1` is 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. + +--- + + +### ▶ `is not ...` is not `is (not ...)` + +```py +>>> 'something' is not None +True +>>> 'something' is (not None) +False +``` + +#### 💡 Explanation + +- `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. +- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. +- In the example, `(not None)` evaluates to `True` since the value `None` is `False` in a boolean context, so the expression becomes `'something' is True`. + +--- + +### ▶ A tic-tac-toe where X wins in the first attempt! + + +```py +# Let's initialize a row +row = [""] * 3 #row i['', '', ''] +# Let's make a board +board = [row] * 3 +``` + +**Output:** + +```py +>>> board +[['', '', ''], ['', '', ''], ['', '', '']] +>>> board[0] +['', '', ''] +>>> board[0][0] +'' +>>> board[0][0] = "X" +>>> board +[['X', '', ''], ['X', '', ''], ['X', '', '']] +``` + +We didn't assign three `"X"`s, did we? + +#### 💡 Explanation: + +When we initialize `row` variable, this visualization explains what happens in the memory + +

+ + + + Shows a memory segment after row is initialized. + +

+ +And when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`) + +

+ + + + Shows a memory segment after board is initialized. + +

+ +We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue). + +```py +>>> board = [['']*3 for _ in range(3)] +>>> board[0][0] = "X" +>>> board +[['X', '', ''], ['', '', ''], ['', '', '']] +``` + +--- + +### ▶ Schrödinger's variable * + + + +```py +funcs = [] +results = [] +for x in range(7): + def some_func(): + return x + funcs.append(some_func) + results.append(some_func()) # note the function call here + +funcs_results = [func() for func in funcs] +``` + +**Output (Python version):** +```py +>>> results +[0, 1, 2, 3, 4, 5, 6] +>>> funcs_results +[6, 6, 6, 6, 6, 6, 6] +``` + +The values of `x` were different in every iteration prior to appending `some_func` to `funcs`, but all the functions return 6 when they're evaluated after the loop completes. + +2. + +```py +>>> powers_of_x = [lambda x: x**i for i in range(10)] +>>> [f(2) for f in powers_of_x] +[512, 512, 512, 512, 512, 512, 512, 512, 512, 512] +``` + +#### 💡 Explanation: +* When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the *variable*, not its *value*. The function looks up `x` in the surrounding context, rather than using the value of `x` at the time the function is created. So all of the functions use the latest value assigned to the variable for computation. We can see that it's using the `x` from the surrounding context (i.e. *not* a local variable) with: +```py +>>> import inspect +>>> inspect.getclosurevars(funcs[0]) +ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) +``` +Since `x` is a global value, we can change the value that the `funcs` will lookup and return by updating `x`: + +```py +>>> x = 42 +>>> [func() for func in funcs] +[42, 42, 42, 42, 42, 42, 42] +``` + +* To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why does this work?** Because this will define the variable *inside* the function's scope. It will no longer go to the surrounding (global) scope to look up the variables value but will create a local variable that stores the value of `x` at that point in time. + +```py +funcs = [] +for x in range(7): + def some_func(x=x): + return x + funcs.append(some_func) +``` + +**Output:** + +```py +>>> funcs_results = [func() for func in funcs] +>>> funcs_results +[0, 1, 2, 3, 4, 5, 6] +``` + +It is not longer using the `x` in the global scope: + +```py +>>> inspect.getclosurevars(funcs[0]) +ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) +``` + +--- + +### ▶ The chicken-egg problem * + +1\. +```py +>>> isinstance(3, int) +True +>>> isinstance(type, object) +True +>>> isinstance(object, type) +True +``` + +So which is the "ultimate" base class? There's more to the confusion by the way, + +2\. + +```py +>>> class A: pass +>>> isinstance(A, A) +False +>>> isinstance(type, type) +True +>>> isinstance(object, object) +True +``` + +3\. + +```py +>>> issubclass(int, object) +True +>>> issubclass(type, object) +True +>>> issubclass(object, type) +False +``` + + +#### 💡 Explanation + +- `type` is a [metaclass](https://realpython.com/python-metaclasses/) in Python. +- **Everything** is an `object` in Python, which includes classes as well as their objects (instances). +- class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`. +- There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking about these relationships (`issubclass` and `isinstance`) in terms of Python classes. The relationship between `object` and `type` can't be reproduced in pure python. To be more precise the following relationships can't be reproduced in pure Python, + + class A is an instance of class B, and class B is an instance of class A. + + class A is an instance of itself. +- These relationships between `object` and `type` (both being instances of each other as well as themselves) exist in Python because of "cheating" at the implementation level. + +--- + +### ▶ Subclass relationships + +**Output:** +```py +>>> from collections.abc import Hashable +>>> issubclass(list, object) +True +>>> issubclass(object, Hashable) +True +>>> issubclass(list, Hashable) +False +``` + +The Subclass relationships were expected to be transitive, right? (i.e., if `A` is a subclass of `B`, and `B` is a subclass of `C`, the `A` _should_ a subclass of `C`) + +#### 💡 Explanation: + +* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass. +* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey "`__hash__`" method in `cls` or anything it inherits from. +* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation. +* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/). + +--- + +### ▶ Methods equality and identity + + +1. +```py +class SomeClass: + def method(self): + pass + + @classmethod + def classm(cls): + pass + + @staticmethod + def staticm(): + pass +``` + +**Output:** +```py +>>> print(SomeClass.method is SomeClass.method) +True +>>> print(SomeClass.classm is SomeClass.classm) +False +>>> print(SomeClass.classm == SomeClass.classm) +True +>>> print(SomeClass.staticm is SomeClass.staticm) +True +``` + +Accessing `classm` twice, we get an equal object, but not the *same* one? Let's see what happens +with instances of `SomeClass`: + +2. +```py +o1 = SomeClass() +o2 = SomeClass() +``` + +**Output:** +```py +>>> print(o1.method == o2.method) +False +>>> print(o1.method == o1.method) +True +>>> print(o1.method is o1.method) +False +>>> print(o1.classm is o1.classm) +False +>>> print(o1.classm == o1.classm == o2.classm == SomeClass.classm) +True +>>> print(o1.staticm is o1.staticm is o2.staticm is SomeClass.staticm) +True +``` + +Accessing `classm` or `method` twice, creates equal but not *same* objects for the same instance of `SomeClass`. + +#### 💡 Explanation +* Functions are [descriptors](https://docs.python.org/3/howto/descriptor.html). Whenever a function is accessed as an +attribute, the descriptor is invoked, creating a method object which "binds" the function with the object owning the +attribute. If called, the method calls the function, implicitly passing the bound object as the first argument +(this is how we get `self` as the first argument, despite not passing it explicitly). +```py +>>> o1.method +> +``` +* Accessing the attribute multiple times creates a method object every time! Therefore `o1.method is o1.method` is +never truthy. Accessing functions as class attributes (as opposed to instance) does not create methods, however; so +`SomeClass.method is SomeClass.method` is truthy. +```py +>>> SomeClass.method + +``` +* `classmethod` transforms functions into class methods. Class methods are descriptors that, when accessed, create +a method object which binds the *class* (type) of the object, instead of the object itself. +```py +>>> o1.classm +> +``` +* Unlike functions, `classmethod`s will create a method also when accessed as class attributes (in which case they +bind the class, not to the type of it). So `SomeClass.classm is SomeClass.classm` is falsy. +```py +>>> SomeClass.classm +> +``` +* A method object compares equal when both the functions are equal, and the bound objects are the same. So +`o1.method == o1.method` is truthy, although not the same object in memory. +* `staticmethod` transforms functions into a "no-op" descriptor, which returns the function as-is. No method +objects are ever created, so comparison with `is` is truthy. +```py +>>> o1.staticm + +>>> SomeClass.staticm + +``` +* Having to create new "method" objects every time Python calls instance methods and having to modify the arguments +every time in order to insert `self` affected performance badly. +CPython 3.7 [solved it](https://bugs.python.org/issue26110) by introducing new opcodes that deal with calling methods +without creating the temporary method objects. This is used only when the accessed function is actually called, so the +snippets here are not affected, and still generate methods :) + +### ▶ All-true-ation * + + + +```py +>>> all([True, True, True]) +True +>>> all([True, True, False]) +False + +>>> all([]) +True +>>> all([[]]) +False +>>> all([[[]]]) +True +``` + +Why's this True-False alteration? + +#### 💡 Explanation: + +- The implementation of `all` function is equivalent to + +- ```py + def all(iterable): + for element in iterable: + if not element: + return False + return True + ``` + +- `all([])` returns `True` since the iterable is empty. +- `all([[]])` returns `False` because the passed array has one element, `[]`, and in python, an empty list is falsy. +- `all([[[]]])` and higher recursive variants are always `True`. This is because the passed array's single element (`[[...]]`) is no longer empty, and lists with values are truthy. + +--- + +### ▶ The surprising comma + +**Output (< 3.6):** + +```py +>>> def f(x, y,): +... print(x, y) +... +>>> def g(x=4, y=5,): +... print(x, y) +... +>>> def h(x, **kwargs,): + File "", line 1 + def h(x, **kwargs,): + ^ +SyntaxError: invalid syntax + +>>> def h(*args,): + File "", line 1 + def h(*args,): + ^ +SyntaxError: invalid syntax +``` + +#### 💡 Explanation: + +- Trailing comma is not always legal in formal parameters list of a Python function. +- In Python, the argument list is defined partially with leading commas and partially with trailing commas. This conflict causes situations where a comma is trapped in the middle, and no rule accepts it. +- **Note:** The trailing comma problem is [fixed in Python 3.6](https://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python. + +--- + +### ▶ Strings and the backslashes + +**Output:** +```py +>>> print("\"") +" + +>>> print(r"\"") +\" + +>>> print(r"\") +File "", line 1 + print(r"\") + ^ +SyntaxError: EOL while scanning string literal + +>>> r'\'' == "\\'" +True +``` + +#### 💡 Explanation + +- 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' + ``` +- In a raw string literal (as indicated by the prefix `r`), the backslashes pass themselves as is along with the behavior of escaping the following character. + ```py + >>> r'wt\"f' == 'wt\\"f' + True + >>> print(repr(r'wt\"f')) + 'wt\\"f' + + >>> print("\n") + + >>> print(r"\\n") + '\\n' + ``` +- This means when a parser encounters a backslash in a raw string, it expects another character following it. And in our case (`print(r"\")`), the backslash escaped the trailing quote, leaving the parser without a terminating quote (hence the `SyntaxError`). That's why backslashes don't work at the end of a raw string. + +--- + +### ▶ not knot! + +```py +x = True +y = False +``` + +**Output:** +```py +>>> not x == y +True +>>> x == not y + File "", line 1 + x == not y + ^ +SyntaxError: invalid syntax +``` + +#### 💡 Explanation: + +* Operator precedence affects how an expression is evaluated, and `==` operator has higher precedence than `not` operator in Python. +* So `not x == y` is equivalent to `not (x == y)` which is equivalent to `not (True == False)` finally evaluating to `True`. +* But `x == not y` raises a `SyntaxError` because it can be thought of being equivalent to `(x == not) y` and not `x == (not y)` which you might have expected at first sight. +* The parser expected the `not` token to be a part of the `not in` operator (because both `==` and `not in` operators have the same precedence), but after not being able to find an `in` token following the `not` token, it raises a `SyntaxError`. + +--- + +### ▶ Half triple-quoted strings + +**Output:** +```py +>>> print('wtfpython''') +wtfpython +>>> print("wtfpython""") +wtfpython +>>> # The following statements raise `SyntaxError` +>>> # print('''wtfpython') +>>> # print("""wtfpython") + File "", line 3 + print("""wtfpython") + ^ +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, + ``` + >>> print("wtf" "python") + wtfpython + >>> 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 +# A simple example to count the number of booleans and +# integers in an iterable of mixed data types. +mixed_list = [False, 1.0, "some_string", 3, True, [], False] +integers_found_so_far = 0 +booleans_found_so_far = 0 + +for item in mixed_list: + if isinstance(item, int): + integers_found_so_far += 1 + elif isinstance(item, bool): + booleans_found_so_far += 1 +``` + +**Output:** +```py +>>> integers_found_so_far +4 +>>> booleans_found_so_far +0 +``` + + +2\. +```py +>>> some_bool = True +>>> "wtf" * some_bool +'wtf' +>>> some_bool = False +>>> "wtf" * some_bool +'' +``` + +3\. + +```py +def tell_truth(): + True = False + if True == False: + print("I have lost faith in truth!") +``` + +**Output (< 3.x):** + +```py +>>> tell_truth() +I have lost faith in truth! +``` + + + +#### 💡 Explanation: + +* `bool` is a subclass of `int` in Python + + ```py + >>> issubclass(bool, int) + True + >>> issubclass(int, bool) + False + ``` + +* And thus, `True` and `False` are instances of `int` + ```py + >>> isinstance(True, int) + True + >>> isinstance(False, int) + True + ``` + +* The integer value of `True` is `1` and that of `False` is `0`. + ```py + >>> int(True) + 1 + >>> int(False) + 0 + ``` + +* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for the rationale behind it. + +* Initially, Python used to have no `bool` type (people used 0 for false and non-zero value like 1 for true). `True`, `False`, and a `bool` type was added in 2.x versions, but, for backward compatibility, `True` and `False` couldn't be made constants. They just were built-in variables, and it was possible to reassign them + +* Python 3 was backward-incompatible, the issue was finally fixed, and thus the last snippet won't work with Python 3.x! + +--- + +### ▶ Class attributes and instance attributes + +1\. +```py +class A: + x = 1 + +class B(A): + pass + +class C(A): + pass +``` + +**Output:** +```py +>>> A.x, B.x, C.x +(1, 1, 1) +>>> B.x = 2 +>>> A.x, B.x, C.x +(1, 2, 1) +>>> A.x = 3 +>>> A.x, B.x, C.x # C.x changed, but B.x didn't +(3, 2, 3) +>>> a = A() +>>> a.x, A.x +(3, 3) +>>> a.x += 1 +>>> a.x, A.x +(4, 3) +``` + +2\. +```py +class SomeClass: + some_var = 15 + some_list = [5] + another_list = [5] + def __init__(self, x): + self.some_var = x + 1 + self.some_list = self.some_list + [x] + self.another_list += [x] +``` + +**Output:** + +```py +>>> some_obj = SomeClass(420) +>>> some_obj.some_list +[5, 420] +>>> some_obj.another_list +[5, 420] +>>> another_obj = SomeClass(111) +>>> another_obj.some_list +[5, 111] +>>> another_obj.another_list +[5, 420, 111] +>>> another_obj.another_list is SomeClass.another_list +True +>>> another_obj.another_list is some_obj.another_list +True +``` + +#### 💡 Explanation: + +* Class variables and variables in class instances are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of the current class, the parent classes are searched for it. +* The `+=` operator modifies the mutable object in-place without creating a new object. So changing the attribute of one instance affects the other instances and the class attribute as well. + +--- + +### ▶ yielding None + +```py +some_iterable = ('a', 'b') + +def some_func(val): + return "something" +``` + +**Output (<= 3.7.x):** + +```py +>>> [x for x in some_iterable] +['a', 'b'] +>>> [(yield x) for x in some_iterable] + at 0x7f70b0a4ad58> +>>> list([(yield x) for x in some_iterable]) +['a', 'b'] +>>> list((yield x) for x in some_iterable) +['a', None, 'b', None] +>>> list(some_func((yield x)) for x in some_iterable) +['a', 'something', 'b', 'something'] +``` + +#### 💡 Explanation: +- This is a bug in CPython's handling of `yield` in generators and comprehensions. +- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions +- Related bug report: https://bugs.python.org/issue10544 +- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`. + +--- + + +### ▶ Yielding from... return! * + +1\. + +```py +def some_func(x): + if x == 3: + return ["wtf"] + else: + yield from range(x) +``` + +**Output (> 3.3):** + +```py +>>> list(some_func(3)) +[] +``` + +Where did the `"wtf"` go? Is it due to some special effect of `yield from`? Let's validate that, + +2\. + +```py +def some_func(x): + if x == 3: + return ["wtf"] + else: + for i in range(x): + yield i +``` + +**Output:** + +```py +>>> list(some_func(3)) +[] +``` + +The same result, this didn't work either. + +#### 💡 Explanation: + ++ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that, + +> "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." + ++ In the case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically caught inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. + ++ To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, + + ```py + try: + next(some_func(3)) + except StopIteration as e: + some_string = e.value + ``` + + ```py + >>> some_string + ["wtf"] + ``` + +--- + +### ▶ Nan-reflexivity * + + + +1\. + +```py +a = float('inf') +b = float('nan') +c = float('-iNf') # These strings are case-insensitive +d = float('nan') +``` + +**Output:** + +```py +>>> a +inf +>>> b +nan +>>> c +-inf +>>> float('some_other_string') +ValueError: could not convert string to float: some_other_string +>>> a == -c # inf==inf +True +>>> None == None # None == None +True +>>> b == d # but nan!=nan +False +>>> 50 / a +0.0 +>>> a / a +nan +>>> 23 + b +nan +``` + +2\. + +```py +>>> x = float('nan') +>>> y = x / x +>>> y is y # identity holds +True +>>> y == y # equality fails of y +False +>>> [y] == [y] # but the equality succeeds for the list containing y +True +``` + + + +#### 💡 Explanation: + +- `'inf'` and `'nan'` are special strings (case-insensitive), which, when explicitly typecast-ed to `float` type, are used to represent mathematical "infinity" and "not a number" respectively. + +- Since according to 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') + >>> x == x, [x] == [x] + (False, True) + >>> y = float('nan') + >>> y == y, [y] == [y] + (False, True) + >>> x == y, [x] == [y] + (False, False) + ``` + + Since the identities of `x` and `y` are different, the values are considered, which are also different; hence the comparison returns `False` this time. + +- Interesting read: [Reflexivity, and other pillars of civilization](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) + +--- + +### ▶ Mutating the immutable! + + + +This might seem trivial if you know how references work in Python. + +```py +some_tuple = ("A", "tuple", "with", "values") +another_tuple = ([1, 2], [3, 4], [5, 6]) +``` + +**Output:** +```py +>>> some_tuple[2] = "change this" +TypeError: 'tuple' object does not support item assignment +>>> another_tuple[2].append(1000) #This throws no error +>>> another_tuple +([1, 2], [3, 4], [5, 6, 1000]) +>>> another_tuple[2] += [99, 999] +TypeError: 'tuple' object does not support item assignment +>>> another_tuple +([1, 2], [3, 4], [5, 6, 1000, 99, 999]) +``` + +But I thought tuples were immutable... + +#### 💡 Explanation: + +* Quoting from https://docs.python.org/3/reference/datamodel.html + + > Immutable sequences + An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.) + +* `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place. +* There's also an explanation in [official Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works). + +--- + +### ▶ The disappearing variable from outer scope + + +```py +e = 7 +try: + raise Exception() +except Exception as e: + pass +``` + +**Output (Python 2.x):** +```py +>>> print(e) +# prints nothing +``` + +**Output (Python 3.x):** +```py +>>> print(e) +NameError: name 'e' is not defined +``` + +#### 💡 Explanation: + +* Source: https://docs.python.org/3/reference/compound_stmts.html#except + + When an exception has been assigned using `as` target, it is cleared at the end of the `except` clause. This is as if + + ```py + except E as N: + foo + ``` + + was translated into + + ```py + except E as N: + try: + foo + finally: + del N + ``` + + This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because, with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs. + +* 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) + + x = 5 + y = [5, 4, 3] + ``` + + **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] + ``` + +* In Python 2.x, the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing. + + **Output (Python 2.x):** + ```py + >>> e + Exception() + >>> print e + # Nothing is printed! + ``` + +--- + + +### ▶ The mysterious key type conversion + +```py +class SomeClass(str): + pass + +some_dict = {'s': 42} +``` + +**Output:** +```py +>>> type(list(some_dict.keys())[0]) +str +>>> s = SomeClass('s') +>>> some_dict[s] = 40 +>>> some_dict # expected: Two different keys-value pairs +{'s': 40} +>>> type(list(some_dict.keys())[0]) +str +``` + +#### 💡 Explanation: + +* Both the object `s` and the string `"s"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class. +* `SomeClass("s") == "s"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class. +* Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary. +* For the desired behavior, we can redefine the `__eq__` method in `SomeClass` + ```py + class SomeClass(str): + def __eq__(self, other): + return ( + type(self) is SomeClass + and type(other) is SomeClass + and super().__eq__(other) + ) + + # When we define a custom __eq__, Python stops automatically inheriting the + # __hash__ method, so we need to define it as well + __hash__ = str.__hash__ + + some_dict = {'s':42} + ``` + + **Output:** + ```py + >>> s = SomeClass('s') + >>> some_dict[s] = 40 + >>> some_dict + {'s': 40, 's': 42} + >>> keys = list(some_dict.keys()) + >>> type(keys[0]), type(keys[1]) + (__main__.SomeClass, str) + ``` + +--- + +### ▶ Let's see if you can guess this? + +```py +a, b = a[b] = {}, 5 +``` + +**Output:** +```py +>>> a +{5: ({...}, 5)} +``` + +#### 💡 Explanation: + +* According to [Python language reference](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), assignment statements have the form + ``` + (target_list "=")+ (expression_list | yield_expression) + ``` + and + +> An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. + +* The `+` in `(target_list "=")+` means there can be **one or more** target lists. In this case, target lists are `a, b` and `a[b]` (note the expression list is exactly one, which in our case is `{}, 5`). + +* After the expression list is evaluated, its value is unpacked to the target lists from **left to right**. So, in our case, first the `{}, 5` tuple is unpacked to `a, b` and we now have `a = {}` and `b = 5`. + +* `a` is now assigned to `{}`, which is a mutable object. + +* The second target list is `a[b]` (you may expect this to throw an error because both `a` and `b` have not been defined in the statements before. But remember, we just assigned `a` to `{}` and `b` to `5`). + +* Now, we are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference (the `{...}` in the output refers to the same object that `a` is already referencing). Another simpler example of circular reference could be + ```py + >>> some_list = some_list[0] = [0] + >>> some_list + [[...]] + >>> some_list[0] + [[...]] + >>> some_list is some_list[0] + True + >>> some_list[0][0][0][0][0][0] == some_list + True + ``` + Similar is the case in our example (`a[b][0]` is the same object as `a`) + +* So to sum it up, you can break the example down to + ```py + a, b = {}, 5 + a[b] = a, b + ``` + And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a` + ```py + >>> a[b][0] is a + True + ``` + + +--- + +### ▶ Exceeds the limit for integer string conversion +```py +>>> # Python 3.10.6 +>>> int("2" * 5432) + +>>> # Python 3.10.8 +>>> int("2" * 5432) +``` + +**Output:** +```py +>>> # Python 3.10.6 +222222222222222222222222222222222222222222222222222222222222222... + +>>> # Python 3.10.8 +Traceback (most recent call last): + ... +ValueError: Exceeds the limit (4300) for integer string conversion: + value has 5432 digits; use sys.set_int_max_str_digits() + to increase the limit. +``` + +#### 💡 Explanation: +This call to `int()` works fine in Python 3.10.6 and raises a ValueError in Python 3.10.8. Note that Python can still work with large integers. The error is only raised when converting between integers and strings. + +Fortunately, you can increase the limit for the allowed number of digits when you expect an operation to exceed it. To do this, you can use one of the following: +- The -X int_max_str_digits command-line flag +- The set_int_max_str_digits() function from the sys module +- The PYTHONINTMAXSTRDIGITS environment variable + +[Check the documentation](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) for more details on changing the default limit if you expect your code to exceed this value. + + +--- + + +## Section: Slippery Slopes + +### ▶ Modifying a dictionary while iterating over it + +```py +x = {0: None} + +for i in x: + del x[i] + x[i+1] = None + print(i) +``` + +**Output (Python 2.7- Python 3.5):** + +``` +0 +1 +2 +3 +4 +5 +6 +7 +``` + +Yes, it runs for exactly **eight** times and stops. + +#### 💡 Explanation: + +* Iteration over a dictionary that you edit at the same time is not supported. +* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. +* How deleted keys are handled and when the resize occurs might be different for different Python implementations. +* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. +* Python 3.7.6 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. + +--- + +### ▶ Stubborn `del` operation + + + +```py +class SomeClass: + def __del__(self): + print("Deleted!") +``` + +**Output:** +1\. +```py +>>> x = SomeClass() +>>> y = x +>>> del x # this should print "Deleted!" +>>> del y +Deleted! +``` + +Phew, deleted at last. You might have guessed what saved `__del__` from being called in our first attempt to delete `x`. Let's add more twists to the example. + +2\. +```py +>>> x = SomeClass() +>>> y = x +>>> del x +>>> y # check if y exists +<__main__.SomeClass instance at 0x7f98a1a67fc8> +>>> del y # Like previously, this should print "Deleted!" +>>> globals() # oh, it didn't. Let's check all our global variables and confirm +Deleted! +{'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None} +``` + +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. ++ Calling `globals` (or really, executing anything that will have a non `None` result) caused `_` to reference the new result, dropping the existing reference. Now the reference count reached 0 and we can see "Deleted!" being printed (finally!). + +--- + +### ▶ The out of scope variable + + +1\. +```py +a = 1 +def some_func(): + return a + +def another_func(): + a += 1 + return a +``` + +2\. +```py +def some_closure_func(): + a = 1 + def some_inner_func(): + return a + return some_inner_func() + +def another_closure_func(): + a = 1 + def another_inner_func(): + a += 1 + return a + return another_inner_func() +``` + +**Output:** +```py +>>> some_func() +1 +>>> another_func() +UnboundLocalError: local variable 'a' referenced before assignment + +>>> some_closure_func() +1 +>>> another_closure_func() +UnboundLocalError: local variable 'a' referenced before assignment +``` + +#### 💡 Explanation: +* When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error. +* To modify the outer scope variable `a` in `another_func`, we have to use the `global` keyword. + ```py + def another_func() + global a + a += 1 + return a + ``` + + **Output:** + ```py + >>> 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. + ```py + def another_func(): + a = 1 + def another_inner_func(): + nonlocal a + a += 1 + return a + return another_inner_func() + ``` + + **Output:** + ```py + >>> another_func() + 2 + ``` +* The keywords `global` and `nonlocal` 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] +list_3 = [1, 2, 3, 4] +list_4 = [1, 2, 3, 4] + +for idx, item in enumerate(list_1): + del item + +for idx, item in enumerate(list_2): + list_2.remove(item) + +for idx, item in enumerate(list_3[:]): + list_3.remove(item) + +for idx, item in enumerate(list_4): + list_4.pop(idx) +``` + +**Output:** +```py +>>> list_1 +[1, 2, 3, 4] +>>> list_2 +[2, 4] +>>> list_3 +[] +>>> list_4 +[2, 4] +``` + +Can you guess why the output is `[2, 4]`? + +#### 💡 Explanation: + +* 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 + ``` + +**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. + +**Why the output is `[2, 4]`?** +- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence. + +* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example +* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python. + +--- + + +### ▶ Lossy zip of iterators * + + +```py +>>> numbers = list(range(7)) +>>> numbers +[0, 1, 2, 3, 4, 5, 6] +>>> first_three, remaining = numbers[:3], numbers[3:] +>>> first_three, remaining +([0, 1, 2], [3, 4, 5, 6]) +>>> numbers_iter = iter(numbers) +>>> list(zip(numbers_iter, first_three)) +[(0, 0), (1, 1), (2, 2)] +# so far so good, let's zip the remaining +>>> list(zip(numbers_iter, remaining)) +[(4, 3), (5, 4), (6, 5)] +``` +Where did element `3` go from the `numbers` list? + +#### 💡 Explanation: + +- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function, + ```py + def zip(*iterables): + sentinel = object() + iterators = [iter(it) for it in iterables] + while iterators: + result = [] + for it in iterators: + elem = next(it, sentinel) + if elem is sentinel: return + result.append(elem) + yield tuple(result) + ``` +- So the function takes in arbitrary number of 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)] + ``` + The first argument of zip should be the one with fewest elements. + +--- + +### ▶ Loop variables leaking out! + +1\. +```py +for x in range(7): + if x == 6: + print(x, ': for x inside loop') +print(x, ': x in global') +``` + +**Output:** +```py +6 : for x inside loop +6 : x in global +``` + +But `x` was never defined outside the scope of for loop... + +2\. +```py +# This time let's initialize x first +x = -1 +for x in range(7): + if x == 6: + print(x, ': for x inside loop') +print(x, ': x in global') +``` + +**Output:** +```py +6 : for x inside loop +6 : x in global +``` + +3\. + +**Output (Python 2.x):** +```py +>>> x = 1 +>>> print([x for x in range(5)]) +[0, 1, 2, 3, 4] +>>> print(x) +4 +``` + +**Output (Python 3.x):** +```py +>>> x = 1 +>>> print([x for x in range(5)]) +[0, 1, 2, 3, 4] +>>> print(x) +1 +``` + +#### 💡 Explanation: + +- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable. + +- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) 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." + +--- + +### ▶ Beware of default mutable arguments! + + +```py +def some_func(default_arg=[]): + default_arg.append("some_string") + return default_arg +``` + +**Output:** +```py +>>> some_func() +['some_string'] +>>> some_func() +['some_string', 'some_string'] +>>> some_func([]) +['some_string'] +>>> some_func() +['some_string', 'some_string', 'some_string'] +``` + +#### 💡 Explanation: + +- 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 + ``` + + **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'],) + ``` + +- 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 + ``` + +--- + +### ▶ Catching the Exceptions + +```py +some_list = [1, 2, 3] +try: + # This should raise an ``IndexError`` + print(some_list[4]) +except IndexError, ValueError: + print("Caught!") + +try: + # This should raise a ``ValueError`` + some_list.remove(4) +except IndexError, ValueError: + print("Caught again!") +``` + +**Output (Python 2.x):** +```py +Caught! + +ValueError: list.remove(x): x not in list +``` + +**Output (Python 3.x):** +```py + File "", line 3 + except IndexError, ValueError: + ^ +SyntaxError: invalid syntax +``` + +#### 💡 Explanation + +* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example, + ```py + some_list = [1, 2, 3] + try: + # This should raise a ``ValueError`` + some_list.remove(4) + except (IndexError, ValueError), e: + print("Caught again!") + print(e) + ``` + **Output (Python 2.x):** + ``` + Caught again! + list.remove(x): x not in list + ``` + **Output (Python 3.x):** + ```py + File "", line 4 + except (IndexError, ValueError), e: + ^ + IndentationError: unindent does not match any outer indentation level + ``` + +* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example, + ```py + some_list = [1, 2, 3] + try: + some_list.remove(4) + + except (IndexError, ValueError) as e: + print("Caught again!") + print(e) + ``` + **Output:** + ``` + Caught again! + list.remove(x): x not in list + ``` + +--- + +### ▶ Same operands, different story! + +1\. +```py +a = [1, 2, 3, 4] +b = a +a = a + [5, 6, 7, 8] +``` + +**Output:** +```py +>>> a +[1, 2, 3, 4, 5, 6, 7, 8] +>>> b +[1, 2, 3, 4] +``` + +2\. +```py +a = [1, 2, 3, 4] +b = a +a += [5, 6, 7, 8] +``` + +**Output:** +```py +>>> a +[1, 2, 3, 4, 5, 6, 7, 8] +>>> b +[1, 2, 3, 4, 5, 6, 7, 8] +``` + +#### 💡 Explanation: + +* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this. + +* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged. + +* The expression `a += [5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. + +--- + +### ▶ Name resolution ignoring class scope + +1\. +```py +x = 5 +class SomeClass: + x = 17 + y = (x for i in range(10)) +``` + +**Output:** +```py +>>> list(SomeClass.y)[0] +5 +``` + +2\. +```py +x = 5 +class SomeClass: + x = 17 + y = [x for i in range(10)] +``` + +**Output (Python 2.x):** +```py +>>> SomeClass.y[0] +17 +``` + +**Output (Python 3.x):** +```py +>>> SomeClass.y[0] +5 +``` + +#### 💡 Explanation +- Scopes nested inside class definition ignore names bound at the class level. +- A generator expression has its own scope. +- Starting from Python 3.X, list comprehensions also have their own scope. + +--- + +### ▶ Rounding like a banker * + +Let's implement a naive function to get the middle element of a list: +```py +def get_middle(some_list): + mid_index = round(len(some_list) / 2) + return some_list[mid_index - 1] +``` + +**Python 3.x:** +```py +>>> get_middle([1]) # looks good +1 +>>> get_middle([1,2,3]) # looks good +2 +>>> get_middle([1,2,3,4,5]) # huh? +2 +>>> len([1,2,3,4,5]) / 2 # good +2.5 +>>> round(len([1,2,3,4,5]) / 2) # why? +2 +``` +It seems as though Python rounded 2.5 to 2. + +#### 💡 Explanation: + +- This is not a float precision error, in fact, this behavior is intentional. Since Python 3.0, `round()` uses [banker's rounding](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even) where .5 fractions are rounded to the nearest **even** number: + +```py +>>> round(0.5) +0 +>>> round(1.5) +2 +>>> round(2.5) +2 +>>> import numpy # numpy does the same +>>> numpy.round(0.5) +0.0 +>>> numpy.round(1.5) +2.0 +>>> numpy.round(2.5) +2.0 +``` + +- This is the recommended way to round .5 fractions as described in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules). However, the other way (round away from zero) is taught in school most of the time, so banker's rounding is likely not that well known. Furthermore, some of the most popular programming languages (for example: JavaScript, Java, C/C++, Ruby, Rust) do not use banker's rounding either. Therefore, this is still quite special to Python and may result in confusion when rounding fractions. +- See the [round() docs](https://docs.python.org/3/library/functions.html#round) or [this stackoverflow thread](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) for more information. +- Note that `get_middle([1])` only returned 1 because the index was `round(0.5) - 1 = 0 - 1 = -1`, returning the last element in the list. + +--- + +### ▶ Needles in a Haystack * + + + +I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios, + +1\. + +```py +x, y = (0, 1) if True else None, None +``` + +**Output:** + +```py +>>> x, y # expected (0, 1) +((0, 1), None) +``` + +2\. + +```py +t = ('one', 'two') +for i in t: + print(i) + +t = ('one') +for i in t: + print(i) + +t = () +print(t) +``` + +**Output:** + +```py +one +two +o +n +e +tuple() +``` + +3\. + +``` +ten_words_list = [ + "some", + "very", + "big", + "list", + "that" + "consists", + "of", + "exactly", + "ten", + "words" +] +``` + +**Output** + +```py +>>> len(ten_words_list) +9 +``` + +4\. Not asserting strongly enough + +```py +a = "python" +b = "javascript" +``` + +**Output:** + +```py +# An assert statement with an assertion failure message. +>>> assert(a == b, "Both languages are different") +# No AssertionError is raised +``` + +5\. + +```py +some_list = [1, 2, 3] +some_dict = { + "key_1": 1, + "key_2": 2, + "key_3": 3 +} + +some_list = some_list.append(4) +some_dict = some_dict.update({"key_4": 4}) +``` + +**Output:** + +```py +>>> print(some_list) +None +>>> print(some_dict) +None +``` + +6\. + +```py +def some_recursive_func(a): + if a[0] == 0: + return + a[0] -= 1 + some_recursive_func(a) + return a + +def similar_recursive_func(a): + if a == 0: + return a + a -= 1 + similar_recursive_func(a) + return a +``` + +**Output:** + +```py +>>> some_recursive_func([5, 0]) +[0, 0] +>>> similar_recursive_func(5) +4 +``` + +#### 💡 Explanation: + +* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. + +* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. + +* `()` is a special token and denotes empty `tuple`. + +* In 3, as you might have already figured out, there's a missing comma after 5th element (`"that"`) in the list. So by implicit string literal concatenation, + + ```py + >>> ten_words_list + ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] + ``` + +* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up, + + ```py + >>> a = "python" + >>> b = "javascript" + >>> assert a == b + Traceback (most recent call last): + File "", line 1, in + AssertionError + + >>> assert (a == b, "Values are not equal") + :1: SyntaxWarning: assertion is always true, perhaps remove parentheses? + + >>> assert a == b, "Values are not equal" + Traceback (most recent call last): + File "", line 1, in + AssertionError: Values are not equal + ``` + +* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). + +* Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignment of an immutable (`a -= 1`) is not an alteration of the value. + +* Being aware of these nitpicks can save you hours of debugging effort in the long run. + +--- + + +### ▶ Splitsies * + +```py +>>> 'a'.split() +['a'] + +# is same as +>>> 'a'.split(' ') +['a'] + +# but +>>> len(''.split()) +0 + +# isn't the same as +>>> len(''.split(' ')) +1 +``` + +#### 💡 Explanation: + +- It might appear at first that the default separator for split is a single space `' '`, but as per the [docs](https://docs.python.org/3/library/stdtypes.html#str.split) + > If sep is not specified or is `None`, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns `[]`. + > If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). Splitting an empty string with a specified separator returns `['']`. +- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear, + ```py + >>> ' a '.split(' ') + ['', 'a', ''] + >>> ' a '.split() + ['a'] + >>> ''.split(' ') + [''] + ``` + +--- + +### ▶ Wild imports * + + + +```py +# File: module.py + +def some_weird_name_func_(): + print("works!") + +def _another_weird_name_func(): + print("works!") + +``` + +**Output** + +```py +>>> from module import * +>>> some_weird_name_func_() +"works!" +>>> _another_weird_name_func() +Traceback (most recent call last): + File "", line 1, in +NameError: name '_another_weird_name_func' is not defined +``` + +#### 💡 Explanation: + +- It 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! + ``` +- If you really want to use wildcard imports, then you'd have to define the list `__all__` in your module that will contain a list of public objects that'll be available when we do wildcard imports. + ```py + __all__ = ['_another_weird_name_func'] + + def some_weird_name_func_(): + print("works!") + + def _another_weird_name_func(): + print("works!") + ``` + **Output** + + ```py + >>> _another_weird_name_func() + "works!" + >>> some_weird_name_func_() + Traceback (most recent call last): + File "", line 1, in + NameError: name 'some_weird_name_func_' is not defined + ``` + +--- + +### ▶ All sorted? * + + + +```py +>>> x = 7, 8, 9 +>>> sorted(x) == x +False +>>> sorted(x) == sorted(x) +True + +>>> y = reversed(x) +>>> sorted(y) == sorted(y) +False +``` + +#### 💡 Explanation: + +- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. + +- ```py + >>> [] == tuple() + False + >>> x = 7, 8, 9 + >>> type(x), type(sorted(x)) + (tuple, list) + ``` + +- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first. + +- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list. + + ```py + >>> x = 7, 8, 9 + >>> y = reversed(x) + >>> sorted(y), sorted(y) + ([7, 8, 9], []) + ``` + +--- + +### ▶ Midnight time doesn't exist? + +```py +from datetime import datetime + +midnight = datetime(2018, 1, 1, 0, 0) +midnight_time = midnight.time() + +noon = datetime(2018, 1, 1, 12, 0) +noon_time = noon.time() + +if midnight_time: + print("Time at midnight is", midnight_time) + +if noon_time: + print("Time at noon is", noon_time) +``` + +**Output (< 3.5):** + +```py +('Time at noon is', datetime.time(12, 0)) +``` +The midnight time is not printed. + +#### 💡 Explanation: + +Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of "empty." + +--- +--- + + + +## Section: The Hidden treasures! + +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 +import antigravity +``` + +**Output:** +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/). + +--- + +### ▶ `goto`, but why? + + +```py +from goto import goto, label +for i in range(9): + for j in range(9): + for k in range(9): + print("I am trapped, please rescue!") + if k == 2: + goto .breakout # breaking out from a deeply nested loop +label .breakout +print("Freedom!") +``` + +**Output (Python 2.3):** +```py +I am trapped, please rescue! +I am trapped, please rescue! +Freedom! +``` + +#### 💡 Explanation: +- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004. +- Current versions of Python do not have this module. +- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python. + +--- + +### ▶ 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 +from __future__ import braces +``` + +**Output:** +```py + File "some_file.py", line 1 + from __future__ import braces +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. ++ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement. + +--- + +### ▶ Let's meet Friendly Language Uncle For Life + +**Output (Python 3.x)** +```py +>>> from __future__ import barry_as_FLUFL +>>> "Ruby" != "Python" # there's no doubt about it + File "some_file.py", line 1 + "Ruby" != "Python" + ^ +SyntaxError: invalid syntax + +>>> "Ruby" <> "Python" +True +``` + +There we go. + +#### 💡 Explanation: +- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means). +- Quoting from the PEP-401 + + > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. +- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/). +- 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"')) + ``` + +--- + +### ▶ Even Python understands that love is complicated + +```py +import this +``` + +Wait, what's **this**? `this` is love :heart: + +**Output:** +``` +The Zen of Python, by Tim Peters + +Beautiful is better than ugly. +Explicit is better than implicit. +Simple is better than complex. +Complex is better than complicated. +Flat is better than nested. +Sparse is better than dense. +Readability counts. +Special cases aren't special enough to break the rules. +Although practicality beats purity. +Errors should never pass silently. +Unless explicitly silenced. +In the face of ambiguity, refuse the temptation to guess. +There should be one-- and preferably only one --obvious way to do it. +Although that way may not be obvious at first unless you're Dutch. +Now is better than never. +Although never is often better than *right* now. +If the implementation is hard to explain, it's a bad idea. +If the implementation is easy to explain, it may be a good idea. +Namespaces are one honking great idea -- let's do more of those! +``` + +It's the Zen of Python! + +```py +>>> love = this +>>> this is love +True +>>> love is True +False +>>> love is False +False +>>> love is not True or False +True +>>> love is not True or False; love is love # Love is complicated +True +``` + +#### 💡 Explanation: + +* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)). +* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens). +* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators). + +--- + +### ▶ Yes, it exists! + +**The `else` clause for loops.** One typical example might be: + +```py + def does_exists_num(l, to_find): + for num in l: + if num == to_find: + print("Exists!") + break + else: + print("Does not exist") +``` + +**Output:** +```py +>>> some_list = [1, 2, 3, 4, 5] +>>> does_exists_num(some_list, 4) +Exists! +>>> does_exists_num(some_list, -1) +Does not exist +``` + +**The `else` clause in exception handling.** An example, + +```py +try: + pass +except: + print("Exception occurred!!!") +else: + print("Try block executed successfully...") +``` + +**Output:** +```py +Try block executed successfully... +``` + +#### 💡 Explanation: +- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a "nobreak" clause. +- `else` clause after a try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. + +--- +### ▶ Ellipsis * + +```py +def some_func(): + Ellipsis +``` + +**Output** +```py +>>> some_func() +# No output, No Error + +>>> SomeRandomString +Traceback (most recent call last): + File "", line 1, in +NameError: name 'SomeRandomString' is not defined + +>>> Ellipsis +Ellipsis +``` + +#### 💡 Explanation +- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`. + ```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 + ```py + >>> import numpy as np + >>> three_dimensional_array = np.arange(8).reshape(2, 2, 2) + array([ + [ + [0, 1], + [2, 3] + ], + + [ + [4, 5], + [6, 7] + ] + ]) + ``` + So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions + ```py + >>> three_dimensional_array[:,:,1] + array([[1, 3], + [5, 7]]) + >>> three_dimensional_array[..., 1] # using Ellipsis. + array([[1, 3], + [5, 7]]) + ``` + Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`) + + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`)) + + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the "no argument passed" and "None value passed" scenarios). + +--- + +### ▶ Inpinity + +The spelling is intended. Please, don't submit a patch for this. + +**Output (Python 3.x):** +```py +>>> infinity = float('infinity') +>>> hash(infinity) +314159 +>>> hash(float('-inf')) +-314159 +``` + +#### 💡 Explanation: +- Hash of infinity is 10⁵ x π. +- Interestingly, the hash of `float('-inf')` is "-10⁵ x π" in Python 3, whereas "-10⁵ x e" in Python 2. + +--- + +### ▶ Let's mangle + +1\. +```py +class Yo(object): + def __init__(self): + self.__honey = True + self.bro = True +``` + +**Output:** +```py +>>> Yo().bro +True +>>> Yo().__honey +AttributeError: 'Yo' object has no attribute '__honey' +>>> Yo()._Yo__honey +True +``` + +2\. +```py +class Yo(object): + def __init__(self): + # Let's try something symmetrical this time + self.__honey__ = True + self.bro = True +``` + +**Output:** +```py +>>> Yo().bro +True + +>>> Yo()._Yo__honey__ +Traceback (most recent call last): + File "", line 1, in +AttributeError: 'Yo' object has no attribute '_Yo__honey__' +``` + +Why did `Yo()._Yo__honey` work? + +3\. + +```py +_A__variable = "Some value" + +class A(object): + def some_func(self): + return __variable # not initialized anywhere yet +``` + +**Output:** +```py +>>> A().__variable +Traceback (most recent call last): + File "", line 1, in +AttributeError: 'A' object has no attribute '__variable' + +>>> A().some_func() +'Some value' +``` + + +#### 💡 Explanation: + +* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces. +* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a "dunder") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. +* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class. +* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores. +* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope. +* Also, if the mangled name is longer than 255 characters, truncation will happen. + +--- +--- + +## Section: Appearances are deceptive! + +### ▶ Skipping lines? + +**Output:** +```py +>>> value = 11 +>>> valuе = 32 +>>> value +11 +``` + +Wut? + +**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell. + +#### 💡 Explanation + +Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter. + +```py +>>> ord('е') # cyrillic 'e' (Ye) +1077 +>>> ord('e') # latin 'e', as used in English and typed using standard keyboard +101 +>>> 'е' == 'e' +False + +>>> value = 42 # latin e +>>> valuе = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here +>>> value +42 +``` + +The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example. + +--- + +### ▶ Teleportation + + + +```py +# `pip install numpy` first. +import numpy as np + +def energy_send(x): + # Initializing a numpy array + np.array([float(x)]) + +def energy_receive(): + # Return an empty numpy array + return np.empty((), dtype=np.float).tolist() +``` + +**Output:** +```py +>>> energy_send(123.456) +>>> energy_receive() +123.456 +``` + +Where's the Nobel Prize? + +#### 💡 Explanation: + +* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate. +* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always). + +--- + +### ▶ Well, something is fishy... + +```py +def square(x): + """ + A simple function to calculate the square of a number by addition. + """ + sum_so_far = 0 + for counter in range(x): + sum_so_far = sum_so_far + x + return sum_so_far +``` + +**Output (Python 2.x):** + +```py +>>> square(10) +10 +``` + +Shouldn't that be 100? + +**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell. + +#### 💡 Explanation + +* **Don't mix tabs and spaces!** The character just preceding return is a "tab", and the code is indented by multiple of "4 spaces" elsewhere in the example. +* This is how Python handles tabs: + + > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...> +* So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. +* Python 3 is kind enough to throw an error for such cases automatically. + + **Output (Python 3.x):** + ```py + TabError: inconsistent use of tabs and spaces in indentation + ``` + +--- +--- + +## Section: Miscellaneous + + +### ▶ `+=` is faster + + +```py +# using "+", three strings: +>>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) +0.25748300552368164 +# using "+=", three strings: +>>> timeit.timeit("s1 += s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) +0.012188911437988281 +``` + +#### 💡 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 = "" + for i in range(iters): + s += "xyz" + assert len(s) == 3*iters + +def add_bytes_with_plus(iters): + s = b"" + for i in range(iters): + s += b"xyz" + assert len(s) == 3*iters + +def add_string_with_format(iters): + fs = "{}"*iters + s = fs.format(*(["xyz"]*iters)) + assert len(s) == 3*iters + +def add_string_with_join(iters): + l = [] + for i in range(iters): + l.append("xyz") + s = "".join(l) + assert len(s) == 3*iters + +def convert_list_to_string(l, iters): + s = "".join(l) + assert len(s) == 3*iters +``` + +**Output:** + +```py +# Executed in ipython shell using %timeit for better readability of results. +# You can also use the timeit module in normal python shell/scriptm=, example usage below +# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) + +>>> NUM_ITERS = 1000 +>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) +124 µs ± 4.73 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) +>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) +211 µs ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_format(NUM_ITERS) +61 µs ± 2.18 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_join(NUM_ITERS) +117 µs ± 3.21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> l = ["xyz"]*NUM_ITERS +>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) +10.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +``` + +Let's increase the number of iterations by a factor of 10. + +```py +>>> NUM_ITERS = 10000 +>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time +1.26 ms ± 76.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase +6.82 ms ± 134 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase +645 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> %timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase +1.17 ms ± 7.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +>>> l = ["xyz"]*NUM_ITERS +>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase +86.3 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) +``` + +#### 💡 Explanation +- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces. +- Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function) +- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings). +- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster. +- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + "x" + "y" + "z"` instead of `s += "xyz"`, the increase would have been quadratic. + ```py + def add_string_with_plus(iters): + s = "" + for i in range(iters): + s = s + "x" + "y" + "z" + assert len(s) == 3*iters + + >>> %timeit -n100 add_string_with_plus(1000) + 388 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) + >>> %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time + 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) + ``` +- 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. + +--- + +### ▶ 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)} +``` + +**Output:** +```py +>>> %timeit some_dict['5'] +28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +>>> some_dict[1] = 1 +>>> %timeit some_dict['5'] +37.2 ns ± 0.265 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) + +>>> %timeit another_dict['5'] +28.5 ns ± 0.142 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +>>> another_dict[1] # Trying to access a key that doesn't exist +Traceback (most recent call last): + File "", line 1, in +KeyError: 1 +>>> %timeit another_dict['5'] +38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) +``` +Why are same lookups becoming slower? + +#### 💡 Explanation: ++ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys. ++ The specialized function (named `lookdict_unicode` in CPython's [source](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method. ++ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function. ++ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary. That's why attempting a failed lookup has the same effect. + + +### ▶ Bloating instance `dict`s * + +```py +import sys + +class SomeClass: + def __init__(self): + self.some_attr1 = 1 + self.some_attr2 = 2 + self.some_attr3 = 3 + self.some_attr4 = 4 + + +def dict_size(o): + return sys.getsizeof(o.__dict__) + +``` + +**Output:** (Python 3.8, other Python 3 versions may vary a little) +```py +>>> o1 = SomeClass() +>>> o2 = SomeClass() +>>> dict_size(o1) +104 +>>> dict_size(o2) +104 +>>> del o1.some_attr1 +>>> o3 = SomeClass() +>>> dict_size(o3) +232 +>>> dict_size(o1) +232 +``` + +Let's try again... In a new interpreter: + +```py +>>> o1 = SomeClass() +>>> o2 = SomeClass() +>>> dict_size(o1) +104 # as expected +>>> o1.some_attr5 = 5 +>>> o1.some_attr6 = 6 +>>> dict_size(o1) +360 +>>> dict_size(o2) +272 +>>> o3 = SomeClass() +>>> dict_size(o3) +232 +``` + +What makes those dictionaries become bloated? And why are newly created objects bloated as well? + +#### 💡 Explanation: ++ CPython is able to reuse the same "keys" object in multiple dictionaries. This was added in [PEP 412](https://www.python.org/dev/peps/pep-0412/) with the motivation to reduce memory usage, specifically in dictionaries of instances - where keys (instance attributes) tend to be common to all instances. ++ This optimization is entirely seamless for instance dictionaries, but it is disabled if certain assumptions are broken. ++ Key-sharing dictionaries do not support deletion; if an instance attribute is deleted, the dictionary is "unshared", and key-sharing is disabled for all future instances of the same class. ++ 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 * + +* `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`. + +* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java. + ```py + >>> a = 5 + >>> a + 5 + >>> ++a + 5 + >>> --a + 5 + ``` + + **💡 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*? + ```py + >>> a = 42 + >>> a -=- 1 + >>> a + 43 + ``` + It is used as an alternative incrementation operator, together with another one + ```py + >>> a +=+ 1 + >>> a + >>> 44 + ``` + **💡 Explanation:** This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case. + +* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. + + ```py + >>> False ** False == True + True + >>> False ** True == False + True + >>> True ** False == True + True + >>> True ** True == True + True + ``` + + **💡 Explanation:** If you replace `False` and `True` by 0 and 1 and do the maths, the truth table is equivalent to 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 + ``` + + **💡 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'" + ``` + +* Python uses 2 bytes for local variable storage in functions. In theory, this means that only 65536 variables can be defined in a function. However, python has a handy solution built in that can be used to store more than 2^16 variable names. The following code demonstrates what happens in the stack when more than 65536 local variables are defined (Warning: This code prints around 2^18 lines of text, so be prepared!): + + ```py + import dis + exec(""" + def f(): + """ + """ + """.join(["X" + str(x) + "=" + str(x) for x in range(65539)])) + + f() + + 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. + +* Sometimes, the `print` method might not print values immediately. For example, + + ```py + # File some_file.py + import time + + print("wtfpython", end="_") + time.sleep(3) + ``` + + This will print the `wtfpython` after 3 seconds due to the `end` argument because the output buffer is flushed either after encountering `\n` or when the program finishes execution. We can force the buffer to flush by passing `flush=True` argument. + +* List slicing with out of the bounds indices throws no errors + ```py + >>> some_list = [1, 2, 3, 4, 5] + >>> some_list[111:] + [] + ``` + +* Slicing an iterable not always creates a new object. For example, + ```py + >>> some_str = "wtfpython" + >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n'] + >>> some_list is some_list[:] # False expected because a new object is created. + False + >>> some_str is some_str[:] # True because strings are immutable, so making a new object is of not much use. + True + ``` + +* `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](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 + ``` + +* `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear + ```py + def count(s, sub): + result = 0 + for i in range(len(s) + 1 - len(sub)): + result += (s[i:i + len(sub)] == sub) + return result + ``` + The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string. + +--- +--- + +# Contributing + +A few ways in which you can contribute to wtfpython, + +- Suggesting new examples +- Helping with translation (See [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation)) +- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc. +- Identifying gaps (things like inadequate explanation, redundant examples, etc.) +- Any creative suggestions to make this project more fun and useful + +Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) to discuss things. + +PS: Please don't reach out with backlinking requests, no links will be added unless they're highly relevant to the project. + +# Acknowledgements + +The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by 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 +* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines +* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python +* https://www.python.org/doc/humor/ +* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator +* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues +* WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). + +# 🎓 License + +[![WTFPL 2.0][license-image]][license-url] + +© [Satwik Kansal](https://satwikkansal.xyz) + +[license-url]: http://www.wtfpl.net +[license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square + +## Surprise your friends as well! + +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!) + +## Need a pdf version? + +I've received a few requests for the pdf (and epub) version of wtfpython. You can add your details [here](https://form.jotform.com/221593245656057) to get them as soon as they are finished. + + +**That's all folks!** For upcoming content like this, you can add your email [here](https://form.jotform.com/221593598380062). From ed79efdb4ea7b41ae40565df6cbd2f462d566702 Mon Sep 17 00:00:00 2001 From: Mohamad Reza Date: Thu, 27 Feb 2025 15:03:20 +0330 Subject: [PATCH 176/210] add farsi introduction --- translations/fa-farsi/README.md | 83 +++++++++++++++++++-------------- 1 file changed, 47 insertions(+), 36 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 6d89f3bb..e20363a4 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -9,31 +9,39 @@

کاوش و درک پایتون از طریق تکه‌های کد شگفت‌انگیز.

-ترجمه‌ها: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +ترجمه‌ها: [انگلیسی English](https://github.com/satwikkansal/wtfpython) | [چینی 中文](https://github.com/leisurelicht/wtfpython-cn) | [ویتنامی Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [اسپانیایی Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [کره‌ای 한국어](https://github.com/buttercrab/wtfpython-ko) | [روسی Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [آلمانی Deutsch](https://github.com/BenSt099/wtfpython) | [اضافه کردن ترجمه](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) -Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) +حالت‌های دیگر: [وبسایت تعاملی](https://wtfpython-interactive.vercel.app) | [دفترچه تعاملی](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) -Python, being a beautifully designed high-level and interpreter-based programming language, provides us with many features for the programmer's comfort. But sometimes, the outcomes of a Python snippet may not seem obvious at first sight. -Here's a fun project attempting to explain what exactly is happening under the hood for some counter-intuitive snippets and lesser-known features in Python. +پایتون، یه زبان زیبا طراحی شده، سطح بالا و مبتنی بر مفسره که قابلیت‌های بسیاری برای راحتی ما برنامه‌نویس‌ها فراهم می‌کنه. +ولی گاهی اوقات قطعه‌کدهایی رو می‌بینیم که تو نگاه اول خروجی‌هاشون واضح نیست. -While some of the examples you see below may not be WTFs in the truest sense, but they'll reveal some of the interesting parts of Python that you might be unaware of. I find it a nice way to learn the internals of a programming language, and I believe that you'll find it interesting too! +این یه پروژه باحاله که سعی داریم توش توضیح بدیم که پشت پرده یه سری قطعه‌کدهای غیرشهودی و فابلیت‌های کمتر شناخته شده پایتون +چه خبره. -If you're an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt. You may have already experienced some of them before, and I might be able to revive sweet old memories of yours! :sweat_smile: +درحالی که بعضی از مثال‌هایی که قراره تو این سند ببینید واقعا پشم‌ریزون نیستند ولی بخش‌های جالبی از پایتون رو ظاهر می‌کنند که +ممکنه شما از وجودشون بی‌خبر باشید. به نظرم این شیوه جالبیه برای یادگیری جزئیات داخلی یه زبان برنامه نویسی و باور دارم که +برای شما هم جالب خواهد بود. -PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) (the examples marked with asterisk are the ones added in the latest major revision). +اگه شما یه پایتون کار سابقه‌دار هستید، می‌تونید از این فرصت به عنوان یه چالش برای خودتون استفاده کنید تا بیشتر مثال‌ها رو +تو تلاش اول حدس بزنید. ممکنه شما بعضی از این مثال‌ها رو قبلا تجربه کرده باشید و من خاطراتشون رو در این سند براتون زنده +کرده باشم! :sweat_smile: -So, here we go... +پ.ن: اگه شما قبلا این سند رو خوندید، می‌تونید تغییرات جدید رو در بخش انتشار (فعلا در [اینجا](https://github.com/satwikkansal/wtfpython/)) مطالعه کنید +(مثال‌هایی که کنارشون علامت ستاره دارند، در آخرین ویرایش اضافه شده‌اند). -# Table of Contents +پس، بزن بریم... + +# فهرست مطالب -- [Table of Contents](#table-of-contents) -- [Structure of the Examples](#structure-of-the-examples) -- [Usage](#usage) +- [فهرست مطالب](#فهرست-مطالب) +- [ساختار مثال‌ها](#structure-of-the-examples) +- [استفاده](#استفاده) - [👀 Examples](#-examples) - [Section: Strain your brain!](#section-strain-your-brain) - [▶ First things first! \*](#-first-things-first-) @@ -175,52 +183,55 @@ So, here we go... -# Structure of the Examples +# ساختار مثال‌ها -All the examples are structured like below: +همه مثال‌ها به صورت زیر ساخته می‌شوند: -> ### ▶ Some fancy Title +> ### ▶ یه اسم خوشگل > > ```py -> # Set up the code. -> # Preparation for the magic... +> # راه اندازی کد +> # آماده سازی برای جادو... > ``` > -> **Output (Python version(s)):** +> **خروجی (نسخه(های) پایتون):** > > ```py > >>> triggering_statement -> Some unexpected output +> یه خروجی غیرمنتظره > ``` -> (Optional): One line describing the unexpected output. +> (دلخواه): توضیح یک‌خطی خروجی غیرمنتظره > > -> #### 💡 Explanation: +> #### 💡 توضیح: > -> * Brief explanation of what's happening and why is it happening. +> * توضیح کوتاه درمورد این‌که چی داره اتفاق میافته و چرا. > ```py -> # Set up code -> # More examples for further clarification (if necessary) +> # راه اندازی کد +> # مثال‌های بیشتر برای شفاف سازی (در صورت نیاز) > ``` -> **Output (Python version(s)):** +> **خروجی (نسخه(های) پایتون):** > > ```py -> >>> trigger # some example that makes it easy to unveil the magic -> # some justified output +> >>> trigger # یک مثال که رونمایی از جادو رو راحت‌تر می‌کنه +> # یک خروجی توجیه شده و واضح > ``` -**Note:** All the examples are tested on Python 3.5.2 interactive interpreter, and they should work for all the Python versions unless explicitly specified before the output. +**توجه:** همه مثال‌ها در برنامه مفسر تعاملی پایتون نسخه +۳.۵.۲ آزمایش شده‌اند و باید در همه نسخه‌های پایتون کار +کنند مگراینکه به صورت جداگانه و به طور واضح نسخه مخصوص +پایتون قبل از خروجی ذکر شده باشد. -# Usage -A nice way to get the most out of these examples, in my opinion, is to read them in sequential order, and for every example: -- Carefully read the initial code for setting up the example. If you're an experienced Python programmer, you'll successfully anticipate what's going to happen next most of the time. -- Read the output snippets and, - + Check if the outputs are the same as you'd expect. - + Make sure if you know the exact reason behind the output being the way it is. - - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfpython/issues/new)). - - If yes, give a gentle pat on your back, and you may skip to the next example. +# استفاده +یه راه خوب برای بیشتر بهره بردن، به نظرم، اینه که مثال‌ها رو به ترتیب متوالی بخونید و برای هر مثال: +- کد ابتدایی برای راه اندازی مثال رو با دقت بخونید. اگه شما یه پایتون کار سابقه‌دار باشید، با موفقیت بیشتر اوقات اتفاق بعدی رو پیش‌بینی می‌کنید. +- قطعه خروجی رو بخونید و + + بررسی کنید که آیا خروجی‌ها همونطور که انتظار دارید هستند. + + مطمئین بشید که دقیقا دلیل اینکه خروجی اون طوری هست رو می‌دونید. + - اگه نمی‌دونید (که کاملا عادیه و اصلا بد نیست)، یک نفس عمیق بکشید و توضیحات رو بخونید (و اگه نفهمیدید، داد بزنید! و [اینجا](https://github.com/emargi/wtfpython/issues/new) درموردش حرف بزنید). + - اگه می‌دونید، به افتخار خودتون یه دست محکم بزنید و برید سراغ مثال بعدی. --- # 👀 Examples From 1280f9c6709f1834fb531eedc9bc87a6f34ff509 Mon Sep 17 00:00:00 2001 From: Mohamad Reza Date: Thu, 27 Feb 2025 15:25:36 +0330 Subject: [PATCH 177/210] add first example in farsi --- translations/fa-farsi/README.md | 60 +++++++++++++++++---------------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index e20363a4..efcbb852 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -42,10 +42,10 @@ - [فهرست مطالب](#فهرست-مطالب) - [ساختار مثال‌ها](#structure-of-the-examples) - [استفاده](#استفاده) -- [👀 Examples](#-examples) - - [Section: Strain your brain!](#section-strain-your-brain) - - [▶ First things first! \*](#-first-things-first-) - - [💡 Explanation](#-explanation) +- [👀 مثال‌ها](#-مثال‌ها) + - [بخش: ذهن خود را به چالش بکشید!](#بخش-ذهن-خود-را-به-چالش-بکشید) + - [▶ اول از همه! \*](#-اول-از-همه-) + - [💡 توضیحات](#-توضیحات) - [▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند](#-بعضی-وقتها-رشتهها-میتوانند-دردسرساز-شوند) - [💡 Explanation:](#-explanation-1) - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) @@ -234,16 +234,16 @@ - اگه می‌دونید، به افتخار خودتون یه دست محکم بزنید و برید سراغ مثال بعدی. --- -# 👀 Examples +# 👀 مثال‌ها -## Section: Strain your brain! +## بخش: ذهن خود را به چالش بکشید! -### ▶ First things first! * +### ▶ اول از همه! * -For some reason, the Python 3.8's "Walrus" operator (`:=`) has become quite popular. Let's check it out, +به دلایلی، عملگر "Walrus" (`:=`) که در نسخه ۳.۸ پایتون معرفی شد، خیلی محبوب شده. بیاید بررسیش کنیم. 1\. @@ -260,7 +260,7 @@ File "", line 1 ^ SyntaxError: invalid syntax ->>> (a := "wtf_walrus") # This works though +>>> (a := "wtf_walrus") # ولی این کار می‌کنه 'wtf_walrus' >>> a 'wtf_walrus' @@ -280,19 +280,19 @@ SyntaxError: invalid syntax >>> a 6 ->>> a, b = 6, 9 # Typical unpacking +>>> a, b = 6, 9 # باز کردن معمولی >>> a, b (6, 9) ->>> (a, b = 16, 19) # Oops +>>> (a, b = 16, 19) # آخ آخ File "", line 1 (a, b = 16, 19) ^ SyntaxError: invalid syntax ->>> (a, b := 16, 19) # This prints out a weird 3-tuple +>>> (a, b := 16, 19) # این یه تاپل ۳تایی چاپ می‌کنه رو صفحه (6, 16, 19) ->>> a # a is still unchanged? +>>> a # هنوز تغییر نکرده؟ 6 >>> b @@ -301,33 +301,35 @@ SyntaxError: invalid syntax -#### 💡 Explanation +#### 💡 توضیحات -**Quick walrus operator refresher** +**مرور سریع بر عملگر Walrus** -The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression. +عملگر Walrus همونطور که اشاره شد، در نسخه ۳.۸ پایتون معرفی +شد. این عملگر می‌تونه تو مقعیت‌هایی کاربردی باشه که شما می‌خواید داخل یه عبارت، مقادیری رو به متغیرها اختصاص بدید ```py def some_func(): - # Assume some expensive computation here + # فرض کنید اینجا یک سری محاسبه سنگین انجام میشه # time.sleep(1000) return 5 -# So instead of, +# پس به جای اینکه این کارو بکنید: if some_func(): - print(some_func()) # Which is bad practice since computation is happening twice + print(some_func()) # که خیلی راه نادرستیه چون محاسبه دوبار انجام میشه -# or +# یا حتی این کارو کنید (که کار بدی هم نیست) a = some_func() if a: print(a) -# Now you can concisely write +# می‌تونید از این به بعد به طور مختصر بنویسید: if a := some_func(): print(a) + ``` -**Output (> 3.8):** +**خروجی (+۳.۸):** ```py 5 @@ -335,15 +337,15 @@ if a := some_func(): 5 ``` -This saved one line of code, and implicitly prevented invoking `some_func` twice. +این باعث میشه که یک خط کمتر کد بزنیم و از دوبار فراخوندن `some_func` جلوگیری کرد. -- 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`. +- "عبارت اختصاص‌دادن مقدار" بدون پرانتز (نحوه استفاده عملگر Walrus)، در سطح بالا محدود است، `SyntaxError` در عبارت `a := "wtf_walrus"` در قطعه‌کد اول به همین دلیل است. قرار دادن آن داخل پرانتز، همانطور که می‌خواستیم کار کرد و مقدار را به `a` اختصاص داد. -- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. +- به طور معمول، قرار دادن عبارتی که دارای `=` است داخل پرانتز مجاز نیست. به همین دلیل ‍عبارت `(a, b = 6, 9)` به ما خطای سینتکس داد. -- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, +- قائده استفاده از عملگر Walrus به صورت `NAME:= expr` است، به طوری که `NAME` یک شناسه صحیح و `expr` یک عبارت صحیح است. به همین دلیل باز و بسته کردن با تکرار (iterable) پشتیبانی نمی‌شوند. پس، - - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9) ` (where `a`'s value is 6') + - عبارت `(a := 6, 9)` معادل عبارت `((a := 6), 9)` و در نهایت `(a, 9)` است. (که مقدار `a` عدد 6 است) ```py >>> (a := 6, 9) == ((a := 6), 9) @@ -351,11 +353,11 @@ This saved one line of code, and implicitly prevented invoking `some_func` twice >>> x = (a := 696, 9) >>> x (696, 9) - >>> x[0] is a # Both reference same memory location + >>> x[0] is a # هر دو به یک مکان در حافظه دستگاه اشاره می‌کنند True ``` - - Similarly, `(a, b := 16, 19)` is equivalent to `(a, (b := 16), 19)` which is nothing but a 3-tuple. + - به طور مشابه، عبارت `(a, b := 16, 19)` معادل عبارت `(a, (b := 16), 19)` است که چیزی جز یک تاپل ۳تایی نیست. --- From e374a889e2005b7e4fff90172f5be5bed0114f3d Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Fri, 28 Feb 2025 09:05:27 +0300 Subject: [PATCH 178/210] Setup markdownlint Github Action --- .github/workflows/pr.yml | 7 +++++++ .markdownlint.yaml | 4 +++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 4da1774b..2120da77 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -14,4 +14,11 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - name: Write git diff to temp file + run: | + git fetch origin + git diff origin/${{ github.base_ref }} --unified=0 *.md translations/*/*.md \ + > ${{ runner.temp }}/diff.md - uses: DavidAnson/markdownlint-cli2-action@v17 + with: + globs: "${{ runner.temp }}/diff.md" diff --git a/.markdownlint.yaml b/.markdownlint.yaml index 7ebffd8d..09e4e924 100644 --- a/.markdownlint.yaml +++ b/.markdownlint.yaml @@ -1,4 +1,3 @@ -# MD013/line-length MD013: line_length: 120 @@ -13,3 +12,6 @@ MD033: false # no-inline-html : Bare URL used (site should be attributed transparently, because otherwise we have to un-necesarily explain where the link directs) MD034: false + +# first-line-h1 : First line in a file should be a top-level heading (Ignore because diff file will never have valid heading) +MD041: false From 6592360507af3faa32f2f795f75cb438932ebcf0 Mon Sep 17 00:00:00 2001 From: Mohamad Reza Date: Tue, 4 Mar 2025 17:14:28 +0330 Subject: [PATCH 179/210] update farsi translation - first section --- translations/fa-farsi/section1-temp.md | 492 +++++++++++++++++++++++++ 1 file changed, 492 insertions(+) create mode 100644 translations/fa-farsi/section1-temp.md diff --git a/translations/fa-farsi/section1-temp.md b/translations/fa-farsi/section1-temp.md new file mode 100644 index 00000000..eca01fa1 --- /dev/null +++ b/translations/fa-farsi/section1-temp.md @@ -0,0 +1,492 @@ +## بخش: ذهن خود را به چالش بکشید! + +### ▶ اول از همه! * + + + + +به دلایلی، عملگر "Walrus" (`:=`) که در نسخه ۳.۸ پایتون معرفی شد، خیلی محبوب شده. بیاید بررسیش کنیم. + +1\. + +```py +# Python version 3.8+ + +>>> a = "wtf_walrus" +>>> a +'wtf_walrus' + +>>> a := "wtf_walrus" +File "", line 1 + a := "wtf_walrus" + ^ +SyntaxError: invalid syntax + +>>> (a := "wtf_walrus") # ولی این کار می‌کنه +'wtf_walrus' +>>> a +'wtf_walrus' +``` + +2 \. + +```py +# Python version 3.8+ + +>>> a = 6, 9 +>>> a +(6, 9) + +>>> (a := 6, 9) +(6, 9) +>>> a +6 + +>>> a, b = 6, 9 # باز کردن معمولی +>>> a, b +(6, 9) +>>> (a, b = 16, 19) # آخ آخ + File "", line 1 + (a, b = 16, 19) + ^ +SyntaxError: invalid syntax + +>>> (a, b := 16, 19) # این یه تاپل ۳تایی چاپ می‌کنه رو صفحه +(6, 16, 19) + +>>> a # هنوز تغییر نکرده؟ +6 + +>>> b +16 +``` + + + +#### 💡 توضیحات + +**مرور سریع بر عملگر Walrus** + +عملگر Walrus همونطور که اشاره شد، در نسخه ۳.۸ پایتون معرفی +شد. این عملگر می‌تونه تو مقعیت‌هایی کاربردی باشه که شما می‌خواید داخل یه عبارت، مقادیری رو به متغیرها اختصاص بدید + +```py +def some_func(): + # فرض کنید اینجا یک سری محاسبه سنگین انجام میشه + # time.sleep(1000) + return 5 + +# پس به جای اینکه این کارو بکنید: +if some_func(): + print(some_func()) # که خیلی راه نادرستیه چون محاسبه دوبار انجام میشه + +# یا حتی این کارو کنید (که کار بدی هم نیست) +a = some_func() +if a: + print(a) + +# می‌تونید از این به بعد به طور مختصر بنویسید: +if a := some_func(): + print(a) + +``` + +**خروجی (+۳.۸):** + +```py +5 +5 +5 +``` + +این باعث میشه که یک خط کمتر کد بزنیم و از دوبار فراخوندن `some_func` جلوگیری کرد. + +- "عبارت اختصاص‌دادن مقدار" بدون پرانتز (نحوه استفاده عملگر Walrus)، در سطح بالا محدود است، `SyntaxError` در عبارت `a := "wtf_walrus"` در قطعه‌کد اول به همین دلیل است. قرار دادن آن داخل پرانتز، همانطور که می‌خواستیم کار کرد و مقدار را به `a` اختصاص داد. + +- به طور معمول، قرار دادن عبارتی که دارای `=` است داخل پرانتز مجاز نیست. به همین دلیل ‍عبارت `(a, b = 6, 9)` به ما خطای سینتکس داد. + +- قائده استفاده از عملگر Walrus به صورت `NAME:= expr` است، به طوری که `NAME` یک شناسه صحیح و `expr` یک عبارت صحیح است. به همین دلیل باز و بسته کردن با تکرار (iterable) پشتیبانی نمی‌شوند. پس، + + - عبارت `(a := 6, 9)` معادل عبارت `((a := 6), 9)` و در نهایت `(a, 9)` است. (که مقدار `a` عدد 6 است) + + ```py + >>> (a := 6, 9) == ((a := 6), 9) + True + >>> x = (a := 696, 9) + >>> x + (696, 9) + >>> x[0] is a # هر دو به یک مکان در حافظه دستگاه اشاره می‌کنند + True + ``` + + - به طور مشابه، عبارت `(a, b := 16, 19)` معادل عبارت `(a, (b := 16), 19)` است که چیزی جز یک تاپل ۳تایی نیست. + +--- + +### ▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند + + +1\. + +```py +>>> a = "some_string" +>>> id(a) +140420665652016 +>>> id("some" + "_" + "string") # دقت کنید که هردو شناسه یکسانند. +140420665652016 +``` + +2\. +```py +>>> a = "wtf" +>>> b = "wtf" +>>> a is b +True + +>>> a = "wtf!" +>>> b = "wtf!" +>>> a is b +False + +``` + +3\. + +```py +>>> a, b = "wtf!", "wtf!" +>>> a is b # همه‌ی نسخه‌ها به جز 3.7.x +True + +>>> a = "wtf!"; b = "wtf!" +>>> a is b # ممکن است True یا False باشد بسته به جایی که آن را اجرا می‌کنید (python shell / ipython / به‌صورت اسکریپت) +False +``` + +```py +# این بار در فایل some_file.py +a = "wtf!" +b = "wtf!" +print(a is b) + +# موقع اجرای ماژول، True را چاپ می‌کند! +``` + +4\. + +**خروجی (< Python3.7 )** + +```py +>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' +True +>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' +False +``` + +منطقیه، نه؟ + +#### 💡 توضیحات: ++ در قطعه‌کد اول و دوم، رفتار کد به دلیل یک بهینه سازی در CPython است (به نام داوطلب سازی رشته‌ها) که باعث می‌شود از برخی مقادیر غیرقابل تغییر، به جای مقداردهی مجدد، دوباره استفاده شود. ++ بیشتر متغیرهایی که به‌این صورت جایگزین می‌شوند، در حافظه دستگاه به مقدار داوطلب خود اشاره می‌کنند (تا از حافظه کمتری استفاده شود) ++ در قطعه‌کدهای بالا، رشته‌ها به‌صورت غیرمستقیم داوطلب می‌شوند. تصمیم اینکه رشته‌ها چه زمانی به صورت غیرمستقیم داوطلب شوند به نحوه پیاده‌سازی و مقداردهی آن‌ها بستگی دارد. برخی قوانین وجود دارند تا بتوانیم داوطلب شدن یا نشدن یک رشته را حدس بزنیم: + * همه رشته‌ها با طول صفر یا یک داوطلب می‌شوند. + * رشته‌ها در زمان کامپایل داوطلب می‌شوند (`'wtf'` داوطلب می‌شود اما `''.join(['w', 't', 'f'])` داوطلب نمی‌شود) + * رشته‌هایی که از حروف ASCII ، اعداد صحیح و آندرلاین تشکیل نشده‌باشند داوطلب نمی‌شود. به همین دلیل `'wtf!'` به خاطر وجود `'!'` داوطلب نشد. پیاده‌سازی این قانون در CPython در [اینجا](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) قرار دارد. + +

+ + + + Shows a string interning process. + +

+ ++ زمانی که `"wtf!"` را در یک خط به `a` و `b` اختصاص می‌دهیم، مفسر پایتون شیء جدید می‌سازد و متغیر دوم را به آن ارجاع می‌دهد. اگر مقدار دهی در خط‌های جدا از هم انجام شود، در واقع مفسر "خبر ندارد" که یک شیء مختص به `"wtf!"` از قبل در برنامه وجود دارد (زیرا `"wtf!"` به دلایلی که در بالا گفته شد، به‌صورت غیرمستقیم داوطلب نمی‌شود). این بهینه سازی در زمان کامپایل انجام می‌شود. این بهینه سازی همچنین برای نسخه های (x).۳.۷ وجود ندارد (برای گفت‌وگوی بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) را ببینید). ++ یک واحد کامپایل در یک محیط تعاملی مانند IPython از یک عبارت تشکیل می‌شود، در حالی که برای ماژول‌ها شامل کل ماژول می‌شود. `a, b = "wtf!", "wtf!"` یک عبارت است. در حالی که `a = "wtf!"; b = "wtf!"` دو عبارت در یک خط است. به همین دلیل شناسه‌ها در `a = "wtf!"; b = "wtf!"` متفاوتند و همین‌طور وقتی با مفسر پایتون داخل فایل `some_file.py` اجرا می‌شوند، شناسه‌ها یکسانند. ++ تغییر ناگهانی در خروجی قطعه‌کد چهارم به دلیل [بهینه‌سازی پنجره‌ای](https://en.wikipedia.org/wiki/Peephole_optimization) است که تکنیکی معروف به جمع آوری ثابت‌ها است. به همین خاطر عبارت `'a'*20` با `'aaaaaaaaaaaaaaaaaaaa'` در هنگام کامپایل جایگزین می‌شود تا کمی بار از دوش چرخه‌ساعتی پردازنده کم شود. تکنیک جمع آوری ثابت‌ها فقط مخصوص رشته‌هایی با طول کمتر از 21 است. (چرا؟ فرض کنید که فایل `.pyc` که توسط کامپایلر ساخته می‌شود چقدر بزرگ می‌شد اگر عبارت `'a'*10**10`). [این](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) هم کد پیاده‌سازی این تکنیک در CPython. ++ توجه: در پایتون ۳.۷، جمع آوری ثابت‌ها از بهینه‌ساز پنجره‌ای به بهینه‌ساز AST جدید انتقال داده شد همراه با تغییراتی در منطق آن. پس چهارمین قطعه‌کد در پایتون نسخه ۳.۷ کار نمی‌کند. شما می‌توانید در [اینجا](https://bugs.python.org/issue11549) بیشتر درمورد این تغییرات بخوانید. + +--- + + +### ▶ مراقب عملیات‌های زنجیره‌ای باشید + +```py +>>> (False == False) in [False] # منطقیه +False +>>> False == (False in [False]) # منطقیه +False +>>> False == False in [False] # حالا چی؟ +True + +>>> True is False == False +False +>>> False is False is False +True + +>>> 1 > 0 < 1 +True +>>> (1 > 0) < 1 +False +>>> 1 > (0 < 1) +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` و `0 <= x <= 100` عالی عمل می‌کنه. + +* عبارت `False is False is False` معادل عبارت `(False is False) and (False is False)` است +* عبارت `True is False == False` معادل عبارت `(True is False) and (False == False)` است و از آنجایی که قسمت اول این عبارت (`True is False`) پس از ارزیابی برابر با `False` می‌شود. پس کل عبارت معادل `False` می‌شود. +* عبارت `1 > 0 < 1` معادل عبارت `(1 > 0) and (0 < 1)` است. +* عبارت `(1 > 0) < 1` معادل عبارت `True < 1` است و : + ```py + >>> int(True) + 1 + >>> True + 1 # مربوط به این بخش نیست ولی همینجوری گذاشتم + 2 + ``` + پس عبارت `True < 1` معادل عبارت `1 < 1` می‌شود که در کل معادل `False` است. + +--- + +### ▶ چطور از عملگر `is` استفاده نکنیم + +عبارت پایین خیلی معروفه و تو کل اینترنت موجوده. + +1\. + +```py +>>> a = 256 +>>> b = 256 +>>> a is b +True + +>>> a = 257 +>>> b = 257 +>>> a is b +False +``` + +2\. + +```py +>>> a = [] +>>> b = [] +>>> a is b +False + +>>> a = tuple() +>>> b = tuple() +>>> a is b +True +``` + +3\. +**خروجی** + +```py +>>> a, b = 257, 257 +>>> a is b +True +``` + +**خروجی (مخصوص نسخه‌های (x).۳.۷)** + +```py +>>> a, b = 257, 257 +>>> a is b +False +``` + +#### 💡 توضیحات: + +**فرض بین عملگرهای `is` و `==`** + +* عملگر `is` بررسی میکنه که دو متغیر در حافظه دستگاه به یک شیء اشاره میکنند یا نه (یعنی شناسه متغیرها رو با هم تطبیق میده). +* عملگر `==` مقدار متغیرها رو با هم مقایسه میکنه و یکسان بودنشون رو بررسی میکنه. +* پس `is` برای معادل بودن متغیرها در حافظه دستگاه و `==` برای معادل بودن مقادیر استفاده میشه. یه مثال برای شفاف سازی بیشتر: + ```py + >>> class A: pass + >>> A() is A() # این‌ها دو شیء خالی هستند که در دو جای مختلف در حافظه قرار دارند. + False + ``` + +**عدد `256` از قبل تو حافظه قرار داده شده ولی `257` نه؟** + +وقتی پایتون رو اجرا می‌کنید اعداد از `-5` تا `256` در حافظه ذخیره میشن. چون این اعداد خیلی پرکاربرد هستند پس منطقیه که اون‌ها رو در حافظه دستگاه، آماده داشته باشیم. + +نقل قول از https://docs.python.org/3/c-api/long.html +> در پیاده سازی فعلی یک آرایه از اشیاء عددی صحیح برای تمام اعداد صحیح بین `-5` تا `256` نگه‌داری می‌شود. وقتی شما یک عدد صحیح در این بازه به مقداردهی می‌کنید، فقط یک ارجاع به آن عدد که از قبل در حافظه ذخیره شده است دریافت می‌کنید. پس تغییر مقدار عدد 1 باید ممکن باشد. که در این مورد من به رفتار پایتون شک دارم تعریف‌نشده است. :-) + +```py +>>> id(256) +10922528 +>>> a = 256 +>>> b = 256 +>>> id(a) +10922528 +>>> id(b) +10922528 +>>> id(257) +140084850247312 +>>> x = 257 +>>> y = 257 +>>> id(x) +140084850247440 +>>> id(y) +140084850247344 +``` + +در اینجا مفسر وقتی عبارت `y = 257` رو اجرا میکنه، به اندازه کافی زیرکانه عمل نمیکنه که تشخیص بده که ما یک عدد صحیح با مقدار `257` در حافظه ذخیره کرده‌ایم، پس به ساختن یک شیء جدید در حافظه ادامه میده. + +یک بهینه سازی مشابه شامل حال مقادیر **غیرقابل تغییر** دیگه مانند تاپل‌های خالی هم میشه. از اونجایی که لیست‌ها قابل تغییرند، عبارت `[] is []` مقدار `False` رو برمیگردونه و عبارت `() is ()` مقدار `True` رو برمیگردونه. به همین دلیله که قطعه کد دوم چنین رفتاری داره. بریم سراغ سومی. + +**متغیرهای `a` و `b` وقتی در یک خط با مقادیر یکسانی مقداردهی میشن، هردو به یک شیء در حافظه اشاره میکنن** + +**خروجی** + +```py +>>> a, b = 257, 257 +>>> id(a) +140640774013296 +>>> id(b) +140640774013296 +>>> a = 257 +>>> b = 257 +>>> id(a) +140640774013392 +>>> id(b) +140640774013488 +``` + +* وقتی a و b در یک خط با `257` مقداردهی میشن، مفسر پایتون یک شیء برای یکی از متغیرها در حافظه میسازه و متغیر دوم رو در حافظه به اون ارجاع میده. اگه این کار رو تو دو خط جدا از هم انجام بدید، درواقع مفسر پایتون از وجود مقدار `257` به عنوان یک شیء، "خبر نداره". + +* این یک بهینه سازی توسط کامپایلر هست و مخصوصا در محیط تعاملی به کار برده میشه. وقتی شما دو خط رو در یک مفسر زنده وارد می‌کنید، اون‌ها به صورت جداگانه کامپایل میشن، به همین دلیل بهینه سازی به صورت جداگانه برای هرکدوم اعمال میشه. اگر بخواهید این مثال رو در یک فایل `.py` امتحان کنید، رفتار متفاوتی می‌بینید زیرا فایل به صورت کلی و یک‌جا کامپایل میشه. این بهینه سازی محدود به اعداد صحیح نیست و برای انواع داده‌های غیرقابل تغییر دیگه مانند رشته‌ها (مثال "رشته‌ها می‌توانند دردسرساز شوند" رو ببینید) و اعداد اعشاری هم اعمال میشه. + + ```py + >>> a, b = 257.0, 257.0 + >>> a is b + True + ``` + +* چرا این برای پایتون ۳.۷ کار نکرد؟ دلیل انتزاعیش اینه که چنین بهینه‌سازی‌های کامپایلری وابسته به پیاده‌سازی هستن (یعنی بسته به نسخه، و نوع سیستم‌عامل و چیزهای دیگه تغییر میکنن). من هنوز پیگیرم که بدونم که کدوم تغییر تو پیاده‌سازی باعث همچین مشکلاتی میشه، می‌تونید برای خبرهای بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) رو نگاه کنید. + +--- + + +### ▶ کلیدهای هش + +1\. +```py +some_dict = {} +some_dict[5.5] = "JavaScript" +some_dict[5.0] = "Ruby" +some_dict[5] = "Python" +``` + +**Output:** + +```py +>>> some_dict[5.5] +"JavaScript" +>>> some_dict[5.0] # رشته ("Python")، رشته ("Ruby") رو از بین برد؟ +"Python" +>>> some_dict[5] +"Python" + +>>> complex_five = 5 + 0j +>>> type(complex_five) +complex +>>> some_dict[complex_five] +"Python" +``` + +خب، چرا Python همه جارو گرفت؟ + + +#### 💡 توضیحات +* تو دیکشنری‌های پایتون چیزی که کلیدها رو یگانه میکنه مقدار کلیدهاست، نه شناسه اون‌ها. پس با اینکه `5`، `5.0` و `5 + 0j` شیءهای متمایزی از نوع‌های متفاوتی هستند ولی از اون جایی که مقدارشون با هم برابره، نمیتونن داخل یه `dict` به عنوان کلید جدا از هم باشن (حتی به عنوان مقادیر داخل یه `set` نمیتونن باشن). وقتی بخواید داخل یه دیکشنری جست‌وجو کنید، به محض اینکه یکی از این داده‌ها رو وارد کنید، مقدار نگاشته‌شده به کلیدی که مقدار برابر با اون داده داره ولی نوعش متفاوته، با موفقیت برگردونده میشه (به جای اینکه به ارور `KeyError` بردخورد کنید.). + ```py + >>> 5 == 5.0 == 5 + 0j + True + >>> 5 is not 5.0 is not 5 + 0j + True + >>> some_dict = {} + >>> some_dict[5.0] = "Ruby" + >>> 5.0 in some_dict + True + >>> (5 in some_dict) and (5 + 0j in some_dict) + True + ``` +* همچنین این قانون برای مقداردهی توی دیکشنری هم اعمال میشه. وقتی شما عبارت `some_dict[5] = "Python"` رو اجرا می‌کنید، پایتون دنبال کلیدی با مقدار یکسان می‌گرده که اینجا ما داریم `5.0 -> "Ruby"` و مقدار نگاشته‌شده به این کلید در دیکشنری رو با مقدار جدید جایگزین میکنه و کلید رو همونجوری که هست باقی میذاره. + ```py + >>> some_dict + {5.0: 'Ruby'} + >>> some_dict[5] = "Python" + >>> some_dict + {5.0: 'Python'} + ``` +* خب پس چطوری میتونیم مقدار خود کلید رو به `5` تغییر بدیم (جای `5.0`)؟ راستش ما نمیتونیم این کار رو درجا انجام بدیم، ولی میتونیم اول اون کلید رو پاک کنیم (`del some_dict[5.0]`) و بعد کلیدی که میخوایم رو قرار بدیم (`some_dict[5]`) تا بتونیم عدد صحیح `5` رو به جای عدد اعشاری `5.0` به عنوان کلید داخل دیکشنری داشته باشیم. درکل خیلی کم پیش میاد که بخوایم چنین کاری کنیم. + +* پایتون چطوری توی دیکشنری که کلید `5.0` رو داره، کلید `5` رو پیدا کرد؟ پایتون این کار رو توی زمان ثابتی توسط توابع هش انجام میده بدون اینکه مجبور باشه همه کلیدها رو بررسی کنه. وقتی پایتون دنبال کلیدی مثل `foo` داخل یه `dict` میگرده، اول مقدار `hash(foo)` رو محاسبه میکنه (که توی زمان ثابتی انجام میشه). از اونجایی که توی پایتون برای مقایسه برابری مقدار دو شیء لازمه که هش یکسانی هم داشته باشند ([مستندات](https://docs.python.org/3/reference/datamodel.html#object.__hash__)). `5`، `5.0` و `5 + 0j` مقدار هش یکسانی دارند. + ```py + >>> 5 == 5.0 == 5 + 0j + True + >>> hash(5) == hash(5.0) == hash(5 + 0j) + True + ``` + **توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیده‌ای معروف [تصادم هش]() میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند. + +--- + +### ▶ در عمق وجود همه ما یکسان هستیم + +```py +class WTF: + pass +``` + +**Output:** +```py +>>> WTF() == WTF() # دو نمونه متفاوت از یک کلاس نمیتونند برابر هم باشند +False +>>> WTF() is WTF() # شناسه‌ها هم متفاوتند +False +>>> hash(WTF()) == hash(WTF()) # هش‌ها هم _باید_ متفاوت باشند +True +>>> id(WTF()) == id(WTF()) +True +``` + +#### 💡 توضیحات: +* وقتی `id` صدا زده شد، پایتون یک شیء با کلاس `WTF` ساخت و اون رو به تابع `id` داد. تابع `id` شناسه این شیء رو میگیره (درواقع آدرس اون شیء در حافظه دستگاه) و شیء رو حذف میکنه. +* وقتی این کار رو دو بار متوالی انجام بدیم، پایتون آدرس یکسانی رو به شیء دوم اختصاص میده. از اونجایی که (در CPython) تابع `id` از آدرس شیءها توی حافظه به عنوان شناسه برای اون‌ها استفاده میکنه، پس شناسه این دو شیء یکسانه. +* پس، شناسه یک شیء تا زمانی که اون شیء وجود داره، منحصربه‌فرده. بعد از اینکه اون شیء حذف میشه یا قبل از اینکه اون شیء به وجود بیاد، چیز دیگه‌ای میتونه اون شناسه رو داشته باشه. +* ولی چرا با عملگر `is` مقدار `False` رو دریافت کردیم؟ بیاید با یه قطعه‌کد ببینیم دلیلش رو. + ```py + class WTF(object): + def __init__(self): print("I") + def __del__(self): print("D") + ``` + + **خروجی:** + ```py + >>> WTF() is WTF() + I + I + D + D + False + >>> id(WTF()) == id(WTF()) + I + D + I + D + True + ``` + همونطور که مشاهده می‌کنید، ترتیب حذف شدن شیءها باعث تفاوت میشه. + +--- From 4d8e193d654c5ad90df0e65eca276b3434230c18 Mon Sep 17 00:00:00 2001 From: Mohamad Reza Date: Tue, 11 Mar 2025 00:41:07 +0330 Subject: [PATCH 180/210] update farsi translation - section 1 --- translations/fa-farsi/section1-temp.md | 298 +++++++++++++++++++++++++ 1 file changed, 298 insertions(+) diff --git a/translations/fa-farsi/section1-temp.md b/translations/fa-farsi/section1-temp.md index eca01fa1..9d70bb40 100644 --- a/translations/fa-farsi/section1-temp.md +++ b/translations/fa-farsi/section1-temp.md @@ -490,3 +490,301 @@ True همونطور که مشاهده می‌کنید، ترتیب حذف شدن شیءها باعث تفاوت میشه. --- + + +### ▶ بی‌نظمی در خود نظم * + +```py +from collections import OrderedDict + +dictionary = dict() +dictionary[1] = 'a'; dictionary[2] = 'b'; + +ordered_dict = OrderedDict() +ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; + +another_ordered_dict = OrderedDict() +another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; + +class DictWithHash(dict): + """ + یک dict که تابع جادویی __hash__ هم توش پیاده شده. + """ + __hash__ = lambda self: 0 + +class OrderedDictWithHash(OrderedDict): + """ + یک OrderedDict که تابع جادویی __hash__ هم توش پیاده شده. + """ + __hash__ = lambda self: 0 +``` + +**Output** +```py +>>> dictionary == ordered_dict # اگر مقدار اولی با دومی برابره +True +>>> dictionary == another_ordered_dict # و مقدار اولی با سومی برابره +True +>>> ordered_dict == another_ordered_dict # پس چرا مقدار دومی با سومی برابر نیست؟ +False + +# ما همه‌مون میدونیم که یک مجموعه فقط شامل عناصر منحصربه‌فرد و غیرتکراریه. +# بیاید یک مجموعه از این دیکشنری‌ها بسازیم ببینیم چه اتفاقی میافته... + +>>> len({dictionary, ordered_dict, another_ordered_dict}) +Traceback (most recent call last): + File "", line 1, in +TypeError: unhashable type: 'dict' + +# منطقیه چون dict ها __hash__ توشون پیاده‌سازی نشده. پس بیاید از +# کلاس‌هایی که خودمون درست کردیم استفاده کنیم. +>>> dictionary = DictWithHash() +>>> dictionary[1] = 'a'; dictionary[2] = 'b'; +>>> ordered_dict = OrderedDictWithHash() +>>> ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; +>>> another_ordered_dict = OrderedDictWithHash() +>>> another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; +>>> len({dictionary, ordered_dict, another_ordered_dict}) +1 +>>> len({ordered_dict, another_ordered_dict, dictionary}) # ترتیب رو عوض می‌کنیم +2 +``` + +چی شد؟ + +#### 💡 توضیحات: + +- دلیل اینکه این مقایسه بین متغیرهای `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` ها رو هرجایی که یک دیکشنری عادی کاربرد داره، جایگزین کنیم و استفاده کنیم. +- خب، حالا چرا تغییر ترتیب روی طول مجموعه‌ای که از دیکشنری‌ها ساختیم، تاثیر گذاشت؟ جوابش همین رفتار مقایسه‌ای غیرانتقالی بین این شیءهاست. از اونجایی که `set` ها مجموعه‌ای از عناصر غیرتکراری و بدون نظم هستند، ترتیبی که عناصر تو این مجموعه‌ها درج میشن نباید مهم باشه. ولی در این مورد، مهم هست. بیاید کمی تجزیه و تحلیلش کنیم. + ```py + >>> some_set = set() + >>> some_set.add(dictionary) # این شیء‌ها از قطعه‌کدهای بالا هستند. + >>> 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_ordered_dict in another_set` برابر با `False` هست چون `ordered_dict` از قبل داخل `another_set` هست و همونطور که قبلا مشاهده کردید، مقدار `ordered_dict == another_ordered_dict` برابر با `False` هست. + +--- + + +### ▶ تلاش کن... * + +```py +def some_func(): + try: + return 'from_try' + finally: + return 'from_finally' + +def another_func(): + for _ in range(3): + try: + continue + finally: + print("Finally!") + +def one_more_func(): + try: + for i in range(3): + try: + 1 / i + except ZeroDivisionError: + # بذارید اینجا ارور بدیم و بیرون حلقه بهش + # رسیدگی کنیم + raise ZeroDivisionError("A trivial divide by zero error") + finally: + print("Iteration", i) + break + except ZeroDivisionError as e: + print("Zero division error occurred", e) +``` + +**خروجی:** + +```py +>>> some_func() +'from_finally' + +>>> another_func() +Finally! +Finally! +Finally! + +>>> 1 / 0 +Traceback (most recent call last): + File "", line 1, in +ZeroDivisionError: division by zero + +>>> one_more_func() +Iteration 0 + +``` + +#### 💡 Explanation: + +- وقتی یک عبارت `return`، `break` یا `continue` داخل بخش `try` از یک عبارت "try...finally" اجرا میشه، بخش `fianlly` هم هنگام خارج شدن اجرا میشه. +- مقدار بازگشتی یک تابع از طریق آخرین عبارت `return` که داخل تابع اجرا میشه، مشخص میشه. از اونجایی که بخش `finally` همیشه اجرا میشه، عبارت `return` که داخل بخش `finally` هست آخرین عبارتیه که اجرا میشه. +- نکته اینجاست که اگه بخش داخل بخش `finally` یک عبارت `return` یا `break` اجرا بشه، `exception` موقتی که ذخیره شده، رها میشه. + +--- + + +### ▶ برای چی? + +```py +some_string = "wtf" +some_dict = {} +for i, some_dict[i] in enumerate(some_string): + i = 10 +``` + +**Output:** +```py +>>> some_dict # یک دیکشنری مرتب‌شده نمایان میشه. +{0: 'w', 1: 't', 2: 'f'} +``` + +#### 💡 توضیحات: +* یک حلقه `for` در [گرامر پایتون](https://docs.python.org/3/reference/grammar.html) این طور تعریف میشه: + ``` + for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] + ``` + به طوری که `exprlist` یک هدف برای مقداردهیه. این یعنی، معادل عبارت `{exprlist} = {next_value}` **برای هر شیء داخل `testlist` اجرا می‌شود**. + یک مثال جالب برای نشون دادن این تعریف: + ```py + for i in range(4): + print(i) + i = 10 + ``` + + **خروجی:** + ``` + 0 + 1 + 2 + 3 + ``` + + آیا انتظار داشتید که حلقه فقط یک بار اجرا بشه؟ + + **💡 توضیحات:** + + - عبارت مقداردهی `i = 10` به خاطر نحوه کار کردن حلقه‌ها، هیچوقت باعث تغییر در تکرار حلقه نمیشه. قبل از شروع هر تکرار، مقدار بعدی که توسط شیء قابل تکرار (که در اینجا `range(4)` است) ارائه میشه، از بسته خارج میشه و به متغیرهای لیست هدف (که در اینجا `i` است) مقداردهی میشه. + +* تابع `enumerate(some_string)`، یک متغیر `i` (که یک شمارنده اقزایشی است) و یک حرف از حروف رشته `some_string` رو در هر تکرار برمیگردونه. و بعدش برای کلید `i` (تازه مقداردهی‌شده) در دیکشنری `some_dict`، مقدار اون حرف رو تنظیم می‌کنه. بازشده این حلقه می‌تونه مانند مثال زیر ساده بشه: + ```py + >>> i, some_dict[i] = (0, 'w') + >>> i, some_dict[i] = (1, 't') + >>> i, some_dict[i] = (2, 'f') + >>> some_dict + ``` + +--- + +### ▶ اختلاف زمانی در محاسبه + +1\. +```py +array = [1, 8, 15] +# یک عبارت تولیدکننده عادی +gen = (x for x in array if array.count(x) > 0) +array = [2, 8, 22] +``` + +**خروجی:** + +```py +>>> print(list(gen)) # پس بقیه مقدارها کجا رفتن؟ +[8] +``` + +2\. + +```py +array_1 = [1,2,3,4] +gen_1 = (x for x in array_1) +array_1 = [1,2,3,4,5] + +array_2 = [1,2,3,4] +gen_2 = (x for x in array_2) +array_2[:] = [1,2,3,4,5] +``` + +**خروجی:** +```py +>>> print(list(gen_1)) +[1, 2, 3, 4] + +>>> print(list(gen_2)) +[1, 2, 3, 4, 5] +``` + +3\. + +```py +array_3 = [1, 2, 3] +array_4 = [10, 20, 30] +gen = (i + j for i in array_3 for j in array_4) + +array_3 = [4, 5, 6] +array_4 = [400, 500, 600] +``` + +**خروجی:** +```py +>>> print(list(gen)) +[401, 501, 601, 402, 502, 602, 403, 503, 603] +``` + +#### 💡 توضیحات + +- در یک عبارت [تولیدکننده](https://wiki.python.org/moin/Generators)، عبارت بند `in` در هنگام تعریف محاسبه میشه ولی عبارت شرطی در زمان اجرا محاسبه میشه. +- پس قبل از زمان اجرا، `array` دوباره با لیست `[2, 8, 22]` مقداردهی میشه و از آن‌جایی که در مقدار جدید `array`، بین `1`، `8` و `15`، فقط تعداد `8` بزرگتر از `0` است، تولیدکننده فقط مقدار `8` رو برمیگردونه +- تفاوت در مقدار `gen_1` و `gen_2` در بخش دوم به خاطر نحوه مقداردهی دوباره `array_1` و `array_2` است. +- در مورد اول، متغیر `array_1` به شیء جدید `[1,2,3,4,5]` وصله و از اون جایی که عبارت بند `in` در هنگام تعریف محاسبه میشه، `array_1` داخل تولیدکننده هنوز به شیء قدیمی `[1,2,3,4]` (که هنوز حذف نشده) +- در مورد دوم، مقداردهی برشی به `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` بلافاصله محاسبه میشه و باقی عبارت‌ها به تعویق انداخته میشن تا زمانی که تولیدکننده اجرا بشه. + +--- + + +### ▶ هر گردی، گردو نیست + +```py +>>> 'something' is not None +True +>>> 'something' is (not None) +False +``` + +#### 💡 توضیحات +- عملگر `is not` یک عملگر باینری واحده و رفتارش متفاوت تر از استفاده `is` و `not` به صورت جداگانه‌ست. +- عملگر `is not` مقدار `False` رو برمیگردونه اگر متغیرها در هردو سمت این عملگر به شیء یکسانی اشاره کنند و درغیر این صورت، مقدار `True` برمیگردونه +- در مثال بالا، عبارت `(not None)` برابره با مقدار `True` از اونجایی که مقدار `None` در زمینه boolean به `False` تبدیل میشه. پس کل عبارت معادل عبارت `'something' is True` میشه. + +--- From 5dde16cd859354c91c8667812dc8b7648a30760f Mon Sep 17 00:00:00 2001 From: Mohamad Reza Date: Tue, 11 Mar 2025 00:48:59 +0330 Subject: [PATCH 181/210] translate missed words --- translations/fa-farsi/section1-temp.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/translations/fa-farsi/section1-temp.md b/translations/fa-farsi/section1-temp.md index 9d70bb40..f14400dd 100644 --- a/translations/fa-farsi/section1-temp.md +++ b/translations/fa-farsi/section1-temp.md @@ -387,7 +387,7 @@ some_dict[5.0] = "Ruby" some_dict[5] = "Python" ``` -**Output:** +**خروجی:** ```py >>> some_dict[5.5] @@ -449,7 +449,7 @@ class WTF: pass ``` -**Output:** +**خروجی:** ```py >>> WTF() == WTF() # دو نمونه متفاوت از یک کلاس نمیتونند برابر هم باشند False @@ -519,7 +519,7 @@ class OrderedDictWithHash(OrderedDict): __hash__ = lambda self: 0 ``` -**Output** +**خروجی** ```py >>> dictionary == ordered_dict # اگر مقدار اولی با دومی برابره True @@ -643,7 +643,7 @@ Iteration 0 ``` -#### 💡 Explanation: +#### 💡 توضیحات: - وقتی یک عبارت `return`، `break` یا `continue` داخل بخش `try` از یک عبارت "try...finally" اجرا میشه، بخش `fianlly` هم هنگام خارج شدن اجرا میشه. - مقدار بازگشتی یک تابع از طریق آخرین عبارت `return` که داخل تابع اجرا میشه، مشخص میشه. از اونجایی که بخش `finally` همیشه اجرا میشه، عبارت `return` که داخل بخش `finally` هست آخرین عبارتیه که اجرا میشه. @@ -661,7 +661,7 @@ for i, some_dict[i] in enumerate(some_string): i = 10 ``` -**Output:** +**خروجی:** ```py >>> some_dict # یک دیکشنری مرتب‌شده نمایان میشه. {0: 'w', 1: 't', 2: 'f'} From bcd17d39652dc40d091834a79a7764a8dc91cefa Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sun, 16 Mar 2025 19:25:55 +0100 Subject: [PATCH 182/210] Translate info sections at the end --- translations/fa-farsi/README.md | 178 ++++++++++++++++---------------- 1 file changed, 90 insertions(+), 88 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index efcbb852..b8fbb9dc 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -40,146 +40,146 @@ - [فهرست مطالب](#فهرست-مطالب) -- [ساختار مثال‌ها](#structure-of-the-examples) +- [ساختار مثال‌ها](#ساختار-مثالها) - [استفاده](#استفاده) -- [👀 مثال‌ها](#-مثال‌ها) +- [👀 مثال‌ها](#-مثالها) - [بخش: ذهن خود را به چالش بکشید!](#بخش-ذهن-خود-را-به-چالش-بکشید) - [▶ اول از همه! \*](#-اول-از-همه-) - [💡 توضیحات](#-توضیحات) - [▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند](#-بعضی-وقتها-رشتهها-میتوانند-دردسرساز-شوند) - - [💡 Explanation:](#-explanation-1) + - [💡 Explanation:](#-explanation) - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - - [💡 Explanation:](#-explanation-2) + - [💡 Explanation:](#-explanation-1) - [▶ How not to use `is` operator](#-how-not-to-use-is-operator) - - [💡 Explanation:](#-explanation-3) + - [💡 Explanation:](#-explanation-2) - [▶ Hash brownies](#-hash-brownies) - - [💡 Explanation](#-explanation-4) + - [💡 Explanation](#-explanation-3) - [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) - - [💡 Explanation:](#-explanation-5) + - [💡 Explanation:](#-explanation-4) - [▶ Disorder within order \*](#-disorder-within-order-) - - [💡 Explanation:](#-explanation-6) + - [💡 Explanation:](#-explanation-5) - [▶ Keep trying... \*](#-keep-trying-) - - [💡 Explanation:](#-explanation-7) + - [💡 Explanation:](#-explanation-6) - [▶ For what?](#-for-what) - - [💡 Explanation:](#-explanation-8) + - [💡 Explanation:](#-explanation-7) - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - - [💡 Explanation](#-explanation-9) + - [💡 Explanation](#-explanation-8) - [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) - - [💡 Explanation](#-explanation-10) + - [💡 Explanation](#-explanation-9) - [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - - [💡 Explanation:](#-explanation-11) + - [💡 Explanation:](#-explanation-10) - [▶ Schrödinger's variable \*](#-schrödingers-variable-) - - [💡 Explanation:](#-explanation-12) + - [💡 Explanation:](#-explanation-11) - [▶ The chicken-egg problem \*](#-the-chicken-egg-problem-) - - [💡 Explanation](#-explanation-13) + - [💡 Explanation](#-explanation-12) - [▶ Subclass relationships](#-subclass-relationships) - - [💡 Explanation:](#-explanation-14) + - [💡 Explanation:](#-explanation-13) - [▶ Methods equality and identity](#-methods-equality-and-identity) - - [💡 Explanation](#-explanation-15) + - [💡 Explanation](#-explanation-14) - [▶ All-true-ation \*](#-all-true-ation-) + - [💡 Explanation:](#-explanation-15) - [💡 Explanation:](#-explanation-16) - - [💡 Explanation:](#-explanation-17) - [▶ Strings and the backslashes](#-strings-and-the-backslashes) - - [💡 Explanation](#-explanation-18) + - [💡 Explanation](#-explanation-17) - [▶ not knot!](#-not-knot) - - [💡 Explanation:](#-explanation-19) + - [💡 Explanation:](#-explanation-18) - [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - - [💡 Explanation:](#-explanation-20) + - [💡 Explanation:](#-explanation-19) - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - - [💡 Explanation:](#-explanation-21) + - [💡 Explanation:](#-explanation-20) - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - - [💡 Explanation:](#-explanation-22) + - [💡 Explanation:](#-explanation-21) - [▶ yielding None](#-yielding-none) - - [💡 Explanation:](#-explanation-23) + - [💡 Explanation:](#-explanation-22) - [▶ Yielding from... return! \*](#-yielding-from-return-) - - [💡 Explanation:](#-explanation-24) + - [💡 Explanation:](#-explanation-23) - [▶ Nan-reflexivity \*](#-nan-reflexivity-) - - [💡 Explanation:](#-explanation-25) + - [💡 Explanation:](#-explanation-24) - [▶ Mutating the immutable!](#-mutating-the-immutable) - - [💡 Explanation:](#-explanation-26) + - [💡 Explanation:](#-explanation-25) - [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) - - [💡 Explanation:](#-explanation-27) + - [💡 Explanation:](#-explanation-26) - [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) - - [💡 Explanation:](#-explanation-28) + - [💡 Explanation:](#-explanation-27) - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) - - [💡 Explanation:](#-explanation-29) + - [💡 Explanation:](#-explanation-28) - [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) - - [💡 Explanation:](#-explanation-30) + - [💡 Explanation:](#-explanation-29) - [Section: Slippery Slopes](#section-slippery-slopes) - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) - - [💡 Explanation:](#-explanation-31) + - [💡 Explanation:](#-explanation-30) - [▶ Stubborn `del` operation](#-stubborn-del-operation) - - [💡 Explanation:](#-explanation-32) + - [💡 Explanation:](#-explanation-31) - [▶ The out of scope variable](#-the-out-of-scope-variable) - - [💡 Explanation:](#-explanation-33) + - [💡 Explanation:](#-explanation-32) - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - - [💡 Explanation:](#-explanation-34) + - [💡 Explanation:](#-explanation-33) - [▶ Lossy zip of iterators \*](#-lossy-zip-of-iterators-) - - [💡 Explanation:](#-explanation-35) + - [💡 Explanation:](#-explanation-34) - [▶ Loop variables leaking out!](#-loop-variables-leaking-out) - - [💡 Explanation:](#-explanation-36) + - [💡 Explanation:](#-explanation-35) - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - - [💡 Explanation:](#-explanation-37) + - [💡 Explanation:](#-explanation-36) - [▶ Catching the Exceptions](#-catching-the-exceptions) - - [💡 Explanation](#-explanation-38) + - [💡 Explanation](#-explanation-37) - [▶ Same operands, different story!](#-same-operands-different-story) - - [💡 Explanation:](#-explanation-39) + - [💡 Explanation:](#-explanation-38) - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - - [💡 Explanation](#-explanation-40) + - [💡 Explanation](#-explanation-39) - [▶ Rounding like a banker \*](#-rounding-like-a-banker-) - - [💡 Explanation:](#-explanation-41) + - [💡 Explanation:](#-explanation-40) - [▶ Needles in a Haystack \*](#-needles-in-a-haystack-) - - [💡 Explanation:](#-explanation-42) + - [💡 Explanation:](#-explanation-41) - [▶ Splitsies \*](#-splitsies-) - - [💡 Explanation:](#-explanation-43) + - [💡 Explanation:](#-explanation-42) - [▶ Wild imports \*](#-wild-imports-) - - [💡 Explanation:](#-explanation-44) + - [💡 Explanation:](#-explanation-43) - [▶ All sorted? \*](#-all-sorted-) - - [💡 Explanation:](#-explanation-45) + - [💡 Explanation:](#-explanation-44) - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - - [💡 Explanation:](#-explanation-46) + - [💡 Explanation:](#-explanation-45) - [Section: The Hidden treasures!](#section-the-hidden-treasures) - [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) - - [💡 Explanation:](#-explanation-47) + - [💡 Explanation:](#-explanation-46) - [▶ `goto`, but why?](#-goto-but-why) - - [💡 Explanation:](#-explanation-48) + - [💡 Explanation:](#-explanation-47) - [▶ Brace yourself!](#-brace-yourself) - - [💡 Explanation:](#-explanation-49) + - [💡 Explanation:](#-explanation-48) - [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) - - [💡 Explanation:](#-explanation-50) + - [💡 Explanation:](#-explanation-49) - [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) - - [💡 Explanation:](#-explanation-51) + - [💡 Explanation:](#-explanation-50) - [▶ Yes, it exists!](#-yes-it-exists) - - [💡 Explanation:](#-explanation-52) + - [💡 Explanation:](#-explanation-51) - [▶ Ellipsis \*](#-ellipsis-) - - [💡 Explanation](#-explanation-53) + - [💡 Explanation](#-explanation-52) - [▶ Inpinity](#-inpinity) - - [💡 Explanation:](#-explanation-54) + - [💡 Explanation:](#-explanation-53) - [▶ Let's mangle](#-lets-mangle) - - [💡 Explanation:](#-explanation-55) + - [💡 Explanation:](#-explanation-54) - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - [▶ Skipping lines?](#-skipping-lines) - - [💡 Explanation](#-explanation-56) + - [💡 Explanation](#-explanation-55) - [▶ Teleportation](#-teleportation) - - [💡 Explanation:](#-explanation-57) + - [💡 Explanation:](#-explanation-56) - [▶ Well, something is fishy...](#-well-something-is-fishy) - - [💡 Explanation](#-explanation-58) + - [💡 Explanation](#-explanation-57) - [Section: Miscellaneous](#section-miscellaneous) - [▶ `+=` is faster](#--is-faster) - - [💡 Explanation:](#-explanation-59) + - [💡 Explanation:](#-explanation-58) - [▶ Let's make a giant string!](#-lets-make-a-giant-string) - - [💡 Explanation](#-explanation-60) + - [💡 Explanation](#-explanation-59) - [▶ Slowing down `dict` lookups \*](#-slowing-down-dict-lookups-) - - [💡 Explanation:](#-explanation-61) + - [💡 Explanation:](#-explanation-60) - [▶ Bloating instance `dict`s \*](#-bloating-instance-dicts-) - - [💡 Explanation:](#-explanation-62) + - [💡 Explanation:](#-explanation-61) - [▶ Minor Ones \*](#-minor-ones-) -- [Contributing](#contributing) -- [Acknowledgements](#acknowledgements) - - [Some nice Links!](#some-nice-links) -- [🎓 License](#-license) - - [Surprise your friends as well!](#surprise-your-friends-as-well) - - [Need a pdf version?](#need-a-pdf-version) +- [‫ مشارکت](#-مشارکت) +- [‫ تقدیر و تشکر](#-تقدیر-و-تشکر) + - [‫ چند لینک جالب!](#-چند-لینک-جالب) +- [‫ 🎓 مجوز](#--مجوز) + - [‫ دوستانتان را هم شگفت‌زده کنید!](#-دوستانتان-را-هم-شگفتزده-کنید) + - [‫ آیا به یک نسخه pdf نیاز دارید؟](#-آیا-به-یک-نسخه-pdf-نیاز-دارید) @@ -3893,25 +3893,26 @@ What makes those dictionaries become bloated? And why are newly created objects --- --- -# Contributing +# ‫ مشارکت -A few ways in which you can contribute to wtfpython, +‫چند روشی که می‌توانید در wtfpython مشارکت داشته باشید: -- Suggesting new examples -- Helping with translation (See [issues labeled translation](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation)) -- Minor corrections like pointing out outdated snippets, typos, formatting errors, etc. -- Identifying gaps (things like inadequate explanation, redundant examples, etc.) -- Any creative suggestions to make this project more fun and useful +- ‫ پیشنهاد مثال‌های جدید +- ‫ کمک به ترجمه (به [مشکلات برچسب ترجمه](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation) مراجعه کنید) +- ‫ اصلاحات جزئی مثل اشاره به تکه‌کدهای قدیمی، اشتباهات تایپی، خطاهای قالب‌بندی و غیره. +- ‫ شناسایی نواقص (مانند توضیحات ناکافی، مثال‌های تکراری و ...) +- ‫ هر پیشنهاد خلاقانه‌ای برای مفیدتر و جذاب‌تر شدن این پروژه -Please see [CONTRIBUTING.md](/CONTRIBUTING.md) for more details. Feel free to create a new [issue](https://github.com/satwikkansal/wtfpython/issues/new) to discuss things. +‫ برای اطلاعات بیشتر [CONTRIBUTING.md](/CONTRIBUTING.md) را مشاهده کنید. برای بحث درباره موارد مختلف می‌توانید یک [مشکل جدید](https://github.com/satwikkansal/wtfpython/issues/new) ایجاد کنید. -PS: Please don't reach out with backlinking requests, no links will be added unless they're highly relevant to the project. +‫ نکته: لطفاً برای درخواست بک‌لینک (backlink) تماس نگیرید. هیچ لینکی اضافه نمی‌شود مگر اینکه ارتباط بسیار زیادی با پروژه داشته باشد. -# Acknowledgements +# ‫ تقدیر و تشکر -The idea and design for this collection were initially inspired by Denys Dovhan's awesome project [wtfjs](https://github.com/denysdovhan/wtfjs). The overwhelming support by Pythonistas gave it the shape it is in right now. +‫ ایده و طراحی این مجموعه ابتدا از پروژه عالی [wtfjs](https://github.com/denysdovhan/wtfjs) توسط Denys Dovhan الهام گرفته شد. حمایت فوق‌العاده‌ جامعه پایتون باعث شد پروژه به شکل امروزی خود درآید. -#### 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 @@ -3922,7 +3923,7 @@ The idea and design for this collection were initially inspired by Denys Dovhan' * https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues * WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). -# 🎓 License +# ‫ 🎓 مجوز [![WTFPL 2.0][license-image]][license-url] @@ -3931,15 +3932,16 @@ The idea and design for this collection were initially inspired by Denys Dovhan' [license-url]: http://www.wtfpl.net [license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square -## Surprise your friends as well! +## ‫ دوستانتان را هم شگفت‌زده کنید! + +‫ اگر از wtfpython خوشتان آمد، می‌توانید با این لینک‌های سریع آن را با دوستانتان به اشتراک بگذارید: -If you like wtfpython, you can use these quick links to share it with your friends, +‫ [توییتر](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) | [لینکدین](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!) | [فیسبوک](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? +## ‫ آیا به یک نسخه pdf نیاز دارید؟ -I've received a few requests for the pdf (and epub) version of wtfpython. You can add your details [here](https://form.jotform.com/221593245656057) to get them as soon as they are finished. +‫ من چند درخواست برای نسخه PDF (و epub) کتاب wtfpython دریافت کرده‌ام. برای دریافت این نسخه‌ها به محض آماده شدن، می‌توانید اطلاعات خود را [اینجا](https://form.jotform.com/221593245656057) وارد کنید. -**That's all folks!** For upcoming content like this, you can add your email [here](https://form.jotform.com/221593598380062). +‫ **همین بود دوستان!** برای دریافت مطالب آینده مشابه این، می‌توانید ایمیل خود را [اینجا](https://form.jotform.com/221593598380062) اضافه کنید. From 31bc257d118603ce8f2d6f0f8581da50f5936bce Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sun, 16 Mar 2025 21:03:21 +0100 Subject: [PATCH 183/210] translate miscellaneous section --- translations/fa-farsi/README.md | 181 ++++++++++++++++---------------- 1 file changed, 93 insertions(+), 88 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index b8fbb9dc..f55f843b 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -164,16 +164,16 @@ - [💡 Explanation:](#-explanation-56) - [▶ Well, something is fishy...](#-well-something-is-fishy) - [💡 Explanation](#-explanation-57) - - [Section: Miscellaneous](#section-miscellaneous) - - [▶ `+=` is faster](#--is-faster) - - [💡 Explanation:](#-explanation-58) - - [▶ Let's make a giant string!](#-lets-make-a-giant-string) - - [💡 Explanation](#-explanation-59) - - [▶ Slowing down `dict` lookups \*](#-slowing-down-dict-lookups-) - - [💡 Explanation:](#-explanation-60) - - [▶ Bloating instance `dict`s \*](#-bloating-instance-dicts-) - - [💡 Explanation:](#-explanation-61) - - [▶ Minor Ones \*](#-minor-ones-) + - [بخش: متفرقه](#بخش-متفرقه) + - [▶ `+=` سریع‌تر است](#--سریعتر-است) + - [‫ 💡 توضیح:](#---توضیح) + - [‫ ▶ بیایید یک رشته‌ی بزرگ بسازیم!](#--بیایید-یک-رشتهی-بزرگ-بسازیم) + - [💡 توضیحات](#-توضیحات-1) + - [▶ ‫ کُند کردن جستجوها در `dict` \*](#---کُند-کردن-جستجوها-در-dict-) + - [‫ 💡 توضیح:](#---توضیح-1) + - [‫ ▶ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#--حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) + - [💡 توضیح:](#-توضیح) + - [‫ ▶ موارد جزئی \*](#---موارد-جزئی-) - [‫ مشارکت](#-مشارکت) - [‫ تقدیر و تشکر](#-تقدیر-و-تشکر) - [‫ چند لینک جالب!](#-چند-لینک-جالب) @@ -3539,27 +3539,27 @@ Shouldn't that be 100? --- --- -## Section: Miscellaneous +## بخش: متفرقه -### ▶ `+=` is faster +### ▶ `+=` سریع‌تر است ```py -# using "+", three strings: +# استفاده از "+"، سه رشته: >>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) 0.25748300552368164 -# using "+=", three strings: +# استفاده از "+="، سه رشته: >>> timeit.timeit("s1 += s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100) 0.012188911437988281 ``` -#### 💡 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. +#### ‫ 💡 توضیح: ++ ‫ استفاده از `+=` برای اتصال بیش از دو رشته سریع‌تر از `+` است، زیرا هنگام محاسبه رشته‌ی نهایی، رشته‌ی اول (به‌عنوان مثال `s1` در عبارت `s1 += s2 + s3`) از بین نمی‌رود. --- -### ▶ Let's make a giant string! +### ‫ ▶ بیایید یک رشته‌ی بزرگ بسازیم! ```py def add_string_with_plus(iters): @@ -3593,10 +3593,11 @@ def convert_list_to_string(l, iters): **Output:** +‫ اجرا شده در پوسته‌ی ipython با استفاده از `%timeit` برای خوانایی بهتر نتایج. +‫ همچنین می‌توانید از ماژول `timeit` در پوسته یا اسکریپت عادی پایتون استفاده کنید؛ نمونه‌ی استفاده در زیر آمده است: +timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) + ```py -# Executed in ipython shell using %timeit for better readability of results. -# You can also use the timeit module in normal python shell/scriptm=, example usage below -# timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) >>> NUM_ITERS = 1000 >>> %timeit -n1000 add_string_with_plus(NUM_ITERS) @@ -3612,29 +3613,30 @@ def convert_list_to_string(l, iters): 10.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` -Let's increase the number of iterations by a factor of 10. +‫ بیایید تعداد تکرارها را ۱۰ برابر افزایش دهیم. ```py >>> NUM_ITERS = 10000 ->>> %timeit -n1000 add_string_with_plus(NUM_ITERS) # Linear increase in execution time +>>> %timeit -n1000 add_string_with_plus(NUM_ITERS) # افزایش خطی در زمان اجرا 1.26 ms ± 76.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ->>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) # Quadratic increase +>>> %timeit -n1000 add_bytes_with_plus(NUM_ITERS) # افزایش درجه دو (افزایش مربعی) 6.82 ms ± 134 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ->>> %timeit -n1000 add_string_with_format(NUM_ITERS) # Linear increase +>>> %timeit -n1000 add_string_with_format(NUM_ITERS) # افزایش خطی 645 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ->>> %timeit -n1000 add_string_with_join(NUM_ITERS) # Linear increase +>>> %timeit -n1000 add_string_with_join(NUM_ITERS) # افزایش خطی 1.17 ms ± 7.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) >>> l = ["xyz"]*NUM_ITERS ->>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) # Linear increase +>>> %timeit -n1000 convert_list_to_string(l, NUM_ITERS) # افزایش خطی 86.3 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` -#### 💡 Explanation -- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) or [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) on these links. They are used to measure the execution time of code pieces. -- Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases (justified with the execution times of `add_bytes_with_plus` function) -- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for very short strings). -- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster. -- Unlike `add_bytes_with_plus` because of the `+=` optimizations discussed in the previous example, `add_string_with_plus` didn't show a quadratic increase in execution time. Had the statement been `s = s + "x" + "y" + "z"` instead of `s += "xyz"`, the increase would have been quadratic. +#### 💡 توضیحات +توضیحات +- ‫ برای اطلاعات بیشتر درباره‌ی [timeit](https://docs.python.org/3/library/timeit.html) یا [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit)، می‌توانید به این لینک‌ها مراجعه کنید. این توابع برای اندازه‌گیری زمان اجرای قطعه‌کدها استفاده می‌شوند. +- ‫ برای تولید رشته‌های طولانی از `+` استفاده نکنید — در پایتون، نوع داده‌ی `str` تغییرناپذیر (immutable) است؛ بنابراین برای هر الحاق (concatenation)، رشته‌ی چپ و راست باید در رشته‌ی جدید کپی شوند. اگر چهار رشته‌ی ۱۰ حرفی را متصل کنید، به‌جای کپی ۴۰ کاراکتر، باید `(10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90` کاراکتر کپی کنید. این وضعیت با افزایش تعداد و طول رشته‌ها به‌صورت درجه دو (مربعی) بدتر می‌شود (که توسط زمان اجرای تابع `add_bytes_with_plus` تأیید شده است). +- ‫ بنابراین توصیه می‌شود از `.format` یا سینتکس `%` استفاده کنید (البته این روش‌ها برای رشته‌های بسیار کوتاه کمی کندتر از `+` هستند). +- ‫ اما بهتر از آن، اگر محتوای شما از قبل به‌شکل یک شیء قابل تکرار (iterable) موجود است، از دستور `''.join(iterable_object)` استفاده کنید که بسیار سریع‌تر است. +- ‫ برخلاف تابع `add_bytes_with_plus` و به‌دلیل بهینه‌سازی‌های انجام‌شده برای عملگر `+=` (که در مثال قبلی توضیح داده شد)، تابع `add_string_with_plus` افزایشی درجه دو در زمان اجرا نشان نداد. اگر دستور به‌صورت `s = s + "x" + "y" + "z"` بود (به‌جای `s += "xyz"`)، افزایش زمان اجرا درجه دو می‌شد. ```py def add_string_with_plus(iters): s = "" @@ -3644,23 +3646,24 @@ Let's increase the number of iterations by a factor of 10. >>> %timeit -n100 add_string_with_plus(1000) 388 µs ± 22.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) - >>> %timeit -n100 add_string_with_plus(10000) # Quadratic increase in execution time + >>> %timeit -n100 add_string_with_plus(10000) # افزایش درجه دو در زمان اجرا 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` -- So many ways to format and create a giant string are somewhat in contrast to the [Zen of Python](https://www.python.org/dev/peps/pep-0020/), according to which, +- ‫ وجود راه‌های متعدد برای قالب‌بندی و ایجاد رشته‌های بزرگ تا حدودی در تضاد با [ذِن پایتون](https://www.python.org/dev/peps/pep-0020/) است که می‌گوید: + - > There should be one-- and preferably only one --obvious way to do it. + > ‫ «باید یک راه — و ترجیحاً فقط یک راه — واضح برای انجام آن وجود داشته باشد.» --- -### ▶ Slowing down `dict` lookups * +### ▶ ‫ کُند کردن جستجوها در `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)} ``` -**Output:** +‫ **خروجی:** ```py >>> %timeit some_dict['5'] 28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) @@ -3670,23 +3673,23 @@ another_dict = {str(i): 1 for i in range(1_000_000)} >>> %timeit another_dict['5'] 28.5 ns ± 0.142 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) ->>> another_dict[1] # Trying to access a key that doesn't exist +>>> another_dict[1] # تلاش برای دسترسی به کلیدی که وجود ندارد Traceback (most recent call last): File "", line 1, in KeyError: 1 >>> %timeit another_dict['5'] 38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) ``` -Why are same lookups becoming slower? +چرا جستجوهای یکسان کندتر می‌شوند؟ -#### 💡 Explanation: -+ CPython has a generic dictionary lookup function that handles all types of keys (`str`, `int`, any object ...), and a specialized one for the common case of dictionaries composed of `str`-only keys. -+ The specialized function (named `lookdict_unicode` in CPython's [source](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841)) knows all existing keys (including the looked-up key) are strings, and uses the faster & simpler string comparison to compare keys, instead of calling the `__eq__` method. -+ The first time a `dict` instance is accessed with a non-`str` key, it's modified so future lookups use the generic function. -+ This process is not reversible for the particular `dict` instance, and the key doesn't even have to exist in the dictionary. That's why attempting a failed lookup has the same effect. +#### ‫ 💡 توضیح: ++ ‫ در CPython یک تابع عمومی برای جستجوی کلید در دیکشنری‌ها وجود دارد که از تمام انواع کلیدها (`str`، `int` و هر شیء دیگر) پشتیبانی می‌کند؛ اما برای حالت متداولی که تمام کلیدها از نوع `str` هستند، یک تابع بهینه‌شده‌ی اختصاصی نیز وجود دارد. ++ ‫ تابع اختصاصی (که در کد منبع CPython با نام [`lookdict_unicode`](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841) شناخته می‌شود) فرض می‌کند که تمام کلیدهای موجود در دیکشنری (از جمله کلیدی که در حال جستجوی آن هستید) رشته (`str`) هستند و برای مقایسه‌ی کلیدها، به‌جای فراخوانی متد `__eq__`، از مقایسه‌ی سریع‌تر و ساده‌تر رشته‌ای استفاده می‌کند. ++ ‫ اولین باری که یک دیکشنری (`dict`) با کلیدی غیر از `str` فراخوانی شود، این حالت تغییر می‌کند و جستجوهای بعدی از تابع عمومی استفاده خواهند کرد. ++ ‫ این فرایند برای آن نمونه‌ی خاص از دیکشنری غیرقابل بازگشت است و حتی لازم نیست کلید موردنظر در دیکشنری موجود باشد. به همین دلیل است که حتی تلاش ناموفق برای دسترسی به کلیدی ناموجود نیز باعث ایجاد همین تأثیر (کند شدن جستجو) می‌شود. -### ▶ Bloating instance `dict`s * +### ‫ ▶ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) * ```py import sys @@ -3704,7 +3707,7 @@ def dict_size(o): ``` -**Output:** (Python 3.8, other Python 3 versions may vary a little) +‫ **خروجی:** (پایتون ۳.۸؛ سایر نسخه‌های پایتون ۳ ممکن است کمی متفاوت باشند) ```py >>> o1 = SomeClass() >>> o2 = SomeClass() @@ -3720,13 +3723,13 @@ def dict_size(o): 232 ``` -Let's try again... In a new interpreter: +‫ بیایید دوباره امتحان کنیم... در یک مفسر (interpreter) جدید: ```py >>> o1 = SomeClass() >>> o2 = SomeClass() >>> dict_size(o1) -104 # as expected +104 # همان‌طور که انتظار می‌رفت >>> o1.some_attr5 = 5 >>> o1.some_attr6 = 6 >>> dict_size(o1) @@ -3738,28 +3741,29 @@ Let's try again... In a new interpreter: 232 ``` -What makes those dictionaries become bloated? And why are newly created objects bloated as well? +‫ چه چیزی باعث حجیم‌شدن این دیکشنری‌ها می‌شود؟ و چرا اشیاء تازه ساخته‌شده نیز حجیم هستند؟ -#### 💡 Explanation: -+ CPython is able to reuse the same "keys" object in multiple dictionaries. This was added in [PEP 412](https://www.python.org/dev/peps/pep-0412/) with the motivation to reduce memory usage, specifically in dictionaries of instances - where keys (instance attributes) tend to be common to all instances. -+ This optimization is entirely seamless for instance dictionaries, but it is disabled if certain assumptions are broken. -+ Key-sharing dictionaries do not support deletion; if an instance attribute is deleted, the dictionary is "unshared", and key-sharing is disabled for all future instances of the same class. -+ 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__`! +#### 💡 توضیح: ++ ‫ در CPython، امکان استفاده‌ی مجدد از یک شیء «کلیدها» (`keys`) در چندین دیکشنری وجود دارد. این ویژگی در [PEP 412](https://www.python.org/dev/peps/pep-0412/) معرفی شد تا مصرف حافظه کاهش یابد، به‌ویژه برای دیکشنری‌هایی که به نمونه‌ها (instances) تعلق دارند و معمولاً کلیدها (نام صفات نمونه‌ها) بین آن‌ها مشترک است. ++ ‫ این بهینه‌سازی برای دیکشنری‌های نمونه‌ها کاملاً شفاف و خودکار است؛ اما اگر بعضی فرضیات نقض شوند، غیرفعال می‌شود. ++ ‫ دیکشنری‌هایی که کلیدهایشان به اشتراک گذاشته شده باشد، از حذف کلید پشتیبانی نمی‌کنند؛ بنابراین اگر صفتی از یک نمونه حذف شود، دیکشنریِ آن نمونه «غیر مشترک» (`unshared`) شده و این قابلیت اشتراک‌گذاری کلیدها برای تمام نمونه‌هایی که در آینده از آن کلاس ساخته می‌شوند، غیرفعال می‌گردد. ++ ‫ همچنین اگر اندازه‌ی دیکشنری به‌علت اضافه‌شدن کلیدهای جدید تغییر کند (`resize` شود)، اشتراک‌گذاری کلیدها تنها زمانی ادامه می‌یابد که فقط یک دیکشنری در حال استفاده از آن‌ها باشد (این اجازه می‌دهد در متد `__init__` برای اولین نمونه‌ی ساخته‌شده، صفات متعددی تعریف کنید بدون آن‌که اشتراک‌گذاری کلیدها از بین برود). اما اگر چند نمونه همزمان وجود داشته باشند و تغییر اندازه‌ی دیکشنری رخ دهد، قابلیت اشتراک‌گذاری کلیدها برای نمونه‌های بعدی همان کلاس غیرفعال خواهد شد. زیرا CPython دیگر نمی‌تواند مطمئن باشد که آیا نمونه‌های بعدی دقیقاً از مجموعه‌ی یکسانی از صفات استفاده خواهند کرد یا خیر. ++ ‫ نکته‌ای کوچک برای کاهش مصرف حافظه‌ی برنامه: هرگز صفات نمونه‌ها را حذف نکنید و حتماً تمام صفات را در متد `__init__` تعریف و مقداردهی اولیه کنید! -### ▶ Minor Ones * +### ‫ ▶ موارد جزئی * -* `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage) +* ‫ متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) - **💡 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`. + ** ‫💡 توضیح:** اگر `join()` به‌عنوان متدی روی رشته پیاده‌سازی شود، می‌تواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشونده‌ی دیگر کار کند. اگر به‌جای آن روی لیست تعریف می‌شد، باید به‌طور جداگانه برای هر نوع دیگری نیز پیاده‌سازی می‌شد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. + +* ‫ تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح: + + ‫ عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی). + + ‫ عبارت `'a'[0][0][0][0][0]` نیز از نظر معنایی صحیح است، زیرا پایتون برخلاف زبان‌هایی که از C منشعب شده‌اند، نوع داده‌ای جداگانه‌ای برای کاراکتر ندارد. بنابراین انتخاب یک کاراکتر از یک رشته، منجر به بازگشت یک رشته‌ی تک‌کاراکتری می‌شود. + + ‫ عبارات `3 --0-- 5 == 8` و `--5 == 5` هر دو از لحاظ معنایی درست بوده و مقدارشان برابر `True` است. + +* ‫ با فرض اینکه `a` یک عدد باشد، عبارات `++a` و `--a` هر دو در پایتون معتبر هستند؛ اما رفتاری مشابه با عبارات مشابه در زبان‌هایی مانند C، ++C یا جاوا ندارند. -* Given that `a` is a number, `++a` and `--a` are both valid Python statements but don't behave the same way as compared with similar statements in languages like C, C++, or Java. ```py >>> a = 5 >>> a @@ -3770,27 +3774,28 @@ What makes those dictionaries become bloated? And why are newly created objects 5 ``` - **💡 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. + ** ‫ 💡 توضیح:** + + ‫ در گرامر پایتون عملگری به‌نام `++` وجود ندارد. در واقع `++` دو عملگر `+` جداگانه است. + + ‫ عبارت `++a` به‌شکل `+(+a)` تفسیر می‌شود که معادل `a` است. به‌همین ترتیب، خروجی عبارت `--a` نیز قابل توجیه است. + + ‫ این [تاپیک در StackOverflow](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) دلایل نبودن عملگرهای افزایش (`++`) و کاهش (`--`) در پایتون را بررسی می‌کند. + +* ‫ احتمالاً با عملگر Walrus (گراز دریایی) در پایتون آشنا هستید؛ اما تا به حال در مورد *عملگر Space-invader (مهاجم فضایی)* شنیده‌اید؟ -* You must be aware of the Walrus operator in Python. But have you ever heard about *the space-invader operator*? ```py >>> a = 42 >>> a -=- 1 >>> a 43 ``` - It is used as an alternative incrementation operator, together with another one +‫ از آن به‌عنوان جایگزینی برای عملگر افزایش (increment)، در ترکیب با یک عملگر دیگر استفاده می‌شود. ```py >>> a +=+ 1 >>> a >>> 44 ``` - **💡 Explanation:** This prank comes from [Raymond Hettinger's tweet](https://twitter.com/raymondh/status/1131103570856632321?lang=en). The space invader operator is actually just a malformatted `a -= (-1)`. Which is equivalent to `a = a - (- 1)`. Similar for the `a += (+ 1)` case. - -* Python has an undocumented [converse implication](https://en.wikipedia.org/wiki/Converse_implication) operator. + **‫ 💡 توضیح:** این شوخی از [توییت 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 @@ -3803,9 +3808,9 @@ What makes those dictionaries become bloated? And why are newly created objects 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)) - -* Since we are talking operators, there's also `@` operator for matrix multiplication (don't worry, this time it's for real). + ‫ **💡 توضیح:** اگر مقادیر `False` و `True` را به‌ترتیب با اعداد ۰ و ۱ جایگزین کرده و محاسبات را انجام دهید، جدول درستی حاصل، معادل یک عملگر استلزام معکوس خواهد بود. ([منبع](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator)) + +* ‫ حالا که صحبت از عملگرها شد، عملگر `@` نیز برای ضرب ماتریسی در پایتون وجود دارد (نگران نباشید، این بار واقعی است). ```py >>> import numpy as np @@ -3813,16 +3818,16 @@ What makes those dictionaries become bloated? And why are newly created objects 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. + ‫ **💡 توضیح:** عملگر `@` در پایتون ۳٫۵ با در نظر گرفتن نیازهای جامعه علمی اضافه شد. هر شی‌ای می‌تواند متد جادویی `__matmul__` را بازنویسی کند تا رفتار این عملگر را مشخص نماید. -* From Python 3.8 onwards you can use a typical f-string syntax like `f'{some_var=}` for quick debugging. Example, +* ‫ از پایتون ۳٫۸ به بعد می‌توانید از نحو متداول f-string مانند `f'{some_var=}'` برای اشکال‌زدایی سریع استفاده کنید. مثال, ```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!): +* ‫ پایتون برای ذخیره‌سازی متغیرهای محلی در توابع از ۲ بایت استفاده می‌کند. از نظر تئوری، این به معنای امکان تعریف حداکثر ۶۵۵۳۶ متغیر در یک تابع است. با این حال، پایتون راهکار مفیدی ارائه می‌کند که می‌توان با استفاده از آن بیش از ۲^۱۶ نام متغیر را ذخیره کرد. کد زیر نشان می‌دهد وقتی بیش از ۶۵۵۳۶ متغیر محلی تعریف شود، در پشته (stack) چه اتفاقی رخ می‌دهد (هشدار: این کد تقریباً ۲^۱۸ خط متن چاپ می‌کند، بنابراین آماده باشید!): ```py import dis @@ -3836,9 +3841,9 @@ What makes those dictionaries become bloated? And why are newly created objects print(dis.dis(f)) ``` -* Multiple Python threads won't run your *Python code* concurrently (yes, you heard it right!). It may seem intuitive to spawn several threads and let them execute your Python code concurrently, but, because of the [Global Interpreter Lock](https://wiki.python.org/moin/GlobalInterpreterLock) in Python, all you're doing is making your threads execute on the same core turn by turn. Python threads are good for IO-bound tasks, but to achieve actual parallelization in Python for CPU-bound tasks, you might want to use the Python [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) module. +* ‫ چندین رشته (Thread) در پایتون، کدِ *پایتونی* شما را به‌صورت همزمان اجرا نمی‌کنند (بله، درست شنیدید!). شاید به نظر برسد که ایجاد چندین رشته و اجرای همزمان آن‌ها منطقی است، اما به دلیل وجود [قفل مفسر سراسری (GIL)](https://wiki.python.org/moin/GlobalInterpreterLock) در پایتون، تمام کاری که انجام می‌دهید این است که رشته‌هایتان به‌نوبت روی یک هسته اجرا می‌شوند. رشته‌ها در پایتون برای وظایفی مناسب هستند که عملیات I/O دارند، اما برای رسیدن به موازی‌سازی واقعی در وظایف پردازشی سنگین (CPU-bound)، بهتر است از ماژول [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) در پایتون استفاده کنید. -* Sometimes, the `print` method might not print values immediately. For example, +* ‫ گاهی اوقات، متد `print` ممکن است مقادیر را فوراً چاپ نکند. برای مثال، ```py # File some_file.py @@ -3848,16 +3853,16 @@ What makes those dictionaries become bloated? And why are newly created objects 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. + ‫ این کد عبارت `wtfpython` را به دلیل آرگومان `end` پس از ۳ ثانیه چاپ می‌کند؛ چرا که بافر خروجی تنها پس از رسیدن به کاراکتر `\n` یا در زمان اتمام اجرای برنامه تخلیه می‌شود. برای تخلیه‌ی اجباری بافر می‌توانید از آرگومان `flush=True` استفاده کنید. -* List slicing with out of the bounds indices throws no errors +* ‫ برش لیست‌ها (List slicing) با اندیس‌های خارج از محدوده، خطایی ایجاد نمی‌کند. ```py >>> some_list = [1, 2, 3, 4, 5] >>> some_list[111:] [] ``` -* Slicing an iterable not always creates a new object. For example, +* ‫ برش زدن (slicing) یک شئ قابل پیمایش (iterable) همیشه یک شئ جدید ایجاد نمی‌کند. به‌عنوان مثال، ```py >>> some_str = "wtfpython" >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n'] @@ -3867,9 +3872,9 @@ What makes those dictionaries become bloated? And why are newly created objects True ``` -* `int('١٢٣٤٥٦٧٨٩')` returns `123456789` in Python 3. In Python, Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Here's an [interesting story](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) related to this behavior of Python. +* ‫ در پایتون ۳، فراخوانی `int('١٢٣٤٥٦٧٨٩')` مقدار `123456789` را برمی‌گرداند. در پایتون، نویسه‌های ده‌دهی (Decimal characters) شامل تمام ارقامی هستند که می‌توانند برای تشکیل اعداد در مبنای ده استفاده شوند؛ به‌عنوان مثال نویسه‌ی U+0660 که همان رقم صفر عربی-هندی است. [اینجا](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) داستان جالبی درباره این رفتار پایتون آمده است. -* You can separate numeric literals with underscores (for better readability) from Python 3 onwards. +* ‫ از پایتون ۳ به بعد، می‌توانید برای افزایش خوانایی، اعداد را با استفاده از زیرخط (`_`) جدا کنید. ```py >>> six_million = 6_000_000 @@ -3880,7 +3885,7 @@ What makes those dictionaries become bloated? And why are newly created objects 4027435774 ``` -* `'abc'.count('') == 4`. Here's an approximate implementation of `count` method, which would make the things more clear +* ‫ عبارت `'abc'.count('') == 4` مقدار `True` برمی‌گرداند. در اینجا یک پیاده‌سازی تقریبی از متد `count` آورده شده که این موضوع را شفاف‌تر می‌کند: ```py def count(s, sub): result = 0 @@ -3888,7 +3893,7 @@ What makes those dictionaries become bloated? And why are newly created objects result += (s[i:i + len(sub)] == sub) return result ``` - The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string. +‫ این رفتار به این دلیل است که زیررشته‌ی خالی (`''`) با برش‌هایی (slices) به طول صفر در رشته‌ی اصلی مطابقت پیدا می‌کند. --- --- From 7ff13596635e3306e698fd933276f4668c5e7dc6 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sun, 16 Mar 2025 21:51:16 +0100 Subject: [PATCH 184/210] Translate Section: Appearances are deceptive --- translations/fa-farsi/README.md | 83 +++++++++++++++++---------------- 1 file changed, 42 insertions(+), 41 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index f55f843b..f85f1c1b 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -157,15 +157,15 @@ - [💡 Explanation:](#-explanation-53) - [▶ Let's mangle](#-lets-mangle) - [💡 Explanation:](#-explanation-54) - - [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - - [▶ Skipping lines?](#-skipping-lines) - - [💡 Explanation](#-explanation-55) - - [▶ Teleportation](#-teleportation) - - [💡 Explanation:](#-explanation-56) - - [▶ Well, something is fishy...](#-well-something-is-fishy) - - [💡 Explanation](#-explanation-57) + - [‫ بخش: ظاهرها فریبنده‌اند!](#-بخش-ظاهرها-فریبندهاند) + - [▶ ‫ خطوط را رد می‌کند؟](#--خطوط-را-رد-میکند) + - [‫ 💡 توضیح](#--توضیح) + - [▶ ‫ تله‌پورت کردن](#--تلهپورت-کردن) + - [‫ 💡 توضیح:](#--توضیح-1) + - [▶ ‫ خب، یک جای کار مشکوک است...](#--خب-یک-جای-کار-مشکوک-است) + - [‫ 💡 توضیح](#--توضیح-2) - [بخش: متفرقه](#بخش-متفرقه) - - [▶ `+=` سریع‌تر است](#--سریعتر-است) + - [‫ ▶ `+=` سریع‌تر است](#---سریعتر-است) - [‫ 💡 توضیح:](#---توضیح) - [‫ ▶ بیایید یک رشته‌ی بزرگ بسازیم!](#--بیایید-یک-رشتهی-بزرگ-بسازیم) - [💡 توضیحات](#-توضیحات-1) @@ -3427,9 +3427,9 @@ AttributeError: 'A' object has no attribute '__variable' --- --- -## Section: Appearances are deceptive! +## ‫ بخش: ظاهرها فریبنده‌اند! -### ▶ Skipping lines? +### ▶ ‫ خطوط را رد می‌کند؟ **Output:** ```py @@ -3439,33 +3439,33 @@ AttributeError: 'A' object has no attribute '__variable' 11 ``` -Wut? +‫ چی? -**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell. +‫ **نکته:** ساده‌ترین روش برای بازتولید این رفتار، کپی کردن دستورات از کد بالا و جایگذاری (paste) آن‌ها در فایل یا محیط تعاملی (shell) خودتان است. -#### 💡 Explanation +#### ‫ 💡 توضیح -Some non-Western characters look identical to letters in the English alphabet but are considered distinct by the interpreter. +‫ برخی از حروف غیرغربی کاملاً مشابه حروف الفبای انگلیسی به نظر می‌رسند، اما مفسر پایتون آن‌ها را متفاوت در نظر می‌گیرد. ```py ->>> ord('е') # cyrillic 'e' (Ye) +>>> ord('е') # حرف سیریلیک «е» (Ye) 1077 ->>> ord('e') # latin 'e', as used in English and typed using standard keyboard +>>> ord('e') # حرف لاتین «e»، که در انگلیسی استفاده می‌شود و با صفحه‌کلید استاندارد تایپ می‌گردد 101 >>> 'е' == 'e' False ->>> value = 42 # latin e ->>> valuе = 23 # cyrillic 'e', Python 2.x interpreter would raise a `SyntaxError` here +>>> value = 42 # حرف لاتین e +>>> valuе = 23 # حرف سیریلیک «е»؛ مفسر پایتون نسخه ۲ در اینجا خطای `SyntaxError` ایجاد می‌کند >>> value 42 ``` -The built-in `ord()` function returns a character's Unicode [code point](https://en.wikipedia.org/wiki/Code_point), and different code positions of Cyrillic 'e' and Latin 'e' justify the behavior of the above example. +‫ تابع داخلی `ord()`، [کدپوینت](https://fa.wikipedia.org/wiki/کدپوینت) یونیکد مربوط به یک نویسه را برمی‌گرداند. موقعیت‌های کدی متفاوت برای حرف سیریلیک «е» و حرف لاتین «e»، علت رفتار مثال بالا را توجیه می‌کنند. --- -### ▶ Teleportation +### ▶ ‫ تله‌پورت کردن @@ -3474,36 +3474,36 @@ The built-in `ord()` function returns a character's Unicode [code point](https:/ import numpy as np def energy_send(x): - # Initializing a numpy array + # مقداردهی اولیه یک آرایه numpy np.array([float(x)]) def energy_receive(): - # Return an empty numpy array + # بازگرداندن یک آرایه‌ی خالی numpy return np.empty((), dtype=np.float).tolist() ``` -**Output:** +‫ **خروجی:** ```py >>> energy_send(123.456) >>> energy_receive() 123.456 ``` -Where's the Nobel Prize? +‫ جایزه نوبل کجاست؟ -#### 💡 Explanation: +#### ‫ 💡 توضیح: -* Notice that the numpy array created in the `energy_send` function is not returned, so that memory space is free to reallocate. -* `numpy.empty()` returns the next free memory slot without reinitializing it. This memory spot just happens to be the same one that was just freed (usually, but not always). +* ‫ توجه کنید که آرایه‌ی numpy ایجادشده در تابع `energy_send` برگردانده نشده است، بنابراین فضای حافظه‌ی آن آزاد شده و مجدداً قابل استفاده است. +* ‫ تابع `numpy.empty()` نزدیک‌ترین فضای حافظه‌ی آزاد را بدون مقداردهی مجدد برمی‌گرداند. این فضای حافظه معمولاً همان فضایی است که به‌تازگی آزاد شده است (البته معمولاً این اتفاق می‌افتد و نه همیشه). --- -### ▶ Well, something is fishy... +### ▶ ‫ خب، یک جای کار مشکوک است... ```py def square(x): """ - A simple function to calculate the square of a number by addition. + یک تابع ساده برای محاسبه‌ی مربع یک عدد با استفاده از جمع. """ sum_so_far = 0 for counter in range(x): @@ -3511,27 +3511,28 @@ def square(x): return sum_so_far ``` -**Output (Python 2.x):** +‫ **خروجی (پایتون 2.X):** ```py >>> square(10) 10 ``` -Shouldn't that be 100? +‫ آیا این نباید ۱۰۰ باشد؟ -**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell. +‫ **نکته:** اگر نمی‌توانید این مشکل را بازتولید کنید، سعی کنید فایل [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) را از طریق شِل اجرا کنید. -#### 💡 Explanation +#### ‫ 💡 توضیح -* **Don't mix tabs and spaces!** The character just preceding return is a "tab", and the code is indented by multiple of "4 spaces" elsewhere in the example. -* This is how Python handles tabs: - - > First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...> -* So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop. -* Python 3 is kind enough to throw an error for such cases automatically. +* ‫ **تب‌ها و فاصله‌ها (space) را با هم ترکیب نکنید!** کاراکتری که دقیقاً قبل از دستور return آمده یک «تب» است، در حالی که در بقیۀ مثال، کد با مضربی از «۴ فاصله» تورفتگی دارد. +* ‫ نحوۀ برخورد پایتون با تب‌ها به این صورت است: + + > ‫ ابتدا تب‌ها (از چپ به راست) با یک تا هشت فاصله جایگزین می‌شوند به‌طوری که تعداد کل کاراکترها تا انتهای آن جایگزینی، مضربی از هشت باشد <...> +* ‫ بنابراین «تب» در آخرین خط تابع `square` با هشت فاصله جایگزین شده و به همین دلیل داخل حلقه قرار می‌گیرد. +* ‫ پایتون ۳ آنقدر هوشمند هست که چنین مواردی را به‌صورت خودکار با خطا اعلام کند. + + ‫ **خروجی (Python 3.x):** - **Output (Python 3.x):** ```py TabError: inconsistent use of tabs and spaces in indentation ``` @@ -3542,7 +3543,7 @@ Shouldn't that be 100? ## بخش: متفرقه -### ▶ `+=` سریع‌تر است +### ‫ ▶ `+=` سریع‌تر است ```py From ddab1b6ad23b1b83afc1fca0b03c003796fb9504 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Mon, 17 Mar 2025 10:44:44 +0100 Subject: [PATCH 185/210] Translate hidden treasures section --- translations/fa-farsi/README.md | 212 ++++++++++++++++---------------- 1 file changed, 108 insertions(+), 104 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index f85f1c1b..43a51793 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -138,32 +138,32 @@ - [💡 Explanation:](#-explanation-44) - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - [💡 Explanation:](#-explanation-45) - - [Section: The Hidden treasures!](#section-the-hidden-treasures) - - [▶ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) - - [💡 Explanation:](#-explanation-46) - - [▶ `goto`, but why?](#-goto-but-why) - - [💡 Explanation:](#-explanation-47) - - [▶ Brace yourself!](#-brace-yourself) - - [💡 Explanation:](#-explanation-48) - - [▶ Let's meet Friendly Language Uncle For Life](#-lets-meet-friendly-language-uncle-for-life) - - [💡 Explanation:](#-explanation-49) - - [▶ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated) - - [💡 Explanation:](#-explanation-50) - - [▶ Yes, it exists!](#-yes-it-exists) - - [💡 Explanation:](#-explanation-51) + - [‫ بخش: گنجینه‌های پنهان!](#-بخش-گنجینههای-پنهان) + - [▶ ‫ خب پایتون، می‌توانی کاری کنی پرواز کنم؟](#--خب-پایتون-میتوانی-کاری-کنی-پرواز-کنم) + - [‫ 💡 توضیح:](#--توضیح) + - [▶ ‫ `goto`، ولی چرا؟](#--goto-ولی-چرا) + - [‫ 💡 توضیح:](#--توضیح-1) + - [▶ ‫ خودتان را آماده کنید!](#--خودتان-را-آماده-کنید) + - [‫ 💡 توضیح:](#--توضیح-2) + - [▶ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم](#--بیایید-با-عمو-زبان-مهربان-برای-همیشه-آشنا-شویم) + - [‫ 💡 توضیح:](#--توضیح-3) + - [▶ ‫ حتی پایتون هم می‌داند که عشق پیچیده است](#--حتی-پایتون-هم-میداند-که-عشق-پیچیده-است) + - [‫ 💡 توضیح:](#--توضیح-4) + - [▶ ‫ بله، این واقعاً وجود دارد!](#--بله-این-واقعاً-وجود-دارد) + - [‫ 💡 توضیح:](#--توضیح-5) - [▶ Ellipsis \*](#-ellipsis-) - - [💡 Explanation](#-explanation-52) - - [▶ Inpinity](#-inpinity) - - [💡 Explanation:](#-explanation-53) - - [▶ Let's mangle](#-lets-mangle) - - [💡 Explanation:](#-explanation-54) + - [‫ 💡توضیح](#-توضیح) + - [▶ ‫ بی‌نهایت (`Inpinity`)](#--بینهایت-inpinity) + - [‫ 💡 توضیح:](#--توضیح-6) + - [▶ ‫ بیایید خرابکاری کنیم](#--بیایید-خرابکاری-کنیم) + - [‫ 💡 توضیح:](#--توضیح-7) - [‫ بخش: ظاهرها فریبنده‌اند!](#-بخش-ظاهرها-فریبندهاند) - [▶ ‫ خطوط را رد می‌کند؟](#--خطوط-را-رد-میکند) - - [‫ 💡 توضیح](#--توضیح) + - [‫ 💡 توضیح](#--توضیح-8) - [▶ ‫ تله‌پورت کردن](#--تلهپورت-کردن) - - [‫ 💡 توضیح:](#--توضیح-1) + - [‫ 💡 توضیح:](#--توضیح-9) - [▶ ‫ خب، یک جای کار مشکوک است...](#--خب-یک-جای-کار-مشکوک-است) - - [‫ 💡 توضیح](#--توضیح-2) + - [‫ 💡 توضیح](#--توضیح-10) - [بخش: متفرقه](#بخش-متفرقه) - [‫ ▶ `+=` سریع‌تر است](#---سریعتر-است) - [‫ 💡 توضیح:](#---توضیح) @@ -172,7 +172,7 @@ - [▶ ‫ کُند کردن جستجوها در `dict` \*](#---کُند-کردن-جستجوها-در-dict-) - [‫ 💡 توضیح:](#---توضیح-1) - [‫ ▶ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#--حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) - - [💡 توضیح:](#-توضیح) + - [💡 توضیح:](#-توضیح-1) - [‫ ▶ موارد جزئی \*](#---موارد-جزئی-) - [‫ مشارکت](#-مشارکت) - [‫ تقدیر و تشکر](#-تقدیر-و-تشکر) @@ -3064,29 +3064,29 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t -## Section: The Hidden treasures! +## ‫ بخش: گنجینه‌های پنهان! -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 import antigravity ``` -**Output:** +‫ **خروجی:** 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/). +#### ‫ 💡 توضیح: ++ ‫ ماژول `antigravity` یکی از معدود ایستر اِگ‌هایی است که توسط توسعه‌دهندگان پایتون ارائه شده است. ++ ‫ دستور `import antigravity` باعث می‌شود مرورگر وب به سمت [کمیک کلاسیک XKCD](https://xkcd.com/353/) در مورد پایتون باز شود. ++ ‫ البته موضوع عمیق‌تر است؛ در واقع یک **ایستر اگ دیگر داخل این ایستر اگ** وجود دارد. اگر به [کد منبع](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17) نگاه کنید، یک تابع تعریف شده که ادعا می‌کند [الگوریتم جئوهشینگ XKCD](https://xkcd.com/426/) را پیاده‌سازی کرده است. --- -### ▶ `goto`, but why? +### ▶ ‫ `goto`، ولی چرا؟ ```py @@ -3096,56 +3096,56 @@ for i in range(9): for k in range(9): print("I am trapped, please rescue!") if k == 2: - goto .breakout # breaking out from a deeply nested loop + goto .breakout # خروج از یک حلقه‌ی تودرتوی عمیق label .breakout print("Freedom!") ``` -**Output (Python 2.3):** +‫ **خروجی (پایتون ۲.۳):** ```py I am trapped, please rescue! I am trapped, please rescue! Freedom! ``` -#### 💡 Explanation: -- A working version of `goto` in Python was [announced](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html) as an April Fool's joke on 1st April 2004. -- Current versions of Python do not have this module. -- Although it works, but please don't use it. Here's the [reason](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) to why `goto` is not present in Python. +#### ‫ 💡 توضیح: +- ‫ نسخه‌ی قابل استفاده‌ای از `goto` در پایتون به عنوان یک شوخی [در اول آوریل ۲۰۰۴ معرفی شد](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html). +- ‫ نسخه‌های فعلی پایتون فاقد این ماژول هستند. +- ‫ اگرچه این ماژول واقعاً کار می‌کند، ولی لطفاً از آن استفاده نکنید. در [این صفحه](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) می‌توانید دلیل عدم حضور دستور `goto` در پایتون را مطالعه کنید. --- -### ▶ 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, +‫ اگر جزو افرادی هستید که دوست ندارند در پایتون برای مشخص کردن محدوده‌ها از فضای خالی (whitespace) استفاده کنند، می‌توانید با ایمپورت کردن ماژول زیر از آکولاد `{}` به سبک زبان C استفاده کنید: ```py from __future__ import braces ``` -**Output:** +‫ **خروجی:** ```py File "some_file.py", line 1 from __future__ import braces 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)? +‫ آکولاد؟ هرگز! اگر از این بابت ناامید شدید، بهتر است از جاوا استفاده کنید. خب، یک چیز شگفت‌آور دیگر؛ آیا می‌توانید تشخیص دهید که ارور `SyntaxError` در کجای کد ماژول `__future__` [اینجا](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. -+ When the CPython compiler encounters a [future statement](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements), it first runs the appropriate code in `future.c` before treating it as a normal import statement. +#### ‫ 💡 توضیح: ++ ‫ ماژول `__future__` معمولاً برای ارائه قابلیت‌هایی از نسخه‌های آینده پایتون به کار می‌رود. اما کلمه «future» (آینده) در این زمینه خاص، حالت طنز و کنایه دارد. ++ ‫ این مورد یک «ایستر اگ» (easter egg) است که به احساسات جامعه برنامه‌نویسان پایتون در این خصوص اشاره دارد. ++ ‫ کد مربوط به این موضوع در واقع [اینجا](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) در فایل `future.c` قرار دارد. ++ ‫ زمانی که کامپایلر CPython با یک [عبارت future](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements) مواجه می‌شود، ابتدا کد مرتبط در `future.c` را اجرا کرده و سپس آن را همانند یک دستور ایمپورت عادی در نظر می‌گیرد. --- -### ▶ Let's meet Friendly Language Uncle For Life +### ▶ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم **Output (Python 3.x)** ```py >>> from __future__ import barry_as_FLUFL ->>> "Ruby" != "Python" # there's no doubt about it +>>> "Ruby" != "Python" # شکی در این نیست. File "some_file.py", line 1 "Ruby" != "Python" ^ @@ -3155,15 +3155,17 @@ SyntaxError: invalid syntax True ``` -There we go. +‫ حالا می‌رسیم به اصل ماجرا. -#### 💡 Explanation: -- This is relevant to [PEP-401](https://www.python.org/dev/peps/pep-0401/) released on April 1, 2009 (now you know, what it means). -- Quoting from the PEP-401 +#### ‫ 💡 توضیح: +- ‫ این مورد مربوط به [PEP-401](https://www.python.org/dev/peps/pep-0401/) است که در تاریخ ۱ آوریل ۲۰۰۹ منتشر شد (اکنون می‌دانید این یعنی چه!). +- ‫ نقل قولی از PEP-401: + + > ‫ با توجه به اینکه عملگر نابرابری `!=` در پایتون ۳.۰ یک اشتباه وحشتناک و انگشت‌سوز (!) بوده است، عمو زبان مهربان برای همیشه (FLUFL) عملگر الماسی‌شکل `<>` را مجدداً به‌عنوان تنها روش درست برای این منظور بازگردانده است. - > 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, +- ‫ البته «عمو بَری» چیزهای بیشتری برای گفتن در این 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"')) @@ -3171,7 +3173,7 @@ There we go. --- -### ▶ Even Python understands that love is complicated +### ▶ ‫ حتی پایتون هم می‌داند که عشق پیچیده است ```py import this @@ -3179,7 +3181,7 @@ import this Wait, what's **this**? `this` is love :heart: -**Output:** +‫ **خروجی:** ``` The Zen of Python, by Tim Peters @@ -3204,7 +3206,7 @@ If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ``` -It's the Zen of Python! +‫ این ذنِ پایتون است! ```py >>> love = this @@ -3216,21 +3218,21 @@ False False >>> love is not True or False True ->>> love is not True or False; love is love # Love is complicated +>>> love is not True or False; love is love # عشق پیجیده است True ``` -#### 💡 Explanation: +#### ‫ 💡 توضیح: -* `this` module in Python is an easter egg for The Zen Of Python ([PEP 20](https://www.python.org/dev/peps/pep-0020)). -* And if you think that's already interesting enough, check out the implementation of [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py). Interestingly, **the code for the Zen violates itself** (and that's probably the only place where this happens). -* Regarding the statement `love is not True or False; love is love`, ironic but it's self-explanatory (if not, please see the examples related to `is` and `is not` operators). +* ‫ ماژول `this` در پایتون، یک ایستر اگ برای «ذنِ پایتون» ([PEP 20](https://www.python.org/dev/peps/pep-0020)) است. +* ‫ اگر این موضوع به‌اندازه کافی جالب است، حتماً پیاده‌سازی [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py) را ببینید. نکته جالب این است که **کد مربوط به ذنِ پایتون، خودش اصول ذن را نقض کرده است** (و احتمالاً این تنها جایی است که چنین اتفاقی می‌افتد). +* ‫ درباره جمله `love is not True or False; love is love`، اگرچه طعنه‌آمیز است، اما خود گویاست. (اگر واضح نیست، لطفاً مثال‌های مربوط به عملگرهای `is` و `is not` را مشاهده کنید.) --- -### ▶ Yes, it exists! +### ▶ ‫ بله، این واقعاً وجود دارد! -**The `else` clause for loops.** One typical example might be: +‫ **عبارت `else` برای حلقه‌ها.** یک مثال معمول آن می‌تواند چنین باشد: ```py def does_exists_num(l, to_find): @@ -3242,7 +3244,7 @@ True print("Does not exist") ``` -**Output:** +**خروجی:** ```py >>> some_list = [1, 2, 3, 4, 5] >>> does_exists_num(some_list, 4) @@ -3251,7 +3253,7 @@ Exists! Does not exist ``` -**The `else` clause in exception handling.** An example, +**عبارت `else` در مدیریت استثناها.** مثالی از آن: ```py try: @@ -3262,14 +3264,14 @@ else: print("Try block executed successfully...") ``` -**Output:** +**خروجی:** ```py Try block executed successfully... ``` -#### 💡 Explanation: -- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations. You can think of it as a "nobreak" clause. -- `else` clause after a try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully. +#### ‫ 💡 توضیح: +- عبارت `else` بعد از حلقه‌ها تنها زمانی اجرا می‌شود که در هیچ‌کدام از تکرارها (`iterations`) از دستور `break` استفاده نشده باشد. می‌توانید آن را به عنوان یک شرط «بدون شکست» (nobreak) در نظر بگیرید. +- عبارت `else` پس از بلاک `try` به عنوان «عبارت تکمیل» (`completion clause`) نیز شناخته می‌شود؛ چراکه رسیدن به عبارت `else` در ساختار `try` به این معنی است که بلاک `try` بدون رخ دادن استثنا با موفقیت تکمیل شده است. --- ### ▶ Ellipsis * @@ -3279,10 +3281,10 @@ def some_func(): Ellipsis ``` -**Output** +**خروجی** ```py >>> some_func() -# No output, No Error +# بدون خروجی و بدون خطا >>> SomeRandomString Traceback (most recent call last): @@ -3293,15 +3295,16 @@ NameError: name 'SomeRandomString' is not defined Ellipsis ``` -#### 💡 Explanation -- In Python, `Ellipsis` is a globally available built-in object which is equivalent to `...`. +#### ‫ 💡توضیح +- ‫ در پایتون، `Ellipsis` یک شیء درونی (`built-in`) است که به صورت سراسری (`global`) در دسترس است و معادل `...` است. ```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 +- ‫ `Ellipsis` می‌تواند برای چندین منظور استفاده شود: + + ‫ به عنوان یک نگه‌دارنده برای کدی که هنوز نوشته نشده است (مانند دستور `pass`) + + ‫ در سینتکس برش (`slicing`) برای نمایش برش کامل در ابعاد باقی‌مانده + ```py >>> import numpy as np >>> three_dimensional_array = np.arange(8).reshape(2, 2, 2) @@ -3317,26 +3320,27 @@ Ellipsis ] ]) ``` - So our `three_dimensional_array` is an array of array of arrays. Let's say we want to print the second element (index `1`) of all the innermost arrays, we can use Ellipsis to bypass all the preceding dimensions + ‫ بنابراین، آرایه‌ی `three_dimensional_array` ما، آرایه‌ای از آرایه‌ها از آرایه‌ها است. فرض کنیم می‌خواهیم عنصر دوم (اندیس `1`) از تمامی آرایه‌های درونی را چاپ کنیم؛ در این حالت می‌توانیم از `Ellipsis` برای عبور از تمامی ابعاد قبلی استفاده کنیم: ```py >>> three_dimensional_array[:,:,1] array([[1, 3], [5, 7]]) - >>> three_dimensional_array[..., 1] # using Ellipsis. + >>> three_dimensional_array[..., 1] # با استفاده از Ellipsis. array([[1, 3], [5, 7]]) ``` - Note: this will work for any number of dimensions. You can even select slice in first and last dimension and ignore the middle ones this way (`n_dimensional_array[firs_dim_slice, ..., last_dim_slice]`) - + In [type hinting](https://docs.python.org/3/library/typing.html) to indicate only a part of the type (like `(Callable[..., int]` or `Tuple[str, ...]`)) - + You may also use Ellipsis as a default function argument (in the cases when you want to differentiate between the "no argument passed" and "None value passed" scenarios). + ‫ نکته: این روش برای آرایه‌هایی با هر تعداد بُعد کار می‌کند. حتی می‌توانید از برش (`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 +### ▶ ‫ بی‌نهایت (`Inpinity`) -The spelling is intended. Please, don't submit a patch for this. +‫ این املای کلمه تعمداً به همین شکل نوشته شده است. لطفاً برای اصلاح آن درخواست (`patch`) ارسال نکنید. -**Output (Python 3.x):** +‫ **خروجی (پایتون 3.x):** ```py >>> infinity = float('infinity') >>> hash(infinity) @@ -3345,13 +3349,13 @@ The spelling is intended. Please, don't submit a patch for this. -314159 ``` -#### 💡 Explanation: -- Hash of infinity is 10⁵ x π. -- Interestingly, the hash of `float('-inf')` is "-10⁵ x π" in Python 3, whereas "-10⁵ x e" in Python 2. +#### ‫ 💡 توضیح: +- ‫ هش (`hash`) مقدار بی‌نهایت برابر با 10⁵ × π است. +- ‫ نکته جالب اینکه در پایتون ۳ هشِ مقدار `float('-inf')` برابر با «-10⁵ × π» است، در حالی که در پایتون ۲ برابر با «-10⁵ × e» است. --- -### ▶ Let's mangle +### ▶ ‫ بیایید خرابکاری کنیم 1\. ```py @@ -3361,7 +3365,7 @@ class Yo(object): self.bro = True ``` -**Output:** +‫ **خروجی:** ```py >>> Yo().bro True @@ -3375,12 +3379,12 @@ True ```py class Yo(object): def __init__(self): - # Let's try something symmetrical this time + # این بار بیایید چیزی متقارن را امتحان کنیم self.__honey__ = True self.bro = True ``` -**Output:** +‫ **خروجی:** ```py >>> Yo().bro True @@ -3391,7 +3395,7 @@ Traceback (most recent call last): AttributeError: 'Yo' object has no attribute '_Yo__honey__' ``` -Why did `Yo()._Yo__honey` work? +چرا کد `Yo()._Yo__honey` کار کرد؟ 3\. @@ -3400,10 +3404,10 @@ _A__variable = "Some value" class A(object): def some_func(self): - return __variable # not initialized anywhere yet + return __variable # هنوز در هیچ جا مقداردهی اولیه نشده است ``` -**Output:** +‫ **خروجی:** ```py >>> A().__variable Traceback (most recent call last): @@ -3415,14 +3419,14 @@ AttributeError: 'A' object has no attribute '__variable' ``` -#### 💡 Explanation: +#### ‫ 💡 توضیح: -* [Name Mangling](https://en.wikipedia.org/wiki/Name_mangling) is used to avoid naming collisions between different namespaces. -* In Python, the interpreter modifies (mangles) the class member names starting with `__` (double underscore a.k.a "dunder") and not ending with more than one trailing underscore by adding `_NameOfTheClass` in front. -* So, to access `__honey` attribute in the first snippet, we had to append `_Yo` to the front, which would prevent conflicts with the same name attribute defined in any other class. -* But then why didn't it work in the second snippet? Because name mangling excludes the names ending with double underscores. -* The third snippet was also a consequence of name mangling. The name `__variable` in the statement `return __variable` was mangled to `_A__variable`, which also happens to be the name of the variable we declared in the outer scope. -* Also, if the mangled name is longer than 255 characters, truncation will happen. +* ‫ [تغییر نام](https://en.wikipedia.org/wiki/Name_mangling) برای جلوگیری از برخورد نام‌ها بین فضاهای نام مختلف استفاده می‌شود. +* ‫ در پایتون، مفسر نام‌های اعضای کلاس که با `__` (دو آندرلاین که به عنوان "دندر" شناخته می‌شود) شروع می‌شوند و بیش از یک آندرلاین انتهایی ندارند را با اضافه کردن `_NameOfTheClass` در ابتدای آنها تغییر می‌دهد. +* ‫ بنابراین، برای دسترسی به ویژگی `__honey` در اولین قطعه کد، مجبور بودیم `_Yo` را به ابتدای آن اضافه کنیم، که از بروز تعارض با ویژگی با همان نام تعریف‌شده در هر کلاس دیگری جلوگیری می‌کند. +* ‫ اما چرا در دومین قطعه کد کار نکرد؟ زیرا تغییر نام، نام‌هایی که با دو آندرلاین خاتمه می‌یابند را شامل نمی‌شود. +* ‫ قطعه سوم نیز نتیجه تغییر نام بود. نام `__variable` در عبارت `return __variable` به `_A__variable` تغییر یافت، که همچنین همان نام متغیری است که در محدوده بیرونی تعریف کرده بودیم. +* ‫ همچنین، اگر نام تغییر یافته بیش از ۲۵۵ کاراکتر باشد، برش داده می‌شود. --- --- From 2ca7ebe2a4ccf04775271e3ec2e448889af196ca Mon Sep 17 00:00:00 2001 From: Mohamad Reza Date: Tue, 18 Mar 2025 15:20:17 +0330 Subject: [PATCH 186/210] update farsi translation - section 1 --- translations/fa-farsi/section1-temp.md | 217 +++++++++++++++++++++++++ 1 file changed, 217 insertions(+) diff --git a/translations/fa-farsi/section1-temp.md b/translations/fa-farsi/section1-temp.md index f14400dd..7c37b261 100644 --- a/translations/fa-farsi/section1-temp.md +++ b/translations/fa-farsi/section1-temp.md @@ -585,6 +585,7 @@ TypeError: unhashable type: 'dict' >>> len(another_set) 2 ``` + پس بی‌ثباتی تو این رفتار به خاطر اینه که مقدار `another_ordered_dict in another_set` برابر با `False` هست چون `ordered_dict` از قبل داخل `another_set` هست و همونطور که قبلا مشاهده کردید، مقدار `ordered_dict == another_ordered_dict` برابر با `False` هست. --- @@ -788,3 +789,219 @@ False - در مثال بالا، عبارت `(not None)` برابره با مقدار `True` از اونجایی که مقدار `None` در زمینه boolean به `False` تبدیل میشه. پس کل عبارت معادل عبارت `'something' is True` میشه. --- + + +### ▶ یک بازی دوز که توش X همون اول برنده میشه! + + +```py +# بیاید یک سطر تشکیل بدیم +row = [""] * 3 #row i['', '', ''] +# حالا بیاید تخته بازی رو ایجاد کنیم +board = [row] * 3 +``` + +**خروجی:** + +```py +>>> board +[['', '', ''], ['', '', ''], ['', '', '']] +>>> board[0] +['', '', ''] +>>> board[0][0] +'' +>>> board[0][0] = "X" +>>> board +[['X', '', ''], ['X', '', ''], ['X', '', '']] +``` + +ما که سه‌تا `"X"` نذاشتیم. گذاشتیم مگه؟ + +#### 💡 توضیحات: + +وقتی متغیر `row` رو تشکیل میدیم، تصویر زیر نشون میده که چه اتفاقی در حافظه دستگاه میافته. + +

+ + + + Shows a memory segment after row is initialized. + +

+ +و وقتی متغیر `board` رو با ضرب کردن متغیر `row` تشکیل میدیم، تصویر زیر به صورت کلی نشون میده که چه اتفاقی در حافظه میافته (هر کدوم از عناصر `board[0]`، `board[1]` و `board[2]` در حافظه به لیست یکسانی به نشانی `row` اشاره میکنند). + +

+ + + + Shows a memory segment after board is initialized. + +

+ +ما می‌تونیم با استفاده نکردن از متغیر `row` برای تولید متغیر `board` از این سناریو پرهیز کنیم. (در [این](https://github.com/satwikkansal/wtfpython/issues/68) موضوع پرسیده شده). + +```py +>>> board = [['']*3 for _ in range(3)] +>>> board[0][0] = "X" +>>> board +[['X', '', ''], ['', '', ''], ['', '', '']] +``` + +--- + + +### ▶ متغیر شرودینگر * + + + +```py +funcs = [] +results = [] +for x in range(7): + def some_func(): + return x + funcs.append(some_func) + results.append(some_func()) # note the function call here + +funcs_results = [func() for func in funcs] +``` + +**خروجی:** +```py +>>> results +[0, 1, 2, 3, 4, 5, 6] +>>> funcs_results +[6, 6, 6, 6, 6, 6, 6] +``` + +مقدار `x` در هر تکرار حلقه قبل از اضافه کردن `some_func` به لیست `funcs` متفاوت بود، ولی همه توابع در خارج از حلقه مقدار `6` رو برمیگردونند. + +2. + +```py +>>> powers_of_x = [lambda x: x**i for i in range(10)] +>>> [f(2) for f in powers_of_x] +[512, 512, 512, 512, 512, 512, 512, 512, 512, 512] +``` + +#### 💡 توضیحات: +* وقتی یک تابع رو در داخل یک حلقه تعریف می‌کنیم که در بدنه‌اش از متغیر اون حلقه استفاده شده، بست این تابع به *متغیر* وصله، نه *مقدار* اون. تابع به جای اینکه از مقدار `x` در زمان تعریف تابع استفاده کنه، در زمینه اطرافش دنبال `x` می‌گرده. پس همه این توابع از آخرین مقداری که به متغیر `x` مقداردهی شده برای محاسباتشون استفاده می‌کنند. ما می‌تونیم ببینیم که این توابع از متغیر `x` که در زمینه اطرافشون (*نه* از متغیر محلی) هست، استفاده می‌کنند، به این صورت: + +```py +>>> import inspect +>>> inspect.getclosurevars(funcs[0]) +ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) +``` + +از اونجایی که `x` یک متغیر سراسریه (گلوبال)، ما می‌تونیم مقداری که توابع داخل `funcs` دنبالشون می‌گردند و برمیگردونند رو با به‌روز کردن `x` تغییر بدیم: + +```py +>>> x = 42 +>>> [func() for func in funcs] +[42, 42, 42, 42, 42, 42, 42] +``` + +* برای رسیدن به رفتار موردنظر شما می‌تونید متغیر حلقه رو به عنوان یک متغیر اسم‌دار به تابع بدید. **چرا در این صورت کار می‌کنه؟** چون اینجوری یک متغیر در دامنه خود تابع تعریف میشه. تابع دیگه دنبال مقدار `x` در دامنه اطراف (سراسری) نمی‌گرده ولی یک متغیر محلی برای ذخیره کردن مقدار `x` در اون لحظه می‌سازه. + +```py +funcs = [] +for x in range(7): + def some_func(x=x): + return x + funcs.append(some_func) +``` + +**خروجی:** + +```py +>>> funcs_results = [func() for func in funcs] +>>> funcs_results +[0, 1, 2, 3, 4, 5, 6] +``` + +دیگه از متغیر `x` در دامنه سراسری استفاده نمی‌کنه: + +```py +>>> inspect.getclosurevars(funcs[0]) +ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) +``` + +--- + + +### ▶ اول مرغ بوده یا تخم مرغ؟ * + +1\. +```py +>>> isinstance(3, int) +True +>>> isinstance(type, object) +True +>>> isinstance(object, type) +True +``` + +پس کدوم کلاس پایه "نهایی" هست؟ راستی سردرگمی بیشتری هم تو راهه. + +2\. + +```py +>>> class A: pass +>>> isinstance(A, A) +False +>>> isinstance(type, type) +True +>>> isinstance(object, object) +True +``` + +3\. + +```py +>>> issubclass(int, object) +True +>>> issubclass(type, object) +True +>>> issubclass(object, type) +False +``` + + +#### 💡 توضیحات + +- در پایتون، `type` یک [متاکلاس](https://realpython.com/python-metaclasses/) است. +- در پایتون **همه چیز** یک `object` است، که کلاس‌ها و همچنین نمونه‌هاشون (یا همان instance های کلاس‌ها) هم شامل این موضوع میشن. +- کلاس `type` یک متاکلاسه برای کلاس `object` و همه کلاس‌ها (همچنین کلاس `type`) به صورت مستقیم یا غیرمستقیم از کلاس `object` ارث بری کرده است. +- هیچ کلاس پایه واقعی بین کلاس‌های `object` و `type` وجود نداره. سردرگمی که در قطعه‌کدهای بالا به وجود اومده، به خاطر اینه که ما به این روابط (یعنی `issubclass` و `isinstance`) از دیدگاه کلاس‌های پایتون فکر می‌کنیم. رابطه بین `object` و `type` رو در پایتون خالص نمیشه بازتولید کرد. برای اینکه دقیق‌تر باشیم، رابطه‌های زیر در پایتون خالص نمی‌تونند بازتولید بشن. + + کلاس A یک نمونه از کلاس B، و کلاس B یک نمونه از کلاس A باشه. + + کلاس A یک نمونه از خودش باشه. +- +- این روابط بین `object` و `type` (که هردو نمونه یکدیگه و همچنین خودشون باشند) به خاطر "تقلب" در مرحله پیاده‌سازی، وجود دارند. + +--- + + +### ▶ روابط بین زیرمجموعه کلاس‌ها + +**خروجی:** +```py +>>> from collections.abc import Hashable +>>> issubclass(list, object) +True +>>> issubclass(object, Hashable) +True +>>> issubclass(list, Hashable) +False +``` + +ما انتظار داشتیم که روابط بین زیرکلاس‌ها، انتقالی باشند، درسته؟ (یعنی اگه `A` زیرکلاس `B` باشه و `B` هم زیرکلاس `C` باشه، کلس `A` __باید__ زیرکلاس `C` باشه) + +#### 💡 توضیحات: + +* روابط بین زیرکلاس‌ها در پایتون لزوما انتقالی نیستند. همه مجازند که تابع `__subclasscheck__` دلخواه خودشون رو در یک متاکلاس تعریف کنند. +* وقتی عبارت `issubclass(cls, Hashable)` اجرا میشه، برنامه دنبال یک تابع "غیر نادرست" (یا non-Falsy) در `cls` یا هرچیزی که ازش ارث‌بری می‌کنه، می‌گرده. +* از اونجایی که `object` قابل هش شدنه، ولی `list` این‌طور نیست، رابطه انتقالی شکسته میشه. +* توضیحات با جزئیات بیشتر [اینجا](https://www.naftaliharris.com/blog/python-subclass-intransitivity/) پیدا میشه. + +--- From c956abd9b3db5105d29a35733306e38398f3f981 Mon Sep 17 00:00:00 2001 From: Mohamad Reza Date: Tue, 18 Mar 2025 16:03:14 +0330 Subject: [PATCH 187/210] replace offensive word in farsi translation --- translations/fa-farsi/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 43a51793..fa53fdb7 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -20,7 +20,7 @@ این یه پروژه باحاله که سعی داریم توش توضیح بدیم که پشت پرده یه سری قطعه‌کدهای غیرشهودی و فابلیت‌های کمتر شناخته شده پایتون چه خبره. -درحالی که بعضی از مثال‌هایی که قراره تو این سند ببینید واقعا پشم‌ریزون نیستند ولی بخش‌های جالبی از پایتون رو ظاهر می‌کنند که +درحالی که بعضی از مثال‌هایی که قراره تو این سند ببینید واقعا عجیب و غریب نیستند ولی بخش‌های جالبی از پایتون رو ظاهر می‌کنند که ممکنه شما از وجودشون بی‌خبر باشید. به نظرم این شیوه جالبیه برای یادگیری جزئیات داخلی یه زبان برنامه نویسی و باور دارم که برای شما هم جالب خواهد بود. From 9330752306e48a497e1a4153557dffefd5df1f81 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Fri, 28 Mar 2025 14:34:10 +0100 Subject: [PATCH 188/210] Translate slippery Slopes section --- translations/fa-farsi/README.md | 404 ++++++++++++++++---------------- 1 file changed, 201 insertions(+), 203 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index fa53fdb7..6443cd8a 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -105,65 +105,65 @@ - [💡 Explanation:](#-explanation-28) - [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) - [💡 Explanation:](#-explanation-29) - - [Section: Slippery Slopes](#section-slippery-slopes) - - [▶ Modifying a dictionary while iterating over it](#-modifying-a-dictionary-while-iterating-over-it) + - [‫ بخش: شیب‌های لغزنده](#-بخش-شیبهای-لغزنده) + - [▶ ‫ تغییر یک دیکشنری هنگام پیمایش روی آن](#--تغییر-یک-دیکشنری-هنگام-پیمایش-روی-آن) + - [‫ 💡 توضیح:](#--توضیح) + - [▶ عملیات سرسختانه‌ی `del`](#-عملیات-سرسختانهی-del) + - [‫ 💡 توضیح:](#--توضیح-1) + - [▶ ‫ متغیری که از حوزه خارج است](#--متغیری-که-از-حوزه-خارج-است) + - [‫ 💡 توضیح:](#--توضیح-2) + - [▶ ‫ حذف المان‌های لیست در حین پیمایش](#--حذف-المانهای-لیست-در-حین-پیمایش) - [💡 Explanation:](#-explanation-30) - - [▶ Stubborn `del` operation](#-stubborn-del-operation) - - [💡 Explanation:](#-explanation-31) - - [▶ The out of scope variable](#-the-out-of-scope-variable) - - [💡 Explanation:](#-explanation-32) - - [▶ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - - [💡 Explanation:](#-explanation-33) - - [▶ Lossy zip of iterators \*](#-lossy-zip-of-iterators-) - - [💡 Explanation:](#-explanation-34) - - [▶ Loop variables leaking out!](#-loop-variables-leaking-out) - - [💡 Explanation:](#-explanation-35) - - [▶ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - - [💡 Explanation:](#-explanation-36) - - [▶ Catching the Exceptions](#-catching-the-exceptions) - - [💡 Explanation](#-explanation-37) - - [▶ Same operands, different story!](#-same-operands-different-story) - - [💡 Explanation:](#-explanation-38) - - [▶ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - - [💡 Explanation](#-explanation-39) - - [▶ Rounding like a banker \*](#-rounding-like-a-banker-) - - [💡 Explanation:](#-explanation-40) - - [▶ Needles in a Haystack \*](#-needles-in-a-haystack-) - - [💡 Explanation:](#-explanation-41) - - [▶ Splitsies \*](#-splitsies-) - - [💡 Explanation:](#-explanation-42) - - [▶ Wild imports \*](#-wild-imports-) - - [💡 Explanation:](#-explanation-43) - - [▶ All sorted? \*](#-all-sorted-) - - [💡 Explanation:](#-explanation-44) - - [▶ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - - [💡 Explanation:](#-explanation-45) + - [▶ ‫ زیپِ دارای اتلاف برای پیمایشگرها \*](#--زیپِ-دارای-اتلاف-برای-پیمایشگرها-) + - [‫ 💡 توضیحات:](#--توضیحات) + - [▶ ‫ نشت کردن متغیرهای حلقه!](#--نشت-کردن-متغیرهای-حلقه) + - [💡 ‫ توضیحات:](#--توضیحات-1) + - [▶ ‫ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید!](#--مراقب-آرگومانهای-تغییرپذیر-پیشفرض-باشید) + - [💡 ‫ توضیحات:](#--توضیحات-2) + - [▶ ‫ گرفتن استثناها (Exceptions)](#--گرفتن-استثناها-exceptions) + - [💡 ‫ توضیحات](#--توضیحات-3) + - [▶ ‫ عملوندهای یکسان، داستانی متفاوت!](#--عملوندهای-یکسان-داستانی-متفاوت) + - [💡 ‫ توضیحات:](#--توضیحات-4) + - [▶ ‫ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس](#--تفکیک-نامها-با-نادیده-گرفتن-حوزهی-کلاس) + - [💡 ‫ توضیحات](#--توضیحات-5) + - [▶ ‫ گرد کردن به روش بانکدار \*](#--گرد-کردن-به-روش-بانکدار-) + - [💡 ‫ توضیحات:](#--توضیحات-6) + - [▶ ‫ سوزن‌هایی در انبار کاه \*](#--سوزنهایی-در-انبار-کاه-) + - [💡 ‫ توضیحات:](#--توضیحات-7) + - [▶ ‫ تقسیم‌ها \*](#--تقسیمها-) + - [💡 ‫ توضیحات:](#--توضیحات-8) + - [▶ واردسازی‌های عمومی \*](#-واردسازیهای-عمومی-) + - [💡 ‫ توضیحات:](#--توضیحات-9) + - [▶ ‫ همه چیز مرتب شده؟ \*](#--همه-چیز-مرتب-شده-) + - [💡 ‫ توضیحات:](#--توضیحات-10) + - [▶ ‫ زمان نیمه‌شب وجود ندارد؟](#--زمان-نیمهشب-وجود-ندارد) + - [💡 ‫ توضیحات:](#--توضیحات-11) - [‫ بخش: گنجینه‌های پنهان!](#-بخش-گنجینههای-پنهان) - [▶ ‫ خب پایتون، می‌توانی کاری کنی پرواز کنم؟](#--خب-پایتون-میتوانی-کاری-کنی-پرواز-کنم) - - [‫ 💡 توضیح:](#--توضیح) + - [‫ 💡 توضیح:](#--توضیح-3) - [▶ ‫ `goto`، ولی چرا؟](#--goto-ولی-چرا) - - [‫ 💡 توضیح:](#--توضیح-1) + - [‫ 💡 توضیح:](#--توضیح-4) - [▶ ‫ خودتان را آماده کنید!](#--خودتان-را-آماده-کنید) - - [‫ 💡 توضیح:](#--توضیح-2) + - [‫ 💡 توضیح:](#--توضیح-5) - [▶ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم](#--بیایید-با-عمو-زبان-مهربان-برای-همیشه-آشنا-شویم) - - [‫ 💡 توضیح:](#--توضیح-3) + - [‫ 💡 توضیح:](#--توضیح-6) - [▶ ‫ حتی پایتون هم می‌داند که عشق پیچیده است](#--حتی-پایتون-هم-میداند-که-عشق-پیچیده-است) - - [‫ 💡 توضیح:](#--توضیح-4) + - [‫ 💡 توضیح:](#--توضیح-7) - [▶ ‫ بله، این واقعاً وجود دارد!](#--بله-این-واقعاً-وجود-دارد) - - [‫ 💡 توضیح:](#--توضیح-5) + - [‫ 💡 توضیح:](#--توضیح-8) - [▶ Ellipsis \*](#-ellipsis-) - [‫ 💡توضیح](#-توضیح) - [▶ ‫ بی‌نهایت (`Inpinity`)](#--بینهایت-inpinity) - - [‫ 💡 توضیح:](#--توضیح-6) + - [‫ 💡 توضیح:](#--توضیح-9) - [▶ ‫ بیایید خرابکاری کنیم](#--بیایید-خرابکاری-کنیم) - - [‫ 💡 توضیح:](#--توضیح-7) + - [‫ 💡 توضیح:](#--توضیح-10) - [‫ بخش: ظاهرها فریبنده‌اند!](#-بخش-ظاهرها-فریبندهاند) - [▶ ‫ خطوط را رد می‌کند؟](#--خطوط-را-رد-میکند) - - [‫ 💡 توضیح](#--توضیح-8) + - [‫ 💡 توضیح](#--توضیح-11) - [▶ ‫ تله‌پورت کردن](#--تلهپورت-کردن) - - [‫ 💡 توضیح:](#--توضیح-9) + - [‫ 💡 توضیح:](#--توضیح-12) - [▶ ‫ خب، یک جای کار مشکوک است...](#--خب-یک-جای-کار-مشکوک-است) - - [‫ 💡 توضیح](#--توضیح-10) + - [‫ 💡 توضیح](#--توضیح-13) - [بخش: متفرقه](#بخش-متفرقه) - [‫ ▶ `+=` سریع‌تر است](#---سریعتر-است) - [‫ 💡 توضیح:](#---توضیح) @@ -2112,9 +2112,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} @@ -2125,7 +2125,7 @@ for i in x: print(i) ``` -**Output (Python 2.7- Python 3.5):** +‫ **خروجی (پایتون 2.7تا پایتون 3.5):** ``` 0 @@ -2138,19 +2138,19 @@ for i in x: 7 ``` -Yes, it runs for exactly **eight** times and stops. +‫ بله، دقیقاً **هشت** مرتبه اجرا می‌شود و سپس متوقف می‌شود. -#### 💡 Explanation: +#### ‫ 💡 توضیح: -* Iteration over a dictionary that you edit at the same time is not supported. -* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail. -* How deleted keys are handled and when the resize occurs might be different for different Python implementations. -* So for Python versions other than Python 2.7 - Python 3.5, the count might be different from 8 (but whatever the count is, it's going to be the same every time you run it). You can find some discussion around this [here](https://github.com/satwikkansal/wtfpython/issues/53) or in [this](https://stackoverflow.com/questions/44763802/bug-in-python-dict) StackOverflow thread. -* Python 3.7.6 onwards, you'll see `RuntimeError: dictionary keys changed during iteration` exception if you try to do this. +- ‫ پیمایش روی یک دیکشنری در حالی که همزمان آن را ویرایش می‌کنید پشتیبانی نمی‌شود. +- ‫ هشت بار اجرا می‌شود چون در آن لحظه دیکشنری برای نگهداری کلیدهای بیشتر تغییر اندازه می‌دهد (ما هشت ورودی حذف داریم، بنابراین تغییر اندازه لازم است). این در واقع یک جزئیات پیاده‌سازی است. +- ‫ اینکه کلیدهای حذف‌شده چگونه مدیریت می‌شوند و چه زمانی تغییر اندازه اتفاق می‌افتد ممکن است در پیاده‌سازی‌های مختلف پایتون متفاوت باشد. +- ‫ بنابراین در نسخه‌های دیگر پایتون (به جز Python 2.7 - Python 3.5)، تعداد ممکن است متفاوت از ۸ باشد (اما هر چه که باشد، در هر بار اجرا یکسان خواهد بود). می‌توانید برخی مباحث پیرامون این موضوع را [اینجا](https://github.com/satwikkansal/wtfpython/issues/53) یا در این [رشته‌ی StackOverflow](https://stackoverflow.com/questions/44763802/bug-in-python-dict) مشاهده کنید. +- ‫ از نسخه‌ی Python 3.7.6 به بعد، در صورت تلاش برای انجام این کار، خطای `RuntimeError: dictionary keys changed during iteration` را دریافت خواهید کرد. --- -### ▶ Stubborn `del` operation +### ▶ عملیات سرسختانه‌ی `del` @@ -2160,42 +2160,42 @@ class SomeClass: print("Deleted!") ``` -**Output:** +‫ **خروجی:** 1\. ```py >>> x = SomeClass() >>> y = x ->>> del x # this should print "Deleted!" +>>> del x # باید این عبارت را چاپ کند "Deleted!" >>> del y Deleted! ``` -Phew, deleted at last. You might have guessed what saved `__del__` from being called in our first attempt to delete `x`. Let's add more twists to the example. +‫ «خُب، بالاخره حذف شد.» احتمالاً حدس زده‌اید چه چیزی جلوی فراخوانی `__del__` را در اولین تلاشی که برای حذف `x` داشتیم، گرفته بود. بیایید مثال را پیچیده‌تر کنیم. 2\. ```py >>> x = SomeClass() >>> y = x >>> del x ->>> y # check if y exists +>>> y # بررسی وجود y <__main__.SomeClass instance at 0x7f98a1a67fc8> ->>> del y # Like previously, this should print "Deleted!" ->>> globals() # oh, it didn't. Let's check all our global variables and confirm +>>> del y # مثل قبل، باید این عبارت را چاپ کند "Deleted!" +>>> globals() # اوه، چاپ نکرد. بیایید مقادیر گلوبال را بررسی کنیم. Deleted! {'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None} ``` -Okay, now it's deleted :confused: +‫ «باشه، حالا حذف شد» :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. -+ Calling `globals` (or really, executing anything that will have a non `None` result) caused `_` to reference the new result, dropping the existing reference. Now the reference count reached 0 and we can see "Deleted!" being printed (finally!). +#### ‫ 💡 توضیح: +- ‫ عبارت `del x` مستقیماً باعث فراخوانی `x.__del__()` نمی‌شود. +- ‫ وقتی به دستور `del x` می‌رسیم، پایتون نام `x` را از حوزه‌ی فعلی حذف کرده و شمارنده‌ی مراجع شیٔ‌ای که `x` به آن اشاره می‌کرد را یک واحد کاهش می‌دهد. فقط وقتی شمارنده‌ی مراجع شیٔ به صفر برسد، تابع `__del__()` فراخوانی می‌شود. +- ‫ در خروجی دوم، متد `__del__()` فراخوانی نشد چون دستور قبلی (`>>> y`) در مفسر تعاملی یک ارجاع دیگر به شیٔ ایجاد کرده بود (به صورت خاص، متغیر جادویی `_` به مقدار آخرین عبارت غیر `None` در REPL اشاره می‌کند). بنابراین مانع از رسیدن شمارنده‌ی مراجع به صفر در هنگام اجرای `del y` شد. +- ‫ فراخوانی `globals` (یا هر چیزی که نتیجه‌اش `None` نباشد) باعث می‌شود که `_` به نتیجه‌ی جدید اشاره کند و ارجاع قبلی از بین برود. حالا شمارنده‌ی مراجع به صفر می‌رسد و عبارت «Deleted!» (حذف شد!) نمایش داده می‌شود. --- -### ▶ The out of scope variable +### ▶ ‫ متغیری که از حوزه خارج است 1\. @@ -2225,7 +2225,7 @@ def another_closure_func(): return another_inner_func() ``` -**Output:** +‫ **خروجی:** ```py >>> some_func() 1 @@ -2238,9 +2238,9 @@ UnboundLocalError: local variable 'a' referenced before assignment 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. +#### ‫ 💡 توضیح: +* ‫ وقتی در محدوده (Scope) یک تابع به متغیری مقداردهی می‌کنید، آن متغیر در همان حوزه محلی تعریف می‌شود. بنابراین `a` در تابع `another_func` تبدیل به متغیر محلی می‌شود، اما پیش‌تر در همان حوزه مقداردهی نشده است، و این باعث خطا می‌شود. +* ‫ برای تغییر متغیر سراسری `a` در تابع `another_func`، باید از کلیدواژه‌ی `global` استفاده کنیم. ```py def another_func() global a @@ -2248,13 +2248,13 @@ UnboundLocalError: local variable 'a' referenced before assignment return a ``` - **Output:** + **خروجی:** ```py >>> 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. +* ‫ در تابع `another_closure_func`، متغیر `a` در حوزه‌ی `another_inner_func` محلی می‌شود ولی پیش‌تر در آن حوزه مقداردهی نشده است. به همین دلیل خطا می‌دهد. +* ‫ برای تغییر متغیر حوزه‌ی بیرونی `a` در `another_inner_func`، باید از کلیدواژه‌ی `nonlocal` استفاده کنیم. دستور `nonlocal` به مفسر می‌گوید که متغیر را در نزدیک‌ترین حوزه‌ی بیرونی (به‌جز حوزه‌ی global) جستجو کند. ```py def another_func(): a = 1 @@ -2265,17 +2265,17 @@ UnboundLocalError: local variable 'a' referenced before assignment return another_inner_func() ``` - **Output:** + ‫ **خروجی:** ```py >>> 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. +* ‫ کلیدواژه‌های `global` و `nonlocal` به مفسر پایتون می‌گویند که متغیر جدیدی را تعریف نکند و به جای آن در حوزه‌های بیرونی (سراسری یا میانجی) آن را بیابد. +* ‫ برای مطالعه‌ی بیشتر در مورد نحوه‌ی کار فضای نام‌ها و مکانیزم تعیین حوزه‌ها در پایتون، می‌توانید این [مقاله کوتاه ولی عالی](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) را بخوانید. --- -### ▶ Deleting a list item while iterating +### ▶ ‫ حذف المان‌های لیست در حین پیمایش ```py list_1 = [1, 2, 3, 4] @@ -2296,7 +2296,7 @@ for idx, item in enumerate(list_4): list_4.pop(idx) ``` -**Output:** +‫**خروجی:** ```py >>> list_1 [1, 2, 3, 4] @@ -2308,35 +2308,35 @@ for idx, item in enumerate(list_4): [2, 4] ``` -Can you guess why the output is `[2, 4]`? +‫ می‌توانید حدس بزنید چرا خروجی `[2, 4]` است؟ #### 💡 Explanation: -* 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. +* ‫ هیچ‌وقت ایده‌ی خوبی نیست که شیئی را که روی آن پیمایش می‌کنید تغییر دهید. روش درست این است که روی یک کپی از آن شیء پیمایش کنید؛ در این‌جا `list_3[:]` دقیقاً همین کار را می‌کند. ```py >>> some_list = [1, 2, 3, 4] >>> id(some_list) 139798789457608 - >>> id(some_list[:]) # Notice that python creates new object for sliced list. + >>> id(some_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. +‫ **تفاوت بین `del`، `remove` و `pop`:** +* ‫ `del var_name` فقط اتصال `var_name` را از فضای نام محلی یا سراسری حذف می‌کند (به همین دلیل است که `list_1` تحت تأثیر قرار نمی‌گیرد). +* ‫ متد `remove` اولین مقدار مطابق را حذف می‌کند، نه یک اندیس خاص را؛ اگر مقدار مورد نظر پیدا نشود، خطای `ValueError` ایجاد می‌شود. +* ‫ متد `pop` عنصری را در یک اندیس مشخص حذف کرده و آن را برمی‌گرداند؛ اگر اندیس نامعتبری مشخص شود، خطای `IndexError` ایجاد می‌شود. -**Why the output is `[2, 4]`?** -- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence. +‫ **چرا خروجی `[2, 4]` است؟** +- ‫ پیمایش لیست به صورت اندیس به اندیس انجام می‌شود، و هنگامی که عدد `1` را از `list_2` یا `list_4` حذف می‌کنیم، محتوای لیست به `[2, 3, 4]` تغییر می‌کند. در این حالت عناصر باقی‌مانده به سمت چپ جابه‌جا شده و جایگاهشان تغییر می‌کند؛ یعنی عدد `2` در اندیس 0 و عدد `3` در اندیس 1 قرار می‌گیرد. از آنجا که در مرحله بعدی حلقه به سراغ اندیس 1 می‌رود (که اکنون مقدار آن `3` است)، عدد `2` به طور کامل نادیده گرفته می‌شود. این اتفاق مشابه برای هر عنصر یک‌درمیان در طول پیمایش لیست رخ خواهد داد. -* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example -* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python. +* ‫ برای توضیح بیشتر این مثال، این [تاپیک StackOverflow](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) را ببینید. +* ‫ همچنین برای نمونه مشابهی مربوط به دیکشنری‌ها در پایتون، این [تاپیک مفید StackOverflow](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) را ببینید. --- -### ▶ Lossy zip of iterators * +### ▶ ‫ زیپِ دارای اتلاف برای پیمایشگرها * ```py @@ -2353,11 +2353,11 @@ Can you guess why the output is `[2, 4]`? >>> list(zip(numbers_iter, remaining)) [(4, 3), (5, 4), (6, 5)] ``` -Where did element `3` go from the `numbers` list? +‫ عنصر `3` از لیست `numbers` چه شد؟ -#### 💡 Explanation: +#### ‫ 💡 توضیحات: -- From Python [docs](https://docs.python.org/3.3/library/functions.html#zip), here's an approximate implementation of zip function, +- ‫ بر اساس [مستندات](https://docs.python.org/3.3/library/functions.html#zip) پایتون، پیاده‌سازی تقریبی تابع `zip` به شکل زیر است: ```py def zip(*iterables): sentinel = object() @@ -2370,9 +2370,9 @@ Where did element `3` go from the `numbers` list? 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, +- ‫ بنابراین این تابع تعداد دلخواهی از اشیای قابل پیمایش (*iterable*) را دریافت می‌کند، و با فراخوانی تابع `next` روی آن‌ها، هر یک از عناصرشان را به لیست `result` اضافه می‌کند. این فرایند زمانی متوقف می‌شود که اولین پیمایشگر به انتها برسد. +- ‫ نکته مهم اینجاست که هر زمان یکی از پیمایشگرها به پایان برسد، عناصر موجود در لیست `result` نیز دور ریخته می‌شوند. این دقیقاً همان اتفاقی است که برای عدد `3` در `numbers_iter` رخ داد. +- ‫ روش صحیح برای انجام عملیات بالا با استفاده از تابع `zip` چنین است: ```py >>> numbers = list(range(7)) >>> numbers_iter = iter(numbers) @@ -2381,11 +2381,11 @@ Where did element `3` go from the `numbers` list? >>> 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. + ‫ اولین آرگومانِ تابع `zip` باید پیمایشگری باشد که کمترین تعداد عنصر را دارد. --- -### ▶ Loop variables leaking out! +### ▶ ‫ نشت کردن متغیرهای حلقه! 1\. ```py @@ -2395,17 +2395,17 @@ for x in range(7): print(x, ': x in global') ``` -**Output:** +‫ **خروجی:** ```py 6 : for x inside loop 6 : x in global ``` -But `x` was never defined outside the scope of for loop... +‫ اما متغیر `x` هرگز خارج از محدوده (scope) حلقه `for` تعریف نشده بود... 2\. ```py -# This time let's initialize x first +# این دفعه، مقدار ایکس را در ابتدا مقداردهی اولیه میکنیم. x = -1 for x in range(7): if x == 6: @@ -2413,7 +2413,7 @@ for x in range(7): print(x, ': x in global') ``` -**Output:** +‫ **خروجی:** ```py 6 : for x inside loop 6 : x in global @@ -2421,7 +2421,7 @@ print(x, ': x in global') 3\. -**Output (Python 2.x):** +‫ **خروجی (Python 2.x):** ```py >>> x = 1 >>> print([x for x in range(5)]) @@ -2430,7 +2430,7 @@ print(x, ': x in global') 4 ``` -**Output (Python 3.x):** +‫ **خروجی (Python 3.x):** ```py >>> x = 1 >>> print([x for x in range(5)]) @@ -2439,17 +2439,17 @@ print(x, ': x in global') 1 ``` -#### 💡 Explanation: +#### 💡 ‫ توضیحات: -- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable. +- ‫ در پایتون، حلقه‌های `for` از حوزه (*scope*) فعلی که در آن قرار دارند استفاده می‌کنند و متغیرهای تعریف‌شده در حلقه حتی بعد از اتمام حلقه نیز باقی می‌مانند. این قاعده حتی در مواردی که متغیر حلقه پیش‌تر در فضای نام سراسری (*global namespace*) تعریف شده باشد نیز صدق می‌کند؛ در چنین حالتی، متغیر موجود مجدداً به مقدار جدید متصل می‌شود. -- 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: +- ‫ تفاوت‌های موجود در خروجی مفسرهای Python 2.x و Python 3.x در مثال مربوط به «لیست‌های ادراکی» (*list comprehension*) به دلیل تغییراتی است که در مستند [«تغییرات جدید در Python 3.0»](https://docs.python.org/3/whatsnew/3.0.html) آمده است: - > "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." + > ‫ «لیست‌های ادراکی دیگر فرم نحوی `[... for var in item1, item2, ...]` را پشتیبانی نمی‌کنند و به جای آن باید از `[... for var in (item1, item2, ...)]` استفاده شود. همچنین توجه داشته باشید که لیست‌های ادراکی در Python 3.x معنای متفاوتی دارند: آن‌ها از لحاظ معنایی به بیان ساده‌تر، مشابه یک عبارت تولیدکننده (*generator expression*) درون تابع `list()` هستند و در نتیجه، متغیرهای کنترل حلقه دیگر به فضای نام بیرونی نشت نمی‌کنند.» --- -### ▶ Beware of default mutable arguments! +### ▶ ‫ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید! ```py @@ -2458,7 +2458,7 @@ def some_func(default_arg=[]): return default_arg ``` -**Output:** +‫ **خروجی:** ```py >>> some_func() ['some_string'] @@ -2470,9 +2470,9 @@ def some_func(default_arg=[]): ['some_string', 'some_string', 'some_string'] ``` -#### 💡 Explanation: +#### 💡 ‫ توضیحات: -- 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. +- ‫ آرگومان‌های تغییرپذیر پیش‌فرض در توابع پایتون، هر بار که تابع فراخوانی می‌شود مقداردهی نمی‌شوند؛ بلکه مقداردهی آنها تنها یک بار در زمان تعریف تابع انجام می‌شود و مقدار اختصاص‌یافته به آن‌ها به عنوان مقدار پیش‌فرض برای فراخوانی‌های بعدی استفاده خواهد شد. هنگامی که به صراحت مقدار `[]` را به عنوان آرگومان به `some_func` ارسال کردیم، مقدار پیش‌فرض برای متغیر `default_arg` مورد استفاده قرار نگرفت، بنابراین تابع همان‌طور که انتظار داشتیم عمل کرد. ```py def some_func(default_arg=[]): @@ -2480,9 +2480,9 @@ def some_func(default_arg=[]): return default_arg ``` - **Output:** + ‫ **خروجی:** ```py - >>> some_func.__defaults__ #This will show the default argument values for the function + >>> some_func.__defaults__ # مقادیر پیشفرض این تابع را نمایش می دهد. ([],) >>> some_func() >>> some_func.__defaults__ @@ -2495,7 +2495,7 @@ def some_func(default_arg=[]): (['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: +- ‫ یک روش رایج برای جلوگیری از باگ‌هایی که به دلیل آرگومان‌های تغییرپذیر رخ می‌دهند، این است که مقدار پیش‌فرض را `None` قرار داده و سپس درون تابع بررسی کنیم که آیا مقداری به آن آرگومان ارسال شده است یا خیر. مثال: ```py def some_func(default_arg=None): @@ -2507,31 +2507,31 @@ def some_func(default_arg=[]): --- -### ▶ Catching the Exceptions +### ▶ ‫ گرفتن استثناها (Exceptions) ```py some_list = [1, 2, 3] try: - # This should raise an ``IndexError`` + # ‫ این باید یک `IndexError` ایجاد کند print(some_list[4]) except IndexError, ValueError: print("Caught!") try: - # This should raise a ``ValueError`` + # ‫ این باید یک `ValueError` ایجاد کند some_list.remove(4) except IndexError, ValueError: print("Caught again!") ``` -**Output (Python 2.x):** +‫ **خروجی (Python 2.x):** ```py Caught! ValueError: list.remove(x): x not in list ``` -**Output (Python 3.x):** +‫ **خروجی (Python 3.x):** ```py File "", line 3 except IndexError, ValueError: @@ -2539,7 +2539,7 @@ ValueError: list.remove(x): x not in list SyntaxError: invalid syntax ``` -#### 💡 Explanation +#### 💡 ‫ توضیحات * To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example, ```py @@ -2551,12 +2551,12 @@ SyntaxError: invalid syntax print("Caught again!") print(e) ``` - **Output (Python 2.x):** + ‫ **خروجی (Python 2.x):** ``` Caught again! list.remove(x): x not in list ``` - **Output (Python 3.x):** + ‫ **خروجی (Python 3.x):** ```py File "", line 4 except (IndexError, ValueError), e: @@ -2574,7 +2574,7 @@ SyntaxError: invalid syntax print("Caught again!") print(e) ``` - **Output:** + ‫ **خروجی:** ``` Caught again! list.remove(x): x not in list @@ -2582,7 +2582,7 @@ SyntaxError: invalid syntax --- -### ▶ Same operands, different story! +### ▶ ‫ عملوندهای یکسان، داستانی متفاوت! 1\. ```py @@ -2591,7 +2591,7 @@ b = a a = a + [5, 6, 7, 8] ``` -**Output:** +‫ **خروجی:** ```py >>> a [1, 2, 3, 4, 5, 6, 7, 8] @@ -2606,7 +2606,7 @@ b = a a += [5, 6, 7, 8] ``` -**Output:** +‫ **خروجی:** ```py >>> a [1, 2, 3, 4, 5, 6, 7, 8] @@ -2614,17 +2614,16 @@ a += [5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8] ``` -#### 💡 Explanation: - -* `a += b` doesn't always behave the same way as `a = a + b`. Classes *may* implement the *`op=`* operators differently, and lists do this. +#### 💡 ‫ توضیحات: +* ‫ عملگر `a += b` همیشه همانند `a = a + b` رفتار نمی‌کند. کلاس‌ها *ممکن است* عملگرهای *`op=`* را به گونه‌ای متفاوت پیاده‌سازی کنند، و لیست‌ها نیز چنین می‌کنند. -* The expression `a = a + [5,6,7,8]` generates a new list and sets `a`'s reference to that new list, leaving `b` unchanged. +* ‫ عبارت `a = a + [5,6,7,8]` یک لیست جدید ایجاد می‌کند و مرجع `a` را به این لیست جدید اختصاص می‌دهد، بدون آنکه `b` را تغییر دهد. -* The expression `a += [5,6,7,8]` is actually mapped to an "extend" function that operates on the list such that `a` and `b` still point to the same list that has been modified in-place. +* ‫ عبارت `a += [5,6,7,8]` در واقع به تابعی معادل «extend» ترجمه می‌شود که روی لیست اصلی عمل می‌کند؛ بنابراین `a` و `b` همچنان به همان لیست اشاره می‌کنند که به‌صورت درجا (in-place) تغییر کرده است. --- -### ▶ Name resolution ignoring class scope +### ▶ ‫ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس 1\. ```py @@ -2634,7 +2633,7 @@ class SomeClass: y = (x for i in range(10)) ``` -**Output:** +‫ **خروجی:** ```py >>> list(SomeClass.y)[0] 5 @@ -2648,28 +2647,28 @@ class SomeClass: y = [x for i in range(10)] ``` -**Output (Python 2.x):** +‫ **خروجی (Python 2.x):** ```py >>> SomeClass.y[0] 17 ``` -**Output (Python 3.x):** +‫ **خروجی (Python 3.x):** ```py >>> SomeClass.y[0] 5 ``` -#### 💡 Explanation -- Scopes nested inside class definition ignore names bound at the class level. -- A generator expression has its own scope. -- Starting from Python 3.X, list comprehensions also have their own scope. +#### 💡 ‫ توضیحات +- ‫ حوزه‌هایی که درون تعریف کلاس تو در تو هستند، نام‌های تعریف‌شده در سطح کلاس را نادیده می‌گیرند. +- ‫ عبارت‌های جنراتور (generator expressions) حوزه‌ی مختص به خود دارند. +- ‫ از پایتون نسخه‌ی ۳ به بعد، لیست‌های فشرده (list comprehensions) نیز حوزه‌ی مختص به خود دارند. --- -### ▶ Rounding like a banker * +### ▶ ‫ گرد کردن به روش بانکدار * -Let's implement a naive function to get the middle element of a list: +‫ بیایید یک تابع ساده برای به‌دست‌آوردن عنصر میانی یک لیست پیاده‌سازی کنیم: ```py def get_middle(some_list): mid_index = round(len(some_list) / 2) @@ -2678,22 +2677,22 @@ def get_middle(some_list): **Python 3.x:** ```py ->>> get_middle([1]) # looks good +>>> get_middle([1]) # خوب به نظر می رسد. 1 ->>> get_middle([1,2,3]) # looks good +>>> get_middle([1,2,3]) # خوب به نظر می رسد. 2 ->>> get_middle([1,2,3,4,5]) # huh? +>>> get_middle([1,2,3,4,5]) # چی? 2 ->>> len([1,2,3,4,5]) / 2 # good +>>> len([1,2,3,4,5]) / 2 # خوبه 2.5 ->>> round(len([1,2,3,4,5]) / 2) # why? +>>> round(len([1,2,3,4,5]) / 2) # چرا? 2 ``` -It seems as though Python rounded 2.5 to 2. +‫ به نظر می‌رسد که پایتون عدد ۲٫۵ را به ۲ گرد کرده است. -#### 💡 Explanation: +#### 💡 ‫ توضیحات: -- This is not a float precision error, in fact, this behavior is intentional. Since Python 3.0, `round()` uses [banker's rounding](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even) where .5 fractions are rounded to the nearest **even** number: +- ‫ این یک خطای مربوط به دقت اعداد اعشاری نیست؛ بلکه این رفتار عمدی است. از پایتون نسخه 3.0 به بعد، تابع `round()` از [گرد کردن بانکی](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even) استفاده می‌کند که در آن کسرهای `.5` به نزدیک‌ترین عدد **زوج** گرد می‌شوند: ```py >>> round(0.5) @@ -2702,7 +2701,7 @@ It seems as though Python rounded 2.5 to 2. 2 >>> round(2.5) 2 ->>> import numpy # numpy does the same +>>> import numpy # numpy هم همینکار را می کند. >>> numpy.round(0.5) 0.0 >>> numpy.round(1.5) @@ -2711,17 +2710,17 @@ It seems as though Python rounded 2.5 to 2. 2.0 ``` -- This is the recommended way to round .5 fractions as described in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules). However, the other way (round away from zero) is taught in school most of the time, so banker's rounding is likely not that well known. Furthermore, some of the most popular programming languages (for example: JavaScript, Java, C/C++, Ruby, Rust) do not use banker's rounding either. Therefore, this is still quite special to Python and may result in confusion when rounding fractions. -- See the [round() docs](https://docs.python.org/3/library/functions.html#round) or [this stackoverflow thread](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) for more information. -- Note that `get_middle([1])` only returned 1 because the index was `round(0.5) - 1 = 0 - 1 = -1`, returning the last element in the list. +- ‫ این روشِ پیشنهادی برای گرد کردن کسرهای `.5` مطابق با استاندارد [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules) است. با این حال، روش دیگر (گرد کردن به سمت دور از صفر) اغلب در مدارس آموزش داده می‌شود؛ بنابراین، «گرد کردن بانکی» احتمالا چندان شناخته‌شده نیست. همچنین، برخی از رایج‌ترین زبان‌های برنامه‌نویسی (مانند جاوااسکریپت، جاوا، C/C++‎، روبی و راست) نیز از گرد کردن بانکی استفاده نمی‌کنند. به همین دلیل این موضوع همچنان مختص پایتون بوده و ممکن است باعث سردرگمی هنگام گرد کردن کسرها شود. +- ‫ برای اطلاعات بیشتر به [مستندات تابع `round()`](https://docs.python.org/3/library/functions.html#round) یا [این بحث در Stack Overflow](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) مراجعه کنید. +- ‫ توجه داشته باشید که `get_middle([1])` فقط به این دلیل مقدار 1 را بازگرداند که اندیس آن `round(0.5) - 1 = 0 - 1 = -1` بود و در نتیجه آخرین عنصر لیست را برمی‌گرداند. --- -### ▶ Needles in a Haystack * +### ▶ ‫ سوزن‌هایی در انبار کاه * -I haven't met even a single experience Pythonist till date who has not come across one or more of the following scenarios, +‫ من تا به امروز حتی یک برنامه‌نویس باتجربهٔ پایتون را ندیده‌ام که حداقل با یکی از سناریوهای زیر مواجه نشده باشد: 1\. @@ -2729,10 +2728,10 @@ I haven't met even a single experience Pythonist till date who has not come acro x, y = (0, 1) if True else None, None ``` -**Output:** +‫ **خروجی:** ```py ->>> x, y # expected (0, 1) +>>> x, y # چیزی که توقع داریم. (0, 1) ((0, 1), None) ``` @@ -2751,7 +2750,7 @@ t = () print(t) ``` -**Output:** +‫ **خروجی:** ```py one @@ -2779,26 +2778,26 @@ ten_words_list = [ ] ``` -**Output** +‫ **خروجی** ```py >>> len(ten_words_list) 9 ``` -4\. Not asserting strongly enough +4\. ‫ عدم تأکید کافی ```py a = "python" b = "javascript" ``` -**Output:** +‫ **خروجی:** ```py -# An assert statement with an assertion failure message. +# ‫ دستور assert همراه با پیام خطای assertion >>> assert(a == b, "Both languages are different") -# No AssertionError is raised +# ‫ هیچ AssertionError ای رخ نمی‌دهد ``` 5\. @@ -2815,7 +2814,7 @@ some_list = some_list.append(4) some_dict = some_dict.update({"key_4": 4}) ``` -**Output:** +‫ **خروجی:** ```py >>> print(some_list) @@ -2842,7 +2841,7 @@ def similar_recursive_func(a): return a ``` -**Output:** +‫ **خروجی:** ```py >>> some_recursive_func([5, 0]) @@ -2851,22 +2850,22 @@ def similar_recursive_func(a): 4 ``` -#### 💡 Explanation: - -* For 1, the correct statement for expected behavior is `x, y = (0, 1) if True else (None, None)`. - -* For 2, the correct statement for expected behavior is `t = ('one',)` or `t = 'one',` (missing comma) otherwise the interpreter considers `t` to be a `str` and iterates over it character by character. +#### 💡 ‫ توضیحات: +* ‫ برای مورد ۱، عبارت صحیح برای رفتار مورد انتظار این است: +`x, y = (0, 1) if True else (None, None)` -* `()` is a special token and denotes empty `tuple`. +* ‫ برای مورد ۲، عبارت صحیح برای رفتار مورد انتظار این است: +‫`t = ('one',)` یا `t = 'one',` (ویرگول از قلم افتاده است). در غیر این صورت مفسر `t` را به عنوان یک `str` در نظر گرفته و به صورت کاراکتر به کاراکتر روی آن پیمایش می‌کند. -* In 3, as you might have already figured out, there's a missing comma after 5th element (`"that"`) in the list. So by implicit string literal concatenation, +* ‫ علامت `()` یک توکن خاص است و نشان‌دهنده‌ی یک `tuple` خالی است. +* ‫ در مورد ۳، همان‌طور که احتمالاً متوجه شدید، بعد از عنصر پنجم (`"that"`) یک ویرگول از قلم افتاده است. بنابراین با الحاق ضمنی رشته‌ها، ```py >>> ten_words_list ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] ``` -* No `AssertionError` was raised in 4th snippet because instead of asserting the individual expression `a == b`, we're asserting entire tuple. The following snippet will clear things up, +* ‫ در قطعه‌ی چهارم هیچ `AssertionError`ای رخ نداد؛ زیرا به جای ارزیابی عبارت تکی `a == b`، کل یک تاپل ارزیابی شده است. قطعه‌ی کد زیر این موضوع را روشن‌تر می‌کند: ```py >>> a = "python" @@ -2885,16 +2884,16 @@ def similar_recursive_func(a): AssertionError: Values are not equal ``` -* As for the fifth snippet, most methods that modify the items of sequence/mapping objects like `list.append`, `dict.update`, `list.sort`, etc. modify the objects in-place and return `None`. The rationale behind this is to improve performance by avoiding making a copy of the object if the operation can be done in-place (Referred from [here](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list)). +* ‫ در قطعه‌ی پنجم، بیشتر متدهایی که اشیای ترتیبی (Sequence) یا نگاشت‌ها (Mapping) را تغییر می‌دهند (مانند `list.append`، `dict.update`، `list.sort` و غیره)، شیء اصلی را به‌صورت درجا (in-place) تغییر داده و مقدار `None` برمی‌گردانند. منطق پشت این تصمیم، بهبود عملکرد با جلوگیری از کپی کردن شیء است (به این [منبع](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list) مراجعه کنید). -* Last one should be fairly obvious, mutable object (like `list`) can be altered in the function, and the reassignment of an immutable (`a -= 1`) is not an alteration of the value. +* ‫ قطعه‌ی آخر نیز نسبتاً واضح است؛ شیء تغییرپذیر (mutable)، مثل `list`، می‌تواند در داخل تابع تغییر کند، درحالی‌که انتساب دوباره‌ی یک شیء تغییرناپذیر (مانند `a -= 1`) باعث تغییر مقدار اصلی آن نخواهد شد. -* Being aware of these nitpicks can save you hours of debugging effort in the long run. +* ‫ آگاهی از این نکات ظریف در بلندمدت می‌تواند ساعت‌ها از زمان شما برای رفع اشکال را صرفه‌جویی کند. --- -### ▶ Splitsies * +### ▶ ‫ تقسیم‌ها * ```py >>> 'a'.split() @@ -2913,12 +2912,12 @@ def similar_recursive_func(a): 1 ``` -#### 💡 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 `['']`. -- Noticing how the leading and trailing whitespaces are handled in the following snippet will make things clear, +- ‫ در نگاه اول ممکن است به نظر برسد جداکننده‌ی پیش‌فرض متد `split` یک فاصله‌ی تکی (`' '`) است؛ اما مطابق با [مستندات رسمی](https://docs.python.org/3/library/stdtypes.html#str.split): + > ‫ اگر `sep` مشخص نشده یا برابر با `None` باشد، یک الگوریتم متفاوت برای جدا کردن اعمال می‌شود: رشته‌هایی از فاصله‌های متوالی به عنوان یک جداکننده‌ی واحد در نظر گرفته شده و در نتیجه، هیچ رشته‌ی خالی‌ای در ابتدا یا انتهای لیست خروجی قرار نمی‌گیرد، حتی اگر رشته‌ی اولیه دارای فاصله‌های اضافی در ابتدا یا انتها باشد. به همین دلیل، تقسیم یک رشته‌ی خالی یا رشته‌ای که فقط شامل فضای خالی است با جداکننده‌ی `None` باعث بازگشت یک لیست خالی `[]` می‌شود. + > ‫ اگر `sep` مشخص شود، جداکننده‌های متوالی در کنار هم قرار نمی‌گیرند و هر جداکننده، یک رشته‌ی خالی جدید ایجاد می‌کند. (مثلاً `'1,,2'.split(',')` مقدار `['1', '', '2']` را برمی‌گرداند.) تقسیم یک رشته‌ی خالی با یک جداکننده‌ی مشخص‌شده نیز باعث بازگشت `['']` می‌شود. +- ‫ توجه به اینکه چگونه فضای خالی در ابتدا و انتهای رشته در قطعه‌ی کد زیر مدیریت شده است، این مفهوم را روشن‌تر می‌کند: ```py >>> ' a '.split(' ') ['', 'a', ''] @@ -2930,7 +2929,7 @@ def similar_recursive_func(a): --- -### ▶ Wild imports * +### ▶ واردسازی‌های عمومی * @@ -2945,7 +2944,7 @@ def _another_weird_name_func(): ``` -**Output** +‫ **خروجی** ```py >>> from module import * @@ -2957,16 +2956,16 @@ Traceback (most recent call last): NameError: name '_another_weird_name_func' is not defined ``` -#### 💡 Explanation: +#### 💡 ‫ توضیحات: -- It is often advisable to not use wildcard imports. The first obvious reason for this is, in wildcard imports, the names with a leading underscore 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. +- ‫ اغلب توصیه می‌شود از واردسازی عمومی (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! ``` -- 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. +- ‫ اگر واقعاً تمایل دارید از واردسازی عمومی استفاده کنید، لازم است فهرستی به نام `__all__` را در ماژول خود تعریف کنید که شامل نام اشیاء عمومی (public) قابل‌دسترس هنگام واردسازی عمومی است. ```py __all__ = ['_another_weird_name_func'] @@ -2976,7 +2975,7 @@ NameError: name '_another_weird_name_func' is not defined def _another_weird_name_func(): print("works!") ``` - **Output** + ‫ **خروجی** ```py >>> _another_weird_name_func() @@ -2989,7 +2988,7 @@ NameError: name '_another_weird_name_func' is not defined --- -### ▶ All sorted? * +### ▶ ‫ همه چیز مرتب شده؟ * @@ -3005,9 +3004,9 @@ True False ``` -#### 💡 Explanation: +#### 💡 ‫ توضیحات: -- The `sorted` method always returns a list, and comparing lists and tuples always returns `False` in Python. +- ‫ متد `sorted` همیشه یک لیست (`list`) برمی‌گرداند، و در پایتون مقایسه‌ی لیست‌ها و تاپل‌ها (`tuple`) همیشه مقدار `False` را برمی‌گرداند. - ```py >>> [] == tuple() @@ -3016,10 +3015,9 @@ False >>> type(x), type(sorted(x)) (tuple, list) ``` +- ‫ برخلاف متد `sorted`، متد `reversed` یک تکرارکننده (iterator) برمی‌گرداند. چرا؟ زیرا مرتب‌سازی نیاز به تغییر درجا (in-place) یا استفاده از ظرف جانبی (مانند یک لیست اضافی) دارد، در حالی که معکوس کردن می‌تواند به‌سادگی با پیمایش از اندیس آخر به اول انجام شود. -- Unlike `sorted`, the `reversed` method returns an iterator. Why? Because sorting requires the iterator to be either modified in-place or use an extra container (a list), whereas reversing can simply work by iterating from the last index to the first. - -- So during comparison `sorted(y) == sorted(y)`, the first call to `sorted()` will consume the iterator `y`, and the next call will just return an empty list. +- ‫ بنابراین در مقایسه‌ی `sorted(y) == sorted(y)`، فراخوانی اولِ `sorted()` تمام عناصرِ تکرارکننده‌ی `y` را مصرف می‌کند، و فراخوانی بعدی یک لیست خالی برمی‌گرداند. ```py >>> x = 7, 8, 9 @@ -3030,7 +3028,7 @@ False --- -### ▶ Midnight time doesn't exist? +### ▶ ‫ زمان نیمه‌شب وجود ندارد؟ ```py from datetime import datetime @@ -3048,14 +3046,14 @@ if noon_time: print("Time at noon is", noon_time) ``` -**Output (< 3.5):** +‫ **خروجی (< 3.5):** ```py ('Time at noon is', datetime.time(12, 0)) ``` The midnight time is not printed. -#### 💡 Explanation: +#### 💡 ‫ توضیحات: Before Python 3.5, the boolean value for `datetime.time` object was considered to be `False` if it represented midnight in UTC. It is error-prone when using the `if obj:` syntax to check if the `obj` is null or some equivalent of "empty." @@ -3142,7 +3140,7 @@ SyntaxError: not a chance ### ▶ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم -**Output (Python 3.x)** +‫ **خروجی (Python 3.x)** ```py >>> from __future__ import barry_as_FLUFL >>> "Ruby" != "Python" # شکی در این نیست. @@ -3435,7 +3433,7 @@ AttributeError: 'A' object has no attribute '__variable' ### ▶ ‫ خطوط را رد می‌کند؟ -**Output:** +‫ **خروجی:** ```py >>> value = 11 >>> valuе = 32 @@ -3596,7 +3594,7 @@ def convert_list_to_string(l, iters): assert len(s) == 3*iters ``` -**Output:** +‫ **خروجی:** ‫ اجرا شده در پوسته‌ی ipython با استفاده از `%timeit` برای خوانایی بهتر نتایج. ‫ همچنین می‌توانید از ماژول `timeit` در پوسته یا اسکریپت عادی پایتون استفاده کنید؛ نمونه‌ی استفاده در زیر آمده است: From 010868a767e6779205c231895bc676e398a656a3 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Tue, 1 Apr 2025 15:58:39 +0200 Subject: [PATCH 189/210] Add partial transations for first section --- translations/fa-farsi/README.md | 406 ++++++++++++++++---------------- 1 file changed, 199 insertions(+), 207 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 6443cd8a..d9133592 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -74,101 +74,101 @@ - [💡 Explanation](#-explanation-12) - [▶ Subclass relationships](#-subclass-relationships) - [💡 Explanation:](#-explanation-13) - - [▶ Methods equality and identity](#-methods-equality-and-identity) - - [💡 Explanation](#-explanation-14) - - [▶ All-true-ation \*](#-all-true-ation-) + - [▶ ‫ برابری و هویت متدها](#--برابری-و-هویت-متدها) + - [💡 ‫ توضیحات](#--توضیحات) + - [▶ ‫ آل-ترو-یشن \*](#--آل-ترو-یشن-) + - [💡 Explanation:](#-explanation-14) + - [💡 ‫ توضیح:](#--توضیح) + - [▶ ‫ رشته‌ها و بک‌اسلش‌ها](#--رشتهها-و-بکاسلشها) + - [💡 ‫ توضیح:](#--توضیح-1) + - [▶ ‫ گره نیست، نَه!](#--گره-نیست-نَه) - [💡 Explanation:](#-explanation-15) - - [💡 Explanation:](#-explanation-16) - - [▶ Strings and the backslashes](#-strings-and-the-backslashes) - - [💡 Explanation](#-explanation-17) - - [▶ not knot!](#-not-knot) - - [💡 Explanation:](#-explanation-18) - - [▶ Half triple-quoted strings](#-half-triple-quoted-strings) - - [💡 Explanation:](#-explanation-19) - - [▶ What's wrong with booleans?](#-whats-wrong-with-booleans) - - [💡 Explanation:](#-explanation-20) - - [▶ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - - [💡 Explanation:](#-explanation-21) + - [▶ رشته‌های نیمه سه‌نقل‌قولی](#-رشتههای-نیمه-سهنقلقولی) + - [💡 ‫ توضیح:](#--توضیح-2) + - [▶ ‫ مشکل بولین ها چیست؟](#--مشکل-بولین-ها-چیست) + - [💡 ‫ توضیحات:](#--توضیحات-1) + - [▶ ‫ ویژگی‌های کلاس و ویژگی‌های نمونه](#--ویژگیهای-کلاس-و-ویژگیهای-نمونه) + - [💡 ‫ توضیح:](#--توضیح-3) - [▶ yielding None](#-yielding-none) - - [💡 Explanation:](#-explanation-22) + - [💡 Explanation:](#-explanation-16) - [▶ Yielding from... return! \*](#-yielding-from-return-) - - [💡 Explanation:](#-explanation-23) - - [▶ Nan-reflexivity \*](#-nan-reflexivity-) - - [💡 Explanation:](#-explanation-24) - - [▶ Mutating the immutable!](#-mutating-the-immutable) - - [💡 Explanation:](#-explanation-25) - - [▶ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) - - [💡 Explanation:](#-explanation-26) - - [▶ The mysterious key type conversion](#-the-mysterious-key-type-conversion) - - [💡 Explanation:](#-explanation-27) - - [▶ Let's see if you can guess this?](#-lets-see-if-you-can-guess-this) - - [💡 Explanation:](#-explanation-28) - - [▶ Exceeds the limit for integer string conversion](#-exceeds-the-limit-for-integer-string-conversion) - - [💡 Explanation:](#-explanation-29) + - [💡 ‫ توضیح:](#--توضیح-4) + - [▶ ‫ بازتاب‌ناپذیری \*](#--بازتابناپذیری-) + - [💡 توضیحات:](#-توضیحات-1) + - [▶ ‫ تغییر دادن اشیای تغییرناپذیر!](#--تغییر-دادن-اشیای-تغییرناپذیر) + - [💡 ‫ توضیحات:](#--توضیحات-2) + - [▶ ‫ متغیری که از اسکوپ بیرونی ناپدید می‌شود](#--متغیری-که-از-اسکوپ-بیرونی-ناپدید-میشود) + - [💡 ‫ توضیحات:](#--توضیحات-3) + - [▶ ‫ تبدیل اسرارآمیز نوع کلید](#--تبدیل-اسرارآمیز-نوع-کلید) + - [💡 ‫ توضیحات:](#--توضیحات-4) + - [▶ ‫ ببینیم می‌توانید این را حدس بزنید؟](#--ببینیم-میتوانید-این-را-حدس-بزنید) + - [💡 ‫ توضیح:](#--توضیح-5) + - [▶ ‫ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود](#--از-حد-مجاز-برای-تبدیل-رشته-به-عدد-صحیح-فراتر-میرود) + - [💡 ‫ توضیح:](#--توضیح-6) - [‫ بخش: شیب‌های لغزنده](#-بخش-شیبهای-لغزنده) - [▶ ‫ تغییر یک دیکشنری هنگام پیمایش روی آن](#--تغییر-یک-دیکشنری-هنگام-پیمایش-روی-آن) - - [‫ 💡 توضیح:](#--توضیح) + - [‫ 💡 توضیح:](#--توضیح-7) - [▶ عملیات سرسختانه‌ی `del`](#-عملیات-سرسختانهی-del) - - [‫ 💡 توضیح:](#--توضیح-1) + - [‫ 💡 توضیح:](#--توضیح-8) - [▶ ‫ متغیری که از حوزه خارج است](#--متغیری-که-از-حوزه-خارج-است) - - [‫ 💡 توضیح:](#--توضیح-2) + - [‫ 💡 توضیح:](#--توضیح-9) - [▶ ‫ حذف المان‌های لیست در حین پیمایش](#--حذف-المانهای-لیست-در-حین-پیمایش) - - [💡 Explanation:](#-explanation-30) + - [💡 Explanation:](#-explanation-17) - [▶ ‫ زیپِ دارای اتلاف برای پیمایشگرها \*](#--زیپِ-دارای-اتلاف-برای-پیمایشگرها-) - - [‫ 💡 توضیحات:](#--توضیحات) + - [‫ 💡 توضیحات:](#--توضیحات-5) - [▶ ‫ نشت کردن متغیرهای حلقه!](#--نشت-کردن-متغیرهای-حلقه) - - [💡 ‫ توضیحات:](#--توضیحات-1) + - [💡 ‫ توضیحات:](#--توضیحات-6) - [▶ ‫ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید!](#--مراقب-آرگومانهای-تغییرپذیر-پیشفرض-باشید) - - [💡 ‫ توضیحات:](#--توضیحات-2) + - [💡 ‫ توضیحات:](#--توضیحات-7) - [▶ ‫ گرفتن استثناها (Exceptions)](#--گرفتن-استثناها-exceptions) - - [💡 ‫ توضیحات](#--توضیحات-3) + - [💡 ‫ توضیحات](#--توضیحات-8) - [▶ ‫ عملوندهای یکسان، داستانی متفاوت!](#--عملوندهای-یکسان-داستانی-متفاوت) - - [💡 ‫ توضیحات:](#--توضیحات-4) + - [💡 ‫ توضیحات:](#--توضیحات-9) - [▶ ‫ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس](#--تفکیک-نامها-با-نادیده-گرفتن-حوزهی-کلاس) - - [💡 ‫ توضیحات](#--توضیحات-5) + - [💡 ‫ توضیحات](#--توضیحات-10) - [▶ ‫ گرد کردن به روش بانکدار \*](#--گرد-کردن-به-روش-بانکدار-) - - [💡 ‫ توضیحات:](#--توضیحات-6) + - [💡 ‫ توضیحات:](#--توضیحات-11) - [▶ ‫ سوزن‌هایی در انبار کاه \*](#--سوزنهایی-در-انبار-کاه-) - - [💡 ‫ توضیحات:](#--توضیحات-7) + - [💡 ‫ توضیحات:](#--توضیحات-12) - [▶ ‫ تقسیم‌ها \*](#--تقسیمها-) - - [💡 ‫ توضیحات:](#--توضیحات-8) + - [💡 ‫ توضیحات:](#--توضیحات-13) - [▶ واردسازی‌های عمومی \*](#-واردسازیهای-عمومی-) - - [💡 ‫ توضیحات:](#--توضیحات-9) + - [💡 ‫ توضیحات:](#--توضیحات-14) - [▶ ‫ همه چیز مرتب شده؟ \*](#--همه-چیز-مرتب-شده-) - - [💡 ‫ توضیحات:](#--توضیحات-10) + - [💡 ‫ توضیحات:](#--توضیحات-15) - [▶ ‫ زمان نیمه‌شب وجود ندارد؟](#--زمان-نیمهشب-وجود-ندارد) - - [💡 ‫ توضیحات:](#--توضیحات-11) + - [💡 ‫ توضیحات:](#--توضیحات-16) - [‫ بخش: گنجینه‌های پنهان!](#-بخش-گنجینههای-پنهان) - [▶ ‫ خب پایتون، می‌توانی کاری کنی پرواز کنم؟](#--خب-پایتون-میتوانی-کاری-کنی-پرواز-کنم) - - [‫ 💡 توضیح:](#--توضیح-3) + - [‫ 💡 توضیح:](#--توضیح-10) - [▶ ‫ `goto`، ولی چرا؟](#--goto-ولی-چرا) - - [‫ 💡 توضیح:](#--توضیح-4) + - [‫ 💡 توضیح:](#--توضیح-11) - [▶ ‫ خودتان را آماده کنید!](#--خودتان-را-آماده-کنید) - - [‫ 💡 توضیح:](#--توضیح-5) + - [‫ 💡 توضیح:](#--توضیح-12) - [▶ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم](#--بیایید-با-عمو-زبان-مهربان-برای-همیشه-آشنا-شویم) - - [‫ 💡 توضیح:](#--توضیح-6) + - [‫ 💡 توضیح:](#--توضیح-13) - [▶ ‫ حتی پایتون هم می‌داند که عشق پیچیده است](#--حتی-پایتون-هم-میداند-که-عشق-پیچیده-است) - - [‫ 💡 توضیح:](#--توضیح-7) + - [‫ 💡 توضیح:](#--توضیح-14) - [▶ ‫ بله، این واقعاً وجود دارد!](#--بله-این-واقعاً-وجود-دارد) - - [‫ 💡 توضیح:](#--توضیح-8) + - [‫ 💡 توضیح:](#--توضیح-15) - [▶ Ellipsis \*](#-ellipsis-) - [‫ 💡توضیح](#-توضیح) - [▶ ‫ بی‌نهایت (`Inpinity`)](#--بینهایت-inpinity) - - [‫ 💡 توضیح:](#--توضیح-9) + - [‫ 💡 توضیح:](#--توضیح-16) - [▶ ‫ بیایید خرابکاری کنیم](#--بیایید-خرابکاری-کنیم) - - [‫ 💡 توضیح:](#--توضیح-10) + - [‫ 💡 توضیح:](#--توضیح-17) - [‫ بخش: ظاهرها فریبنده‌اند!](#-بخش-ظاهرها-فریبندهاند) - [▶ ‫ خطوط را رد می‌کند؟](#--خطوط-را-رد-میکند) - - [‫ 💡 توضیح](#--توضیح-11) + - [‫ 💡 توضیح](#--توضیح-18) - [▶ ‫ تله‌پورت کردن](#--تلهپورت-کردن) - - [‫ 💡 توضیح:](#--توضیح-12) + - [‫ 💡 توضیح:](#--توضیح-19) - [▶ ‫ خب، یک جای کار مشکوک است...](#--خب-یک-جای-کار-مشکوک-است) - - [‫ 💡 توضیح](#--توضیح-13) + - [‫ 💡 توضیح](#--توضیح-20) - [بخش: متفرقه](#بخش-متفرقه) - [‫ ▶ `+=` سریع‌تر است](#---سریعتر-است) - [‫ 💡 توضیح:](#---توضیح) - [‫ ▶ بیایید یک رشته‌ی بزرگ بسازیم!](#--بیایید-یک-رشتهی-بزرگ-بسازیم) - - [💡 توضیحات](#-توضیحات-1) + - [💡 توضیحات](#-توضیحات-2) - [▶ ‫ کُند کردن جستجوها در `dict` \*](#---کُند-کردن-جستجوها-در-dict-) - [‫ 💡 توضیح:](#---توضیح-1) - [‫ ▶ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#--حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) @@ -1238,7 +1238,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A` --- -### ▶ Methods equality and identity +### ▶ ‫ برابری و هویت متدها 1. @@ -1256,7 +1256,7 @@ class SomeClass: pass ``` -**Output:** +‫ **خروجی:** ```py >>> print(SomeClass.method is SomeClass.method) True @@ -1268,8 +1268,8 @@ True True ``` -Accessing `classm` twice, we get an equal object, but not the *same* one? Let's see what happens -with instances of `SomeClass`: +‫ با دوبار دسترسی به `classm`، یک شیء برابر دریافت می‌کنیم، اما *همان* شیء نیست؟ بیایید ببینیم +‫ چه اتفاقی برای نمونه‌های `SomeClass` می‌افتد: 2. ```py @@ -1277,7 +1277,7 @@ o1 = SomeClass() o2 = SomeClass() ``` -**Output:** +‫ **خروجی:** ```py >>> print(o1.method == o2.method) False @@ -1293,53 +1293,41 @@ True True ``` -Accessing `classm` or `method` twice, creates equal but not *same* objects for the same instance of `SomeClass`. +‫ دسترسی به `classm` یا `method` دو بار، اشیایی برابر اما نه *یکسان* را برای همان نمونه از `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). +#### 💡 ‫ توضیحات +* ‫ تابع‌ها [وصاف](https://docs.python.org/3/howto/descriptor.html) هستند. هر زمان که تابعی به عنوان یک ویژگی فراخوانی شود، وصف فعال می‌شود و یک شیء متد ایجاد می‌کند که تابع را به شیء صاحب آن ویژگی "متصل" می‌کند. اگر این متد فراخوانی شود، تابع را با ارسال ضمنی شیء متصل‌شده به عنوان اولین آرگومان صدا می‌زند (به این ترتیب است که `self` را به عنوان اولین آرگومان دریافت می‌کنیم، با وجود اینکه آن را به‌طور صریح ارسال نکرده‌ایم). ```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. +* ‫ دسترسی به ویژگی چندین بار، هر بار یک شیء متد جدید ایجاد می‌کند! بنابراین عبارت `o1.method is o1.method` هرگز درست (truthy) نیست. با این حال، دسترسی به تابع‌ها به عنوان ویژگی‌های کلاس (و نه نمونه) متد ایجاد نمی‌کند؛ بنابراین عبارت `SomeClass.method is SomeClass.method` درست است. ```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. +* ‫ `classmethod` توابع را به متدهای کلاس تبدیل می‌کند. متدهای کلاس وصاف‌هایی هستند که هنگام دسترسی، یک شیء متد ایجاد می‌کنند که به *کلاس* (نوع) شیء متصل می‌شود، نه خود شیء. ```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. +* ‫ برخلاف توابع، `classmethod`‌ها هنگام دسترسی به عنوان ویژگی‌های کلاس نیز یک شیء متد ایجاد می‌کنند (که در این حالت به خود کلاس متصل می‌شوند، نه نوع آن). بنابراین عبارت `SomeClass.classm is SomeClass.classm` نادرست (falsy) است. ```py >>> SomeClass.classm > ``` -* A method object compares equal when both the functions are equal, and the bound objects are the same. So -`o1.method == o1.method` is truthy, although not the same object in memory. -* `staticmethod` transforms functions into a "no-op" descriptor, which returns the function as-is. No method -objects are ever created, so comparison with `is` is truthy. +* ‫ یک شیء متد زمانی برابر در نظر گرفته می‌شود که هم تابع‌ها برابر باشند و هم شیءهای متصل‌شده یکسان باشند. بنابراین عبارت `o1.method == o1.method` درست (truthy) است، هرچند که آن‌ها در حافظه شیء یکسانی نیستند. +* ‫ `staticmethod` توابع را به یک وصف "بدون عملیات" (no-op) تبدیل می‌کند که تابع را به همان صورت بازمی‌گرداند. هیچ شیء متدی ایجاد نمی‌شود، بنابراین مقایسه با `is` نیز درست (truthy) است. ```py >>> o1.staticm >>> SomeClass.staticm ``` -* Having to create new "method" objects every time Python calls instance methods and having to modify the arguments -every time in order to insert `self` affected performance badly. -CPython 3.7 [solved it](https://bugs.python.org/issue26110) by introducing new opcodes that deal with calling methods -without creating the temporary method objects. This is used only when the accessed function is actually called, so the -snippets here are not affected, and still generate methods :) +* ‫ ایجاد شیءهای "متد" جدید در هر بار فراخوانی متدهای نمونه و نیاز به اصلاح آرگومان‌ها برای درج `self`، عملکرد را به شدت تحت تأثیر قرار می‌داد. +CPython 3.7 [این مشکل را حل کرد](https://bugs.python.org/issue26110) با معرفی opcodeهای جدیدی که فراخوانی متدها را بدون ایجاد شیء متد موقتی مدیریت می‌کنند. این به شرطی است که تابع دسترسی‌یافته واقعاً فراخوانی شود، بنابراین قطعه‌کدهای اینجا تحت تأثیر قرار نمی‌گیرند و همچنان متد ایجاد می‌کنند :) -### ▶ All-true-ation * +### ▶ ‫ آل-ترو-یشن * @@ -1357,11 +1345,11 @@ False True ``` -Why's this True-False alteration? +‫ چرا این تغییر درست-نادرسته؟ #### 💡 Explanation: -- The implementation of `all` function is equivalent to +- ‫ پیاده‌سازی تابع `all` معادل است با - ```py def all(iterable): @@ -1371,15 +1359,15 @@ Why's this True-False alteration? return True ``` -- `all([])` returns `True` since the iterable is empty. -- `all([[]])` returns `False` because the passed array has one element, `[]`, and in python, an empty list is falsy. -- `all([[[]]])` and higher recursive variants are always `True`. This is because the passed array's single element (`[[...]]`) is no longer empty, and lists with values are truthy. +- ‫ `all([])` مقدار `True` را برمی‌گرداند چون iterable خالی است. +- ‫ `all([[]])` مقدار `False` را برمی‌گرداند چون آرایه‌ی داده‌شده یک عنصر دارد، یعنی `[]`، و در پایتون، لیست خالی مقدار falsy دارد. +- ‫ `all([[[]]])` و نسخه‌های بازگشتی بالاتر همیشه `True` هستند. دلیلش این است که عنصر واحد آرایه‌ی داده‌شده (`[[...]]`) دیگر خالی نیست، و لیست‌هایی که دارای مقدار باشند، truthy در نظر گرفته می‌شوند. --- -### ▶ The surprising comma +### ▶ ‫ کاما‌ی شگفت‌انگیز -**Output (< 3.6):** +‫ **خروجی (< 3.6):** ```py >>> def f(x, y,): @@ -1401,17 +1389,17 @@ SyntaxError: invalid syntax SyntaxError: invalid syntax ``` -#### 💡 Explanation: +#### 💡 ‫ توضیح: -- Trailing comma is not always legal in formal parameters list of a Python function. -- In Python, the argument list is defined partially with leading commas and partially with trailing commas. This conflict causes situations where a comma is trapped in the middle, and no rule accepts it. -- **Note:** The trailing comma problem is [fixed in Python 3.6](https://bugs.python.org/issue9232). The remarks in [this](https://bugs.python.org/issue9232#msg248399) post discuss in brief different usages of trailing commas in Python. +- ‫ کامای انتهایی همیشه در لیست پارامترهای رسمی یک تابع در پایتون قانونی نیست. +- ‫ در پایتون، لیست آرگومان‌ها تا حدی با کاماهای ابتدایی و تا حدی با کاماهای انتهایی تعریف می‌شود. این تضاد باعث ایجاد موقعیت‌هایی می‌شود که در آن یک کاما در وسط گیر می‌افتد و هیچ قانونی آن را نمی‌پذیرد. +- ‫ **نکته:** مشکل کامای انتهایی در [پایتون ۳.۶ رفع شده است](https://bugs.python.org/issue9232). توضیحات در [این پست](https://bugs.python.org/issue9232#msg248399) به‌طور خلاصه کاربردهای مختلف کاماهای انتهایی در پایتون را بررسی می‌کند. --- -### ▶ Strings and the backslashes +### ▶ ‫ رشته‌ها و بک‌اسلش‌ها -**Output:** +‫ **خروجی:** ```py >>> print("\"") " @@ -1429,14 +1417,14 @@ SyntaxError: EOL while scanning string literal True ``` -#### 💡 Explanation +#### 💡 ‫ توضیح: -- 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). +- ‫ در یک رشته‌ی معمولی در پایتون، بک‌اسلش برای فرار دادن (escape) نویسه‌هایی استفاده می‌شود که ممکن است معنای خاصی داشته باشند (مانند تک‌نقل‌قول، دوتا‌نقل‌قول، و خودِ بک‌اسلش). ```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. +- ‫ در یک رشته‌ی خام (raw string literal) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان شکل منتقل می‌شوند، به‌همراه رفتار فرار دادن نویسه‌ی بعدی. ```py >>> r'wt\"f' == 'wt\\"f' True @@ -1448,18 +1436,18 @@ True >>> 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. +- ‫ در یک رشته‌ی خام (raw string) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان صورت منتقل می‌شوند، همراه با رفتاری که کاراکتر بعدی را فرار می‌دهد (escape می‌کند). --- -### ▶ not knot! +### ▶ ‫ گره نیست، نَه! ```py x = True y = False ``` -**Output:** +‫ **خروجی:** ```py >>> not x == y True @@ -1472,16 +1460,16 @@ SyntaxError: invalid syntax #### 💡 Explanation: -* Operator precedence affects how an expression is evaluated, and `==` operator has higher precedence than `not` operator in Python. -* So `not x == y` is equivalent to `not (x == y)` which is equivalent to `not (True == False)` finally evaluating to `True`. -* But `x == not y` raises a `SyntaxError` because it can be thought of being equivalent to `(x == not) y` and not `x == (not y)` which you might have expected at first sight. -* The parser expected the `not` token to be a part of the `not in` operator (because both `==` and `not in` operators have the same precedence), but after not being able to find an `in` token following the `not` token, it raises a `SyntaxError`. +* ‫ تقدم عملگرها بر نحوه‌ی ارزیابی یک عبارت تأثیر می‌گذارد، و در پایتون، عملگر `==` تقدم بالاتری نسبت به عملگر `not` دارد. +* ‫ بنابراین عبارت `not x == y` معادل `not (x == y)` است که خودش معادل `not (True == False)` بوده و در نهایت به `True` ارزیابی می‌شود. +* ‫ اما `x == not y` یک `SyntaxError` ایجاد می‌کند، چون می‌توان آن را به صورت `(x == not) y` تفسیر کرد، نه آن‌طور که در نگاه اول انتظار می‌رود یعنی `x == (not y)`. +* ‫ تجزیه‌گر (parser) انتظار دارد که توکن `not` بخشی از عملگر `not in` باشد (چون هر دو عملگر `==` و `not in` تقدم یکسانی دارند)، اما پس از اینکه توکن `in` بعد از `not` پیدا نمی‌شود، خطای `SyntaxError` صادر می‌شود. --- -### ▶ Half triple-quoted strings +### ▶ رشته‌های نیمه سه‌نقل‌قولی -**Output:** +‫ **خروجی:** ```py >>> print('wtfpython''') wtfpython @@ -1496,25 +1484,25 @@ wtfpython 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, +#### 💡 ‫ توضیح: ++ ‫ پایتون از الحاق ضمنی [رشته‌های متنی](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation) پشتیبانی می‌کند. برای مثال، ``` >>> print("wtf" "python") wtfpython >>> 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. ++ ‫ `'''` و `"""` نیز جداکننده‌های رشته‌ای در پایتون هستند که باعث ایجاد SyntaxError می‌شوند، چون مفسر پایتون هنگام اسکن رشته‌ای که با سه‌نقل‌قول آغاز شده، انتظار یک سه‌نقل‌قول پایانی به‌عنوان جداکننده را دارد. --- -### ▶ What's wrong with booleans? +### ▶ ‫ مشکل بولین ها چیست؟ 1\. ```py -# A simple example to count the number of booleans and -# integers in an iterable of mixed data types. +# یک مثال ساده برای شمردن تعداد مقادیر بولی و +# اعداد صحیح در یک iterable با انواع داده‌ی مخلوط. mixed_list = [False, 1.0, "some_string", 3, True, [], False] integers_found_so_far = 0 booleans_found_so_far = 0 @@ -1526,7 +1514,7 @@ for item in mixed_list: booleans_found_so_far += 1 ``` -**Output:** +‫ **خروجی:** ```py >>> integers_found_so_far 4 @@ -1554,7 +1542,7 @@ def tell_truth(): print("I have lost faith in truth!") ``` -**Output (< 3.x):** +‫ **خروجی (< 3.x):** ```py >>> tell_truth() @@ -1563,9 +1551,9 @@ I have lost faith in truth! -#### 💡 Explanation: +#### 💡 ‫ توضیحات: -* `bool` is a subclass of `int` in Python +* ‫ در پایتون، `bool` زیرکلاسی از `int` است ```py >>> issubclass(bool, int) @@ -1574,7 +1562,7 @@ I have lost faith in truth! False ``` -* And thus, `True` and `False` are instances of `int` +* ‫ و بنابراین، `True` و `False` نمونه‌هایی از `int` هستند ```py >>> isinstance(True, int) True @@ -1582,7 +1570,7 @@ I have lost faith in truth! True ``` -* The integer value of `True` is `1` and that of `False` is `0`. +* ‫ مقدار عددی `True` برابر با `1` و مقدار عددی `False` برابر با `0` است. ```py >>> int(True) 1 @@ -1590,15 +1578,15 @@ I have lost faith in truth! 0 ``` -* See this StackOverflow [answer](https://stackoverflow.com/a/8169049/4354153) for the rationale behind it. +* ‫ این پاسخ در StackOverflow را ببینید: [answer](https://stackoverflow.com/a/8169049/4354153) برای توضیح منطقی پشت این موضوع. -* 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 +* ‫ در ابتدا، پایتون نوع `bool` نداشت (کاربران از 0 برای false و مقادیر غیر صفر مثل 1 برای true استفاده می‌کردند). `True`، `False` و نوع `bool` در نسخه‌های 2.x اضافه شدند، اما برای سازگاری با نسخه‌های قبلی، `True` و `False` نمی‌توانستند به عنوان ثابت تعریف شوند. آن‌ها فقط متغیرهای توکار (built-in) بودند و امکان تغییر مقدارشان وجود داشت. -* Python 3 was backward-incompatible, the issue was finally fixed, and thus the last snippet won't work with Python 3.x! +* ‫ پایتون ۳ با نسخه‌های قبلی ناسازگار بود، این مشکل سرانجام رفع شد، و بنابراین قطعه‌کد آخر در نسخه‌های Python 3.x کار نخواهد کرد! --- -### ▶ Class attributes and instance attributes +### ▶ ‫ ویژگی‌های کلاس و ویژگی‌های نمونه 1\. ```py @@ -1620,7 +1608,7 @@ class C(A): >>> A.x, B.x, C.x (1, 2, 1) >>> A.x = 3 ->>> A.x, B.x, C.x # C.x changed, but B.x didn't +>>> A.x, B.x, C.x # C.x تغییر کرد, اما B.x تغییر نکرد. (3, 2, 3) >>> a = A() >>> a.x, A.x @@ -1642,7 +1630,7 @@ class SomeClass: self.another_list += [x] ``` -**Output:** +‫ **خروجی:** ```py >>> some_obj = SomeClass(420) @@ -1661,10 +1649,11 @@ True True ``` -#### 💡 Explanation: +#### 💡 ‫ توضیح: + +* ‫ متغیرهای کلاس و متغیرهای نمونه‌های کلاس درونی به‌صورت دیکشنری‌هایی از شیء کلاس مدیریت می‌شوند. اگر نام متغیری در دیکشنری کلاس جاری پیدا نشود، کلاس‌های والد برای آن جست‌وجو می‌شوند. +* ‫ عملگر `+=` شیء قابل‌تغییر (mutable) را به‌صورت درجا (in-place) تغییر می‌دهد بدون اینکه شیء جدیدی ایجاد کند. بنابراین، تغییر ویژگی یک نمونه بر نمونه‌های دیگر و همچنین ویژگی کلاس تأثیر می‌گذارد. -* Class variables and variables in class instances are internally handled as dictionaries of a class object. If a variable name is not found in the dictionary of the current class, the parent classes are searched for it. -* The `+=` operator modifies the mutable object in-place without creating a new object. So changing the attribute of one instance affects the other instances and the class attribute as well. --- @@ -1713,14 +1702,14 @@ def some_func(x): yield from range(x) ``` -**Output (> 3.3):** +‫ **خروجی (> 3.3):** ```py >>> list(some_func(3)) [] ``` -Where did the `"wtf"` go? Is it due to some special effect of `yield from`? Let's validate that, +‫ چی شد که `"wtf"` ناپدید شد؟ آیا به خاطر اثر خاصی از `yield from` است؟ بیایید این موضوع را بررسی کنیم، 2\. @@ -1733,24 +1722,24 @@ def some_func(x): yield i ``` -**Output:** +‫ **خروجی:** ```py >>> list(some_func(3)) [] ``` -The same result, this didn't work either. +‫ همان نتیجه، این یکی هم کار نکرد. -#### 💡 Explanation: +#### 💡 ‫ توضیح: -+ From Python 3.3 onwards, it became possible to use `return` statement with values inside generators (See [PEP380](https://www.python.org/dev/peps/pep-0380/)). The [official docs](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) say that, ++ ‫ از پایتون نسخه ۳.۳ به بعد، امکان استفاده از عبارت `return` همراه با مقدار در داخل ژنراتورها فراهم شد (نگاه کنید به [PEP380](https://www.python.org/dev/peps/pep-0380/)). [مستندات رسمی](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) می‌گویند: -> "... `return expr` in a generator causes `StopIteration(expr)` to be raised upon exit from the generator." +> ‫ "... `return expr` در یک ژنراتور باعث می‌شود که هنگام خروج از ژنراتور، `StopIteration(expr)` ایجاد شود." -+ In the case of `some_func(3)`, `StopIteration` is raised at the beginning because of `return` statement. The `StopIteration` exception is automatically caught inside the `list(...)` wrapper and the `for` loop. Therefore, the above two snippets result in an empty list. ++ ‫ در حالت `some_func(3)`، استثنای `StopIteration` در ابتدای اجرا به دلیل وجود دستور `return` رخ می‌دهد. این استثنا به‌طور خودکار درون پوشش `list(...)` و حلقه `for` گرفته می‌شود. بنابراین، دو قطعه‌کد بالا منجر به یک لیست خالی می‌شوند. -+ To get `["wtf"]` from the generator `some_func` we need to catch the `StopIteration` exception, ++ ‫ برای اینکه مقدار `["wtf"]` را از ژنراتور `some_func` بگیریم، باید استثنای `StopIteration` را خودمان مدیریت کنیم، ```py try: @@ -1766,7 +1755,7 @@ The same result, this didn't work either. --- -### ▶ Nan-reflexivity * +### ▶ ‫ بازتاب‌ناپذیری * @@ -1775,11 +1764,11 @@ The same result, this didn't work either. ```py a = float('inf') b = float('nan') -c = float('-iNf') # These strings are case-insensitive +c = float('-iNf') # این رشته‌ها نسبت به حروف بزرگ و کوچک حساس نیستند d = float('nan') ``` -**Output:** +‫ **خروجی:** ```py >>> a @@ -1794,7 +1783,7 @@ ValueError: could not convert string to float: some_other_string True >>> None == None # None == None True ->>> b == d # but nan!=nan +>>> b == d # اما nan!=nan False >>> 50 / a 0.0 @@ -1809,21 +1798,21 @@ nan ```py >>> x = float('nan') >>> y = x / x ->>> y is y # identity holds +>>> y is y # برابری هویتی برقرار است True ->>> y == y # equality fails of y +>>> y == y #برابری در مورد y برقرار نیست False ->>> [y] == [y] # but the equality succeeds for the list containing y +>>> [y] == [y] # اما برابری برای لیستی که شامل y است برقرار می‌شود True ``` -#### 💡 Explanation: +#### 💡 توضیحات: -- `'inf'` and `'nan'` are special strings (case-insensitive), which, when explicitly typecast-ed to `float` type, are used to represent mathematical "infinity" and "not a number" respectively. +- ‫ `'inf'` و `'nan'` رشته‌هایی خاص هستند (نسبت به حروف بزرگ و کوچک حساس نیستند) که وقتی به‌طور صریح به نوع `float` تبدیل شوند، به ترتیب برای نمایش "بی‌نهایت" ریاضی و "عدد نیست" استفاده می‌شوند. -- 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, +- ‫ از آنجا که طبق استاندارد IEEE، `NaN != NaN`، پایبندی به این قانون فرض بازتاب‌پذیری (reflexivity) یک عنصر در مجموعه‌ها را در پایتون نقض می‌کند؛ یعنی اگر `x` عضوی از مجموعه‌ای مثل `list` باشد، پیاده‌سازی‌هایی مانند مقایسه، بر اساس این فرض هستند که `x == x`. به دلیل همین فرض، ابتدا هویت (identity) دو عنصر مقایسه می‌شود (چون سریع‌تر است) و فقط زمانی مقادیر مقایسه می‌شوند که هویت‌ها متفاوت باشند. قطعه‌کد زیر موضوع را روشن‌تر می‌کند، ```py >>> x = float('nan') @@ -1836,24 +1825,24 @@ True (False, False) ``` - Since the identities of `x` and `y` are different, the values are considered, which are also different; hence the comparison returns `False` this time. + ‫ از آنجا که هویت‌های `x` و `y` متفاوت هستند، مقادیر آن‌ها در نظر گرفته می‌شوند که آن‌ها نیز متفاوت‌اند؛ بنابراین مقایسه این بار `False` را برمی‌گرداند. -- Interesting read: [Reflexivity, and other pillars of civilization](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) +- ‫ خواندنی جالب: [بازتاب‌پذیری و دیگر ارکان تمدن](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) --- -### ▶ Mutating the immutable! +### ▶ ‫ تغییر دادن اشیای تغییرناپذیر! -This might seem trivial if you know how references work in Python. +‫ این موضوع ممکن است بدیهی به نظر برسد اگر با نحوه‌ی کار ارجاع‌ها در پایتون آشنا باشید. ```py some_tuple = ("A", "tuple", "with", "values") another_tuple = ([1, 2], [3, 4], [5, 6]) ``` -**Output:** +‫ **خروجی:** ```py >>> some_tuple[2] = "change this" TypeError: 'tuple' object does not support item assignment @@ -1866,21 +1855,22 @@ TypeError: 'tuple' object does not support item assignment ([1, 2], [3, 4], [5, 6, 1000, 99, 999]) ``` -But I thought tuples were immutable... +اما من فکر می‌کردم تاپل‌ها تغییرناپذیر هستند... -#### 💡 Explanation: +#### 💡 ‫ توضیحات: -* Quoting from https://docs.python.org/3/reference/datamodel.html +* ‫ نقل‌قول از https://docs.python.org/3/reference/datamodel.html - > Immutable sequences - An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.) + > ‫ دنباله‌های تغییرناپذیر + ‫ شیئی از نوع دنباله‌ی تغییرناپذیر، پس از ایجاد دیگر قابل تغییر نیست. (اگر شیء شامل ارجاع‌هایی به اشیای دیگر باشد، این اشیای دیگر ممکن است قابل تغییر باشند و تغییر کنند؛ اما مجموعه‌ی اشیایی که مستقیماً توسط یک شیء تغییرناپذیر ارجاع داده می‌شوند، نمی‌تواند تغییر کند.) + +* ‫ عملگر `+=` لیست را به‌صورت درجا (in-place) تغییر می‌دهد. تخصیص به یک عضو کار نمی‌کند، اما زمانی که استثنا ایجاد می‌شود، عضو موردنظر پیش از آن به‌صورت درجا تغییر کرده است. +* ‫ همچنین توضیحی در [پرسش‌های متداول رسمی پایتون](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works) وجود دارد. -* `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place. -* There's also an explanation in [official Python FAQ](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works). --- -### ▶ The disappearing variable from outer scope +### ▶ ‫ متغیری که از اسکوپ بیرونی ناپدید می‌شود ```py @@ -1894,7 +1884,7 @@ except Exception as e: **Output (Python 2.x):** ```py >>> print(e) -# prints nothing +# ‫ چیزی چاپ نمی شود. ``` **Output (Python 3.x):** @@ -1903,18 +1893,17 @@ except Exception as e: NameError: name 'e' is not defined ``` -#### 💡 Explanation: - -* Source: https://docs.python.org/3/reference/compound_stmts.html#except +#### 💡 ‫ توضیحات: +* ‫ منبع: [مستندات رسمی پایتون](https://docs.python.org/3/reference/compound_stmts.html#except) - When an exception has been assigned using `as` target, it is cleared at the end of the `except` clause. This is as if +‫ هنگامی که یک استثنا (Exception) با استفاده از کلمه‌ی کلیدی `as` به متغیری تخصیص داده شود، این متغیر در انتهای بلاکِ `except` پاک می‌شود. این رفتار مشابه کد زیر است: ```py except E as N: foo ``` - was translated into + ‫ به این شکل ترجمه شده باشد: ```py except E as N: @@ -1924,9 +1913,10 @@ NameError: name 'e' is not defined del N ``` - This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because, with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs. +‫ این بدان معناست که استثنا باید به نام دیگری انتساب داده شود تا بتوان پس از پایان بند `except` به آن ارجاع داد. استثناها پاک می‌شوند چون با داشتن «ردیابی» (traceback) ضمیمه‌شده، یک چرخه‌ی مرجع (reference cycle) با قاب پشته (stack frame) تشکیل می‌دهند که باعث می‌شود تمام متغیرهای محلی (locals) در آن قاب تا زمان پاکسازی حافظه (garbage collection) باقی بمانند. + +* ‫ در پایتون، بندها (`clauses`) حوزه‌ی مستقل ندارند. در مثال بالا، همه‌چیز در یک حوزه‌ی واحد قرار دارد، و متغیر `e` در اثر اجرای بند `except` حذف می‌شود. این موضوع در مورد توابع صادق نیست، زیرا توابع حوزه‌های داخلی جداگانه‌ای دارند. مثال زیر این نکته را نشان می‌دهد: -* 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): @@ -1937,7 +1927,7 @@ NameError: name 'e' is not defined y = [5, 4, 3] ``` - **Output:** + ‫ **خروجی:** ```py >>> f(x) UnboundLocalError: local variable 'x' referenced before assignment @@ -1949,20 +1939,20 @@ NameError: name 'e' is not defined [5, 4, 3] ``` -* In Python 2.x, the variable name `e` gets assigned to `Exception()` instance, so when you try to print, it prints nothing. +* ‫ در پایتون نسخه‌ی ۲.x، نام متغیر `e` به یک نمونه از `Exception()` انتساب داده می‌شود، بنابراین وقتی سعی کنید آن را چاپ کنید، چیزی نمایش داده نمی‌شود. - **Output (Python 2.x):** + ‫ **خروجی (Python 2.x):** ```py >>> e Exception() >>> print e - # Nothing is printed! + # چیزی چاپ نمی شود. ``` --- -### ▶ The mysterious key type conversion +### ▶ ‫ تبدیل اسرارآمیز نوع کلید ```py class SomeClass(str): @@ -1971,7 +1961,7 @@ class SomeClass(str): some_dict = {'s': 42} ``` -**Output:** +‫ **خروجی:** ```py >>> type(list(some_dict.keys())[0]) str @@ -1983,12 +1973,12 @@ str str ``` -#### 💡 Explanation: +#### 💡 ‫ توضیحات: -* Both the object `s` and the string `"s"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class. -* `SomeClass("s") == "s"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class. -* Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary. -* For the desired behavior, we can redefine the `__eq__` method in `SomeClass` +* ‫ هر دو شیء `s` و رشته‌ی `"s"` به دلیل ارث‌بری `SomeClass` از متد `__hash__` کلاس `str`، هش یکسانی دارند. +* ‫ عبارت `SomeClass("s") == "s"` به دلیل ارث‌بری `SomeClass` از متد `__eq__` کلاس `str` برابر با `True` ارزیابی می‌شود. +* ‫ از آنجا که این دو شیء هش یکسان و برابری دارند، به عنوان یک کلید مشترک در دیکشنری در نظر گرفته می‌شوند. +* ‫ برای رسیدن به رفتار دلخواه، می‌توانیم متد `__eq__` را در کلاس `SomeClass` بازتعریف کنیم. ```py class SomeClass(str): def __eq__(self, other): @@ -1998,14 +1988,14 @@ str and super().__eq__(other) ) - # When we define a custom __eq__, Python stops automatically inheriting the - # __hash__ method, so we need to define it as well + # ‫ هنگامی که متد __eq__ را به‌طور دلخواه تعریف می‌کنیم، پایتون دیگر متد __hash__ را به صورت خودکار به ارث نمی‌برد، + # ‫ بنابراین باید متد __hash__ را نیز مجدداً تعریف کنیم. __hash__ = str.__hash__ some_dict = {'s':42} ``` - **Output:** + ‫ **خروجی:** ```py >>> s = SomeClass('s') >>> some_dict[s] = 40 @@ -2018,37 +2008,37 @@ str --- -### ▶ Let's see if you can guess this? +### ▶ ‫ ببینیم می‌توانید این را حدس بزنید؟ ```py a, b = a[b] = {}, 5 ``` -**Output:** +‫ **خروجی:** ```py >>> a {5: ({...}, 5)} ``` -#### 💡 Explanation: +#### 💡 ‫ توضیح: -* According to [Python language reference](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements), assignment statements have the form +* ‫ طبق [مرجع زبان پایتون](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)، دستورات انتساب فرم زیر را دارند: ``` (target_list "=")+ (expression_list | yield_expression) ``` - and + و -> An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. +> ‫ یک دستور انتساب ابتدا فهرست عبارت‌ها (expression list) را ارزیابی می‌کند (توجه کنید این عبارت می‌تواند یک عبارت تکی یا فهرستی از عبارت‌ها جداشده با ویرگول باشد که دومی به یک تاپل منجر می‌شود)، سپس شیء حاصل را به هریک از اهداف انتساب از **چپ به راست** تخصیص می‌دهد. -* 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`). +* ‫ علامت `+` در `(target_list "=")+` به این معناست که می‌توان **یک یا چند** هدف انتساب داشت. در این حالت، اهداف انتساب ما `a, b` و `a[b]` هستند (توجه کنید که عبارت ارزیابی‌شده دقیقاً یکی است، که در اینجا `{}` و `5` است). -* After the expression list is evaluated, its value is unpacked to the target lists from **left to right**. So, in our case, first the `{}, 5` tuple is unpacked to `a, b` and we now have `a = {}` and `b = 5`. +* ‫ پس از ارزیابی عبارت، نتیجه از **چپ به راست** به اهداف انتساب داده می‌شود. در این مثال ابتدا تاپل `({}, 5)` به `a, b` باز می‌شود، بنابراین `a = {}` و `b = 5` خواهیم داشت. -* `a` is now assigned to `{}`, which is a mutable object. +* ‫ حالا `a` یک شیء قابل تغییر (mutable) است (`{}`). -* The second target list is `a[b]` (you may expect this to throw an error because both `a` and `b` have not been defined in the statements before. But remember, we just assigned `a` to `{}` and `b` to `5`). +* ‫ هدف انتساب بعدی `a[b]` است (شاید انتظار داشته باشید که اینجا خطا بگیریم زیرا پیش از این هیچ مقداری برای `a` و `b` مشخص نشده است؛ اما به یاد داشته باشید که در گام قبل به `a` مقدار `{}` و به `b` مقدار `5` دادیم). -* Now, we are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference (the `{...}` in the output refers to the same object that `a` is already referencing). Another simpler example of circular reference could be +* ‫ اکنون، کلید `5` در دیکشنری به تاپل `({}, 5)` مقداردهی می‌شود و یک مرجع دوری (Circular Reference) ایجاد می‌کند (علامت `{...}` در خروجی به همان شیئی اشاره دارد که قبلاً توسط `a` به آن ارجاع داده شده است). یک مثال ساده‌تر از مرجع دوری می‌تواند به این صورت باشد: ```py >>> some_list = some_list[0] = [0] >>> some_list @@ -2060,14 +2050,15 @@ a, b = a[b] = {}, 5 >>> some_list[0][0][0][0][0][0] == some_list True ``` - Similar is the case in our example (`a[b][0]` is the same object as `a`) + ‫ در مثال ما نیز شرایط مشابه است (`a[b][0]` همان شیئی است که `a` به آن اشاره دارد). + -* So to sum it up, you can break the example down to +* ‫ بنابراین برای جمع‌بندی، می‌توانید مثال بالا را به این صورت ساده کنید: ```py a, b = {}, 5 a[b] = a, b ``` - And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a` + ‫ و مرجع دوری به این دلیل قابل توجیه است که `a[b][0]` همان شیئی است که `a` به آن اشاره دارد. ```py >>> a[b][0] is a True @@ -2076,7 +2067,7 @@ a, b = a[b] = {}, 5 --- -### ▶ Exceeds the limit for integer string conversion +### ▶ ‫ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود ```py >>> # Python 3.10.6 >>> int("2" * 5432) @@ -2085,7 +2076,7 @@ a, b = a[b] = {}, 5 >>> int("2" * 5432) ``` -**Output:** +‫ **خروجی:** ```py >>> # Python 3.10.6 222222222222222222222222222222222222222222222222222222222222222... @@ -2098,15 +2089,16 @@ ValueError: Exceeds the limit (4300) for integer string conversion: to increase the limit. ``` -#### 💡 Explanation: -This call to `int()` works fine in Python 3.10.6 and raises a ValueError in Python 3.10.8. Note that Python can still work with large integers. The error is only raised when converting between integers and strings. +#### 💡 ‫ توضیح: +‫ فراخوانی تابع `int()` در نسخه‌ی Python 3.10.6 به‌خوبی کار می‌کند اما در نسخه‌ی Python 3.10.8 منجر به خطای `ValueError` می‌شود. توجه کنید که پایتون همچنان قادر به کار با اعداد صحیح بزرگ است. این خطا تنها هنگام تبدیل اعداد صحیح به رشته یا برعکس رخ می‌دهد. + +‫ خوشبختانه می‌توانید در صورت انتظار عبور از این حد مجاز، مقدار آن را افزایش دهید. برای انجام این کار می‌توانید از یکی از روش‌های زیر استفاده کنید: -Fortunately, you can increase the limit for the allowed number of digits when you expect an operation to exceed it. To do this, you can use one of the following: -- The -X int_max_str_digits command-line flag -- The set_int_max_str_digits() function from the sys module -- The PYTHONINTMAXSTRDIGITS environment variable +- ‫ استفاده از فلگ خط فرمان `-X int_max_str_digits` +- ‫ تابع `set_int_max_str_digits()` از ماژول `sys` +- ‫ متغیر محیطی `PYTHONINTMAXSTRDIGITS` -[Check the documentation](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) for more details on changing the default limit if you expect your code to exceed this value. +‫ برای جزئیات بیشتر درباره‌ی تغییر مقدار پیش‌فرض این حد مجاز، [مستندات رسمی پایتون](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) را مشاهده کنید. --- From 0fcad66357611da88e664ecab918afb2ab790870 Mon Sep 17 00:00:00 2001 From: Mohamad Reza Date: Fri, 4 Apr 2025 01:22:36 +0330 Subject: [PATCH 190/210] update farsi translations for section 1, and delete the temp file --- translations/fa-farsi/README.md | 406 +++++----- translations/fa-farsi/section1-temp.md | 1007 ------------------------ 2 files changed, 206 insertions(+), 1207 deletions(-) delete mode 100644 translations/fa-farsi/section1-temp.md diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index d9133592..2dbaa0ca 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -47,33 +47,33 @@ - [▶ اول از همه! \*](#-اول-از-همه-) - [💡 توضیحات](#-توضیحات) - [▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند](#-بعضی-وقتها-رشتهها-میتوانند-دردسرساز-شوند) - - [💡 Explanation:](#-explanation) - - [▶ Be careful with chained operations](#-be-careful-with-chained-operations) - - [💡 Explanation:](#-explanation-1) - - [▶ How not to use `is` operator](#-how-not-to-use-is-operator) - - [💡 Explanation:](#-explanation-2) - - [▶ Hash brownies](#-hash-brownies) - - [💡 Explanation](#-explanation-3) - - [▶ Deep down, we're all the same.](#-deep-down-were-all-the-same) - - [💡 Explanation:](#-explanation-4) - - [▶ Disorder within order \*](#-disorder-within-order-) - - [💡 Explanation:](#-explanation-5) - - [▶ Keep trying... \*](#-keep-trying-) - - [💡 Explanation:](#-explanation-6) - - [▶ For what?](#-for-what) - - [💡 Explanation:](#-explanation-7) - - [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy) - - [💡 Explanation](#-explanation-8) - - [▶ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) - - [💡 Explanation](#-explanation-9) - - [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt) - - [💡 Explanation:](#-explanation-10) - - [▶ Schrödinger's variable \*](#-schrödingers-variable-) - - [💡 Explanation:](#-explanation-11) - - [▶ The chicken-egg problem \*](#-the-chicken-egg-problem-) - - [💡 Explanation](#-explanation-12) - - [▶ Subclass relationships](#-subclass-relationships) - - [💡 Explanation:](#-explanation-13) + - [💡 توضیح:](#-توضیح) + - [▶ مراقب عملیات‌های زنجیره‌ای باشید](#-مراقب-عملیاتهای-زنجیرهای-باشید) + - [💡 توضیحات:](#-توضیحات-1) + - [▶ چطور از عملگر `is` استفاده نکنیم](#-چطور-از-عملگر-is-استفاده-نکنیم) + - [💡 توضیحات:](#-توضیحات-2) + - [▶ کلیدهای هش](#-کلیدهای-هش) + - [💡 توضیحات](#-توضیحات-3) + - [▶ در عمق وجود همه ما یکسان هستیم](#-در-عمق-وجود-همه-ما-یکسان-هستیم) + - [💡 توضیحات:](#-توضیحات-4) + - [▶ بی‌نظمی در خود نظم \*](#-بینظمی-در-خود-نظم-) + - [💡 توضیحات:](#-توضیحات-5) + - [▶ تلاش کن... \*](#-تلاش-کن-) + - [💡 توضیحات:](#-توضیحات-6) + - [▶ برای چی؟](#-برای-چی) + - [💡 توضیحات:](#-توضیحات-7) + - [▶ اختلاف زمانی در محاسبه](#-اختلاف-زمانی-در-محاسبه) + - [💡 توضیحات](#-توضیحات-8) + - [▶ هر گردی، گردو نیست](#-هر-گردی-گردو-نیست) + - [💡 توضیحات](#-توضیحات-9) + - [▶ یک بازی دوز که توش X همون اول برنده میشه!](#-یک-بازی-دوز-که-توش-X-همون-اول-برنده-میشه) + - [💡 توضیحات:](#-توضیحات-10) + - [▶ متغیر شرودینگر \*](#-متغیر-شرودینگر-) + - [💡 توضیحات:](#-توضیحات-11) + - [▶ اول مرغ بوده یا تخم مرغ؟ \*](#-اول-مرغ-بوده-یا-تخم-مرغ-) + - [💡 توضیحات](#-توضیحات-12) + - [▶ روابط بین زیرمجموعه کلاس‌ها](#-روابط-بین-زیرمجموعه-کلاسها) + - [💡 توضیحات:](#-توضیحات-13) - [▶ ‫ برابری و هویت متدها](#--برابری-و-هویت-متدها) - [💡 ‫ توضیحات](#--توضیحات) - [▶ ‫ آل-ترو-یشن \*](#--آل-ترو-یشن-) @@ -370,7 +370,7 @@ if a := some_func(): >>> a = "some_string" >>> id(a) 140420665652016 ->>> id("some" + "_" + "string") # دقت کنید که هردو ID یکی هستند. +>>> id("some" + "_" + "string") # دقت کنید که هردو شناسه یکسانند. 140420665652016 ``` @@ -420,15 +420,16 @@ True False ``` -Makes sense, right? +منطقیه، نه؟ + +#### 💡 توضیحات: ++ در قطعه‌کد اول و دوم، رفتار کد به دلیل یک بهینه سازی در CPython است (به نام داوطلب سازی رشته‌ها) که باعث می‌شود از برخی مقادیر غیرقابل تغییر، به جای مقداردهی مجدد، دوباره استفاده شود. ++ بیشتر متغیرهایی که به‌این صورت جایگزین می‌شوند، در حافظه دستگاه به مقدار داوطلب خود اشاره می‌کنند (تا از حافظه کمتری استفاده شود) ++ در قطعه‌کدهای بالا، رشته‌ها به‌صورت غیرمستقیم داوطلب می‌شوند. تصمیم اینکه رشته‌ها چه زمانی به صورت غیرمستقیم داوطلب شوند به نحوه پیاده‌سازی و مقداردهی آن‌ها بستگی دارد. برخی قوانین وجود دارند تا بتوانیم داوطلب شدن یا نشدن یک رشته را حدس بزنیم: + * همه رشته‌ها با طول صفر یا یک داوطلب می‌شوند. + * رشته‌ها در زمان کامپایل داوطلب می‌شوند (`'wtf'` داوطلب می‌شود اما `''.join(['w', 't', 'f'])` داوطلب نمی‌شود) + * رشته‌هایی که از حروف ASCII ، اعداد صحیح و آندرلاین تشکیل نشده‌باشند داوطلب نمی‌شود. به همین دلیل `'wtf!'` به خاطر وجود `'!'` داوطلب نشد. پیاده‌سازی این قانون در CPython در [اینجا](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) قرار دارد. -#### 💡 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: - * All length 0 and length 1 strings are interned. - * Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned) - * Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)

@@ -437,22 +438,22 @@ 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. -+ 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). ++ زمانی که `"wtf!"` را در یک خط به `a` و `b` اختصاص می‌دهیم، مفسر پایتون شیء جدید می‌سازد و متغیر دوم را به آن ارجاع می‌دهد. اگر مقدار دهی در خط‌های جدا از هم انجام شود، در واقع مفسر "خبر ندارد" که یک شیء مختص به `"wtf!"` از قبل در برنامه وجود دارد (زیرا `"wtf!"` به دلایلی که در بالا گفته شد، به‌صورت غیرمستقیم داوطلب نمی‌شود). این بهینه سازی در زمان کامپایل انجام می‌شود. این بهینه سازی همچنین برای نسخه های (x).۳.۷ وجود ندارد (برای گفت‌وگوی بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) را ببینید). ++ یک واحد کامپایل در یک محیط تعاملی مانند IPython از یک عبارت تشکیل می‌شود، در حالی که برای ماژول‌ها شامل کل ماژول می‌شود. `a, b = "wtf!", "wtf!"` یک عبارت است. در حالی که `a = "wtf!"; b = "wtf!"` دو عبارت در یک خط است. به همین دلیل شناسه‌ها در `a = "wtf!"; b = "wtf!"` متفاوتند و همین‌طور وقتی با مفسر پایتون داخل فایل `some_file.py` اجرا می‌شوند، شناسه‌ها یکسانند. ++ تغییر ناگهانی در خروجی قطعه‌کد چهارم به دلیل [بهینه‌سازی پنجره‌ای](https://en.wikipedia.org/wiki/Peephole_optimization) است که تکنیکی معروف به جمع آوری ثابت‌ها است. به همین خاطر عبارت `'a'*20` با `'aaaaaaaaaaaaaaaaaaaa'` در هنگام کامپایل جایگزین می‌شود تا کمی بار از دوش چرخه‌ساعتی پردازنده کم شود. تکنیک جمع آوری ثابت‌ها فقط مخصوص رشته‌هایی با طول کمتر از 21 است. (چرا؟ فرض کنید که فایل `.pyc` که توسط کامپایلر ساخته می‌شود چقدر بزرگ می‌شد اگر عبارت `'a'*10**10`). [این](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) هم کد پیاده‌سازی این تکنیک در CPython. ++ توجه: در پایتون ۳.۷، جمع آوری ثابت‌ها از بهینه‌ساز پنجره‌ای به بهینه‌ساز AST جدید انتقال داده شد همراه با تغییراتی در منطق آن. پس چهارمین قطعه‌کد در پایتون نسخه ۳.۷ کار نمی‌کند. شما می‌توانید در [اینجا](https://bugs.python.org/issue11549) بیشتر درمورد این تغییرات بخوانید. --- -### ▶ Be careful with chained operations +### ▶ مراقب عملیات‌های زنجیره‌ای باشید ```py ->>> (False == False) in [False] # makes sense +>>> (False == False) in [False] # منطقیه False ->>> False == (False in [False]) # makes sense +>>> False == (False in [False]) # منطقیه False ->>> False == False in [False] # now what? +>>> False == False in [False] # حالا چی؟ True >>> True is False == False @@ -468,31 +469,30 @@ False False ``` -#### 💡 Explanation: - -As per https://docs.python.org/3/reference/expressions.html#comparisons +#### 💡 توضیحات: -> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once. +طبق 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 است. فقط دقت کنید که هر عبارت یک بار ارزیابی می‌شود. -While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. +شاید چنین رفتاری برای شما احمقانه به نظر بیاد ولی برای عملیات‌هایی مثل `a == b == c` و `0 <= x <= 100` عالی عمل می‌کنه. -* `False is False is False` is equivalent to `(False is False) and (False is False)` -* `True is False == False` is equivalent to `(True is False) and (False == False)` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. -* `1 > 0 < 1` is equivalent to `(1 > 0) and (0 < 1)` which evaluates to `True`. -* The expression `(1 > 0) < 1` is equivalent to `True < 1` and +* عبارت `False is False is False` معادل عبارت `(False is False) and (False is False)` است +* عبارت `True is False == False` معادل عبارت `(True is False) and (False == False)` است و از آنجایی که قسمت اول این عبارت (`True is False`) پس از ارزیابی برابر با `False` می‌شود. پس کل عبارت معادل `False` می‌شود. +* عبارت `1 > 0 < 1` معادل عبارت `(1 > 0) and (0 < 1)` است. +* عبارت `(1 > 0) < 1` معادل عبارت `True < 1` است و : ```py >>> int(True) 1 - >>> True + 1 #not relevant for this example, but just for fun + >>> True + 1 # مربوط به این بخش نیست ولی همینجوری گذاشتم 2 ``` - So, `1 < 1` evaluates to `False` + پس عبارت `True < 1` معادل عبارت `1 < 1` می‌شود که در کل معادل `False` است. --- -### ▶ How not to use `is` operator +### ▶ چطور از عملگر `is` استفاده نکنیم -The following is a very famous example present all over the internet. +عبارت پایین خیلی معروفه و تو کل اینترنت موجوده. 1\. @@ -523,7 +523,7 @@ True ``` 3\. -**Output** +**خروجی** ```py >>> a, b = 257, 257 @@ -531,7 +531,7 @@ True True ``` -**Output (Python 3.7.x specifically)** +**خروجی (مخصوص نسخه‌های (x).۳.۷)** ```py >>> a, b = 257, 257 @@ -539,25 +539,25 @@ True False ``` -#### 💡 Explanation: +#### 💡 توضیحات: -**The difference between `is` and `==`** +**فرض بین عملگرهای `is` و `==`** -* `is` operator checks if both the operands refer to the same object (i.e., it checks if the identity of the operands matches or not). -* `==` operator compares the values of both the operands and checks if they are the same. -* So `is` is for reference equality and `==` is for value equality. An example to clear things up, +* عملگر `is` بررسی میکنه که دو متغیر در حافظه دستگاه به یک شیء اشاره میکنند یا نه (یعنی شناسه متغیرها رو با هم تطبیق میده). +* عملگر `==` مقدار متغیرها رو با هم مقایسه میکنه و یکسان بودنشون رو بررسی میکنه. +* پس `is` برای معادل بودن متغیرها در حافظه دستگاه و `==` برای معادل بودن مقادیر استفاده میشه. یه مثال برای شفاف سازی بیشتر: ```py >>> class A: pass - >>> A() is A() # These are two empty objects at two different memory locations. + >>> A() is A() # این‌ها دو شیء خالی هستند که در دو جای مختلف در حافظه قرار دارند. False ``` -**`256` is an existing object but `257` isn't** +**عدد `256` از قبل تو حافظه قرار داده شده ولی `257` نه؟** -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. +وقتی پایتون رو اجرا می‌کنید اعداد از `-5` تا `256` در حافظه ذخیره میشن. چون این اعداد خیلی پرکاربرد هستند پس منطقیه که اون‌ها رو در حافظه دستگاه، آماده داشته باشیم. -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. :-) +نقل قول از https://docs.python.org/3/c-api/long.html +> در پیاده سازی فعلی یک آرایه از اشیاء عددی صحیح برای تمام اعداد صحیح بین `-5` تا `256` نگه‌داری می‌شود. وقتی شما یک عدد صحیح در این بازه به مقداردهی می‌کنید، فقط یک ارجاع به آن عدد که از قبل در حافظه ذخیره شده است دریافت می‌کنید. پس تغییر مقدار عدد 1 باید ممکن باشد. که در این مورد من به رفتار پایتون شک دارم تعریف‌نشده است. :-) ```py >>> id(256) @@ -578,13 +578,13 @@ Quoting from https://docs.python.org/3/c-api/long.html 140084850247344 ``` -Here the interpreter isn't smart enough while executing `y = 257` to recognize that we've already created an integer of the value `257,` and so it goes on to create another object in the memory. +در اینجا مفسر وقتی عبارت `y = 257` رو اجرا میکنه، به اندازه کافی زیرکانه عمل نمیکنه که تشخیص بده که ما یک عدد صحیح با مقدار `257` در حافظه ذخیره کرده‌ایم، پس به ساختن یک شیء جدید در حافظه ادامه میده. -Similar optimization applies to other **immutable** objects like empty tuples as well. Since lists are mutable, that's why `[] is []` will return `False` and `() is ()` will return `True`. This explains our second snippet. Let's move on to the third one, +یک بهینه سازی مشابه شامل حال مقادیر **غیرقابل تغییر** دیگه مانند تاپل‌های خالی هم میشه. از اونجایی که لیست‌ها قابل تغییرند، عبارت `[] is []` مقدار `False` رو برمیگردونه و عبارت `() is ()` مقدار `True` رو برمیگردونه. به همین دلیله که قطعه کد دوم چنین رفتاری داره. بریم سراغ سومی. -**Both `a` and `b` refer to the same object when initialized with same value in the same line.** +**متغیرهای `a` و `b` وقتی در یک خط با مقادیر یکسانی مقداردهی میشن، هردو به یک شیء در حافظه اشاره میکنن** -**Output** +**خروجی** ```py >>> a, b = 257, 257 @@ -600,9 +600,9 @@ Similar optimization applies to other **immutable** objects like empty tuples as 140640774013488 ``` -* When a and b are set to `257` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already `257` as an object. +* وقتی a و b در یک خط با `257` مقداردهی میشن، مفسر پایتون یک شیء برای یکی از متغیرها در حافظه میسازه و متغیر دوم رو در حافظه به اون ارجاع میده. اگه این کار رو تو دو خط جدا از هم انجام بدید، درواقع مفسر پایتون از وجود مقدار `257` به عنوان یک شیء، "خبر نداره". -* It's a compiler optimization and specifically applies to the interactive environment. When you enter two lines in a live interpreter, they're compiled separately, therefore optimized separately. If you were to try this example in a `.py` file, you would not see the same behavior, because the file is compiled all at once. This optimization is not limited to integers, it works for other immutable data types like strings (check the "Strings are tricky example") and floats as well, +* این یک بهینه سازی توسط کامپایلر هست و مخصوصا در محیط تعاملی به کار برده میشه. وقتی شما دو خط رو در یک مفسر زنده وارد می‌کنید، اون‌ها به صورت جداگانه کامپایل میشن، به همین دلیل بهینه سازی به صورت جداگانه برای هرکدوم اعمال میشه. اگر بخواهید این مثال رو در یک فایل `.py` امتحان کنید، رفتار متفاوتی می‌بینید زیرا فایل به صورت کلی و یک‌جا کامپایل میشه. این بهینه سازی محدود به اعداد صحیح نیست و برای انواع داده‌های غیرقابل تغییر دیگه مانند رشته‌ها (مثال "رشته‌ها می‌توانند دردسرساز شوند" رو ببینید) و اعداد اعشاری هم اعمال میشه. ```py >>> a, b = 257.0, 257.0 @@ -610,12 +610,12 @@ Similar optimization applies to other **immutable** objects like empty tuples as True ``` -* Why didn't this work for Python 3.7? The abstract reason is because such compiler optimizations are implementation specific (i.e. may change with version, OS, etc). I'm still figuring out what exact implementation change cause the issue, you can check out this [issue](https://github.com/satwikkansal/wtfpython/issues/100) for updates. +* چرا این برای پایتون ۳.۷ کار نکرد؟ دلیل انتزاعیش اینه که چنین بهینه‌سازی‌های کامپایلری وابسته به پیاده‌سازی هستن (یعنی بسته به نسخه، و نوع سیستم‌عامل و چیزهای دیگه تغییر میکنن). من هنوز پیگیرم که بدونم که کدوم تغییر تو پیاده‌سازی باعث همچین مشکلاتی میشه، می‌تونید برای خبرهای بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) رو نگاه کنید. --- -### ▶ Hash brownies +### ▶ کلیدهای هش 1\. ```py @@ -625,12 +625,12 @@ some_dict[5.0] = "Ruby" some_dict[5] = "Python" ``` -**Output:** +**خروجی:** ```py >>> some_dict[5.5] "JavaScript" ->>> some_dict[5.0] # "Python" destroyed the existence of "Ruby"? +>>> some_dict[5.0] # رشته ("Python")، رشته ("Ruby") رو از بین برد؟ "Python" >>> some_dict[5] "Python" @@ -642,12 +642,11 @@ complex "Python" ``` -So, why is Python all over the place? - +خب، چرا Python همه جارو گرفت؟ -#### 💡 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`): +#### 💡 توضیحات +* تو دیکشنری‌های پایتون چیزی که کلیدها رو یگانه میکنه مقدار کلیدهاست، نه شناسه اون‌ها. پس با اینکه `5`، `5.0` و `5 + 0j` شیءهای متمایزی از نوع‌های متفاوتی هستند ولی از اون جایی که مقدارشون با هم برابره، نمیتونن داخل یه `dict` به عنوان کلید جدا از هم باشن (حتی به عنوان مقادیر داخل یه `set` نمیتونن باشن). وقتی بخواید داخل یه دیکشنری جست‌وجو کنید، به محض اینکه یکی از این داده‌ها رو وارد کنید، مقدار نگاشته‌شده به کلیدی که مقدار برابر با اون داده داره ولی نوعش متفاوته، با موفقیت برگردونده میشه (به جای اینکه به ارور `KeyError` بردخورد کنید.). ```py >>> 5 == 5.0 == 5 + 0j True @@ -660,7 +659,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. +* همچنین این قانون برای مقداردهی توی دیکشنری هم اعمال میشه. وقتی شما عبارت `some_dict[5] = "Python"` رو اجرا می‌کنید، پایتون دنبال کلیدی با مقدار یکسان می‌گرده که اینجا ما داریم `5.0 -> "Ruby"` و مقدار نگاشته‌شده به این کلید در دیکشنری رو با مقدار جدید جایگزین میکنه و کلید رو همونجوری که هست باقی میذاره. ```py >>> some_dict {5.0: 'Ruby'} @@ -668,51 +667,50 @@ 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. +* خب پس چطوری میتونیم مقدار خود کلید رو به `5` تغییر بدیم (جای `5.0`)؟ راستش ما نمیتونیم این کار رو درجا انجام بدیم، ولی میتونیم اول اون کلید رو پاک کنیم (`del some_dict[5.0]`) و بعد کلیدی که میخوایم رو قرار بدیم (`some_dict[5]`) تا بتونیم عدد صحیح `5` رو به جای عدد اعشاری `5.0` به عنوان کلید داخل دیکشنری داشته باشیم. درکل خیلی کم پیش میاد که بخوایم چنین کاری کنیم. -* 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. +* پایتون چطوری توی دیکشنری که کلید `5.0` رو داره، کلید `5` رو پیدا کرد؟ پایتون این کار رو توی زمان ثابتی توسط توابع هش انجام میده بدون اینکه مجبور باشه همه کلیدها رو بررسی کنه. وقتی پایتون دنبال کلیدی مثل `foo` داخل یه `dict` میگرده، اول مقدار `hash(foo)` رو محاسبه میکنه (که توی زمان ثابتی انجام میشه). از اونجایی که توی پایتون برای مقایسه برابری مقدار دو شیء لازمه که هش یکسانی هم داشته باشند ([مستندات](https://docs.python.org/3/reference/datamodel.html#object.__hash__)). `5`، `5.0` و `5 + 0j` مقدار هش یکسانی دارند. ```py >>> 5 == 5.0 == 5 + 0j True >>> hash(5) == hash(5.0) == hash(5 + 0j) 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.) + **توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیده‌ای معروف [تصادم هش]() میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند. --- -### ▶ Deep down, we're all the same. +### ▶ در عمق وجود همه ما یکسان هستیم ```py class WTF: pass ``` -**Output:** +**خروجی:** ```py ->>> WTF() == WTF() # two different instances can't be equal +>>> WTF() == WTF() # دو نمونه متفاوت از یک کلاس نمیتونند برابر هم باشند False ->>> WTF() is WTF() # identities are also different +>>> WTF() is WTF() # شناسه‌ها هم متفاوتند False ->>> hash(WTF()) == hash(WTF()) # hashes _should_ be different as well +>>> hash(WTF()) == hash(WTF()) # هش‌ها هم _باید_ متفاوت باشند True >>> id(WTF()) == id(WTF()) True ``` -#### 💡 Explanation: - -* When `id` was called, Python created a `WTF` class object and passed it to the `id` function. The `id` function takes its `id` (its memory location), and throws away the object. The object is destroyed. -* When we do this twice in succession, Python allocates the same memory location to this second object as well. Since (in CPython) `id` uses the memory location as the object id, the id of the two objects is the same. -* So, the object's id is unique only for the lifetime of the object. After the object is destroyed, or before it is created, something else can have the same id. -* But why did the `is` operator evaluate to `False`? Let's see with this snippet. +#### 💡 توضیحات: +* وقتی `id` صدا زده شد، پایتون یک شیء با کلاس `WTF` ساخت و اون رو به تابع `id` داد. تابع `id` شناسه این شیء رو میگیره (درواقع آدرس اون شیء در حافظه دستگاه) و شیء رو حذف میکنه. +* وقتی این کار رو دو بار متوالی انجام بدیم، پایتون آدرس یکسانی رو به شیء دوم اختصاص میده. از اونجایی که (در CPython) تابع `id` از آدرس شیءها توی حافظه به عنوان شناسه برای اون‌ها استفاده میکنه، پس شناسه این دو شیء یکسانه. +* پس، شناسه یک شیء تا زمانی که اون شیء وجود داره، منحصربه‌فرده. بعد از اینکه اون شیء حذف میشه یا قبل از اینکه اون شیء به وجود بیاد، چیز دیگه‌ای میتونه اون شناسه رو داشته باشه. +* ولی چرا با عملگر `is` مقدار `False` رو دریافت کردیم؟ بیاید با یه قطعه‌کد ببینیم دلیلش رو. ```py class WTF(object): def __init__(self): print("I") def __del__(self): print("D") ``` - **Output:** + **خروجی:** ```py >>> WTF() is WTF() I @@ -727,11 +725,12 @@ True D True ``` - As you may observe, the order in which the objects are destroyed is what made all the difference here. + همونطور که مشاهده می‌کنید، ترتیب حذف شدن شیءها باعث تفاوت میشه. --- -### ▶ Disorder within order * + +### ▶ بی‌نظمی در خود نظم * ```py from collections import OrderedDict @@ -747,36 +746,36 @@ another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; class DictWithHash(dict): """ - A dict that also implements __hash__ magic. + یک dict که تابع جادویی __hash__ هم توش پیاده شده. """ __hash__ = lambda self: 0 class OrderedDictWithHash(OrderedDict): """ - An OrderedDict that also implements __hash__ magic. + یک OrderedDict که تابع جادویی __hash__ هم توش پیاده شده. """ __hash__ = lambda self: 0 ``` -**Output** +**خروجی** ```py ->>> dictionary == ordered_dict # If a == b +>>> dictionary == ordered_dict # اگر مقدار اولی با دومی برابره True ->>> dictionary == another_ordered_dict # and b == c +>>> dictionary == another_ordered_dict # و مقدار اولی با سومی برابره True ->>> ordered_dict == another_ordered_dict # then why isn't c == a ?? +>>> ordered_dict == another_ordered_dict # پس چرا مقدار دومی با سومی برابر نیست؟ False -# We all know that a set consists of only unique elements, -# let's try making a set of these dictionaries and see what happens... +# ما همه‌مون میدونیم که یک مجموعه فقط شامل عناصر منحصربه‌فرد و غیرتکراریه. +# بیاید یک مجموعه از این دیکشنری‌ها بسازیم ببینیم چه اتفاقی میافته... >>> len({dictionary, ordered_dict, another_ordered_dict}) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'dict' -# Makes sense since dict don't have __hash__ implemented, let's use -# our wrapper classes. +# منطقیه چون dict ها __hash__ توشون پیاده‌سازی نشده. پس بیاید از +# کلاس‌هایی که خودمون درست کردیم استفاده کنیم. >>> dictionary = DictWithHash() >>> dictionary[1] = 'a'; dictionary[2] = 'b'; >>> ordered_dict = OrderedDictWithHash() @@ -785,22 +784,21 @@ TypeError: unhashable type: 'dict' >>> another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; >>> len({dictionary, ordered_dict, another_ordered_dict}) 1 ->>> len({ordered_dict, another_ordered_dict, dictionary}) # changing the order +>>> len({ordered_dict, another_ordered_dict, dictionary}) # ترتیب رو عوض می‌کنیم 2 ``` -What is going on here? +چی شد؟ -#### 💡 Explanation: +#### 💡 توضیحات: -- The reason why intransitive equality didn't hold among `dictionary`, `ordered_dict` and `another_ordered_dict` is because of the way `__eq__` method is implemented in `OrderedDict` class. From the [docs](https://docs.python.org/3/library/collections.html#ordereddict-objects) - - > Equality tests between OrderedDict objects are order-sensitive and are implemented as `list(od1.items())==list(od2.items())`. Equality tests between `OrderedDict` objects and other Mapping objects are order-insensitive like regular dictionaries. -- The reason for this equality 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 +- دلیل اینکه این مقایسه بین متغیرهای `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` ها رو هرجایی که یک دیکشنری عادی کاربرد داره، جایگزین کنیم و استفاده کنیم. +- خب، حالا چرا تغییر ترتیب روی طول مجموعه‌ای که از دیکشنری‌ها ساختیم، تاثیر گذاشت؟ جوابش همین رفتار مقایسه‌ای غیرانتقالی بین این شیءهاست. از اونجایی که `set` ها مجموعه‌ای از عناصر غیرتکراری و بدون نظم هستند، ترتیبی که عناصر تو این مجموعه‌ها درج میشن نباید مهم باشه. ولی در این مورد، مهم هست. بیاید کمی تجزیه و تحلیلش کنیم. + ```py >>> some_set = set() - >>> some_set.add(dictionary) # these are the mapping objects from the snippets above + >>> some_set.add(dictionary) # این شیء‌ها از قطعه‌کدهای بالا هستند. >>> ordered_dict in some_set True >>> some_set.add(ordered_dict) @@ -825,11 +823,13 @@ What is going on here? >>> len(another_set) 2 ``` - So the inconsistency is due to `another_ordered_dict in another_set` being `False` because `ordered_dict` was already present in `another_set` and as observed before, `ordered_dict == another_ordered_dict` is `False`. + + پس بی‌ثباتی تو این رفتار به خاطر اینه که مقدار `another_ordered_dict in another_set` برابر با `False` هست چون `ordered_dict` از قبل داخل `another_set` هست و همونطور که قبلا مشاهده کردید، مقدار `ordered_dict == another_ordered_dict` برابر با `False` هست. --- -### ▶ Keep trying... * + +### ▶ تلاش کن... * ```py def some_func(): @@ -845,13 +845,14 @@ def another_func(): finally: print("Finally!") -def one_more_func(): # A gotcha! +def one_more_func(): try: for i in range(3): try: 1 / i except ZeroDivisionError: - # Let's throw it here and handle it outside for loop + # بذارید اینجا ارور بدیم و بیرون حلقه بهش + # رسیدگی کنیم raise ZeroDivisionError("A trivial divide by zero error") finally: print("Iteration", i) @@ -860,7 +861,7 @@ def one_more_func(): # A gotcha! print("Zero division error occurred", e) ``` -**Output:** +**خروجی:** ```py >>> some_func() @@ -881,16 +882,16 @@ Iteration 0 ``` -#### 💡 Explanation: +#### 💡 توضیحات: -- When a `return`, `break` or `continue` statement is executed in the `try` suite of a "try…finally" statement, the `finally` clause is also executed on the way out. -- The return value of a function is determined by the last `return` statement executed. Since the `finally` clause always executes, a `return` statement executed in the `finally` clause will always be the last one executed. -- The caveat here is, if the finally clause executes a `return` or `break` statement, the temporarily saved exception is discarded. +- وقتی یک عبارت `return`، `break` یا `continue` داخل بخش `try` از یک عبارت "try...finally" اجرا میشه، بخش `fianlly` هم هنگام خارج شدن اجرا میشه. +- مقدار بازگشتی یک تابع از طریق آخرین عبارت `return` که داخل تابع اجرا میشه، مشخص میشه. از اونجایی که بخش `finally` همیشه اجرا میشه، عبارت `return` که داخل بخش `finally` هست آخرین عبارتیه که اجرا میشه. +- نکته اینجاست که اگه بخش داخل بخش `finally` یک عبارت `return` یا `break` اجرا بشه، `exception` موقتی که ذخیره شده، رها میشه. --- -### ▶ For what? +### ▶ برای چی؟ ```py some_string = "wtf" @@ -899,27 +900,26 @@ for i, some_dict[i] in enumerate(some_string): i = 10 ``` -**Output:** +**خروجی:** ```py ->>> some_dict # An indexed dict appears. +>>> some_dict # یک دیکشنری مرتب‌شده نمایان میشه. {0: 'w', 1: 't', 2: 'f'} ``` -#### 💡 Explanation: - -* A `for` statement is defined in the [Python grammar](https://docs.python.org/3/reference/grammar.html) as: +#### 💡 توضیحات: +* یک حلقه `for` در [گرامر پایتون](https://docs.python.org/3/reference/grammar.html) این طور تعریف میشه: ``` for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] ``` - Where `exprlist` is the assignment target. This means that the equivalent of `{exprlist} = {next_value}` is **executed for each item** in the iterable. - An interesting example that illustrates this: + به طوری که `exprlist` یک هدف برای مقداردهیه. این یعنی، معادل عبارت `{exprlist} = {next_value}` **برای هر شیء داخل `testlist` اجرا می‌شود**. + یک مثال جالب برای نشون دادن این تعریف: ```py for i in range(4): print(i) i = 10 ``` - **Output:** + **خروجی:** ``` 0 1 @@ -927,13 +927,13 @@ for i, some_dict[i] in enumerate(some_string): 3 ``` - Did you expect the loop to run just once? + آیا انتظار داشتید که حلقه فقط یک بار اجرا بشه؟ - **💡 Explanation:** + **💡 توضیحات:** - - The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(4)` in this case) is unpacked and assigned the target list variables (`i` in this case). + - عبارت مقداردهی `i = 10` به خاطر نحوه کار کردن حلقه‌ها، هیچوقت باعث تغییر در تکرار حلقه نمیشه. قبل از شروع هر تکرار، مقدار بعدی که توسط شیء قابل تکرار (که در اینجا `range(4)` است) ارائه میشه، از بسته خارج میشه و به متغیرهای لیست هدف (که در اینجا `i` است) مقداردهی میشه. -* The `enumerate(some_string)` function yields a new value `i` (a counter going up) and a character from the `some_string` in each iteration. It then sets the (just assigned) `i` key of the dictionary `some_dict` to that character. The unrolling of the loop can be simplified as: +* تابع `enumerate(some_string)`، یک متغیر `i` (که یک شمارنده اقزایشی است) و یک حرف از حروف رشته `some_string` رو در هر تکرار برمیگردونه. و بعدش برای کلید `i` (تازه مقداردهی‌شده) در دیکشنری `some_dict`، مقدار اون حرف رو تنظیم می‌کنه. بازشده این حلقه می‌تونه مانند مثال زیر ساده بشه: ```py >>> i, some_dict[i] = (0, 'w') >>> i, some_dict[i] = (1, 't') @@ -943,20 +943,20 @@ for i, some_dict[i] in enumerate(some_string): --- -### ▶ Evaluation time discrepancy +### ▶ اختلاف زمانی در محاسبه 1\. ```py array = [1, 8, 15] -# A typical generator expression +# یک عبارت تولیدکننده عادی gen = (x for x in array if array.count(x) > 0) array = [2, 8, 22] ``` -**Output:** +**خروجی:** ```py ->>> print(list(gen)) # Where did the other values go? +>>> print(list(gen)) # پس بقیه مقدارها کجا رفتن؟ [8] ``` @@ -972,7 +972,7 @@ gen_2 = (x for x in array_2) array_2[:] = [1,2,3,4,5] ``` -**Output:** +**خروجی:** ```py >>> print(list(gen_1)) [1, 2, 3, 4] @@ -992,27 +992,27 @@ array_3 = [4, 5, 6] array_4 = [400, 500, 600] ``` -**Output:** +**خروجی:** ```py >>> print(list(gen)) [401, 501, 601, 402, 502, 602, 403, 503, 603] ``` -#### 💡 Explanation +#### 💡 توضیحات -- In a [generator](https://wiki.python.org/moin/Generators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at runtime. -- So before runtime, `array` is re-assigned to the list `[2, 8, 22]`, and since out of `1`, `8` and `15`, only the count of `8` is greater than `0`, the generator only yields `8`. -- The differences in the output of `g1` and `g2` in the second part is due the way variables `array_1` and `array_2` are re-assigned values. -- In the first case, `array_1` is 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. +- در یک عبارت [تولیدکننده](https://wiki.python.org/moin/Generators)، عبارت بند `in` در هنگام تعریف محاسبه میشه ولی عبارت شرطی در زمان اجرا محاسبه میشه. +- پس قبل از زمان اجرا، `array` دوباره با لیست `[2, 8, 22]` مقداردهی میشه و از آن‌جایی که در مقدار جدید `array`، بین `1`، `8` و `15`، فقط تعداد `8` بزرگتر از `0` است، تولیدکننده فقط مقدار `8` رو برمیگردونه +- تفاوت در مقدار `gen_1` و `gen_2` در بخش دوم به خاطر نحوه مقداردهی دوباره `array_1` و `array_2` است. +- در مورد اول، متغیر `array_1` به شیء جدید `[1,2,3,4,5]` وصله و از اون جایی که عبارت بند `in` در هنگام تعریف محاسبه میشه، `array_1` داخل تولیدکننده هنوز به شیء قدیمی `[1,2,3,4]` (که هنوز حذف نشده) +- در مورد دوم، مقداردهی برشی به `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` بلافاصله محاسبه میشه و باقی عبارت‌ها به تعویق انداخته میشن تا زمانی که تولیدکننده اجرا بشه. --- -### ▶ `is not ...` is not `is (not ...)` +### ▶ هر گردی، گردو نیست ```py >>> 'something' is not None @@ -1021,25 +1021,25 @@ True False ``` -#### 💡 Explanation - -- `is not` is a single binary operator, and has behavior different than using `is` and `not` separated. -- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise. -- In the example, `(not None)` evaluates to `True` since the value `None` is `False` in a boolean context, so the expression becomes `'something' is True`. +#### 💡 توضیحات +- عملگر `is not` یک عملگر باینری واحده و رفتارش متفاوت تر از استفاده `is` و `not` به صورت جداگانه‌ست. +- عملگر `is not` مقدار `False` رو برمیگردونه اگر متغیرها در هردو سمت این عملگر به شیء یکسانی اشاره کنند و درغیر این صورت، مقدار `True` برمیگردونه +- در مثال بالا، عبارت `(not None)` برابره با مقدار `True` از اونجایی که مقدار `None` در زمینه boolean به `False` تبدیل میشه. پس کل عبارت معادل عبارت `'something' is True` میشه. --- -### ▶ A tic-tac-toe where X wins in the first attempt! + +### ▶ یک بازی دوز که توش X همون اول برنده میشه! ```py -# Let's initialize a row +# بیاید یک سطر تشکیل بدیم row = [""] * 3 #row i['', '', ''] -# Let's make a board +# حالا بیاید تخته بازی رو ایجاد کنیم board = [row] * 3 ``` -**Output:** +**خروجی:** ```py >>> board @@ -1053,11 +1053,11 @@ board = [row] * 3 [['X', '', ''], ['X', '', ''], ['X', '', '']] ``` -We didn't assign three `"X"`s, did we? +ما که سه‌تا `"X"` نذاشتیم. گذاشتیم مگه؟ -#### 💡 Explanation: +#### 💡 توضیحات: -When we initialize `row` variable, this visualization explains what happens in the memory +وقتی متغیر `row` رو تشکیل میدیم، تصویر زیر نشون میده که چه اتفاقی در حافظه دستگاه میافته.

@@ -1067,7 +1067,7 @@ When we initialize `row` variable, this visualization explains what happens in t

-And when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`) +و وقتی متغیر `board` رو با ضرب کردن متغیر `row` تشکیل میدیم، تصویر زیر به صورت کلی نشون میده که چه اتفاقی در حافظه میافته (هر کدوم از عناصر `board[0]`، `board[1]` و `board[2]` در حافظه به لیست یکسانی به نشانی `row` اشاره میکنند).

@@ -1077,7 +1077,7 @@ And when the `board` is initialized by multiplying the `row`, this is what happe

-We can avoid this scenario here by not using `row` variable to generate `board`. (Asked in [this](https://github.com/satwikkansal/wtfpython/issues/68) issue). +ما می‌تونیم با استفاده نکردن از متغیر `row` برای تولید متغیر `board` از این سناریو پرهیز کنیم. (در [این](https://github.com/satwikkansal/wtfpython/issues/68) موضوع پرسیده شده). ```py >>> board = [['']*3 for _ in range(3)] @@ -1088,7 +1088,8 @@ We can avoid this scenario here by not using `row` variable to generate `board`. --- -### ▶ Schrödinger's variable * + +### ▶ متغیر شرودینگر * @@ -1104,7 +1105,7 @@ for x in range(7): funcs_results = [func() for func in funcs] ``` -**Output (Python version):** +**خروجی:** ```py >>> results [0, 1, 2, 3, 4, 5, 6] @@ -1112,7 +1113,7 @@ funcs_results = [func() for func in funcs] [6, 6, 6, 6, 6, 6, 6] ``` -The values of `x` were different in every iteration prior to appending `some_func` to `funcs`, but all the functions return 6 when they're evaluated after the loop completes. +مقدار `x` در هر تکرار حلقه قبل از اضافه کردن `some_func` به لیست `funcs` متفاوت بود، ولی همه توابع در خارج از حلقه مقدار `6` رو برمیگردونند. 2. @@ -1122,14 +1123,16 @@ The values of `x` were different in every iteration prior to appending `some_fun [512, 512, 512, 512, 512, 512, 512, 512, 512, 512] ``` -#### 💡 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: +#### 💡 توضیحات: +* وقتی یک تابع رو در داخل یک حلقه تعریف می‌کنیم که در بدنه‌اش از متغیر اون حلقه استفاده شده، بست این تابع به *متغیر* وصله، نه *مقدار* اون. تابع به جای اینکه از مقدار `x` در زمان تعریف تابع استفاده کنه، در زمینه اطرافش دنبال `x` می‌گرده. پس همه این توابع از آخرین مقداری که به متغیر `x` مقداردهی شده برای محاسباتشون استفاده می‌کنند. ما می‌تونیم ببینیم که این توابع از متغیر `x` که در زمینه اطرافشون (*نه* از متغیر محلی) هست، استفاده می‌کنند، به این صورت: + ```py >>> import inspect >>> inspect.getclosurevars(funcs[0]) ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) ``` -Since `x` is a global value, we can change the value that the `funcs` will lookup and return by updating `x`: + +از اونجایی که `x` یک متغیر سراسریه (گلوبال)، ما می‌تونیم مقداری که توابع داخل `funcs` دنبالشون می‌گردند و برمیگردونند رو با به‌روز کردن `x` تغییر بدیم: ```py >>> x = 42 @@ -1137,7 +1140,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. +* برای رسیدن به رفتار موردنظر شما می‌تونید متغیر حلقه رو به عنوان یک متغیر اسم‌دار به تابع بدید. **چرا در این صورت کار می‌کنه؟** چون اینجوری یک متغیر در دامنه خود تابع تعریف میشه. تابع دیگه دنبال مقدار `x` در دامنه اطراف (سراسری) نمی‌گرده ولی یک متغیر محلی برای ذخیره کردن مقدار `x` در اون لحظه می‌سازه. ```py funcs = [] @@ -1147,7 +1150,7 @@ for x in range(7): funcs.append(some_func) ``` -**Output:** +**خروجی:** ```py >>> funcs_results = [func() for func in funcs] @@ -1155,7 +1158,7 @@ for x in range(7): [0, 1, 2, 3, 4, 5, 6] ``` -It is not longer using the `x` in the global scope: +دیگه از متغیر `x` در دامنه سراسری استفاده نمی‌کنه: ```py >>> inspect.getclosurevars(funcs[0]) @@ -1164,7 +1167,8 @@ ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) --- -### ▶ The chicken-egg problem * + +### ▶ اول مرغ بوده یا تخم مرغ؟ * 1\. ```py @@ -1176,7 +1180,7 @@ True True ``` -So which is the "ultimate" base class? There's more to the confusion by the way, +پس کدوم کلاس پایه "نهایی" هست؟ راستی سردرگمی بیشتری هم تو راهه. 2\. @@ -1202,21 +1206,23 @@ False ``` -#### 💡 Explanation +#### 💡 توضیحات -- `type` is a [metaclass](https://realpython.com/python-metaclasses/) in Python. -- **Everything** is an `object` in Python, which includes classes as well as their objects (instances). -- class `type` is the metaclass of class `object`, and every class (including `type`) has inherited directly or indirectly from `object`. -- There is no real base class among `object` and `type`. The confusion in the above snippets is arising because we're thinking about these relationships (`issubclass` and `isinstance`) in terms of Python classes. The relationship between `object` and `type` can't be reproduced in pure python. To be more precise the following relationships can't be reproduced in pure Python, - + class A is an instance of class B, and class B is an instance of class A. - + class A is an instance of itself. -- These relationships between `object` and `type` (both being instances of each other as well as themselves) exist in Python because of "cheating" at the implementation level. +- در پایتون، `type` یک [متاکلاس](https://realpython.com/python-metaclasses/) است. +- در پایتون **همه چیز** یک `object` است، که کلاس‌ها و همچنین نمونه‌هاشون (یا همان instance های کلاس‌ها) هم شامل این موضوع میشن. +- کلاس `type` یک متاکلاسه برای کلاس `object` و همه کلاس‌ها (همچنین کلاس `type`) به صورت مستقیم یا غیرمستقیم از کلاس `object` ارث بری کرده است. +- هیچ کلاس پایه واقعی بین کلاس‌های `object` و `type` وجود نداره. سردرگمی که در قطعه‌کدهای بالا به وجود اومده، به خاطر اینه که ما به این روابط (یعنی `issubclass` و `isinstance`) از دیدگاه کلاس‌های پایتون فکر می‌کنیم. رابطه بین `object` و `type` رو در پایتون خالص نمیشه بازتولید کرد. برای اینکه دقیق‌تر باشیم، رابطه‌های زیر در پایتون خالص نمی‌تونند بازتولید بشن. + + کلاس A یک نمونه از کلاس B، و کلاس B یک نمونه از کلاس A باشه. + + کلاس A یک نمونه از خودش باشه. +- +- این روابط بین `object` و `type` (که هردو نمونه یکدیگه و همچنین خودشون باشند) به خاطر "تقلب" در مرحله پیاده‌سازی، وجود دارند. --- -### ▶ Subclass relationships + +### ▶ روابط بین زیرمجموعه کلاس‌ها -**Output:** +**خروجی:** ```py >>> from collections.abc import Hashable >>> issubclass(list, object) @@ -1227,14 +1233,14 @@ 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`) +ما انتظار داشتیم که روابط بین زیرکلاس‌ها، انتقالی باشند، درسته؟ (یعنی اگه `A` زیرکلاس `B` باشه و `B` هم زیرکلاس `C` باشه، کلس `A` __باید__ زیرکلاس `C` باشه) -#### 💡 Explanation: +#### 💡 توضیحات: -* Subclass relationships are not necessarily transitive in Python. Anyone is allowed to define their own, arbitrary `__subclasscheck__` in a metaclass. -* When `issubclass(cls, Hashable)` is called, it simply looks for non-Falsey "`__hash__`" method in `cls` or anything it inherits from. -* Since `object` is hashable, but `list` is non-hashable, it breaks the transitivity relation. -* More detailed explanation can be found [here](https://www.naftaliharris.com/blog/python-subclass-intransitivity/). +* روابط بین زیرکلاس‌ها در پایتون لزوما انتقالی نیستند. همه مجازند که تابع `__subclasscheck__` دلخواه خودشون رو در یک متاکلاس تعریف کنند. +* وقتی عبارت `issubclass(cls, Hashable)` اجرا میشه، برنامه دنبال یک تابع "غیر نادرست" (یا non-Falsy) در `cls` یا هرچیزی که ازش ارث‌بری می‌کنه، می‌گرده. +* از اونجایی که `object` قابل هش شدنه، ولی `list` این‌طور نیست، رابطه انتقالی شکسته میشه. +* توضیحات با جزئیات بیشتر [اینجا](https://www.naftaliharris.com/blog/python-subclass-intransitivity/) پیدا میشه. --- diff --git a/translations/fa-farsi/section1-temp.md b/translations/fa-farsi/section1-temp.md deleted file mode 100644 index 7c37b261..00000000 --- a/translations/fa-farsi/section1-temp.md +++ /dev/null @@ -1,1007 +0,0 @@ -## بخش: ذهن خود را به چالش بکشید! - -### ▶ اول از همه! * - - - - -به دلایلی، عملگر "Walrus" (`:=`) که در نسخه ۳.۸ پایتون معرفی شد، خیلی محبوب شده. بیاید بررسیش کنیم. - -1\. - -```py -# Python version 3.8+ - ->>> a = "wtf_walrus" ->>> a -'wtf_walrus' - ->>> a := "wtf_walrus" -File "", line 1 - a := "wtf_walrus" - ^ -SyntaxError: invalid syntax - ->>> (a := "wtf_walrus") # ولی این کار می‌کنه -'wtf_walrus' ->>> a -'wtf_walrus' -``` - -2 \. - -```py -# Python version 3.8+ - ->>> a = 6, 9 ->>> a -(6, 9) - ->>> (a := 6, 9) -(6, 9) ->>> a -6 - ->>> a, b = 6, 9 # باز کردن معمولی ->>> a, b -(6, 9) ->>> (a, b = 16, 19) # آخ آخ - File "", line 1 - (a, b = 16, 19) - ^ -SyntaxError: invalid syntax - ->>> (a, b := 16, 19) # این یه تاپل ۳تایی چاپ می‌کنه رو صفحه -(6, 16, 19) - ->>> a # هنوز تغییر نکرده؟ -6 - ->>> b -16 -``` - - - -#### 💡 توضیحات - -**مرور سریع بر عملگر Walrus** - -عملگر Walrus همونطور که اشاره شد، در نسخه ۳.۸ پایتون معرفی -شد. این عملگر می‌تونه تو مقعیت‌هایی کاربردی باشه که شما می‌خواید داخل یه عبارت، مقادیری رو به متغیرها اختصاص بدید - -```py -def some_func(): - # فرض کنید اینجا یک سری محاسبه سنگین انجام میشه - # time.sleep(1000) - return 5 - -# پس به جای اینکه این کارو بکنید: -if some_func(): - print(some_func()) # که خیلی راه نادرستیه چون محاسبه دوبار انجام میشه - -# یا حتی این کارو کنید (که کار بدی هم نیست) -a = some_func() -if a: - print(a) - -# می‌تونید از این به بعد به طور مختصر بنویسید: -if a := some_func(): - print(a) - -``` - -**خروجی (+۳.۸):** - -```py -5 -5 -5 -``` - -این باعث میشه که یک خط کمتر کد بزنیم و از دوبار فراخوندن `some_func` جلوگیری کرد. - -- "عبارت اختصاص‌دادن مقدار" بدون پرانتز (نحوه استفاده عملگر Walrus)، در سطح بالا محدود است، `SyntaxError` در عبارت `a := "wtf_walrus"` در قطعه‌کد اول به همین دلیل است. قرار دادن آن داخل پرانتز، همانطور که می‌خواستیم کار کرد و مقدار را به `a` اختصاص داد. - -- به طور معمول، قرار دادن عبارتی که دارای `=` است داخل پرانتز مجاز نیست. به همین دلیل ‍عبارت `(a, b = 6, 9)` به ما خطای سینتکس داد. - -- قائده استفاده از عملگر Walrus به صورت `NAME:= expr` است، به طوری که `NAME` یک شناسه صحیح و `expr` یک عبارت صحیح است. به همین دلیل باز و بسته کردن با تکرار (iterable) پشتیبانی نمی‌شوند. پس، - - - عبارت `(a := 6, 9)` معادل عبارت `((a := 6), 9)` و در نهایت `(a, 9)` است. (که مقدار `a` عدد 6 است) - - ```py - >>> (a := 6, 9) == ((a := 6), 9) - True - >>> x = (a := 696, 9) - >>> x - (696, 9) - >>> x[0] is a # هر دو به یک مکان در حافظه دستگاه اشاره می‌کنند - True - ``` - - - به طور مشابه، عبارت `(a, b := 16, 19)` معادل عبارت `(a, (b := 16), 19)` است که چیزی جز یک تاپل ۳تایی نیست. - ---- - -### ▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند - - -1\. - -```py ->>> a = "some_string" ->>> id(a) -140420665652016 ->>> id("some" + "_" + "string") # دقت کنید که هردو شناسه یکسانند. -140420665652016 -``` - -2\. -```py ->>> a = "wtf" ->>> b = "wtf" ->>> a is b -True - ->>> a = "wtf!" ->>> b = "wtf!" ->>> a is b -False - -``` - -3\. - -```py ->>> a, b = "wtf!", "wtf!" ->>> a is b # همه‌ی نسخه‌ها به جز 3.7.x -True - ->>> a = "wtf!"; b = "wtf!" ->>> a is b # ممکن است True یا False باشد بسته به جایی که آن را اجرا می‌کنید (python shell / ipython / به‌صورت اسکریپت) -False -``` - -```py -# این بار در فایل some_file.py -a = "wtf!" -b = "wtf!" -print(a is b) - -# موقع اجرای ماژول، True را چاپ می‌کند! -``` - -4\. - -**خروجی (< Python3.7 )** - -```py ->>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' -True ->>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' -False -``` - -منطقیه، نه؟ - -#### 💡 توضیحات: -+ در قطعه‌کد اول و دوم، رفتار کد به دلیل یک بهینه سازی در CPython است (به نام داوطلب سازی رشته‌ها) که باعث می‌شود از برخی مقادیر غیرقابل تغییر، به جای مقداردهی مجدد، دوباره استفاده شود. -+ بیشتر متغیرهایی که به‌این صورت جایگزین می‌شوند، در حافظه دستگاه به مقدار داوطلب خود اشاره می‌کنند (تا از حافظه کمتری استفاده شود) -+ در قطعه‌کدهای بالا، رشته‌ها به‌صورت غیرمستقیم داوطلب می‌شوند. تصمیم اینکه رشته‌ها چه زمانی به صورت غیرمستقیم داوطلب شوند به نحوه پیاده‌سازی و مقداردهی آن‌ها بستگی دارد. برخی قوانین وجود دارند تا بتوانیم داوطلب شدن یا نشدن یک رشته را حدس بزنیم: - * همه رشته‌ها با طول صفر یا یک داوطلب می‌شوند. - * رشته‌ها در زمان کامپایل داوطلب می‌شوند (`'wtf'` داوطلب می‌شود اما `''.join(['w', 't', 'f'])` داوطلب نمی‌شود) - * رشته‌هایی که از حروف ASCII ، اعداد صحیح و آندرلاین تشکیل نشده‌باشند داوطلب نمی‌شود. به همین دلیل `'wtf!'` به خاطر وجود `'!'` داوطلب نشد. پیاده‌سازی این قانون در CPython در [اینجا](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) قرار دارد. - -

- - - - Shows a string interning process. - -

- -+ زمانی که `"wtf!"` را در یک خط به `a` و `b` اختصاص می‌دهیم، مفسر پایتون شیء جدید می‌سازد و متغیر دوم را به آن ارجاع می‌دهد. اگر مقدار دهی در خط‌های جدا از هم انجام شود، در واقع مفسر "خبر ندارد" که یک شیء مختص به `"wtf!"` از قبل در برنامه وجود دارد (زیرا `"wtf!"` به دلایلی که در بالا گفته شد، به‌صورت غیرمستقیم داوطلب نمی‌شود). این بهینه سازی در زمان کامپایل انجام می‌شود. این بهینه سازی همچنین برای نسخه های (x).۳.۷ وجود ندارد (برای گفت‌وگوی بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) را ببینید). -+ یک واحد کامپایل در یک محیط تعاملی مانند IPython از یک عبارت تشکیل می‌شود، در حالی که برای ماژول‌ها شامل کل ماژول می‌شود. `a, b = "wtf!", "wtf!"` یک عبارت است. در حالی که `a = "wtf!"; b = "wtf!"` دو عبارت در یک خط است. به همین دلیل شناسه‌ها در `a = "wtf!"; b = "wtf!"` متفاوتند و همین‌طور وقتی با مفسر پایتون داخل فایل `some_file.py` اجرا می‌شوند، شناسه‌ها یکسانند. -+ تغییر ناگهانی در خروجی قطعه‌کد چهارم به دلیل [بهینه‌سازی پنجره‌ای](https://en.wikipedia.org/wiki/Peephole_optimization) است که تکنیکی معروف به جمع آوری ثابت‌ها است. به همین خاطر عبارت `'a'*20` با `'aaaaaaaaaaaaaaaaaaaa'` در هنگام کامپایل جایگزین می‌شود تا کمی بار از دوش چرخه‌ساعتی پردازنده کم شود. تکنیک جمع آوری ثابت‌ها فقط مخصوص رشته‌هایی با طول کمتر از 21 است. (چرا؟ فرض کنید که فایل `.pyc` که توسط کامپایلر ساخته می‌شود چقدر بزرگ می‌شد اگر عبارت `'a'*10**10`). [این](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) هم کد پیاده‌سازی این تکنیک در CPython. -+ توجه: در پایتون ۳.۷، جمع آوری ثابت‌ها از بهینه‌ساز پنجره‌ای به بهینه‌ساز AST جدید انتقال داده شد همراه با تغییراتی در منطق آن. پس چهارمین قطعه‌کد در پایتون نسخه ۳.۷ کار نمی‌کند. شما می‌توانید در [اینجا](https://bugs.python.org/issue11549) بیشتر درمورد این تغییرات بخوانید. - ---- - - -### ▶ مراقب عملیات‌های زنجیره‌ای باشید - -```py ->>> (False == False) in [False] # منطقیه -False ->>> False == (False in [False]) # منطقیه -False ->>> False == False in [False] # حالا چی؟ -True - ->>> True is False == False -False ->>> False is False is False -True - ->>> 1 > 0 < 1 -True ->>> (1 > 0) < 1 -False ->>> 1 > (0 < 1) -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` و `0 <= x <= 100` عالی عمل می‌کنه. - -* عبارت `False is False is False` معادل عبارت `(False is False) and (False is False)` است -* عبارت `True is False == False` معادل عبارت `(True is False) and (False == False)` است و از آنجایی که قسمت اول این عبارت (`True is False`) پس از ارزیابی برابر با `False` می‌شود. پس کل عبارت معادل `False` می‌شود. -* عبارت `1 > 0 < 1` معادل عبارت `(1 > 0) and (0 < 1)` است. -* عبارت `(1 > 0) < 1` معادل عبارت `True < 1` است و : - ```py - >>> int(True) - 1 - >>> True + 1 # مربوط به این بخش نیست ولی همینجوری گذاشتم - 2 - ``` - پس عبارت `True < 1` معادل عبارت `1 < 1` می‌شود که در کل معادل `False` است. - ---- - -### ▶ چطور از عملگر `is` استفاده نکنیم - -عبارت پایین خیلی معروفه و تو کل اینترنت موجوده. - -1\. - -```py ->>> a = 256 ->>> b = 256 ->>> a is b -True - ->>> a = 257 ->>> b = 257 ->>> a is b -False -``` - -2\. - -```py ->>> a = [] ->>> b = [] ->>> a is b -False - ->>> a = tuple() ->>> b = tuple() ->>> a is b -True -``` - -3\. -**خروجی** - -```py ->>> a, b = 257, 257 ->>> a is b -True -``` - -**خروجی (مخصوص نسخه‌های (x).۳.۷)** - -```py ->>> a, b = 257, 257 ->>> a is b -False -``` - -#### 💡 توضیحات: - -**فرض بین عملگرهای `is` و `==`** - -* عملگر `is` بررسی میکنه که دو متغیر در حافظه دستگاه به یک شیء اشاره میکنند یا نه (یعنی شناسه متغیرها رو با هم تطبیق میده). -* عملگر `==` مقدار متغیرها رو با هم مقایسه میکنه و یکسان بودنشون رو بررسی میکنه. -* پس `is` برای معادل بودن متغیرها در حافظه دستگاه و `==` برای معادل بودن مقادیر استفاده میشه. یه مثال برای شفاف سازی بیشتر: - ```py - >>> class A: pass - >>> A() is A() # این‌ها دو شیء خالی هستند که در دو جای مختلف در حافظه قرار دارند. - False - ``` - -**عدد `256` از قبل تو حافظه قرار داده شده ولی `257` نه؟** - -وقتی پایتون رو اجرا می‌کنید اعداد از `-5` تا `256` در حافظه ذخیره میشن. چون این اعداد خیلی پرکاربرد هستند پس منطقیه که اون‌ها رو در حافظه دستگاه، آماده داشته باشیم. - -نقل قول از https://docs.python.org/3/c-api/long.html -> در پیاده سازی فعلی یک آرایه از اشیاء عددی صحیح برای تمام اعداد صحیح بین `-5` تا `256` نگه‌داری می‌شود. وقتی شما یک عدد صحیح در این بازه به مقداردهی می‌کنید، فقط یک ارجاع به آن عدد که از قبل در حافظه ذخیره شده است دریافت می‌کنید. پس تغییر مقدار عدد 1 باید ممکن باشد. که در این مورد من به رفتار پایتون شک دارم تعریف‌نشده است. :-) - -```py ->>> id(256) -10922528 ->>> a = 256 ->>> b = 256 ->>> id(a) -10922528 ->>> id(b) -10922528 ->>> id(257) -140084850247312 ->>> x = 257 ->>> y = 257 ->>> id(x) -140084850247440 ->>> id(y) -140084850247344 -``` - -در اینجا مفسر وقتی عبارت `y = 257` رو اجرا میکنه، به اندازه کافی زیرکانه عمل نمیکنه که تشخیص بده که ما یک عدد صحیح با مقدار `257` در حافظه ذخیره کرده‌ایم، پس به ساختن یک شیء جدید در حافظه ادامه میده. - -یک بهینه سازی مشابه شامل حال مقادیر **غیرقابل تغییر** دیگه مانند تاپل‌های خالی هم میشه. از اونجایی که لیست‌ها قابل تغییرند، عبارت `[] is []` مقدار `False` رو برمیگردونه و عبارت `() is ()` مقدار `True` رو برمیگردونه. به همین دلیله که قطعه کد دوم چنین رفتاری داره. بریم سراغ سومی. - -**متغیرهای `a` و `b` وقتی در یک خط با مقادیر یکسانی مقداردهی میشن، هردو به یک شیء در حافظه اشاره میکنن** - -**خروجی** - -```py ->>> a, b = 257, 257 ->>> id(a) -140640774013296 ->>> id(b) -140640774013296 ->>> a = 257 ->>> b = 257 ->>> id(a) -140640774013392 ->>> id(b) -140640774013488 -``` - -* وقتی a و b در یک خط با `257` مقداردهی میشن، مفسر پایتون یک شیء برای یکی از متغیرها در حافظه میسازه و متغیر دوم رو در حافظه به اون ارجاع میده. اگه این کار رو تو دو خط جدا از هم انجام بدید، درواقع مفسر پایتون از وجود مقدار `257` به عنوان یک شیء، "خبر نداره". - -* این یک بهینه سازی توسط کامپایلر هست و مخصوصا در محیط تعاملی به کار برده میشه. وقتی شما دو خط رو در یک مفسر زنده وارد می‌کنید، اون‌ها به صورت جداگانه کامپایل میشن، به همین دلیل بهینه سازی به صورت جداگانه برای هرکدوم اعمال میشه. اگر بخواهید این مثال رو در یک فایل `.py` امتحان کنید، رفتار متفاوتی می‌بینید زیرا فایل به صورت کلی و یک‌جا کامپایل میشه. این بهینه سازی محدود به اعداد صحیح نیست و برای انواع داده‌های غیرقابل تغییر دیگه مانند رشته‌ها (مثال "رشته‌ها می‌توانند دردسرساز شوند" رو ببینید) و اعداد اعشاری هم اعمال میشه. - - ```py - >>> a, b = 257.0, 257.0 - >>> a is b - True - ``` - -* چرا این برای پایتون ۳.۷ کار نکرد؟ دلیل انتزاعیش اینه که چنین بهینه‌سازی‌های کامپایلری وابسته به پیاده‌سازی هستن (یعنی بسته به نسخه، و نوع سیستم‌عامل و چیزهای دیگه تغییر میکنن). من هنوز پیگیرم که بدونم که کدوم تغییر تو پیاده‌سازی باعث همچین مشکلاتی میشه، می‌تونید برای خبرهای بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) رو نگاه کنید. - ---- - - -### ▶ کلیدهای هش - -1\. -```py -some_dict = {} -some_dict[5.5] = "JavaScript" -some_dict[5.0] = "Ruby" -some_dict[5] = "Python" -``` - -**خروجی:** - -```py ->>> some_dict[5.5] -"JavaScript" ->>> some_dict[5.0] # رشته ("Python")، رشته ("Ruby") رو از بین برد؟ -"Python" ->>> some_dict[5] -"Python" - ->>> complex_five = 5 + 0j ->>> type(complex_five) -complex ->>> some_dict[complex_five] -"Python" -``` - -خب، چرا Python همه جارو گرفت؟ - - -#### 💡 توضیحات -* تو دیکشنری‌های پایتون چیزی که کلیدها رو یگانه میکنه مقدار کلیدهاست، نه شناسه اون‌ها. پس با اینکه `5`، `5.0` و `5 + 0j` شیءهای متمایزی از نوع‌های متفاوتی هستند ولی از اون جایی که مقدارشون با هم برابره، نمیتونن داخل یه `dict` به عنوان کلید جدا از هم باشن (حتی به عنوان مقادیر داخل یه `set` نمیتونن باشن). وقتی بخواید داخل یه دیکشنری جست‌وجو کنید، به محض اینکه یکی از این داده‌ها رو وارد کنید، مقدار نگاشته‌شده به کلیدی که مقدار برابر با اون داده داره ولی نوعش متفاوته، با موفقیت برگردونده میشه (به جای اینکه به ارور `KeyError` بردخورد کنید.). - ```py - >>> 5 == 5.0 == 5 + 0j - True - >>> 5 is not 5.0 is not 5 + 0j - True - >>> some_dict = {} - >>> some_dict[5.0] = "Ruby" - >>> 5.0 in some_dict - True - >>> (5 in some_dict) and (5 + 0j in some_dict) - True - ``` -* همچنین این قانون برای مقداردهی توی دیکشنری هم اعمال میشه. وقتی شما عبارت `some_dict[5] = "Python"` رو اجرا می‌کنید، پایتون دنبال کلیدی با مقدار یکسان می‌گرده که اینجا ما داریم `5.0 -> "Ruby"` و مقدار نگاشته‌شده به این کلید در دیکشنری رو با مقدار جدید جایگزین میکنه و کلید رو همونجوری که هست باقی میذاره. - ```py - >>> some_dict - {5.0: 'Ruby'} - >>> some_dict[5] = "Python" - >>> some_dict - {5.0: 'Python'} - ``` -* خب پس چطوری میتونیم مقدار خود کلید رو به `5` تغییر بدیم (جای `5.0`)؟ راستش ما نمیتونیم این کار رو درجا انجام بدیم، ولی میتونیم اول اون کلید رو پاک کنیم (`del some_dict[5.0]`) و بعد کلیدی که میخوایم رو قرار بدیم (`some_dict[5]`) تا بتونیم عدد صحیح `5` رو به جای عدد اعشاری `5.0` به عنوان کلید داخل دیکشنری داشته باشیم. درکل خیلی کم پیش میاد که بخوایم چنین کاری کنیم. - -* پایتون چطوری توی دیکشنری که کلید `5.0` رو داره، کلید `5` رو پیدا کرد؟ پایتون این کار رو توی زمان ثابتی توسط توابع هش انجام میده بدون اینکه مجبور باشه همه کلیدها رو بررسی کنه. وقتی پایتون دنبال کلیدی مثل `foo` داخل یه `dict` میگرده، اول مقدار `hash(foo)` رو محاسبه میکنه (که توی زمان ثابتی انجام میشه). از اونجایی که توی پایتون برای مقایسه برابری مقدار دو شیء لازمه که هش یکسانی هم داشته باشند ([مستندات](https://docs.python.org/3/reference/datamodel.html#object.__hash__)). `5`، `5.0` و `5 + 0j` مقدار هش یکسانی دارند. - ```py - >>> 5 == 5.0 == 5 + 0j - True - >>> hash(5) == hash(5.0) == hash(5 + 0j) - True - ``` - **توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیده‌ای معروف [تصادم هش]() میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند. - ---- - -### ▶ در عمق وجود همه ما یکسان هستیم - -```py -class WTF: - pass -``` - -**خروجی:** -```py ->>> WTF() == WTF() # دو نمونه متفاوت از یک کلاس نمیتونند برابر هم باشند -False ->>> WTF() is WTF() # شناسه‌ها هم متفاوتند -False ->>> hash(WTF()) == hash(WTF()) # هش‌ها هم _باید_ متفاوت باشند -True ->>> id(WTF()) == id(WTF()) -True -``` - -#### 💡 توضیحات: -* وقتی `id` صدا زده شد، پایتون یک شیء با کلاس `WTF` ساخت و اون رو به تابع `id` داد. تابع `id` شناسه این شیء رو میگیره (درواقع آدرس اون شیء در حافظه دستگاه) و شیء رو حذف میکنه. -* وقتی این کار رو دو بار متوالی انجام بدیم، پایتون آدرس یکسانی رو به شیء دوم اختصاص میده. از اونجایی که (در CPython) تابع `id` از آدرس شیءها توی حافظه به عنوان شناسه برای اون‌ها استفاده میکنه، پس شناسه این دو شیء یکسانه. -* پس، شناسه یک شیء تا زمانی که اون شیء وجود داره، منحصربه‌فرده. بعد از اینکه اون شیء حذف میشه یا قبل از اینکه اون شیء به وجود بیاد، چیز دیگه‌ای میتونه اون شناسه رو داشته باشه. -* ولی چرا با عملگر `is` مقدار `False` رو دریافت کردیم؟ بیاید با یه قطعه‌کد ببینیم دلیلش رو. - ```py - class WTF(object): - def __init__(self): print("I") - def __del__(self): print("D") - ``` - - **خروجی:** - ```py - >>> WTF() is WTF() - I - I - D - D - False - >>> id(WTF()) == id(WTF()) - I - D - I - D - True - ``` - همونطور که مشاهده می‌کنید، ترتیب حذف شدن شیءها باعث تفاوت میشه. - ---- - - -### ▶ بی‌نظمی در خود نظم * - -```py -from collections import OrderedDict - -dictionary = dict() -dictionary[1] = 'a'; dictionary[2] = 'b'; - -ordered_dict = OrderedDict() -ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; - -another_ordered_dict = OrderedDict() -another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; - -class DictWithHash(dict): - """ - یک dict که تابع جادویی __hash__ هم توش پیاده شده. - """ - __hash__ = lambda self: 0 - -class OrderedDictWithHash(OrderedDict): - """ - یک OrderedDict که تابع جادویی __hash__ هم توش پیاده شده. - """ - __hash__ = lambda self: 0 -``` - -**خروجی** -```py ->>> dictionary == ordered_dict # اگر مقدار اولی با دومی برابره -True ->>> dictionary == another_ordered_dict # و مقدار اولی با سومی برابره -True ->>> ordered_dict == another_ordered_dict # پس چرا مقدار دومی با سومی برابر نیست؟ -False - -# ما همه‌مون میدونیم که یک مجموعه فقط شامل عناصر منحصربه‌فرد و غیرتکراریه. -# بیاید یک مجموعه از این دیکشنری‌ها بسازیم ببینیم چه اتفاقی میافته... - ->>> len({dictionary, ordered_dict, another_ordered_dict}) -Traceback (most recent call last): - File "", line 1, in -TypeError: unhashable type: 'dict' - -# منطقیه چون dict ها __hash__ توشون پیاده‌سازی نشده. پس بیاید از -# کلاس‌هایی که خودمون درست کردیم استفاده کنیم. ->>> dictionary = DictWithHash() ->>> dictionary[1] = 'a'; dictionary[2] = 'b'; ->>> ordered_dict = OrderedDictWithHash() ->>> ordered_dict[1] = 'a'; ordered_dict[2] = 'b'; ->>> another_ordered_dict = OrderedDictWithHash() ->>> another_ordered_dict[2] = 'b'; another_ordered_dict[1] = 'a'; ->>> len({dictionary, ordered_dict, another_ordered_dict}) -1 ->>> len({ordered_dict, another_ordered_dict, dictionary}) # ترتیب رو عوض می‌کنیم -2 -``` - -چی شد؟ - -#### 💡 توضیحات: - -- دلیل اینکه این مقایسه بین متغیرهای `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` ها رو هرجایی که یک دیکشنری عادی کاربرد داره، جایگزین کنیم و استفاده کنیم. -- خب، حالا چرا تغییر ترتیب روی طول مجموعه‌ای که از دیکشنری‌ها ساختیم، تاثیر گذاشت؟ جوابش همین رفتار مقایسه‌ای غیرانتقالی بین این شیءهاست. از اونجایی که `set` ها مجموعه‌ای از عناصر غیرتکراری و بدون نظم هستند، ترتیبی که عناصر تو این مجموعه‌ها درج میشن نباید مهم باشه. ولی در این مورد، مهم هست. بیاید کمی تجزیه و تحلیلش کنیم. - ```py - >>> some_set = set() - >>> some_set.add(dictionary) # این شیء‌ها از قطعه‌کدهای بالا هستند. - >>> 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_ordered_dict in another_set` برابر با `False` هست چون `ordered_dict` از قبل داخل `another_set` هست و همونطور که قبلا مشاهده کردید، مقدار `ordered_dict == another_ordered_dict` برابر با `False` هست. - ---- - - -### ▶ تلاش کن... * - -```py -def some_func(): - try: - return 'from_try' - finally: - return 'from_finally' - -def another_func(): - for _ in range(3): - try: - continue - finally: - print("Finally!") - -def one_more_func(): - try: - for i in range(3): - try: - 1 / i - except ZeroDivisionError: - # بذارید اینجا ارور بدیم و بیرون حلقه بهش - # رسیدگی کنیم - raise ZeroDivisionError("A trivial divide by zero error") - finally: - print("Iteration", i) - break - except ZeroDivisionError as e: - print("Zero division error occurred", e) -``` - -**خروجی:** - -```py ->>> some_func() -'from_finally' - ->>> another_func() -Finally! -Finally! -Finally! - ->>> 1 / 0 -Traceback (most recent call last): - File "", line 1, in -ZeroDivisionError: division by zero - ->>> one_more_func() -Iteration 0 - -``` - -#### 💡 توضیحات: - -- وقتی یک عبارت `return`، `break` یا `continue` داخل بخش `try` از یک عبارت "try...finally" اجرا میشه، بخش `fianlly` هم هنگام خارج شدن اجرا میشه. -- مقدار بازگشتی یک تابع از طریق آخرین عبارت `return` که داخل تابع اجرا میشه، مشخص میشه. از اونجایی که بخش `finally` همیشه اجرا میشه، عبارت `return` که داخل بخش `finally` هست آخرین عبارتیه که اجرا میشه. -- نکته اینجاست که اگه بخش داخل بخش `finally` یک عبارت `return` یا `break` اجرا بشه، `exception` موقتی که ذخیره شده، رها میشه. - ---- - - -### ▶ برای چی? - -```py -some_string = "wtf" -some_dict = {} -for i, some_dict[i] in enumerate(some_string): - i = 10 -``` - -**خروجی:** -```py ->>> some_dict # یک دیکشنری مرتب‌شده نمایان میشه. -{0: 'w', 1: 't', 2: 'f'} -``` - -#### 💡 توضیحات: -* یک حلقه `for` در [گرامر پایتون](https://docs.python.org/3/reference/grammar.html) این طور تعریف میشه: - ``` - for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] - ``` - به طوری که `exprlist` یک هدف برای مقداردهیه. این یعنی، معادل عبارت `{exprlist} = {next_value}` **برای هر شیء داخل `testlist` اجرا می‌شود**. - یک مثال جالب برای نشون دادن این تعریف: - ```py - for i in range(4): - print(i) - i = 10 - ``` - - **خروجی:** - ``` - 0 - 1 - 2 - 3 - ``` - - آیا انتظار داشتید که حلقه فقط یک بار اجرا بشه؟ - - **💡 توضیحات:** - - - عبارت مقداردهی `i = 10` به خاطر نحوه کار کردن حلقه‌ها، هیچوقت باعث تغییر در تکرار حلقه نمیشه. قبل از شروع هر تکرار، مقدار بعدی که توسط شیء قابل تکرار (که در اینجا `range(4)` است) ارائه میشه، از بسته خارج میشه و به متغیرهای لیست هدف (که در اینجا `i` است) مقداردهی میشه. - -* تابع `enumerate(some_string)`، یک متغیر `i` (که یک شمارنده اقزایشی است) و یک حرف از حروف رشته `some_string` رو در هر تکرار برمیگردونه. و بعدش برای کلید `i` (تازه مقداردهی‌شده) در دیکشنری `some_dict`، مقدار اون حرف رو تنظیم می‌کنه. بازشده این حلقه می‌تونه مانند مثال زیر ساده بشه: - ```py - >>> i, some_dict[i] = (0, 'w') - >>> i, some_dict[i] = (1, 't') - >>> i, some_dict[i] = (2, 'f') - >>> some_dict - ``` - ---- - -### ▶ اختلاف زمانی در محاسبه - -1\. -```py -array = [1, 8, 15] -# یک عبارت تولیدکننده عادی -gen = (x for x in array if array.count(x) > 0) -array = [2, 8, 22] -``` - -**خروجی:** - -```py ->>> print(list(gen)) # پس بقیه مقدارها کجا رفتن؟ -[8] -``` - -2\. - -```py -array_1 = [1,2,3,4] -gen_1 = (x for x in array_1) -array_1 = [1,2,3,4,5] - -array_2 = [1,2,3,4] -gen_2 = (x for x in array_2) -array_2[:] = [1,2,3,4,5] -``` - -**خروجی:** -```py ->>> print(list(gen_1)) -[1, 2, 3, 4] - ->>> print(list(gen_2)) -[1, 2, 3, 4, 5] -``` - -3\. - -```py -array_3 = [1, 2, 3] -array_4 = [10, 20, 30] -gen = (i + j for i in array_3 for j in array_4) - -array_3 = [4, 5, 6] -array_4 = [400, 500, 600] -``` - -**خروجی:** -```py ->>> print(list(gen)) -[401, 501, 601, 402, 502, 602, 403, 503, 603] -``` - -#### 💡 توضیحات - -- در یک عبارت [تولیدکننده](https://wiki.python.org/moin/Generators)، عبارت بند `in` در هنگام تعریف محاسبه میشه ولی عبارت شرطی در زمان اجرا محاسبه میشه. -- پس قبل از زمان اجرا، `array` دوباره با لیست `[2, 8, 22]` مقداردهی میشه و از آن‌جایی که در مقدار جدید `array`، بین `1`، `8` و `15`، فقط تعداد `8` بزرگتر از `0` است، تولیدکننده فقط مقدار `8` رو برمیگردونه -- تفاوت در مقدار `gen_1` و `gen_2` در بخش دوم به خاطر نحوه مقداردهی دوباره `array_1` و `array_2` است. -- در مورد اول، متغیر `array_1` به شیء جدید `[1,2,3,4,5]` وصله و از اون جایی که عبارت بند `in` در هنگام تعریف محاسبه میشه، `array_1` داخل تولیدکننده هنوز به شیء قدیمی `[1,2,3,4]` (که هنوز حذف نشده) -- در مورد دوم، مقداردهی برشی به `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` بلافاصله محاسبه میشه و باقی عبارت‌ها به تعویق انداخته میشن تا زمانی که تولیدکننده اجرا بشه. - ---- - - -### ▶ هر گردی، گردو نیست - -```py ->>> 'something' is not None -True ->>> 'something' is (not None) -False -``` - -#### 💡 توضیحات -- عملگر `is not` یک عملگر باینری واحده و رفتارش متفاوت تر از استفاده `is` و `not` به صورت جداگانه‌ست. -- عملگر `is not` مقدار `False` رو برمیگردونه اگر متغیرها در هردو سمت این عملگر به شیء یکسانی اشاره کنند و درغیر این صورت، مقدار `True` برمیگردونه -- در مثال بالا، عبارت `(not None)` برابره با مقدار `True` از اونجایی که مقدار `None` در زمینه boolean به `False` تبدیل میشه. پس کل عبارت معادل عبارت `'something' is True` میشه. - ---- - - -### ▶ یک بازی دوز که توش X همون اول برنده میشه! - - -```py -# بیاید یک سطر تشکیل بدیم -row = [""] * 3 #row i['', '', ''] -# حالا بیاید تخته بازی رو ایجاد کنیم -board = [row] * 3 -``` - -**خروجی:** - -```py ->>> board -[['', '', ''], ['', '', ''], ['', '', '']] ->>> board[0] -['', '', ''] ->>> board[0][0] -'' ->>> board[0][0] = "X" ->>> board -[['X', '', ''], ['X', '', ''], ['X', '', '']] -``` - -ما که سه‌تا `"X"` نذاشتیم. گذاشتیم مگه؟ - -#### 💡 توضیحات: - -وقتی متغیر `row` رو تشکیل میدیم، تصویر زیر نشون میده که چه اتفاقی در حافظه دستگاه میافته. - -

- - - - Shows a memory segment after row is initialized. - -

- -و وقتی متغیر `board` رو با ضرب کردن متغیر `row` تشکیل میدیم، تصویر زیر به صورت کلی نشون میده که چه اتفاقی در حافظه میافته (هر کدوم از عناصر `board[0]`، `board[1]` و `board[2]` در حافظه به لیست یکسانی به نشانی `row` اشاره میکنند). - -

- - - - Shows a memory segment after board is initialized. - -

- -ما می‌تونیم با استفاده نکردن از متغیر `row` برای تولید متغیر `board` از این سناریو پرهیز کنیم. (در [این](https://github.com/satwikkansal/wtfpython/issues/68) موضوع پرسیده شده). - -```py ->>> board = [['']*3 for _ in range(3)] ->>> board[0][0] = "X" ->>> board -[['X', '', ''], ['', '', ''], ['', '', '']] -``` - ---- - - -### ▶ متغیر شرودینگر * - - - -```py -funcs = [] -results = [] -for x in range(7): - def some_func(): - return x - funcs.append(some_func) - results.append(some_func()) # note the function call here - -funcs_results = [func() for func in funcs] -``` - -**خروجی:** -```py ->>> results -[0, 1, 2, 3, 4, 5, 6] ->>> funcs_results -[6, 6, 6, 6, 6, 6, 6] -``` - -مقدار `x` در هر تکرار حلقه قبل از اضافه کردن `some_func` به لیست `funcs` متفاوت بود، ولی همه توابع در خارج از حلقه مقدار `6` رو برمیگردونند. - -2. - -```py ->>> powers_of_x = [lambda x: x**i for i in range(10)] ->>> [f(2) for f in powers_of_x] -[512, 512, 512, 512, 512, 512, 512, 512, 512, 512] -``` - -#### 💡 توضیحات: -* وقتی یک تابع رو در داخل یک حلقه تعریف می‌کنیم که در بدنه‌اش از متغیر اون حلقه استفاده شده، بست این تابع به *متغیر* وصله، نه *مقدار* اون. تابع به جای اینکه از مقدار `x` در زمان تعریف تابع استفاده کنه، در زمینه اطرافش دنبال `x` می‌گرده. پس همه این توابع از آخرین مقداری که به متغیر `x` مقداردهی شده برای محاسباتشون استفاده می‌کنند. ما می‌تونیم ببینیم که این توابع از متغیر `x` که در زمینه اطرافشون (*نه* از متغیر محلی) هست، استفاده می‌کنند، به این صورت: - -```py ->>> import inspect ->>> inspect.getclosurevars(funcs[0]) -ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) -``` - -از اونجایی که `x` یک متغیر سراسریه (گلوبال)، ما می‌تونیم مقداری که توابع داخل `funcs` دنبالشون می‌گردند و برمیگردونند رو با به‌روز کردن `x` تغییر بدیم: - -```py ->>> x = 42 ->>> [func() for func in funcs] -[42, 42, 42, 42, 42, 42, 42] -``` - -* برای رسیدن به رفتار موردنظر شما می‌تونید متغیر حلقه رو به عنوان یک متغیر اسم‌دار به تابع بدید. **چرا در این صورت کار می‌کنه؟** چون اینجوری یک متغیر در دامنه خود تابع تعریف میشه. تابع دیگه دنبال مقدار `x` در دامنه اطراف (سراسری) نمی‌گرده ولی یک متغیر محلی برای ذخیره کردن مقدار `x` در اون لحظه می‌سازه. - -```py -funcs = [] -for x in range(7): - def some_func(x=x): - return x - funcs.append(some_func) -``` - -**خروجی:** - -```py ->>> funcs_results = [func() for func in funcs] ->>> funcs_results -[0, 1, 2, 3, 4, 5, 6] -``` - -دیگه از متغیر `x` در دامنه سراسری استفاده نمی‌کنه: - -```py ->>> inspect.getclosurevars(funcs[0]) -ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) -``` - ---- - - -### ▶ اول مرغ بوده یا تخم مرغ؟ * - -1\. -```py ->>> isinstance(3, int) -True ->>> isinstance(type, object) -True ->>> isinstance(object, type) -True -``` - -پس کدوم کلاس پایه "نهایی" هست؟ راستی سردرگمی بیشتری هم تو راهه. - -2\. - -```py ->>> class A: pass ->>> isinstance(A, A) -False ->>> isinstance(type, type) -True ->>> isinstance(object, object) -True -``` - -3\. - -```py ->>> issubclass(int, object) -True ->>> issubclass(type, object) -True ->>> issubclass(object, type) -False -``` - - -#### 💡 توضیحات - -- در پایتون، `type` یک [متاکلاس](https://realpython.com/python-metaclasses/) است. -- در پایتون **همه چیز** یک `object` است، که کلاس‌ها و همچنین نمونه‌هاشون (یا همان instance های کلاس‌ها) هم شامل این موضوع میشن. -- کلاس `type` یک متاکلاسه برای کلاس `object` و همه کلاس‌ها (همچنین کلاس `type`) به صورت مستقیم یا غیرمستقیم از کلاس `object` ارث بری کرده است. -- هیچ کلاس پایه واقعی بین کلاس‌های `object` و `type` وجود نداره. سردرگمی که در قطعه‌کدهای بالا به وجود اومده، به خاطر اینه که ما به این روابط (یعنی `issubclass` و `isinstance`) از دیدگاه کلاس‌های پایتون فکر می‌کنیم. رابطه بین `object` و `type` رو در پایتون خالص نمیشه بازتولید کرد. برای اینکه دقیق‌تر باشیم، رابطه‌های زیر در پایتون خالص نمی‌تونند بازتولید بشن. - + کلاس A یک نمونه از کلاس B، و کلاس B یک نمونه از کلاس A باشه. - + کلاس A یک نمونه از خودش باشه. -- -- این روابط بین `object` و `type` (که هردو نمونه یکدیگه و همچنین خودشون باشند) به خاطر "تقلب" در مرحله پیاده‌سازی، وجود دارند. - ---- - - -### ▶ روابط بین زیرمجموعه کلاس‌ها - -**خروجی:** -```py ->>> from collections.abc import Hashable ->>> issubclass(list, object) -True ->>> issubclass(object, Hashable) -True ->>> issubclass(list, Hashable) -False -``` - -ما انتظار داشتیم که روابط بین زیرکلاس‌ها، انتقالی باشند، درسته؟ (یعنی اگه `A` زیرکلاس `B` باشه و `B` هم زیرکلاس `C` باشه، کلس `A` __باید__ زیرکلاس `C` باشه) - -#### 💡 توضیحات: - -* روابط بین زیرکلاس‌ها در پایتون لزوما انتقالی نیستند. همه مجازند که تابع `__subclasscheck__` دلخواه خودشون رو در یک متاکلاس تعریف کنند. -* وقتی عبارت `issubclass(cls, Hashable)` اجرا میشه، برنامه دنبال یک تابع "غیر نادرست" (یا non-Falsy) در `cls` یا هرچیزی که ازش ارث‌بری می‌کنه، می‌گرده. -* از اونجایی که `object` قابل هش شدنه، ولی `list` این‌طور نیست، رابطه انتقالی شکسته میشه. -* توضیحات با جزئیات بیشتر [اینجا](https://www.naftaliharris.com/blog/python-subclass-intransitivity/) پیدا میشه. - ---- From 2fe5f3d07fa4bfe31afee0b67e4a8e98abf95bac Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sat, 5 Apr 2025 21:02:23 +0200 Subject: [PATCH 191/210] Remove explanations from ToC --- translations/fa-farsi/README.md | 63 --------------------------------- 1 file changed, 63 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 2dbaa0ca..65a23702 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -45,134 +45,71 @@ - [👀 مثال‌ها](#-مثالها) - [بخش: ذهن خود را به چالش بکشید!](#بخش-ذهن-خود-را-به-چالش-بکشید) - [▶ اول از همه! \*](#-اول-از-همه-) - - [💡 توضیحات](#-توضیحات) - [▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند](#-بعضی-وقتها-رشتهها-میتوانند-دردسرساز-شوند) - - [💡 توضیح:](#-توضیح) - [▶ مراقب عملیات‌های زنجیره‌ای باشید](#-مراقب-عملیاتهای-زنجیرهای-باشید) - - [💡 توضیحات:](#-توضیحات-1) - [▶ چطور از عملگر `is` استفاده نکنیم](#-چطور-از-عملگر-is-استفاده-نکنیم) - - [💡 توضیحات:](#-توضیحات-2) - [▶ کلیدهای هش](#-کلیدهای-هش) - - [💡 توضیحات](#-توضیحات-3) - [▶ در عمق وجود همه ما یکسان هستیم](#-در-عمق-وجود-همه-ما-یکسان-هستیم) - - [💡 توضیحات:](#-توضیحات-4) - [▶ بی‌نظمی در خود نظم \*](#-بینظمی-در-خود-نظم-) - - [💡 توضیحات:](#-توضیحات-5) - [▶ تلاش کن... \*](#-تلاش-کن-) - - [💡 توضیحات:](#-توضیحات-6) - [▶ برای چی؟](#-برای-چی) - - [💡 توضیحات:](#-توضیحات-7) - [▶ اختلاف زمانی در محاسبه](#-اختلاف-زمانی-در-محاسبه) - - [💡 توضیحات](#-توضیحات-8) - [▶ هر گردی، گردو نیست](#-هر-گردی-گردو-نیست) - - [💡 توضیحات](#-توضیحات-9) - [▶ یک بازی دوز که توش X همون اول برنده میشه!](#-یک-بازی-دوز-که-توش-X-همون-اول-برنده-میشه) - - [💡 توضیحات:](#-توضیحات-10) - [▶ متغیر شرودینگر \*](#-متغیر-شرودینگر-) - - [💡 توضیحات:](#-توضیحات-11) - [▶ اول مرغ بوده یا تخم مرغ؟ \*](#-اول-مرغ-بوده-یا-تخم-مرغ-) - - [💡 توضیحات](#-توضیحات-12) - [▶ روابط بین زیرمجموعه کلاس‌ها](#-روابط-بین-زیرمجموعه-کلاسها) - - [💡 توضیحات:](#-توضیحات-13) - [▶ ‫ برابری و هویت متدها](#--برابری-و-هویت-متدها) - - [💡 ‫ توضیحات](#--توضیحات) - [▶ ‫ آل-ترو-یشن \*](#--آل-ترو-یشن-) - - [💡 Explanation:](#-explanation-14) - - [💡 ‫ توضیح:](#--توضیح) - [▶ ‫ رشته‌ها و بک‌اسلش‌ها](#--رشتهها-و-بکاسلشها) - - [💡 ‫ توضیح:](#--توضیح-1) - [▶ ‫ گره نیست، نَه!](#--گره-نیست-نَه) - - [💡 Explanation:](#-explanation-15) - [▶ رشته‌های نیمه سه‌نقل‌قولی](#-رشتههای-نیمه-سهنقلقولی) - - [💡 ‫ توضیح:](#--توضیح-2) - [▶ ‫ مشکل بولین ها چیست؟](#--مشکل-بولین-ها-چیست) - - [💡 ‫ توضیحات:](#--توضیحات-1) - [▶ ‫ ویژگی‌های کلاس و ویژگی‌های نمونه](#--ویژگیهای-کلاس-و-ویژگیهای-نمونه) - - [💡 ‫ توضیح:](#--توضیح-3) - [▶ yielding None](#-yielding-none) - - [💡 Explanation:](#-explanation-16) - [▶ Yielding from... return! \*](#-yielding-from-return-) - - [💡 ‫ توضیح:](#--توضیح-4) - [▶ ‫ بازتاب‌ناپذیری \*](#--بازتابناپذیری-) - - [💡 توضیحات:](#-توضیحات-1) - [▶ ‫ تغییر دادن اشیای تغییرناپذیر!](#--تغییر-دادن-اشیای-تغییرناپذیر) - - [💡 ‫ توضیحات:](#--توضیحات-2) - [▶ ‫ متغیری که از اسکوپ بیرونی ناپدید می‌شود](#--متغیری-که-از-اسکوپ-بیرونی-ناپدید-میشود) - - [💡 ‫ توضیحات:](#--توضیحات-3) - [▶ ‫ تبدیل اسرارآمیز نوع کلید](#--تبدیل-اسرارآمیز-نوع-کلید) - - [💡 ‫ توضیحات:](#--توضیحات-4) - [▶ ‫ ببینیم می‌توانید این را حدس بزنید؟](#--ببینیم-میتوانید-این-را-حدس-بزنید) - - [💡 ‫ توضیح:](#--توضیح-5) - [▶ ‫ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود](#--از-حد-مجاز-برای-تبدیل-رشته-به-عدد-صحیح-فراتر-میرود) - - [💡 ‫ توضیح:](#--توضیح-6) - [‫ بخش: شیب‌های لغزنده](#-بخش-شیبهای-لغزنده) - [▶ ‫ تغییر یک دیکشنری هنگام پیمایش روی آن](#--تغییر-یک-دیکشنری-هنگام-پیمایش-روی-آن) - - [‫ 💡 توضیح:](#--توضیح-7) - [▶ عملیات سرسختانه‌ی `del`](#-عملیات-سرسختانهی-del) - - [‫ 💡 توضیح:](#--توضیح-8) - [▶ ‫ متغیری که از حوزه خارج است](#--متغیری-که-از-حوزه-خارج-است) - - [‫ 💡 توضیح:](#--توضیح-9) - [▶ ‫ حذف المان‌های لیست در حین پیمایش](#--حذف-المانهای-لیست-در-حین-پیمایش) - - [💡 Explanation:](#-explanation-17) - [▶ ‫ زیپِ دارای اتلاف برای پیمایشگرها \*](#--زیپِ-دارای-اتلاف-برای-پیمایشگرها-) - - [‫ 💡 توضیحات:](#--توضیحات-5) - [▶ ‫ نشت کردن متغیرهای حلقه!](#--نشت-کردن-متغیرهای-حلقه) - - [💡 ‫ توضیحات:](#--توضیحات-6) - [▶ ‫ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید!](#--مراقب-آرگومانهای-تغییرپذیر-پیشفرض-باشید) - - [💡 ‫ توضیحات:](#--توضیحات-7) - [▶ ‫ گرفتن استثناها (Exceptions)](#--گرفتن-استثناها-exceptions) - - [💡 ‫ توضیحات](#--توضیحات-8) - [▶ ‫ عملوندهای یکسان، داستانی متفاوت!](#--عملوندهای-یکسان-داستانی-متفاوت) - - [💡 ‫ توضیحات:](#--توضیحات-9) - [▶ ‫ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس](#--تفکیک-نامها-با-نادیده-گرفتن-حوزهی-کلاس) - - [💡 ‫ توضیحات](#--توضیحات-10) - [▶ ‫ گرد کردن به روش بانکدار \*](#--گرد-کردن-به-روش-بانکدار-) - - [💡 ‫ توضیحات:](#--توضیحات-11) - [▶ ‫ سوزن‌هایی در انبار کاه \*](#--سوزنهایی-در-انبار-کاه-) - - [💡 ‫ توضیحات:](#--توضیحات-12) - [▶ ‫ تقسیم‌ها \*](#--تقسیمها-) - - [💡 ‫ توضیحات:](#--توضیحات-13) - [▶ واردسازی‌های عمومی \*](#-واردسازیهای-عمومی-) - - [💡 ‫ توضیحات:](#--توضیحات-14) - [▶ ‫ همه چیز مرتب شده؟ \*](#--همه-چیز-مرتب-شده-) - - [💡 ‫ توضیحات:](#--توضیحات-15) - [▶ ‫ زمان نیمه‌شب وجود ندارد؟](#--زمان-نیمهشب-وجود-ندارد) - - [💡 ‫ توضیحات:](#--توضیحات-16) - [‫ بخش: گنجینه‌های پنهان!](#-بخش-گنجینههای-پنهان) - [▶ ‫ خب پایتون، می‌توانی کاری کنی پرواز کنم؟](#--خب-پایتون-میتوانی-کاری-کنی-پرواز-کنم) - - [‫ 💡 توضیح:](#--توضیح-10) - [▶ ‫ `goto`، ولی چرا؟](#--goto-ولی-چرا) - - [‫ 💡 توضیح:](#--توضیح-11) - [▶ ‫ خودتان را آماده کنید!](#--خودتان-را-آماده-کنید) - - [‫ 💡 توضیح:](#--توضیح-12) - [▶ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم](#--بیایید-با-عمو-زبان-مهربان-برای-همیشه-آشنا-شویم) - - [‫ 💡 توضیح:](#--توضیح-13) - [▶ ‫ حتی پایتون هم می‌داند که عشق پیچیده است](#--حتی-پایتون-هم-میداند-که-عشق-پیچیده-است) - - [‫ 💡 توضیح:](#--توضیح-14) - [▶ ‫ بله، این واقعاً وجود دارد!](#--بله-این-واقعاً-وجود-دارد) - - [‫ 💡 توضیح:](#--توضیح-15) - [▶ Ellipsis \*](#-ellipsis-) - - [‫ 💡توضیح](#-توضیح) - [▶ ‫ بی‌نهایت (`Inpinity`)](#--بینهایت-inpinity) - - [‫ 💡 توضیح:](#--توضیح-16) - [▶ ‫ بیایید خرابکاری کنیم](#--بیایید-خرابکاری-کنیم) - - [‫ 💡 توضیح:](#--توضیح-17) - [‫ بخش: ظاهرها فریبنده‌اند!](#-بخش-ظاهرها-فریبندهاند) - [▶ ‫ خطوط را رد می‌کند؟](#--خطوط-را-رد-میکند) - - [‫ 💡 توضیح](#--توضیح-18) - [▶ ‫ تله‌پورت کردن](#--تلهپورت-کردن) - - [‫ 💡 توضیح:](#--توضیح-19) - [▶ ‫ خب، یک جای کار مشکوک است...](#--خب-یک-جای-کار-مشکوک-است) - - [‫ 💡 توضیح](#--توضیح-20) - [بخش: متفرقه](#بخش-متفرقه) - [‫ ▶ `+=` سریع‌تر است](#---سریعتر-است) - - [‫ 💡 توضیح:](#---توضیح) - [‫ ▶ بیایید یک رشته‌ی بزرگ بسازیم!](#--بیایید-یک-رشتهی-بزرگ-بسازیم) - - [💡 توضیحات](#-توضیحات-2) - [▶ ‫ کُند کردن جستجوها در `dict` \*](#---کُند-کردن-جستجوها-در-dict-) - - [‫ 💡 توضیح:](#---توضیح-1) - [‫ ▶ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#--حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) - - [💡 توضیح:](#-توضیح-1) - [‫ ▶ موارد جزئی \*](#---موارد-جزئی-) - [‫ مشارکت](#-مشارکت) - [‫ تقدیر و تشکر](#-تقدیر-و-تشکر) From ec35d8ec141159f31a95b503454bbb7b1b776034 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sat, 5 Apr 2025 21:04:37 +0200 Subject: [PATCH 192/210] Remove RTL char --- translations/fa-farsi/README.md | 862 ++++++++++++++++---------------- 1 file changed, 431 insertions(+), 431 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 65a23702..376bd74a 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -1181,7 +1181,7 @@ False --- -### ▶ ‫ برابری و هویت متدها +### ▶ برابری و هویت متدها 1. @@ -1199,7 +1199,7 @@ class SomeClass: pass ``` -‫ **خروجی:** +**خروجی:** ```py >>> print(SomeClass.method is SomeClass.method) True @@ -1211,8 +1211,8 @@ True True ``` -‫ با دوبار دسترسی به `classm`، یک شیء برابر دریافت می‌کنیم، اما *همان* شیء نیست؟ بیایید ببینیم -‫ چه اتفاقی برای نمونه‌های `SomeClass` می‌افتد: +با دوبار دسترسی به `classm`، یک شیء برابر دریافت می‌کنیم، اما *همان* شیء نیست؟ بیایید ببینیم +چه اتفاقی برای نمونه‌های `SomeClass` می‌افتد: 2. ```py @@ -1220,7 +1220,7 @@ o1 = SomeClass() o2 = SomeClass() ``` -‫ **خروجی:** +**خروجی:** ```py >>> print(o1.method == o2.method) False @@ -1236,41 +1236,41 @@ True True ``` -‫ دسترسی به `classm` یا `method` دو بار، اشیایی برابر اما نه *یکسان* را برای همان نمونه از `SomeClass` ایجاد می‌کند. +دسترسی به `classm` یا `method` دو بار، اشیایی برابر اما نه *یکسان* را برای همان نمونه از `SomeClass` ایجاد می‌کند. -#### 💡 ‫ توضیحات -* ‫ تابع‌ها [وصاف](https://docs.python.org/3/howto/descriptor.html) هستند. هر زمان که تابعی به عنوان یک ویژگی فراخوانی شود، وصف فعال می‌شود و یک شیء متد ایجاد می‌کند که تابع را به شیء صاحب آن ویژگی "متصل" می‌کند. اگر این متد فراخوانی شود، تابع را با ارسال ضمنی شیء متصل‌شده به عنوان اولین آرگومان صدا می‌زند (به این ترتیب است که `self` را به عنوان اولین آرگومان دریافت می‌کنیم، با وجود اینکه آن را به‌طور صریح ارسال نکرده‌ایم). +#### 💡 توضیحات +* تابع‌ها [وصاف](https://docs.python.org/3/howto/descriptor.html) هستند. هر زمان که تابعی به عنوان یک ویژگی فراخوانی شود، وصف فعال می‌شود و یک شیء متد ایجاد می‌کند که تابع را به شیء صاحب آن ویژگی "متصل" می‌کند. اگر این متد فراخوانی شود، تابع را با ارسال ضمنی شیء متصل‌شده به عنوان اولین آرگومان صدا می‌زند (به این ترتیب است که `self` را به عنوان اولین آرگومان دریافت می‌کنیم، با وجود اینکه آن را به‌طور صریح ارسال نکرده‌ایم). ```py >>> o1.method > ``` -* ‫ دسترسی به ویژگی چندین بار، هر بار یک شیء متد جدید ایجاد می‌کند! بنابراین عبارت `o1.method is o1.method` هرگز درست (truthy) نیست. با این حال، دسترسی به تابع‌ها به عنوان ویژگی‌های کلاس (و نه نمونه) متد ایجاد نمی‌کند؛ بنابراین عبارت `SomeClass.method is SomeClass.method` درست است. +* دسترسی به ویژگی چندین بار، هر بار یک شیء متد جدید ایجاد می‌کند! بنابراین عبارت `o1.method is o1.method` هرگز درست (truthy) نیست. با این حال، دسترسی به تابع‌ها به عنوان ویژگی‌های کلاس (و نه نمونه) متد ایجاد نمی‌کند؛ بنابراین عبارت `SomeClass.method is SomeClass.method` درست است. ```py >>> SomeClass.method ``` -* ‫ `classmethod` توابع را به متدهای کلاس تبدیل می‌کند. متدهای کلاس وصاف‌هایی هستند که هنگام دسترسی، یک شیء متد ایجاد می‌کنند که به *کلاس* (نوع) شیء متصل می‌شود، نه خود شیء. +* `classmethod` توابع را به متدهای کلاس تبدیل می‌کند. متدهای کلاس وصاف‌هایی هستند که هنگام دسترسی، یک شیء متد ایجاد می‌کنند که به *کلاس* (نوع) شیء متصل می‌شود، نه خود شیء. ```py >>> o1.classm > ``` -* ‫ برخلاف توابع، `classmethod`‌ها هنگام دسترسی به عنوان ویژگی‌های کلاس نیز یک شیء متد ایجاد می‌کنند (که در این حالت به خود کلاس متصل می‌شوند، نه نوع آن). بنابراین عبارت `SomeClass.classm is SomeClass.classm` نادرست (falsy) است. +* برخلاف توابع، `classmethod`‌ها هنگام دسترسی به عنوان ویژگی‌های کلاس نیز یک شیء متد ایجاد می‌کنند (که در این حالت به خود کلاس متصل می‌شوند، نه نوع آن). بنابراین عبارت `SomeClass.classm is SomeClass.classm` نادرست (falsy) است. ```py >>> SomeClass.classm > ``` -* ‫ یک شیء متد زمانی برابر در نظر گرفته می‌شود که هم تابع‌ها برابر باشند و هم شیءهای متصل‌شده یکسان باشند. بنابراین عبارت `o1.method == o1.method` درست (truthy) است، هرچند که آن‌ها در حافظه شیء یکسانی نیستند. -* ‫ `staticmethod` توابع را به یک وصف "بدون عملیات" (no-op) تبدیل می‌کند که تابع را به همان صورت بازمی‌گرداند. هیچ شیء متدی ایجاد نمی‌شود، بنابراین مقایسه با `is` نیز درست (truthy) است. +* یک شیء متد زمانی برابر در نظر گرفته می‌شود که هم تابع‌ها برابر باشند و هم شیءهای متصل‌شده یکسان باشند. بنابراین عبارت `o1.method == o1.method` درست (truthy) است، هرچند که آن‌ها در حافظه شیء یکسانی نیستند. +* `staticmethod` توابع را به یک وصف "بدون عملیات" (no-op) تبدیل می‌کند که تابع را به همان صورت بازمی‌گرداند. هیچ شیء متدی ایجاد نمی‌شود، بنابراین مقایسه با `is` نیز درست (truthy) است. ```py >>> o1.staticm >>> SomeClass.staticm ``` -* ‫ ایجاد شیءهای "متد" جدید در هر بار فراخوانی متدهای نمونه و نیاز به اصلاح آرگومان‌ها برای درج `self`، عملکرد را به شدت تحت تأثیر قرار می‌داد. +* ایجاد شیءهای "متد" جدید در هر بار فراخوانی متدهای نمونه و نیاز به اصلاح آرگومان‌ها برای درج `self`، عملکرد را به شدت تحت تأثیر قرار می‌داد. CPython 3.7 [این مشکل را حل کرد](https://bugs.python.org/issue26110) با معرفی opcodeهای جدیدی که فراخوانی متدها را بدون ایجاد شیء متد موقتی مدیریت می‌کنند. این به شرطی است که تابع دسترسی‌یافته واقعاً فراخوانی شود، بنابراین قطعه‌کدهای اینجا تحت تأثیر قرار نمی‌گیرند و همچنان متد ایجاد می‌کنند :) -### ▶ ‫ آل-ترو-یشن * +### ▶ آل-ترو-یشن * @@ -1288,11 +1288,11 @@ False True ``` -‫ چرا این تغییر درست-نادرسته؟ +چرا این تغییر درست-نادرسته؟ #### 💡 Explanation: -- ‫ پیاده‌سازی تابع `all` معادل است با +- پیاده‌سازی تابع `all` معادل است با - ```py def all(iterable): @@ -1302,15 +1302,15 @@ True return True ``` -- ‫ `all([])` مقدار `True` را برمی‌گرداند چون iterable خالی است. -- ‫ `all([[]])` مقدار `False` را برمی‌گرداند چون آرایه‌ی داده‌شده یک عنصر دارد، یعنی `[]`، و در پایتون، لیست خالی مقدار falsy دارد. -- ‫ `all([[[]]])` و نسخه‌های بازگشتی بالاتر همیشه `True` هستند. دلیلش این است که عنصر واحد آرایه‌ی داده‌شده (`[[...]]`) دیگر خالی نیست، و لیست‌هایی که دارای مقدار باشند، truthy در نظر گرفته می‌شوند. +- `all([])` مقدار `True` را برمی‌گرداند چون iterable خالی است. +- `all([[]])` مقدار `False` را برمی‌گرداند چون آرایه‌ی داده‌شده یک عنصر دارد، یعنی `[]`، و در پایتون، لیست خالی مقدار falsy دارد. +- `all([[[]]])` و نسخه‌های بازگشتی بالاتر همیشه `True` هستند. دلیلش این است که عنصر واحد آرایه‌ی داده‌شده (`[[...]]`) دیگر خالی نیست، و لیست‌هایی که دارای مقدار باشند، truthy در نظر گرفته می‌شوند. --- -### ▶ ‫ کاما‌ی شگفت‌انگیز +### ▶ کاما‌ی شگفت‌انگیز -‫ **خروجی (< 3.6):** +**خروجی (< 3.6):** ```py >>> def f(x, y,): @@ -1332,17 +1332,17 @@ SyntaxError: invalid syntax SyntaxError: invalid syntax ``` -#### 💡 ‫ توضیح: +#### 💡 توضیح: -- ‫ کامای انتهایی همیشه در لیست پارامترهای رسمی یک تابع در پایتون قانونی نیست. -- ‫ در پایتون، لیست آرگومان‌ها تا حدی با کاماهای ابتدایی و تا حدی با کاماهای انتهایی تعریف می‌شود. این تضاد باعث ایجاد موقعیت‌هایی می‌شود که در آن یک کاما در وسط گیر می‌افتد و هیچ قانونی آن را نمی‌پذیرد. -- ‫ **نکته:** مشکل کامای انتهایی در [پایتون ۳.۶ رفع شده است](https://bugs.python.org/issue9232). توضیحات در [این پست](https://bugs.python.org/issue9232#msg248399) به‌طور خلاصه کاربردهای مختلف کاماهای انتهایی در پایتون را بررسی می‌کند. +- کامای انتهایی همیشه در لیست پارامترهای رسمی یک تابع در پایتون قانونی نیست. +- در پایتون، لیست آرگومان‌ها تا حدی با کاماهای ابتدایی و تا حدی با کاماهای انتهایی تعریف می‌شود. این تضاد باعث ایجاد موقعیت‌هایی می‌شود که در آن یک کاما در وسط گیر می‌افتد و هیچ قانونی آن را نمی‌پذیرد. +- **نکته:** مشکل کامای انتهایی در [پایتون ۳.۶ رفع شده است](https://bugs.python.org/issue9232). توضیحات در [این پست](https://bugs.python.org/issue9232#msg248399) به‌طور خلاصه کاربردهای مختلف کاماهای انتهایی در پایتون را بررسی می‌کند. --- -### ▶ ‫ رشته‌ها و بک‌اسلش‌ها +### ▶ رشته‌ها و بک‌اسلش‌ها -‫ **خروجی:** +**خروجی:** ```py >>> print("\"") " @@ -1360,14 +1360,14 @@ SyntaxError: EOL while scanning string literal True ``` -#### 💡 ‫ توضیح: +#### 💡 توضیح: -- ‫ در یک رشته‌ی معمولی در پایتون، بک‌اسلش برای فرار دادن (escape) نویسه‌هایی استفاده می‌شود که ممکن است معنای خاصی داشته باشند (مانند تک‌نقل‌قول، دوتا‌نقل‌قول، و خودِ بک‌اسلش). +- در یک رشته‌ی معمولی در پایتون، بک‌اسلش برای فرار دادن (escape) نویسه‌هایی استفاده می‌شود که ممکن است معنای خاصی داشته باشند (مانند تک‌نقل‌قول، دوتا‌نقل‌قول، و خودِ بک‌اسلش). ```py >>> "wt\"f" 'wt"f' ``` -- ‫ در یک رشته‌ی خام (raw string literal) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان شکل منتقل می‌شوند، به‌همراه رفتار فرار دادن نویسه‌ی بعدی. +- در یک رشته‌ی خام (raw string literal) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان شکل منتقل می‌شوند، به‌همراه رفتار فرار دادن نویسه‌ی بعدی. ```py >>> r'wt\"f' == 'wt\\"f' True @@ -1379,18 +1379,18 @@ True >>> print(r"\\n") '\\n' ``` -- ‫ در یک رشته‌ی خام (raw string) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان صورت منتقل می‌شوند، همراه با رفتاری که کاراکتر بعدی را فرار می‌دهد (escape می‌کند). +- در یک رشته‌ی خام (raw string) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان صورت منتقل می‌شوند، همراه با رفتاری که کاراکتر بعدی را فرار می‌دهد (escape می‌کند). --- -### ▶ ‫ گره نیست، نَه! +### ▶ گره نیست، نَه! ```py x = True y = False ``` -‫ **خروجی:** +**خروجی:** ```py >>> not x == y True @@ -1403,16 +1403,16 @@ SyntaxError: invalid syntax #### 💡 Explanation: -* ‫ تقدم عملگرها بر نحوه‌ی ارزیابی یک عبارت تأثیر می‌گذارد، و در پایتون، عملگر `==` تقدم بالاتری نسبت به عملگر `not` دارد. -* ‫ بنابراین عبارت `not x == y` معادل `not (x == y)` است که خودش معادل `not (True == False)` بوده و در نهایت به `True` ارزیابی می‌شود. -* ‫ اما `x == not y` یک `SyntaxError` ایجاد می‌کند، چون می‌توان آن را به صورت `(x == not) y` تفسیر کرد، نه آن‌طور که در نگاه اول انتظار می‌رود یعنی `x == (not y)`. -* ‫ تجزیه‌گر (parser) انتظار دارد که توکن `not` بخشی از عملگر `not in` باشد (چون هر دو عملگر `==` و `not in` تقدم یکسانی دارند)، اما پس از اینکه توکن `in` بعد از `not` پیدا نمی‌شود، خطای `SyntaxError` صادر می‌شود. +* تقدم عملگرها بر نحوه‌ی ارزیابی یک عبارت تأثیر می‌گذارد، و در پایتون، عملگر `==` تقدم بالاتری نسبت به عملگر `not` دارد. +* بنابراین عبارت `not x == y` معادل `not (x == y)` است که خودش معادل `not (True == False)` بوده و در نهایت به `True` ارزیابی می‌شود. +* اما `x == not y` یک `SyntaxError` ایجاد می‌کند، چون می‌توان آن را به صورت `(x == not) y` تفسیر کرد، نه آن‌طور که در نگاه اول انتظار می‌رود یعنی `x == (not y)`. +* تجزیه‌گر (parser) انتظار دارد که توکن `not` بخشی از عملگر `not in` باشد (چون هر دو عملگر `==` و `not in` تقدم یکسانی دارند)، اما پس از اینکه توکن `in` بعد از `not` پیدا نمی‌شود، خطای `SyntaxError` صادر می‌شود. --- ### ▶ رشته‌های نیمه سه‌نقل‌قولی -‫ **خروجی:** +**خروجی:** ```py >>> print('wtfpython''') wtfpython @@ -1427,19 +1427,19 @@ wtfpython SyntaxError: EOF while scanning triple-quoted string literal ``` -#### 💡 ‫ توضیح: -+ ‫ پایتون از الحاق ضمنی [رشته‌های متنی](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation) پشتیبانی می‌کند. برای مثال، +#### 💡 توضیح: ++ پایتون از الحاق ضمنی [رشته‌های متنی](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation) پشتیبانی می‌کند. برای مثال، ``` >>> print("wtf" "python") wtfpython >>> print("wtf" "") # or "wtf""" wtf ``` -+ ‫ `'''` و `"""` نیز جداکننده‌های رشته‌ای در پایتون هستند که باعث ایجاد SyntaxError می‌شوند، چون مفسر پایتون هنگام اسکن رشته‌ای که با سه‌نقل‌قول آغاز شده، انتظار یک سه‌نقل‌قول پایانی به‌عنوان جداکننده را دارد. ++ `'''` و `"""` نیز جداکننده‌های رشته‌ای در پایتون هستند که باعث ایجاد SyntaxError می‌شوند، چون مفسر پایتون هنگام اسکن رشته‌ای که با سه‌نقل‌قول آغاز شده، انتظار یک سه‌نقل‌قول پایانی به‌عنوان جداکننده را دارد. --- -### ▶ ‫ مشکل بولین ها چیست؟ +### ▶ مشکل بولین ها چیست؟ 1\. @@ -1457,7 +1457,7 @@ for item in mixed_list: booleans_found_so_far += 1 ``` -‫ **خروجی:** +**خروجی:** ```py >>> integers_found_so_far 4 @@ -1485,7 +1485,7 @@ def tell_truth(): print("I have lost faith in truth!") ``` -‫ **خروجی (< 3.x):** +**خروجی (< 3.x):** ```py >>> tell_truth() @@ -1494,9 +1494,9 @@ I have lost faith in truth! -#### 💡 ‫ توضیحات: +#### 💡 توضیحات: -* ‫ در پایتون، `bool` زیرکلاسی از `int` است +* در پایتون، `bool` زیرکلاسی از `int` است ```py >>> issubclass(bool, int) @@ -1505,7 +1505,7 @@ I have lost faith in truth! False ``` -* ‫ و بنابراین، `True` و `False` نمونه‌هایی از `int` هستند +* و بنابراین، `True` و `False` نمونه‌هایی از `int` هستند ```py >>> isinstance(True, int) True @@ -1513,7 +1513,7 @@ I have lost faith in truth! True ``` -* ‫ مقدار عددی `True` برابر با `1` و مقدار عددی `False` برابر با `0` است. +* مقدار عددی `True` برابر با `1` و مقدار عددی `False` برابر با `0` است. ```py >>> int(True) 1 @@ -1521,15 +1521,15 @@ I have lost faith in truth! 0 ``` -* ‫ این پاسخ در StackOverflow را ببینید: [answer](https://stackoverflow.com/a/8169049/4354153) برای توضیح منطقی پشت این موضوع. +* این پاسخ در StackOverflow را ببینید: [answer](https://stackoverflow.com/a/8169049/4354153) برای توضیح منطقی پشت این موضوع. -* ‫ در ابتدا، پایتون نوع `bool` نداشت (کاربران از 0 برای false و مقادیر غیر صفر مثل 1 برای true استفاده می‌کردند). `True`، `False` و نوع `bool` در نسخه‌های 2.x اضافه شدند، اما برای سازگاری با نسخه‌های قبلی، `True` و `False` نمی‌توانستند به عنوان ثابت تعریف شوند. آن‌ها فقط متغیرهای توکار (built-in) بودند و امکان تغییر مقدارشان وجود داشت. +* در ابتدا، پایتون نوع `bool` نداشت (کاربران از 0 برای false و مقادیر غیر صفر مثل 1 برای true استفاده می‌کردند). `True`، `False` و نوع `bool` در نسخه‌های 2.x اضافه شدند، اما برای سازگاری با نسخه‌های قبلی، `True` و `False` نمی‌توانستند به عنوان ثابت تعریف شوند. آن‌ها فقط متغیرهای توکار (built-in) بودند و امکان تغییر مقدارشان وجود داشت. -* ‫ پایتون ۳ با نسخه‌های قبلی ناسازگار بود، این مشکل سرانجام رفع شد، و بنابراین قطعه‌کد آخر در نسخه‌های Python 3.x کار نخواهد کرد! +* پایتون ۳ با نسخه‌های قبلی ناسازگار بود، این مشکل سرانجام رفع شد، و بنابراین قطعه‌کد آخر در نسخه‌های Python 3.x کار نخواهد کرد! --- -### ▶ ‫ ویژگی‌های کلاس و ویژگی‌های نمونه +### ▶ ویژگی‌های کلاس و ویژگی‌های نمونه 1\. ```py @@ -1573,7 +1573,7 @@ class SomeClass: self.another_list += [x] ``` -‫ **خروجی:** +**خروجی:** ```py >>> some_obj = SomeClass(420) @@ -1592,10 +1592,10 @@ True True ``` -#### 💡 ‫ توضیح: +#### 💡 توضیح: -* ‫ متغیرهای کلاس و متغیرهای نمونه‌های کلاس درونی به‌صورت دیکشنری‌هایی از شیء کلاس مدیریت می‌شوند. اگر نام متغیری در دیکشنری کلاس جاری پیدا نشود، کلاس‌های والد برای آن جست‌وجو می‌شوند. -* ‫ عملگر `+=` شیء قابل‌تغییر (mutable) را به‌صورت درجا (in-place) تغییر می‌دهد بدون اینکه شیء جدیدی ایجاد کند. بنابراین، تغییر ویژگی یک نمونه بر نمونه‌های دیگر و همچنین ویژگی کلاس تأثیر می‌گذارد. +* متغیرهای کلاس و متغیرهای نمونه‌های کلاس درونی به‌صورت دیکشنری‌هایی از شیء کلاس مدیریت می‌شوند. اگر نام متغیری در دیکشنری کلاس جاری پیدا نشود، کلاس‌های والد برای آن جست‌وجو می‌شوند. +* عملگر `+=` شیء قابل‌تغییر (mutable) را به‌صورت درجا (in-place) تغییر می‌دهد بدون اینکه شیء جدیدی ایجاد کند. بنابراین، تغییر ویژگی یک نمونه بر نمونه‌های دیگر و همچنین ویژگی کلاس تأثیر می‌گذارد. --- @@ -1645,14 +1645,14 @@ def some_func(x): yield from range(x) ``` -‫ **خروجی (> 3.3):** +**خروجی (> 3.3):** ```py >>> list(some_func(3)) [] ``` -‫ چی شد که `"wtf"` ناپدید شد؟ آیا به خاطر اثر خاصی از `yield from` است؟ بیایید این موضوع را بررسی کنیم، +چی شد که `"wtf"` ناپدید شد؟ آیا به خاطر اثر خاصی از `yield from` است؟ بیایید این موضوع را بررسی کنیم، 2\. @@ -1665,24 +1665,24 @@ def some_func(x): yield i ``` -‫ **خروجی:** +**خروجی:** ```py >>> list(some_func(3)) [] ``` -‫ همان نتیجه، این یکی هم کار نکرد. +همان نتیجه، این یکی هم کار نکرد. -#### 💡 ‫ توضیح: +#### 💡 توضیح: -+ ‫ از پایتون نسخه ۳.۳ به بعد، امکان استفاده از عبارت `return` همراه با مقدار در داخل ژنراتورها فراهم شد (نگاه کنید به [PEP380](https://www.python.org/dev/peps/pep-0380/)). [مستندات رسمی](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) می‌گویند: ++ از پایتون نسخه ۳.۳ به بعد، امکان استفاده از عبارت `return` همراه با مقدار در داخل ژنراتورها فراهم شد (نگاه کنید به [PEP380](https://www.python.org/dev/peps/pep-0380/)). [مستندات رسمی](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) می‌گویند: -> ‫ "... `return expr` در یک ژنراتور باعث می‌شود که هنگام خروج از ژنراتور، `StopIteration(expr)` ایجاد شود." +> "... `return expr` در یک ژنراتور باعث می‌شود که هنگام خروج از ژنراتور، `StopIteration(expr)` ایجاد شود." -+ ‫ در حالت `some_func(3)`، استثنای `StopIteration` در ابتدای اجرا به دلیل وجود دستور `return` رخ می‌دهد. این استثنا به‌طور خودکار درون پوشش `list(...)` و حلقه `for` گرفته می‌شود. بنابراین، دو قطعه‌کد بالا منجر به یک لیست خالی می‌شوند. ++ در حالت `some_func(3)`، استثنای `StopIteration` در ابتدای اجرا به دلیل وجود دستور `return` رخ می‌دهد. این استثنا به‌طور خودکار درون پوشش `list(...)` و حلقه `for` گرفته می‌شود. بنابراین، دو قطعه‌کد بالا منجر به یک لیست خالی می‌شوند. -+ ‫ برای اینکه مقدار `["wtf"]` را از ژنراتور `some_func` بگیریم، باید استثنای `StopIteration` را خودمان مدیریت کنیم، ++ برای اینکه مقدار `["wtf"]` را از ژنراتور `some_func` بگیریم، باید استثنای `StopIteration` را خودمان مدیریت کنیم، ```py try: @@ -1698,7 +1698,7 @@ def some_func(x): --- -### ▶ ‫ بازتاب‌ناپذیری * +### ▶ بازتاب‌ناپذیری * @@ -1711,7 +1711,7 @@ c = float('-iNf') # این رشته‌ها نسبت به حروف بزرگ و d = float('nan') ``` -‫ **خروجی:** +**خروجی:** ```py >>> a @@ -1753,9 +1753,9 @@ True #### 💡 توضیحات: -- ‫ `'inf'` و `'nan'` رشته‌هایی خاص هستند (نسبت به حروف بزرگ و کوچک حساس نیستند) که وقتی به‌طور صریح به نوع `float` تبدیل شوند، به ترتیب برای نمایش "بی‌نهایت" ریاضی و "عدد نیست" استفاده می‌شوند. +- `'inf'` و `'nan'` رشته‌هایی خاص هستند (نسبت به حروف بزرگ و کوچک حساس نیستند) که وقتی به‌طور صریح به نوع `float` تبدیل شوند، به ترتیب برای نمایش "بی‌نهایت" ریاضی و "عدد نیست" استفاده می‌شوند. -- ‫ از آنجا که طبق استاندارد IEEE، `NaN != NaN`، پایبندی به این قانون فرض بازتاب‌پذیری (reflexivity) یک عنصر در مجموعه‌ها را در پایتون نقض می‌کند؛ یعنی اگر `x` عضوی از مجموعه‌ای مثل `list` باشد، پیاده‌سازی‌هایی مانند مقایسه، بر اساس این فرض هستند که `x == x`. به دلیل همین فرض، ابتدا هویت (identity) دو عنصر مقایسه می‌شود (چون سریع‌تر است) و فقط زمانی مقادیر مقایسه می‌شوند که هویت‌ها متفاوت باشند. قطعه‌کد زیر موضوع را روشن‌تر می‌کند، +- از آنجا که طبق استاندارد IEEE، `NaN != NaN`، پایبندی به این قانون فرض بازتاب‌پذیری (reflexivity) یک عنصر در مجموعه‌ها را در پایتون نقض می‌کند؛ یعنی اگر `x` عضوی از مجموعه‌ای مثل `list` باشد، پیاده‌سازی‌هایی مانند مقایسه، بر اساس این فرض هستند که `x == x`. به دلیل همین فرض، ابتدا هویت (identity) دو عنصر مقایسه می‌شود (چون سریع‌تر است) و فقط زمانی مقادیر مقایسه می‌شوند که هویت‌ها متفاوت باشند. قطعه‌کد زیر موضوع را روشن‌تر می‌کند، ```py >>> x = float('nan') @@ -1768,24 +1768,24 @@ True (False, False) ``` - ‫ از آنجا که هویت‌های `x` و `y` متفاوت هستند، مقادیر آن‌ها در نظر گرفته می‌شوند که آن‌ها نیز متفاوت‌اند؛ بنابراین مقایسه این بار `False` را برمی‌گرداند. + از آنجا که هویت‌های `x` و `y` متفاوت هستند، مقادیر آن‌ها در نظر گرفته می‌شوند که آن‌ها نیز متفاوت‌اند؛ بنابراین مقایسه این بار `False` را برمی‌گرداند. -- ‫ خواندنی جالب: [بازتاب‌پذیری و دیگر ارکان تمدن](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) +- خواندنی جالب: [بازتاب‌پذیری و دیگر ارکان تمدن](https://bertrandmeyer.com/2010/02/06/reflexivity-and-other-pillars-of-civilization/) --- -### ▶ ‫ تغییر دادن اشیای تغییرناپذیر! +### ▶ تغییر دادن اشیای تغییرناپذیر! -‫ این موضوع ممکن است بدیهی به نظر برسد اگر با نحوه‌ی کار ارجاع‌ها در پایتون آشنا باشید. +این موضوع ممکن است بدیهی به نظر برسد اگر با نحوه‌ی کار ارجاع‌ها در پایتون آشنا باشید. ```py some_tuple = ("A", "tuple", "with", "values") another_tuple = ([1, 2], [3, 4], [5, 6]) ``` -‫ **خروجی:** +**خروجی:** ```py >>> some_tuple[2] = "change this" TypeError: 'tuple' object does not support item assignment @@ -1800,20 +1800,20 @@ TypeError: 'tuple' object does not support item assignment اما من فکر می‌کردم تاپل‌ها تغییرناپذیر هستند... -#### 💡 ‫ توضیحات: +#### 💡 توضیحات: -* ‫ نقل‌قول از https://docs.python.org/3/reference/datamodel.html +* نقل‌قول از https://docs.python.org/3/reference/datamodel.html - > ‫ دنباله‌های تغییرناپذیر - ‫ شیئی از نوع دنباله‌ی تغییرناپذیر، پس از ایجاد دیگر قابل تغییر نیست. (اگر شیء شامل ارجاع‌هایی به اشیای دیگر باشد، این اشیای دیگر ممکن است قابل تغییر باشند و تغییر کنند؛ اما مجموعه‌ی اشیایی که مستقیماً توسط یک شیء تغییرناپذیر ارجاع داده می‌شوند، نمی‌تواند تغییر کند.) + > دنباله‌های تغییرناپذیر + شیئی از نوع دنباله‌ی تغییرناپذیر، پس از ایجاد دیگر قابل تغییر نیست. (اگر شیء شامل ارجاع‌هایی به اشیای دیگر باشد، این اشیای دیگر ممکن است قابل تغییر باشند و تغییر کنند؛ اما مجموعه‌ی اشیایی که مستقیماً توسط یک شیء تغییرناپذیر ارجاع داده می‌شوند، نمی‌تواند تغییر کند.) -* ‫ عملگر `+=` لیست را به‌صورت درجا (in-place) تغییر می‌دهد. تخصیص به یک عضو کار نمی‌کند، اما زمانی که استثنا ایجاد می‌شود، عضو موردنظر پیش از آن به‌صورت درجا تغییر کرده است. -* ‫ همچنین توضیحی در [پرسش‌های متداول رسمی پایتون](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works) وجود دارد. +* عملگر `+=` لیست را به‌صورت درجا (in-place) تغییر می‌دهد. تخصیص به یک عضو کار نمی‌کند، اما زمانی که استثنا ایجاد می‌شود، عضو موردنظر پیش از آن به‌صورت درجا تغییر کرده است. +* همچنین توضیحی در [پرسش‌های متداول رسمی پایتون](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works) وجود دارد. --- -### ▶ ‫ متغیری که از اسکوپ بیرونی ناپدید می‌شود +### ▶ متغیری که از اسکوپ بیرونی ناپدید می‌شود ```py @@ -1827,7 +1827,7 @@ except Exception as e: **Output (Python 2.x):** ```py >>> print(e) -# ‫ چیزی چاپ نمی شود. +# چیزی چاپ نمی شود. ``` **Output (Python 3.x):** @@ -1836,17 +1836,17 @@ except Exception as e: NameError: name 'e' is not defined ``` -#### 💡 ‫ توضیحات: -* ‫ منبع: [مستندات رسمی پایتون](https://docs.python.org/3/reference/compound_stmts.html#except) +#### 💡 توضیحات: +* منبع: [مستندات رسمی پایتون](https://docs.python.org/3/reference/compound_stmts.html#except) -‫ هنگامی که یک استثنا (Exception) با استفاده از کلمه‌ی کلیدی `as` به متغیری تخصیص داده شود، این متغیر در انتهای بلاکِ `except` پاک می‌شود. این رفتار مشابه کد زیر است: +هنگامی که یک استثنا (Exception) با استفاده از کلمه‌ی کلیدی `as` به متغیری تخصیص داده شود، این متغیر در انتهای بلاکِ `except` پاک می‌شود. این رفتار مشابه کد زیر است: ```py except E as N: foo ``` - ‫ به این شکل ترجمه شده باشد: + به این شکل ترجمه شده باشد: ```py except E as N: @@ -1856,9 +1856,9 @@ NameError: name 'e' is not defined del N ``` -‫ این بدان معناست که استثنا باید به نام دیگری انتساب داده شود تا بتوان پس از پایان بند `except` به آن ارجاع داد. استثناها پاک می‌شوند چون با داشتن «ردیابی» (traceback) ضمیمه‌شده، یک چرخه‌ی مرجع (reference cycle) با قاب پشته (stack frame) تشکیل می‌دهند که باعث می‌شود تمام متغیرهای محلی (locals) در آن قاب تا زمان پاکسازی حافظه (garbage collection) باقی بمانند. +این بدان معناست که استثنا باید به نام دیگری انتساب داده شود تا بتوان پس از پایان بند `except` به آن ارجاع داد. استثناها پاک می‌شوند چون با داشتن «ردیابی» (traceback) ضمیمه‌شده، یک چرخه‌ی مرجع (reference cycle) با قاب پشته (stack frame) تشکیل می‌دهند که باعث می‌شود تمام متغیرهای محلی (locals) در آن قاب تا زمان پاکسازی حافظه (garbage collection) باقی بمانند. -* ‫ در پایتون، بندها (`clauses`) حوزه‌ی مستقل ندارند. در مثال بالا، همه‌چیز در یک حوزه‌ی واحد قرار دارد، و متغیر `e` در اثر اجرای بند `except` حذف می‌شود. این موضوع در مورد توابع صادق نیست، زیرا توابع حوزه‌های داخلی جداگانه‌ای دارند. مثال زیر این نکته را نشان می‌دهد: +* در پایتون، بندها (`clauses`) حوزه‌ی مستقل ندارند. در مثال بالا، همه‌چیز در یک حوزه‌ی واحد قرار دارد، و متغیر `e` در اثر اجرای بند `except` حذف می‌شود. این موضوع در مورد توابع صادق نیست، زیرا توابع حوزه‌های داخلی جداگانه‌ای دارند. مثال زیر این نکته را نشان می‌دهد: ```py @@ -1870,7 +1870,7 @@ NameError: name 'e' is not defined y = [5, 4, 3] ``` - ‫ **خروجی:** + **خروجی:** ```py >>> f(x) UnboundLocalError: local variable 'x' referenced before assignment @@ -1882,9 +1882,9 @@ NameError: name 'e' is not defined [5, 4, 3] ``` -* ‫ در پایتون نسخه‌ی ۲.x، نام متغیر `e` به یک نمونه از `Exception()` انتساب داده می‌شود، بنابراین وقتی سعی کنید آن را چاپ کنید، چیزی نمایش داده نمی‌شود. +* در پایتون نسخه‌ی ۲.x، نام متغیر `e` به یک نمونه از `Exception()` انتساب داده می‌شود، بنابراین وقتی سعی کنید آن را چاپ کنید، چیزی نمایش داده نمی‌شود. - ‫ **خروجی (Python 2.x):** + **خروجی (Python 2.x):** ```py >>> e Exception() @@ -1895,7 +1895,7 @@ NameError: name 'e' is not defined --- -### ▶ ‫ تبدیل اسرارآمیز نوع کلید +### ▶ تبدیل اسرارآمیز نوع کلید ```py class SomeClass(str): @@ -1904,7 +1904,7 @@ class SomeClass(str): some_dict = {'s': 42} ``` -‫ **خروجی:** +**خروجی:** ```py >>> type(list(some_dict.keys())[0]) str @@ -1916,12 +1916,12 @@ str str ``` -#### 💡 ‫ توضیحات: +#### 💡 توضیحات: -* ‫ هر دو شیء `s` و رشته‌ی `"s"` به دلیل ارث‌بری `SomeClass` از متد `__hash__` کلاس `str`، هش یکسانی دارند. -* ‫ عبارت `SomeClass("s") == "s"` به دلیل ارث‌بری `SomeClass` از متد `__eq__` کلاس `str` برابر با `True` ارزیابی می‌شود. -* ‫ از آنجا که این دو شیء هش یکسان و برابری دارند، به عنوان یک کلید مشترک در دیکشنری در نظر گرفته می‌شوند. -* ‫ برای رسیدن به رفتار دلخواه، می‌توانیم متد `__eq__` را در کلاس `SomeClass` بازتعریف کنیم. +* هر دو شیء `s` و رشته‌ی `"s"` به دلیل ارث‌بری `SomeClass` از متد `__hash__` کلاس `str`، هش یکسانی دارند. +* عبارت `SomeClass("s") == "s"` به دلیل ارث‌بری `SomeClass` از متد `__eq__` کلاس `str` برابر با `True` ارزیابی می‌شود. +* از آنجا که این دو شیء هش یکسان و برابری دارند، به عنوان یک کلید مشترک در دیکشنری در نظر گرفته می‌شوند. +* برای رسیدن به رفتار دلخواه، می‌توانیم متد `__eq__` را در کلاس `SomeClass` بازتعریف کنیم. ```py class SomeClass(str): def __eq__(self, other): @@ -1931,14 +1931,14 @@ str and super().__eq__(other) ) - # ‫ هنگامی که متد __eq__ را به‌طور دلخواه تعریف می‌کنیم، پایتون دیگر متد __hash__ را به صورت خودکار به ارث نمی‌برد، - # ‫ بنابراین باید متد __hash__ را نیز مجدداً تعریف کنیم. + # هنگامی که متد __eq__ را به‌طور دلخواه تعریف می‌کنیم، پایتون دیگر متد __hash__ را به صورت خودکار به ارث نمی‌برد، + # بنابراین باید متد __hash__ را نیز مجدداً تعریف کنیم. __hash__ = str.__hash__ some_dict = {'s':42} ``` - ‫ **خروجی:** + **خروجی:** ```py >>> s = SomeClass('s') >>> some_dict[s] = 40 @@ -1951,37 +1951,37 @@ str --- -### ▶ ‫ ببینیم می‌توانید این را حدس بزنید؟ +### ▶ ببینیم می‌توانید این را حدس بزنید؟ ```py a, b = a[b] = {}, 5 ``` -‫ **خروجی:** +**خروجی:** ```py >>> a {5: ({...}, 5)} ``` -#### 💡 ‫ توضیح: +#### 💡 توضیح: -* ‫ طبق [مرجع زبان پایتون](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)، دستورات انتساب فرم زیر را دارند: +* طبق [مرجع زبان پایتون](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)، دستورات انتساب فرم زیر را دارند: ``` (target_list "=")+ (expression_list | yield_expression) ``` و -> ‫ یک دستور انتساب ابتدا فهرست عبارت‌ها (expression list) را ارزیابی می‌کند (توجه کنید این عبارت می‌تواند یک عبارت تکی یا فهرستی از عبارت‌ها جداشده با ویرگول باشد که دومی به یک تاپل منجر می‌شود)، سپس شیء حاصل را به هریک از اهداف انتساب از **چپ به راست** تخصیص می‌دهد. +> یک دستور انتساب ابتدا فهرست عبارت‌ها (expression list) را ارزیابی می‌کند (توجه کنید این عبارت می‌تواند یک عبارت تکی یا فهرستی از عبارت‌ها جداشده با ویرگول باشد که دومی به یک تاپل منجر می‌شود)، سپس شیء حاصل را به هریک از اهداف انتساب از **چپ به راست** تخصیص می‌دهد. -* ‫ علامت `+` در `(target_list "=")+` به این معناست که می‌توان **یک یا چند** هدف انتساب داشت. در این حالت، اهداف انتساب ما `a, b` و `a[b]` هستند (توجه کنید که عبارت ارزیابی‌شده دقیقاً یکی است، که در اینجا `{}` و `5` است). +* علامت `+` در `(target_list "=")+` به این معناست که می‌توان **یک یا چند** هدف انتساب داشت. در این حالت، اهداف انتساب ما `a, b` و `a[b]` هستند (توجه کنید که عبارت ارزیابی‌شده دقیقاً یکی است، که در اینجا `{}` و `5` است). -* ‫ پس از ارزیابی عبارت، نتیجه از **چپ به راست** به اهداف انتساب داده می‌شود. در این مثال ابتدا تاپل `({}, 5)` به `a, b` باز می‌شود، بنابراین `a = {}` و `b = 5` خواهیم داشت. +* پس از ارزیابی عبارت، نتیجه از **چپ به راست** به اهداف انتساب داده می‌شود. در این مثال ابتدا تاپل `({}, 5)` به `a, b` باز می‌شود، بنابراین `a = {}` و `b = 5` خواهیم داشت. -* ‫ حالا `a` یک شیء قابل تغییر (mutable) است (`{}`). +* حالا `a` یک شیء قابل تغییر (mutable) است (`{}`). -* ‫ هدف انتساب بعدی `a[b]` است (شاید انتظار داشته باشید که اینجا خطا بگیریم زیرا پیش از این هیچ مقداری برای `a` و `b` مشخص نشده است؛ اما به یاد داشته باشید که در گام قبل به `a` مقدار `{}` و به `b` مقدار `5` دادیم). +* هدف انتساب بعدی `a[b]` است (شاید انتظار داشته باشید که اینجا خطا بگیریم زیرا پیش از این هیچ مقداری برای `a` و `b` مشخص نشده است؛ اما به یاد داشته باشید که در گام قبل به `a` مقدار `{}` و به `b` مقدار `5` دادیم). -* ‫ اکنون، کلید `5` در دیکشنری به تاپل `({}, 5)` مقداردهی می‌شود و یک مرجع دوری (Circular Reference) ایجاد می‌کند (علامت `{...}` در خروجی به همان شیئی اشاره دارد که قبلاً توسط `a` به آن ارجاع داده شده است). یک مثال ساده‌تر از مرجع دوری می‌تواند به این صورت باشد: +* اکنون، کلید `5` در دیکشنری به تاپل `({}, 5)` مقداردهی می‌شود و یک مرجع دوری (Circular Reference) ایجاد می‌کند (علامت `{...}` در خروجی به همان شیئی اشاره دارد که قبلاً توسط `a` به آن ارجاع داده شده است). یک مثال ساده‌تر از مرجع دوری می‌تواند به این صورت باشد: ```py >>> some_list = some_list[0] = [0] >>> some_list @@ -1993,15 +1993,15 @@ a, b = a[b] = {}, 5 >>> some_list[0][0][0][0][0][0] == some_list True ``` - ‫ در مثال ما نیز شرایط مشابه است (`a[b][0]` همان شیئی است که `a` به آن اشاره دارد). + در مثال ما نیز شرایط مشابه است (`a[b][0]` همان شیئی است که `a` به آن اشاره دارد). -* ‫ بنابراین برای جمع‌بندی، می‌توانید مثال بالا را به این صورت ساده کنید: +* بنابراین برای جمع‌بندی، می‌توانید مثال بالا را به این صورت ساده کنید: ```py a, b = {}, 5 a[b] = a, b ``` - ‫ و مرجع دوری به این دلیل قابل توجیه است که `a[b][0]` همان شیئی است که `a` به آن اشاره دارد. + و مرجع دوری به این دلیل قابل توجیه است که `a[b][0]` همان شیئی است که `a` به آن اشاره دارد. ```py >>> a[b][0] is a True @@ -2010,7 +2010,7 @@ a, b = a[b] = {}, 5 --- -### ▶ ‫ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود +### ▶ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود ```py >>> # Python 3.10.6 >>> int("2" * 5432) @@ -2019,7 +2019,7 @@ a, b = a[b] = {}, 5 >>> int("2" * 5432) ``` -‫ **خروجی:** +**خروجی:** ```py >>> # Python 3.10.6 222222222222222222222222222222222222222222222222222222222222222... @@ -2032,24 +2032,24 @@ ValueError: Exceeds the limit (4300) for integer string conversion: to increase the limit. ``` -#### 💡 ‫ توضیح: -‫ فراخوانی تابع `int()` در نسخه‌ی Python 3.10.6 به‌خوبی کار می‌کند اما در نسخه‌ی Python 3.10.8 منجر به خطای `ValueError` می‌شود. توجه کنید که پایتون همچنان قادر به کار با اعداد صحیح بزرگ است. این خطا تنها هنگام تبدیل اعداد صحیح به رشته یا برعکس رخ می‌دهد. +#### 💡 توضیح: +فراخوانی تابع `int()` در نسخه‌ی Python 3.10.6 به‌خوبی کار می‌کند اما در نسخه‌ی Python 3.10.8 منجر به خطای `ValueError` می‌شود. توجه کنید که پایتون همچنان قادر به کار با اعداد صحیح بزرگ است. این خطا تنها هنگام تبدیل اعداد صحیح به رشته یا برعکس رخ می‌دهد. -‫ خوشبختانه می‌توانید در صورت انتظار عبور از این حد مجاز، مقدار آن را افزایش دهید. برای انجام این کار می‌توانید از یکی از روش‌های زیر استفاده کنید: +خوشبختانه می‌توانید در صورت انتظار عبور از این حد مجاز، مقدار آن را افزایش دهید. برای انجام این کار می‌توانید از یکی از روش‌های زیر استفاده کنید: -- ‫ استفاده از فلگ خط فرمان `-X int_max_str_digits` -- ‫ تابع `set_int_max_str_digits()` از ماژول `sys` -- ‫ متغیر محیطی `PYTHONINTMAXSTRDIGITS` +- استفاده از فلگ خط فرمان `-X int_max_str_digits` +- تابع `set_int_max_str_digits()` از ماژول `sys` +- متغیر محیطی `PYTHONINTMAXSTRDIGITS` -‫ برای جزئیات بیشتر درباره‌ی تغییر مقدار پیش‌فرض این حد مجاز، [مستندات رسمی پایتون](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) را مشاهده کنید. +برای جزئیات بیشتر درباره‌ی تغییر مقدار پیش‌فرض این حد مجاز، [مستندات رسمی پایتون](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) را مشاهده کنید. --- -## ‫ بخش: شیب‌های لغزنده +## بخش: شیب‌های لغزنده -### ▶ ‫ تغییر یک دیکشنری هنگام پیمایش روی آن +### ▶ تغییر یک دیکشنری هنگام پیمایش روی آن ```py x = {0: None} @@ -2060,7 +2060,7 @@ for i in x: print(i) ``` -‫ **خروجی (پایتون 2.7تا پایتون 3.5):** +**خروجی (پایتون 2.7تا پایتون 3.5):** ``` 0 @@ -2073,15 +2073,15 @@ for i in x: 7 ``` -‫ بله، دقیقاً **هشت** مرتبه اجرا می‌شود و سپس متوقف می‌شود. +بله، دقیقاً **هشت** مرتبه اجرا می‌شود و سپس متوقف می‌شود. -#### ‫ 💡 توضیح: +#### 💡 توضیح: -- ‫ پیمایش روی یک دیکشنری در حالی که همزمان آن را ویرایش می‌کنید پشتیبانی نمی‌شود. -- ‫ هشت بار اجرا می‌شود چون در آن لحظه دیکشنری برای نگهداری کلیدهای بیشتر تغییر اندازه می‌دهد (ما هشت ورودی حذف داریم، بنابراین تغییر اندازه لازم است). این در واقع یک جزئیات پیاده‌سازی است. -- ‫ اینکه کلیدهای حذف‌شده چگونه مدیریت می‌شوند و چه زمانی تغییر اندازه اتفاق می‌افتد ممکن است در پیاده‌سازی‌های مختلف پایتون متفاوت باشد. -- ‫ بنابراین در نسخه‌های دیگر پایتون (به جز Python 2.7 - Python 3.5)، تعداد ممکن است متفاوت از ۸ باشد (اما هر چه که باشد، در هر بار اجرا یکسان خواهد بود). می‌توانید برخی مباحث پیرامون این موضوع را [اینجا](https://github.com/satwikkansal/wtfpython/issues/53) یا در این [رشته‌ی StackOverflow](https://stackoverflow.com/questions/44763802/bug-in-python-dict) مشاهده کنید. -- ‫ از نسخه‌ی Python 3.7.6 به بعد، در صورت تلاش برای انجام این کار، خطای `RuntimeError: dictionary keys changed during iteration` را دریافت خواهید کرد. +- پیمایش روی یک دیکشنری در حالی که همزمان آن را ویرایش می‌کنید پشتیبانی نمی‌شود. +- هشت بار اجرا می‌شود چون در آن لحظه دیکشنری برای نگهداری کلیدهای بیشتر تغییر اندازه می‌دهد (ما هشت ورودی حذف داریم، بنابراین تغییر اندازه لازم است). این در واقع یک جزئیات پیاده‌سازی است. +- اینکه کلیدهای حذف‌شده چگونه مدیریت می‌شوند و چه زمانی تغییر اندازه اتفاق می‌افتد ممکن است در پیاده‌سازی‌های مختلف پایتون متفاوت باشد. +- بنابراین در نسخه‌های دیگر پایتون (به جز Python 2.7 - Python 3.5)، تعداد ممکن است متفاوت از ۸ باشد (اما هر چه که باشد، در هر بار اجرا یکسان خواهد بود). می‌توانید برخی مباحث پیرامون این موضوع را [اینجا](https://github.com/satwikkansal/wtfpython/issues/53) یا در این [رشته‌ی StackOverflow](https://stackoverflow.com/questions/44763802/bug-in-python-dict) مشاهده کنید. +- از نسخه‌ی Python 3.7.6 به بعد، در صورت تلاش برای انجام این کار، خطای `RuntimeError: dictionary keys changed during iteration` را دریافت خواهید کرد. --- @@ -2095,7 +2095,7 @@ class SomeClass: print("Deleted!") ``` -‫ **خروجی:** +**خروجی:** 1\. ```py >>> x = SomeClass() @@ -2105,7 +2105,7 @@ class SomeClass: Deleted! ``` -‫ «خُب، بالاخره حذف شد.» احتمالاً حدس زده‌اید چه چیزی جلوی فراخوانی `__del__` را در اولین تلاشی که برای حذف `x` داشتیم، گرفته بود. بیایید مثال را پیچیده‌تر کنیم. +«خُب، بالاخره حذف شد.» احتمالاً حدس زده‌اید چه چیزی جلوی فراخوانی `__del__` را در اولین تلاشی که برای حذف `x` داشتیم، گرفته بود. بیایید مثال را پیچیده‌تر کنیم. 2\. ```py @@ -2120,17 +2120,17 @@ Deleted! {'__builtins__': , 'SomeClass': , '__package__': None, '__name__': '__main__', '__doc__': None} ``` -‫ «باشه، حالا حذف شد» :confused: +«باشه، حالا حذف شد» :confused: -#### ‫ 💡 توضیح: -- ‫ عبارت `del x` مستقیماً باعث فراخوانی `x.__del__()` نمی‌شود. -- ‫ وقتی به دستور `del x` می‌رسیم، پایتون نام `x` را از حوزه‌ی فعلی حذف کرده و شمارنده‌ی مراجع شیٔ‌ای که `x` به آن اشاره می‌کرد را یک واحد کاهش می‌دهد. فقط وقتی شمارنده‌ی مراجع شیٔ به صفر برسد، تابع `__del__()` فراخوانی می‌شود. -- ‫ در خروجی دوم، متد `__del__()` فراخوانی نشد چون دستور قبلی (`>>> y`) در مفسر تعاملی یک ارجاع دیگر به شیٔ ایجاد کرده بود (به صورت خاص، متغیر جادویی `_` به مقدار آخرین عبارت غیر `None` در REPL اشاره می‌کند). بنابراین مانع از رسیدن شمارنده‌ی مراجع به صفر در هنگام اجرای `del y` شد. -- ‫ فراخوانی `globals` (یا هر چیزی که نتیجه‌اش `None` نباشد) باعث می‌شود که `_` به نتیجه‌ی جدید اشاره کند و ارجاع قبلی از بین برود. حالا شمارنده‌ی مراجع به صفر می‌رسد و عبارت «Deleted!» (حذف شد!) نمایش داده می‌شود. +#### 💡 توضیح: +- عبارت `del x` مستقیماً باعث فراخوانی `x.__del__()` نمی‌شود. +- وقتی به دستور `del x` می‌رسیم، پایتون نام `x` را از حوزه‌ی فعلی حذف کرده و شمارنده‌ی مراجع شیٔ‌ای که `x` به آن اشاره می‌کرد را یک واحد کاهش می‌دهد. فقط وقتی شمارنده‌ی مراجع شیٔ به صفر برسد، تابع `__del__()` فراخوانی می‌شود. +- در خروجی دوم، متد `__del__()` فراخوانی نشد چون دستور قبلی (`>>> y`) در مفسر تعاملی یک ارجاع دیگر به شیٔ ایجاد کرده بود (به صورت خاص، متغیر جادویی `_` به مقدار آخرین عبارت غیر `None` در REPL اشاره می‌کند). بنابراین مانع از رسیدن شمارنده‌ی مراجع به صفر در هنگام اجرای `del y` شد. +- فراخوانی `globals` (یا هر چیزی که نتیجه‌اش `None` نباشد) باعث می‌شود که `_` به نتیجه‌ی جدید اشاره کند و ارجاع قبلی از بین برود. حالا شمارنده‌ی مراجع به صفر می‌رسد و عبارت «Deleted!» (حذف شد!) نمایش داده می‌شود. --- -### ▶ ‫ متغیری که از حوزه خارج است +### ▶ متغیری که از حوزه خارج است 1\. @@ -2160,7 +2160,7 @@ def another_closure_func(): return another_inner_func() ``` -‫ **خروجی:** +**خروجی:** ```py >>> some_func() 1 @@ -2173,9 +2173,9 @@ UnboundLocalError: local variable 'a' referenced before assignment UnboundLocalError: local variable 'a' referenced before assignment ``` -#### ‫ 💡 توضیح: -* ‫ وقتی در محدوده (Scope) یک تابع به متغیری مقداردهی می‌کنید، آن متغیر در همان حوزه محلی تعریف می‌شود. بنابراین `a` در تابع `another_func` تبدیل به متغیر محلی می‌شود، اما پیش‌تر در همان حوزه مقداردهی نشده است، و این باعث خطا می‌شود. -* ‫ برای تغییر متغیر سراسری `a` در تابع `another_func`، باید از کلیدواژه‌ی `global` استفاده کنیم. +#### 💡 توضیح: +* وقتی در محدوده (Scope) یک تابع به متغیری مقداردهی می‌کنید، آن متغیر در همان حوزه محلی تعریف می‌شود. بنابراین `a` در تابع `another_func` تبدیل به متغیر محلی می‌شود، اما پیش‌تر در همان حوزه مقداردهی نشده است، و این باعث خطا می‌شود. +* برای تغییر متغیر سراسری `a` در تابع `another_func`، باید از کلیدواژه‌ی `global` استفاده کنیم. ```py def another_func() global a @@ -2188,8 +2188,8 @@ UnboundLocalError: local variable 'a' referenced before assignment >>> another_func() 2 ``` -* ‫ در تابع `another_closure_func`، متغیر `a` در حوزه‌ی `another_inner_func` محلی می‌شود ولی پیش‌تر در آن حوزه مقداردهی نشده است. به همین دلیل خطا می‌دهد. -* ‫ برای تغییر متغیر حوزه‌ی بیرونی `a` در `another_inner_func`، باید از کلیدواژه‌ی `nonlocal` استفاده کنیم. دستور `nonlocal` به مفسر می‌گوید که متغیر را در نزدیک‌ترین حوزه‌ی بیرونی (به‌جز حوزه‌ی global) جستجو کند. +* در تابع `another_closure_func`، متغیر `a` در حوزه‌ی `another_inner_func` محلی می‌شود ولی پیش‌تر در آن حوزه مقداردهی نشده است. به همین دلیل خطا می‌دهد. +* برای تغییر متغیر حوزه‌ی بیرونی `a` در `another_inner_func`، باید از کلیدواژه‌ی `nonlocal` استفاده کنیم. دستور `nonlocal` به مفسر می‌گوید که متغیر را در نزدیک‌ترین حوزه‌ی بیرونی (به‌جز حوزه‌ی global) جستجو کند. ```py def another_func(): a = 1 @@ -2200,17 +2200,17 @@ UnboundLocalError: local variable 'a' referenced before assignment return another_inner_func() ``` - ‫ **خروجی:** + **خروجی:** ```py >>> another_func() 2 ``` -* ‫ کلیدواژه‌های `global` و `nonlocal` به مفسر پایتون می‌گویند که متغیر جدیدی را تعریف نکند و به جای آن در حوزه‌های بیرونی (سراسری یا میانجی) آن را بیابد. -* ‫ برای مطالعه‌ی بیشتر در مورد نحوه‌ی کار فضای نام‌ها و مکانیزم تعیین حوزه‌ها در پایتون، می‌توانید این [مقاله کوتاه ولی عالی](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) را بخوانید. +* کلیدواژه‌های `global` و `nonlocal` به مفسر پایتون می‌گویند که متغیر جدیدی را تعریف نکند و به جای آن در حوزه‌های بیرونی (سراسری یا میانجی) آن را بیابد. +* برای مطالعه‌ی بیشتر در مورد نحوه‌ی کار فضای نام‌ها و مکانیزم تعیین حوزه‌ها در پایتون، می‌توانید این [مقاله کوتاه ولی عالی](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) را بخوانید. --- -### ▶ ‫ حذف المان‌های لیست در حین پیمایش +### ▶ حذف المان‌های لیست در حین پیمایش ```py list_1 = [1, 2, 3, 4] @@ -2243,11 +2243,11 @@ for idx, item in enumerate(list_4): [2, 4] ``` -‫ می‌توانید حدس بزنید چرا خروجی `[2, 4]` است؟ +می‌توانید حدس بزنید چرا خروجی `[2, 4]` است؟ #### 💡 Explanation: -* ‫ هیچ‌وقت ایده‌ی خوبی نیست که شیئی را که روی آن پیمایش می‌کنید تغییر دهید. روش درست این است که روی یک کپی از آن شیء پیمایش کنید؛ در این‌جا `list_3[:]` دقیقاً همین کار را می‌کند. +* هیچ‌وقت ایده‌ی خوبی نیست که شیئی را که روی آن پیمایش می‌کنید تغییر دهید. روش درست این است که روی یک کپی از آن شیء پیمایش کنید؛ در این‌جا `list_3[:]` دقیقاً همین کار را می‌کند. ```py >>> some_list = [1, 2, 3, 4] @@ -2257,21 +2257,21 @@ for idx, item in enumerate(list_4): 139798779601192 ``` -‫ **تفاوت بین `del`، `remove` و `pop`:** -* ‫ `del var_name` فقط اتصال `var_name` را از فضای نام محلی یا سراسری حذف می‌کند (به همین دلیل است که `list_1` تحت تأثیر قرار نمی‌گیرد). -* ‫ متد `remove` اولین مقدار مطابق را حذف می‌کند، نه یک اندیس خاص را؛ اگر مقدار مورد نظر پیدا نشود، خطای `ValueError` ایجاد می‌شود. -* ‫ متد `pop` عنصری را در یک اندیس مشخص حذف کرده و آن را برمی‌گرداند؛ اگر اندیس نامعتبری مشخص شود، خطای `IndexError` ایجاد می‌شود. +**تفاوت بین `del`، `remove` و `pop`:** +* `del var_name` فقط اتصال `var_name` را از فضای نام محلی یا سراسری حذف می‌کند (به همین دلیل است که `list_1` تحت تأثیر قرار نمی‌گیرد). +* متد `remove` اولین مقدار مطابق را حذف می‌کند، نه یک اندیس خاص را؛ اگر مقدار مورد نظر پیدا نشود، خطای `ValueError` ایجاد می‌شود. +* متد `pop` عنصری را در یک اندیس مشخص حذف کرده و آن را برمی‌گرداند؛ اگر اندیس نامعتبری مشخص شود، خطای `IndexError` ایجاد می‌شود. -‫ **چرا خروجی `[2, 4]` است؟** -- ‫ پیمایش لیست به صورت اندیس به اندیس انجام می‌شود، و هنگامی که عدد `1` را از `list_2` یا `list_4` حذف می‌کنیم، محتوای لیست به `[2, 3, 4]` تغییر می‌کند. در این حالت عناصر باقی‌مانده به سمت چپ جابه‌جا شده و جایگاهشان تغییر می‌کند؛ یعنی عدد `2` در اندیس 0 و عدد `3` در اندیس 1 قرار می‌گیرد. از آنجا که در مرحله بعدی حلقه به سراغ اندیس 1 می‌رود (که اکنون مقدار آن `3` است)، عدد `2` به طور کامل نادیده گرفته می‌شود. این اتفاق مشابه برای هر عنصر یک‌درمیان در طول پیمایش لیست رخ خواهد داد. +**چرا خروجی `[2, 4]` است؟** +- پیمایش لیست به صورت اندیس به اندیس انجام می‌شود، و هنگامی که عدد `1` را از `list_2` یا `list_4` حذف می‌کنیم، محتوای لیست به `[2, 3, 4]` تغییر می‌کند. در این حالت عناصر باقی‌مانده به سمت چپ جابه‌جا شده و جایگاهشان تغییر می‌کند؛ یعنی عدد `2` در اندیس 0 و عدد `3` در اندیس 1 قرار می‌گیرد. از آنجا که در مرحله بعدی حلقه به سراغ اندیس 1 می‌رود (که اکنون مقدار آن `3` است)، عدد `2` به طور کامل نادیده گرفته می‌شود. این اتفاق مشابه برای هر عنصر یک‌درمیان در طول پیمایش لیست رخ خواهد داد. -* ‫ برای توضیح بیشتر این مثال، این [تاپیک StackOverflow](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) را ببینید. -* ‫ همچنین برای نمونه مشابهی مربوط به دیکشنری‌ها در پایتون، این [تاپیک مفید StackOverflow](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) را ببینید. +* برای توضیح بیشتر این مثال، این [تاپیک StackOverflow](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) را ببینید. +* همچنین برای نمونه مشابهی مربوط به دیکشنری‌ها در پایتون، این [تاپیک مفید StackOverflow](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) را ببینید. --- -### ▶ ‫ زیپِ دارای اتلاف برای پیمایشگرها * +### ▶ زیپِ دارای اتلاف برای پیمایشگرها * ```py @@ -2288,11 +2288,11 @@ for idx, item in enumerate(list_4): >>> list(zip(numbers_iter, remaining)) [(4, 3), (5, 4), (6, 5)] ``` -‫ عنصر `3` از لیست `numbers` چه شد؟ +عنصر `3` از لیست `numbers` چه شد؟ -#### ‫ 💡 توضیحات: +#### 💡 توضیحات: -- ‫ بر اساس [مستندات](https://docs.python.org/3.3/library/functions.html#zip) پایتون، پیاده‌سازی تقریبی تابع `zip` به شکل زیر است: +- بر اساس [مستندات](https://docs.python.org/3.3/library/functions.html#zip) پایتون، پیاده‌سازی تقریبی تابع `zip` به شکل زیر است: ```py def zip(*iterables): sentinel = object() @@ -2305,9 +2305,9 @@ for idx, item in enumerate(list_4): result.append(elem) yield tuple(result) ``` -- ‫ بنابراین این تابع تعداد دلخواهی از اشیای قابل پیمایش (*iterable*) را دریافت می‌کند، و با فراخوانی تابع `next` روی آن‌ها، هر یک از عناصرشان را به لیست `result` اضافه می‌کند. این فرایند زمانی متوقف می‌شود که اولین پیمایشگر به انتها برسد. -- ‫ نکته مهم اینجاست که هر زمان یکی از پیمایشگرها به پایان برسد، عناصر موجود در لیست `result` نیز دور ریخته می‌شوند. این دقیقاً همان اتفاقی است که برای عدد `3` در `numbers_iter` رخ داد. -- ‫ روش صحیح برای انجام عملیات بالا با استفاده از تابع `zip` چنین است: +- بنابراین این تابع تعداد دلخواهی از اشیای قابل پیمایش (*iterable*) را دریافت می‌کند، و با فراخوانی تابع `next` روی آن‌ها، هر یک از عناصرشان را به لیست `result` اضافه می‌کند. این فرایند زمانی متوقف می‌شود که اولین پیمایشگر به انتها برسد. +- نکته مهم اینجاست که هر زمان یکی از پیمایشگرها به پایان برسد، عناصر موجود در لیست `result` نیز دور ریخته می‌شوند. این دقیقاً همان اتفاقی است که برای عدد `3` در `numbers_iter` رخ داد. +- روش صحیح برای انجام عملیات بالا با استفاده از تابع `zip` چنین است: ```py >>> numbers = list(range(7)) >>> numbers_iter = iter(numbers) @@ -2316,11 +2316,11 @@ for idx, item in enumerate(list_4): >>> list(zip(remaining, numbers_iter)) [(3, 3), (4, 4), (5, 5), (6, 6)] ``` - ‫ اولین آرگومانِ تابع `zip` باید پیمایشگری باشد که کمترین تعداد عنصر را دارد. + اولین آرگومانِ تابع `zip` باید پیمایشگری باشد که کمترین تعداد عنصر را دارد. --- -### ▶ ‫ نشت کردن متغیرهای حلقه! +### ▶ نشت کردن متغیرهای حلقه! 1\. ```py @@ -2330,13 +2330,13 @@ for x in range(7): print(x, ': x in global') ``` -‫ **خروجی:** +**خروجی:** ```py 6 : for x inside loop 6 : x in global ``` -‫ اما متغیر `x` هرگز خارج از محدوده (scope) حلقه `for` تعریف نشده بود... +اما متغیر `x` هرگز خارج از محدوده (scope) حلقه `for` تعریف نشده بود... 2\. ```py @@ -2348,7 +2348,7 @@ for x in range(7): print(x, ': x in global') ``` -‫ **خروجی:** +**خروجی:** ```py 6 : for x inside loop 6 : x in global @@ -2356,7 +2356,7 @@ print(x, ': x in global') 3\. -‫ **خروجی (Python 2.x):** +**خروجی (Python 2.x):** ```py >>> x = 1 >>> print([x for x in range(5)]) @@ -2365,7 +2365,7 @@ print(x, ': x in global') 4 ``` -‫ **خروجی (Python 3.x):** +**خروجی (Python 3.x):** ```py >>> x = 1 >>> print([x for x in range(5)]) @@ -2374,17 +2374,17 @@ print(x, ': x in global') 1 ``` -#### 💡 ‫ توضیحات: +#### 💡 توضیحات: -- ‫ در پایتون، حلقه‌های `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 @@ -2393,7 +2393,7 @@ def some_func(default_arg=[]): return default_arg ``` -‫ **خروجی:** +**خروجی:** ```py >>> some_func() ['some_string'] @@ -2405,9 +2405,9 @@ def some_func(default_arg=[]): ['some_string', 'some_string', 'some_string'] ``` -#### 💡 ‫ توضیحات: +#### 💡 توضیحات: -- ‫ آرگومان‌های تغییرپذیر پیش‌فرض در توابع پایتون، هر بار که تابع فراخوانی می‌شود مقداردهی نمی‌شوند؛ بلکه مقداردهی آنها تنها یک بار در زمان تعریف تابع انجام می‌شود و مقدار اختصاص‌یافته به آن‌ها به عنوان مقدار پیش‌فرض برای فراخوانی‌های بعدی استفاده خواهد شد. هنگامی که به صراحت مقدار `[]` را به عنوان آرگومان به `some_func` ارسال کردیم، مقدار پیش‌فرض برای متغیر `default_arg` مورد استفاده قرار نگرفت، بنابراین تابع همان‌طور که انتظار داشتیم عمل کرد. +- آرگومان‌های تغییرپذیر پیش‌فرض در توابع پایتون، هر بار که تابع فراخوانی می‌شود مقداردهی نمی‌شوند؛ بلکه مقداردهی آنها تنها یک بار در زمان تعریف تابع انجام می‌شود و مقدار اختصاص‌یافته به آن‌ها به عنوان مقدار پیش‌فرض برای فراخوانی‌های بعدی استفاده خواهد شد. هنگامی که به صراحت مقدار `[]` را به عنوان آرگومان به `some_func` ارسال کردیم، مقدار پیش‌فرض برای متغیر `default_arg` مورد استفاده قرار نگرفت، بنابراین تابع همان‌طور که انتظار داشتیم عمل کرد. ```py def some_func(default_arg=[]): @@ -2415,7 +2415,7 @@ def some_func(default_arg=[]): return default_arg ``` - ‫ **خروجی:** + **خروجی:** ```py >>> some_func.__defaults__ # مقادیر پیشفرض این تابع را نمایش می دهد. ([],) @@ -2430,7 +2430,7 @@ def some_func(default_arg=[]): (['some_string', 'some_string'],) ``` -- ‫ یک روش رایج برای جلوگیری از باگ‌هایی که به دلیل آرگومان‌های تغییرپذیر رخ می‌دهند، این است که مقدار پیش‌فرض را `None` قرار داده و سپس درون تابع بررسی کنیم که آیا مقداری به آن آرگومان ارسال شده است یا خیر. مثال: +- یک روش رایج برای جلوگیری از باگ‌هایی که به دلیل آرگومان‌های تغییرپذیر رخ می‌دهند، این است که مقدار پیش‌فرض را `None` قرار داده و سپس درون تابع بررسی کنیم که آیا مقداری به آن آرگومان ارسال شده است یا خیر. مثال: ```py def some_func(default_arg=None): @@ -2442,31 +2442,31 @@ def some_func(default_arg=[]): --- -### ▶ ‫ گرفتن استثناها (Exceptions) +### ▶ گرفتن استثناها (Exceptions) ```py some_list = [1, 2, 3] try: - # ‫ این باید یک `IndexError` ایجاد کند + # این باید یک `IndexError` ایجاد کند print(some_list[4]) except IndexError, ValueError: print("Caught!") try: - # ‫ این باید یک `ValueError` ایجاد کند + # این باید یک `ValueError` ایجاد کند some_list.remove(4) except IndexError, ValueError: print("Caught again!") ``` -‫ **خروجی (Python 2.x):** +**خروجی (Python 2.x):** ```py Caught! ValueError: list.remove(x): x not in list ``` -‫ **خروجی (Python 3.x):** +**خروجی (Python 3.x):** ```py File "", line 3 except IndexError, ValueError: @@ -2474,7 +2474,7 @@ ValueError: list.remove(x): x not in list SyntaxError: invalid syntax ``` -#### 💡 ‫ توضیحات +#### 💡 توضیحات * To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example, ```py @@ -2486,12 +2486,12 @@ SyntaxError: invalid syntax print("Caught again!") print(e) ``` - ‫ **خروجی (Python 2.x):** + **خروجی (Python 2.x):** ``` Caught again! list.remove(x): x not in list ``` - ‫ **خروجی (Python 3.x):** + **خروجی (Python 3.x):** ```py File "", line 4 except (IndexError, ValueError), e: @@ -2509,7 +2509,7 @@ SyntaxError: invalid syntax print("Caught again!") print(e) ``` - ‫ **خروجی:** + **خروجی:** ``` Caught again! list.remove(x): x not in list @@ -2517,7 +2517,7 @@ SyntaxError: invalid syntax --- -### ▶ ‫ عملوندهای یکسان، داستانی متفاوت! +### ▶ عملوندهای یکسان، داستانی متفاوت! 1\. ```py @@ -2526,7 +2526,7 @@ b = a a = a + [5, 6, 7, 8] ``` -‫ **خروجی:** +**خروجی:** ```py >>> a [1, 2, 3, 4, 5, 6, 7, 8] @@ -2541,7 +2541,7 @@ b = a a += [5, 6, 7, 8] ``` -‫ **خروجی:** +**خروجی:** ```py >>> a [1, 2, 3, 4, 5, 6, 7, 8] @@ -2549,16 +2549,16 @@ a += [5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8] ``` -#### 💡 ‫ توضیحات: -* ‫ عملگر `a += b` همیشه همانند `a = a + b` رفتار نمی‌کند. کلاس‌ها *ممکن است* عملگرهای *`op=`* را به گونه‌ای متفاوت پیاده‌سازی کنند، و لیست‌ها نیز چنین می‌کنند. +#### 💡 توضیحات: +* عملگر `a += b` همیشه همانند `a = a + b` رفتار نمی‌کند. کلاس‌ها *ممکن است* عملگرهای *`op=`* را به گونه‌ای متفاوت پیاده‌سازی کنند، و لیست‌ها نیز چنین می‌کنند. -* ‫ عبارت `a = a + [5,6,7,8]` یک لیست جدید ایجاد می‌کند و مرجع `a` را به این لیست جدید اختصاص می‌دهد، بدون آنکه `b` را تغییر دهد. +* عبارت `a = a + [5,6,7,8]` یک لیست جدید ایجاد می‌کند و مرجع `a` را به این لیست جدید اختصاص می‌دهد، بدون آنکه `b` را تغییر دهد. -* ‫ عبارت `a += [5,6,7,8]` در واقع به تابعی معادل «extend» ترجمه می‌شود که روی لیست اصلی عمل می‌کند؛ بنابراین `a` و `b` همچنان به همان لیست اشاره می‌کنند که به‌صورت درجا (in-place) تغییر کرده است. +* عبارت `a += [5,6,7,8]` در واقع به تابعی معادل «extend» ترجمه می‌شود که روی لیست اصلی عمل می‌کند؛ بنابراین `a` و `b` همچنان به همان لیست اشاره می‌کنند که به‌صورت درجا (in-place) تغییر کرده است. --- -### ▶ ‫ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس +### ▶ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس 1\. ```py @@ -2568,7 +2568,7 @@ class SomeClass: y = (x for i in range(10)) ``` -‫ **خروجی:** +**خروجی:** ```py >>> list(SomeClass.y)[0] 5 @@ -2582,28 +2582,28 @@ class SomeClass: y = [x for i in range(10)] ``` -‫ **خروجی (Python 2.x):** +**خروجی (Python 2.x):** ```py >>> SomeClass.y[0] 17 ``` -‫ **خروجی (Python 3.x):** +**خروجی (Python 3.x):** ```py >>> SomeClass.y[0] 5 ``` -#### 💡 ‫ توضیحات -- ‫ حوزه‌هایی که درون تعریف کلاس تو در تو هستند، نام‌های تعریف‌شده در سطح کلاس را نادیده می‌گیرند. -- ‫ عبارت‌های جنراتور (generator expressions) حوزه‌ی مختص به خود دارند. -- ‫ از پایتون نسخه‌ی ۳ به بعد، لیست‌های فشرده (list comprehensions) نیز حوزه‌ی مختص به خود دارند. +#### 💡 توضیحات +- حوزه‌هایی که درون تعریف کلاس تو در تو هستند، نام‌های تعریف‌شده در سطح کلاس را نادیده می‌گیرند. +- عبارت‌های جنراتور (generator expressions) حوزه‌ی مختص به خود دارند. +- از پایتون نسخه‌ی ۳ به بعد، لیست‌های فشرده (list comprehensions) نیز حوزه‌ی مختص به خود دارند. --- -### ▶ ‫ گرد کردن به روش بانکدار * +### ▶ گرد کردن به روش بانکدار * -‫ بیایید یک تابع ساده برای به‌دست‌آوردن عنصر میانی یک لیست پیاده‌سازی کنیم: +بیایید یک تابع ساده برای به‌دست‌آوردن عنصر میانی یک لیست پیاده‌سازی کنیم: ```py def get_middle(some_list): mid_index = round(len(some_list) / 2) @@ -2623,11 +2623,11 @@ def get_middle(some_list): >>> round(len([1,2,3,4,5]) / 2) # چرا? 2 ``` -‫ به نظر می‌رسد که پایتون عدد ۲٫۵ را به ۲ گرد کرده است. +به نظر می‌رسد که پایتون عدد ۲٫۵ را به ۲ گرد کرده است. -#### 💡 ‫ توضیحات: +#### 💡 توضیحات: -- ‫ این یک خطای مربوط به دقت اعداد اعشاری نیست؛ بلکه این رفتار عمدی است. از پایتون نسخه 3.0 به بعد، تابع `round()` از [گرد کردن بانکی](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even) استفاده می‌کند که در آن کسرهای `.5` به نزدیک‌ترین عدد **زوج** گرد می‌شوند: +- این یک خطای مربوط به دقت اعداد اعشاری نیست؛ بلکه این رفتار عمدی است. از پایتون نسخه 3.0 به بعد، تابع `round()` از [گرد کردن بانکی](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even) استفاده می‌کند که در آن کسرهای `.5` به نزدیک‌ترین عدد **زوج** گرد می‌شوند: ```py >>> round(0.5) @@ -2645,17 +2645,17 @@ def get_middle(some_list): 2.0 ``` -- ‫ این روشِ پیشنهادی برای گرد کردن کسرهای `.5` مطابق با استاندارد [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules) است. با این حال، روش دیگر (گرد کردن به سمت دور از صفر) اغلب در مدارس آموزش داده می‌شود؛ بنابراین، «گرد کردن بانکی» احتمالا چندان شناخته‌شده نیست. همچنین، برخی از رایج‌ترین زبان‌های برنامه‌نویسی (مانند جاوااسکریپت، جاوا، C/C++‎، روبی و راست) نیز از گرد کردن بانکی استفاده نمی‌کنند. به همین دلیل این موضوع همچنان مختص پایتون بوده و ممکن است باعث سردرگمی هنگام گرد کردن کسرها شود. -- ‫ برای اطلاعات بیشتر به [مستندات تابع `round()`](https://docs.python.org/3/library/functions.html#round) یا [این بحث در Stack Overflow](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) مراجعه کنید. -- ‫ توجه داشته باشید که `get_middle([1])` فقط به این دلیل مقدار 1 را بازگرداند که اندیس آن `round(0.5) - 1 = 0 - 1 = -1` بود و در نتیجه آخرین عنصر لیست را برمی‌گرداند. +- این روشِ پیشنهادی برای گرد کردن کسرهای `.5` مطابق با استاندارد [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules) است. با این حال، روش دیگر (گرد کردن به سمت دور از صفر) اغلب در مدارس آموزش داده می‌شود؛ بنابراین، «گرد کردن بانکی» احتمالا چندان شناخته‌شده نیست. همچنین، برخی از رایج‌ترین زبان‌های برنامه‌نویسی (مانند جاوااسکریپت، جاوا، C/C++‎، روبی و راست) نیز از گرد کردن بانکی استفاده نمی‌کنند. به همین دلیل این موضوع همچنان مختص پایتون بوده و ممکن است باعث سردرگمی هنگام گرد کردن کسرها شود. +- برای اطلاعات بیشتر به [مستندات تابع `round()`](https://docs.python.org/3/library/functions.html#round) یا [این بحث در Stack Overflow](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) مراجعه کنید. +- توجه داشته باشید که `get_middle([1])` فقط به این دلیل مقدار 1 را بازگرداند که اندیس آن `round(0.5) - 1 = 0 - 1 = -1` بود و در نتیجه آخرین عنصر لیست را برمی‌گرداند. --- -### ▶ ‫ سوزن‌هایی در انبار کاه * +### ▶ سوزن‌هایی در انبار کاه * -‫ من تا به امروز حتی یک برنامه‌نویس باتجربهٔ پایتون را ندیده‌ام که حداقل با یکی از سناریوهای زیر مواجه نشده باشد: +من تا به امروز حتی یک برنامه‌نویس باتجربهٔ پایتون را ندیده‌ام که حداقل با یکی از سناریوهای زیر مواجه نشده باشد: 1\. @@ -2663,7 +2663,7 @@ def get_middle(some_list): x, y = (0, 1) if True else None, None ``` -‫ **خروجی:** +**خروجی:** ```py >>> x, y # چیزی که توقع داریم. (0, 1) @@ -2685,7 +2685,7 @@ t = () print(t) ``` -‫ **خروجی:** +**خروجی:** ```py one @@ -2713,26 +2713,26 @@ ten_words_list = [ ] ``` -‫ **خروجی** +**خروجی** ```py >>> len(ten_words_list) 9 ``` -4\. ‫ عدم تأکید کافی +4\. عدم تأکید کافی ```py a = "python" b = "javascript" ``` -‫ **خروجی:** +**خروجی:** ```py -# ‫ دستور assert همراه با پیام خطای assertion +# دستور assert همراه با پیام خطای assertion >>> assert(a == b, "Both languages are different") -# ‫ هیچ AssertionError ای رخ نمی‌دهد +# هیچ AssertionError ای رخ نمی‌دهد ``` 5\. @@ -2749,7 +2749,7 @@ some_list = some_list.append(4) some_dict = some_dict.update({"key_4": 4}) ``` -‫ **خروجی:** +**خروجی:** ```py >>> print(some_list) @@ -2776,7 +2776,7 @@ def similar_recursive_func(a): return a ``` -‫ **خروجی:** +**خروجی:** ```py >>> some_recursive_func([5, 0]) @@ -2785,22 +2785,22 @@ def similar_recursive_func(a): 4 ``` -#### 💡 ‫ توضیحات: -* ‫ برای مورد ۱، عبارت صحیح برای رفتار مورد انتظار این است: +#### 💡 توضیحات: +* برای مورد ۱، عبارت صحیح برای رفتار مورد انتظار این است: `x, y = (0, 1) if True else (None, None)` -* ‫ برای مورد ۲، عبارت صحیح برای رفتار مورد انتظار این است: +* برای مورد ۲، عبارت صحیح برای رفتار مورد انتظار این است: ‫`t = ('one',)` یا `t = 'one',` (ویرگول از قلم افتاده است). در غیر این صورت مفسر `t` را به عنوان یک `str` در نظر گرفته و به صورت کاراکتر به کاراکتر روی آن پیمایش می‌کند. -* ‫ علامت `()` یک توکن خاص است و نشان‌دهنده‌ی یک `tuple` خالی است. +* علامت `()` یک توکن خاص است و نشان‌دهنده‌ی یک `tuple` خالی است. -* ‫ در مورد ۳، همان‌طور که احتمالاً متوجه شدید، بعد از عنصر پنجم (`"that"`) یک ویرگول از قلم افتاده است. بنابراین با الحاق ضمنی رشته‌ها، +* در مورد ۳، همان‌طور که احتمالاً متوجه شدید، بعد از عنصر پنجم (`"that"`) یک ویرگول از قلم افتاده است. بنابراین با الحاق ضمنی رشته‌ها، ```py >>> ten_words_list ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] ``` -* ‫ در قطعه‌ی چهارم هیچ `AssertionError`ای رخ نداد؛ زیرا به جای ارزیابی عبارت تکی `a == b`، کل یک تاپل ارزیابی شده است. قطعه‌ی کد زیر این موضوع را روشن‌تر می‌کند: +* در قطعه‌ی چهارم هیچ `AssertionError`ای رخ نداد؛ زیرا به جای ارزیابی عبارت تکی `a == b`، کل یک تاپل ارزیابی شده است. قطعه‌ی کد زیر این موضوع را روشن‌تر می‌کند: ```py >>> a = "python" @@ -2819,16 +2819,16 @@ def similar_recursive_func(a): AssertionError: Values are not equal ``` -* ‫ در قطعه‌ی پنجم، بیشتر متدهایی که اشیای ترتیبی (Sequence) یا نگاشت‌ها (Mapping) را تغییر می‌دهند (مانند `list.append`، `dict.update`، `list.sort` و غیره)، شیء اصلی را به‌صورت درجا (in-place) تغییر داده و مقدار `None` برمی‌گردانند. منطق پشت این تصمیم، بهبود عملکرد با جلوگیری از کپی کردن شیء است (به این [منبع](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list) مراجعه کنید). +* در قطعه‌ی پنجم، بیشتر متدهایی که اشیای ترتیبی (Sequence) یا نگاشت‌ها (Mapping) را تغییر می‌دهند (مانند `list.append`، `dict.update`، `list.sort` و غیره)، شیء اصلی را به‌صورت درجا (in-place) تغییر داده و مقدار `None` برمی‌گردانند. منطق پشت این تصمیم، بهبود عملکرد با جلوگیری از کپی کردن شیء است (به این [منبع](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list) مراجعه کنید). -* ‫ قطعه‌ی آخر نیز نسبتاً واضح است؛ شیء تغییرپذیر (mutable)، مثل `list`، می‌تواند در داخل تابع تغییر کند، درحالی‌که انتساب دوباره‌ی یک شیء تغییرناپذیر (مانند `a -= 1`) باعث تغییر مقدار اصلی آن نخواهد شد. +* قطعه‌ی آخر نیز نسبتاً واضح است؛ شیء تغییرپذیر (mutable)، مثل `list`، می‌تواند در داخل تابع تغییر کند، درحالی‌که انتساب دوباره‌ی یک شیء تغییرناپذیر (مانند `a -= 1`) باعث تغییر مقدار اصلی آن نخواهد شد. -* ‫ آگاهی از این نکات ظریف در بلندمدت می‌تواند ساعت‌ها از زمان شما برای رفع اشکال را صرفه‌جویی کند. +* آگاهی از این نکات ظریف در بلندمدت می‌تواند ساعت‌ها از زمان شما برای رفع اشکال را صرفه‌جویی کند. --- -### ▶ ‫ تقسیم‌ها * +### ▶ تقسیم‌ها * ```py >>> 'a'.split() @@ -2847,12 +2847,12 @@ def similar_recursive_func(a): 1 ``` -#### 💡 ‫ توضیحات: +#### 💡 توضیحات: -- ‫ در نگاه اول ممکن است به نظر برسد جداکننده‌ی پیش‌فرض متد `split` یک فاصله‌ی تکی (`' '`) است؛ اما مطابق با [مستندات رسمی](https://docs.python.org/3/library/stdtypes.html#str.split): - > ‫ اگر `sep` مشخص نشده یا برابر با `None` باشد، یک الگوریتم متفاوت برای جدا کردن اعمال می‌شود: رشته‌هایی از فاصله‌های متوالی به عنوان یک جداکننده‌ی واحد در نظر گرفته شده و در نتیجه، هیچ رشته‌ی خالی‌ای در ابتدا یا انتهای لیست خروجی قرار نمی‌گیرد، حتی اگر رشته‌ی اولیه دارای فاصله‌های اضافی در ابتدا یا انتها باشد. به همین دلیل، تقسیم یک رشته‌ی خالی یا رشته‌ای که فقط شامل فضای خالی است با جداکننده‌ی `None` باعث بازگشت یک لیست خالی `[]` می‌شود. - > ‫ اگر `sep` مشخص شود، جداکننده‌های متوالی در کنار هم قرار نمی‌گیرند و هر جداکننده، یک رشته‌ی خالی جدید ایجاد می‌کند. (مثلاً `'1,,2'.split(',')` مقدار `['1', '', '2']` را برمی‌گرداند.) تقسیم یک رشته‌ی خالی با یک جداکننده‌ی مشخص‌شده نیز باعث بازگشت `['']` می‌شود. -- ‫ توجه به اینکه چگونه فضای خالی در ابتدا و انتهای رشته در قطعه‌ی کد زیر مدیریت شده است، این مفهوم را روشن‌تر می‌کند: +- در نگاه اول ممکن است به نظر برسد جداکننده‌ی پیش‌فرض متد `split` یک فاصله‌ی تکی (`' '`) است؛ اما مطابق با [مستندات رسمی](https://docs.python.org/3/library/stdtypes.html#str.split): + > اگر `sep` مشخص نشده یا برابر با `None` باشد، یک الگوریتم متفاوت برای جدا کردن اعمال می‌شود: رشته‌هایی از فاصله‌های متوالی به عنوان یک جداکننده‌ی واحد در نظر گرفته شده و در نتیجه، هیچ رشته‌ی خالی‌ای در ابتدا یا انتهای لیست خروجی قرار نمی‌گیرد، حتی اگر رشته‌ی اولیه دارای فاصله‌های اضافی در ابتدا یا انتها باشد. به همین دلیل، تقسیم یک رشته‌ی خالی یا رشته‌ای که فقط شامل فضای خالی است با جداکننده‌ی `None` باعث بازگشت یک لیست خالی `[]` می‌شود. + > اگر `sep` مشخص شود، جداکننده‌های متوالی در کنار هم قرار نمی‌گیرند و هر جداکننده، یک رشته‌ی خالی جدید ایجاد می‌کند. (مثلاً `'1,,2'.split(',')` مقدار `['1', '', '2']` را برمی‌گرداند.) تقسیم یک رشته‌ی خالی با یک جداکننده‌ی مشخص‌شده نیز باعث بازگشت `['']` می‌شود. +- توجه به اینکه چگونه فضای خالی در ابتدا و انتهای رشته در قطعه‌ی کد زیر مدیریت شده است، این مفهوم را روشن‌تر می‌کند: ```py >>> ' a '.split(' ') ['', 'a', ''] @@ -2879,7 +2879,7 @@ def _another_weird_name_func(): ``` -‫ **خروجی** +**خروجی** ```py >>> from module import * @@ -2891,16 +2891,16 @@ Traceback (most recent call last): NameError: name '_another_weird_name_func' is not defined ``` -#### 💡 ‫ توضیحات: +#### 💡 توضیحات: -- ‫ اغلب توصیه می‌شود از واردسازی عمومی (wildcard imports) استفاده نکنید. اولین دلیل واضح آن این است که در این نوع واردسازی‌ها، اسامی که با زیرخط (`_`) شروع شوند، وارد نمی‌شوند. این مسئله ممکن است در زمان اجرا به خطا منجر شود. -- ‫ اگر از ساختار `from ... import a, b, c` استفاده کنیم، خطای `NameError` فوق اتفاق نمی‌افتاد. +- اغلب توصیه می‌شود از واردسازی عمومی (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! ``` -- ‫ اگر واقعاً تمایل دارید از واردسازی عمومی استفاده کنید، لازم است فهرستی به نام `__all__` را در ماژول خود تعریف کنید که شامل نام اشیاء عمومی (public) قابل‌دسترس هنگام واردسازی عمومی است. +- اگر واقعاً تمایل دارید از واردسازی عمومی استفاده کنید، لازم است فهرستی به نام `__all__` را در ماژول خود تعریف کنید که شامل نام اشیاء عمومی (public) قابل‌دسترس هنگام واردسازی عمومی است. ```py __all__ = ['_another_weird_name_func'] @@ -2910,7 +2910,7 @@ NameError: name '_another_weird_name_func' is not defined def _another_weird_name_func(): print("works!") ``` - ‫ **خروجی** + **خروجی** ```py >>> _another_weird_name_func() @@ -2923,7 +2923,7 @@ NameError: name '_another_weird_name_func' is not defined --- -### ▶ ‫ همه چیز مرتب شده؟ * +### ▶ همه چیز مرتب شده؟ * @@ -2939,9 +2939,9 @@ True False ``` -#### 💡 ‫ توضیحات: +#### 💡 توضیحات: -- ‫ متد `sorted` همیشه یک لیست (`list`) برمی‌گرداند، و در پایتون مقایسه‌ی لیست‌ها و تاپل‌ها (`tuple`) همیشه مقدار `False` را برمی‌گرداند. +- متد `sorted` همیشه یک لیست (`list`) برمی‌گرداند، و در پایتون مقایسه‌ی لیست‌ها و تاپل‌ها (`tuple`) همیشه مقدار `False` را برمی‌گرداند. - ```py >>> [] == tuple() @@ -2950,9 +2950,9 @@ False >>> type(x), type(sorted(x)) (tuple, list) ``` -- ‫ برخلاف متد `sorted`، متد `reversed` یک تکرارکننده (iterator) برمی‌گرداند. چرا؟ زیرا مرتب‌سازی نیاز به تغییر درجا (in-place) یا استفاده از ظرف جانبی (مانند یک لیست اضافی) دارد، در حالی که معکوس کردن می‌تواند به‌سادگی با پیمایش از اندیس آخر به اول انجام شود. +- برخلاف متد `sorted`، متد `reversed` یک تکرارکننده (iterator) برمی‌گرداند. چرا؟ زیرا مرتب‌سازی نیاز به تغییر درجا (in-place) یا استفاده از ظرف جانبی (مانند یک لیست اضافی) دارد، در حالی که معکوس کردن می‌تواند به‌سادگی با پیمایش از اندیس آخر به اول انجام شود. -- ‫ بنابراین در مقایسه‌ی `sorted(y) == sorted(y)`، فراخوانی اولِ `sorted()` تمام عناصرِ تکرارکننده‌ی `y` را مصرف می‌کند، و فراخوانی بعدی یک لیست خالی برمی‌گرداند. +- بنابراین در مقایسه‌ی `sorted(y) == sorted(y)`، فراخوانی اولِ `sorted()` تمام عناصرِ تکرارکننده‌ی `y` را مصرف می‌کند، و فراخوانی بعدی یک لیست خالی برمی‌گرداند. ```py >>> x = 7, 8, 9 @@ -2963,7 +2963,7 @@ False --- -### ▶ ‫ زمان نیمه‌شب وجود ندارد؟ +### ▶ زمان نیمه‌شب وجود ندارد؟ ```py from datetime import datetime @@ -2981,14 +2981,14 @@ if noon_time: print("Time at noon is", noon_time) ``` -‫ **خروجی (< 3.5):** +**خروجی (< 3.5):** ```py ('Time at noon is', datetime.time(12, 0)) ``` 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." @@ -2997,29 +2997,29 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t -## ‫ بخش: گنجینه‌های پنهان! +## بخش: گنجینه‌های پنهان! -‫ این بخش شامل چند مورد جالب و کمتر شناخته‌شده درباره‌ی پایتون است که بیشتر مبتدی‌هایی مثل من از آن بی‌خبرند (البته دیگر اینطور نیست). +این بخش شامل چند مورد جالب و کمتر شناخته‌شده درباره‌ی پایتون است که بیشتر مبتدی‌هایی مثل من از آن بی‌خبرند (البته دیگر اینطور نیست). -### ▶ ‫ خب پایتون، می‌توانی کاری کنی پرواز کنم؟ +### ▶ خب پایتون، می‌توانی کاری کنی پرواز کنم؟ -‫ خب، بفرمایید +خب، بفرمایید ```py import antigravity ``` -‫ **خروجی:** +**خروجی:** Sshh... It's a super-secret. -#### ‫ 💡 توضیح: -+ ‫ ماژول `antigravity` یکی از معدود ایستر اِگ‌هایی است که توسط توسعه‌دهندگان پایتون ارائه شده است. -+ ‫ دستور `import antigravity` باعث می‌شود مرورگر وب به سمت [کمیک کلاسیک XKCD](https://xkcd.com/353/) در مورد پایتون باز شود. -+ ‫ البته موضوع عمیق‌تر است؛ در واقع یک **ایستر اگ دیگر داخل این ایستر اگ** وجود دارد. اگر به [کد منبع](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17) نگاه کنید، یک تابع تعریف شده که ادعا می‌کند [الگوریتم جئوهشینگ XKCD](https://xkcd.com/426/) را پیاده‌سازی کرده است. +#### 💡 توضیح: ++ ماژول `antigravity` یکی از معدود ایستر اِگ‌هایی است که توسط توسعه‌دهندگان پایتون ارائه شده است. ++ دستور `import antigravity` باعث می‌شود مرورگر وب به سمت [کمیک کلاسیک XKCD](https://xkcd.com/353/) در مورد پایتون باز شود. ++ البته موضوع عمیق‌تر است؛ در واقع یک **ایستر اگ دیگر داخل این ایستر اگ** وجود دارد. اگر به [کد منبع](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17) نگاه کنید، یک تابع تعریف شده که ادعا می‌کند [الگوریتم جئوهشینگ XKCD](https://xkcd.com/426/) را پیاده‌سازی کرده است. --- -### ▶ ‫ `goto`، ولی چرا؟ +### ▶ `goto`، ولی چرا؟ ```py @@ -3034,48 +3034,48 @@ label .breakout print("Freedom!") ``` -‫ **خروجی (پایتون ۲.۳):** +**خروجی (پایتون ۲.۳):** ```py I am trapped, please rescue! I am trapped, please rescue! Freedom! ``` -#### ‫ 💡 توضیح: -- ‫ نسخه‌ی قابل استفاده‌ای از `goto` در پایتون به عنوان یک شوخی [در اول آوریل ۲۰۰۴ معرفی شد](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html). -- ‫ نسخه‌های فعلی پایتون فاقد این ماژول هستند. -- ‫ اگرچه این ماژول واقعاً کار می‌کند، ولی لطفاً از آن استفاده نکنید. در [این صفحه](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) می‌توانید دلیل عدم حضور دستور `goto` در پایتون را مطالعه کنید. +#### 💡 توضیح: +- نسخه‌ی قابل استفاده‌ای از `goto` در پایتون به عنوان یک شوخی [در اول آوریل ۲۰۰۴ معرفی شد](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html). +- نسخه‌های فعلی پایتون فاقد این ماژول هستند. +- اگرچه این ماژول واقعاً کار می‌کند، ولی لطفاً از آن استفاده نکنید. در [این صفحه](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) می‌توانید دلیل عدم حضور دستور `goto` در پایتون را مطالعه کنید. --- -### ▶ ‫ خودتان را آماده کنید! +### ▶ خودتان را آماده کنید! -‫ اگر جزو افرادی هستید که دوست ندارند در پایتون برای مشخص کردن محدوده‌ها از فضای خالی (whitespace) استفاده کنند، می‌توانید با ایمپورت کردن ماژول زیر از آکولاد `{}` به سبک زبان C استفاده کنید: +اگر جزو افرادی هستید که دوست ندارند در پایتون برای مشخص کردن محدوده‌ها از فضای خالی (whitespace) استفاده کنند، می‌توانید با ایمپورت کردن ماژول زیر از آکولاد `{}` به سبک زبان C استفاده کنید: ```py from __future__ import braces ``` -‫ **خروجی:** +**خروجی:** ```py File "some_file.py", line 1 from __future__ import braces SyntaxError: not a chance ``` -‫ آکولاد؟ هرگز! اگر از این بابت ناامید شدید، بهتر است از جاوا استفاده کنید. خب، یک چیز شگفت‌آور دیگر؛ آیا می‌توانید تشخیص دهید که ارور `SyntaxError` در کجای کد ماژول `__future__` [اینجا](https://github.com/python/cpython/blob/master/Lib/__future__.py) ایجاد می‌شود؟ +آکولاد؟ هرگز! اگر از این بابت ناامید شدید، بهتر است از جاوا استفاده کنید. خب، یک چیز شگفت‌آور دیگر؛ آیا می‌توانید تشخیص دهید که ارور `SyntaxError` در کجای کد ماژول `__future__` [اینجا](https://github.com/python/cpython/blob/master/Lib/__future__.py) ایجاد می‌شود؟ -#### ‫ 💡 توضیح: -+ ‫ ماژول `__future__` معمولاً برای ارائه قابلیت‌هایی از نسخه‌های آینده پایتون به کار می‌رود. اما کلمه «future» (آینده) در این زمینه خاص، حالت طنز و کنایه دارد. -+ ‫ این مورد یک «ایستر اگ» (easter egg) است که به احساسات جامعه برنامه‌نویسان پایتون در این خصوص اشاره دارد. -+ ‫ کد مربوط به این موضوع در واقع [اینجا](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) در فایل `future.c` قرار دارد. -+ ‫ زمانی که کامپایلر CPython با یک [عبارت future](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements) مواجه می‌شود، ابتدا کد مرتبط در `future.c` را اجرا کرده و سپس آن را همانند یک دستور ایمپورت عادی در نظر می‌گیرد. +#### 💡 توضیح: ++ ماژول `__future__` معمولاً برای ارائه قابلیت‌هایی از نسخه‌های آینده پایتون به کار می‌رود. اما کلمه «future» (آینده) در این زمینه خاص، حالت طنز و کنایه دارد. ++ این مورد یک «ایستر اگ» (easter egg) است که به احساسات جامعه برنامه‌نویسان پایتون در این خصوص اشاره دارد. ++ کد مربوط به این موضوع در واقع [اینجا](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) در فایل `future.c` قرار دارد. ++ زمانی که کامپایلر CPython با یک [عبارت future](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements) مواجه می‌شود، ابتدا کد مرتبط در `future.c` را اجرا کرده و سپس آن را همانند یک دستور ایمپورت عادی در نظر می‌گیرد. --- -### ▶ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم +### ▶ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم -‫ **خروجی (Python 3.x)** +**خروجی (Python 3.x)** ```py >>> from __future__ import barry_as_FLUFL >>> "Ruby" != "Python" # شکی در این نیست. @@ -3088,16 +3088,16 @@ SyntaxError: invalid syntax True ``` -‫ حالا می‌رسیم به اصل ماجرا. +حالا می‌رسیم به اصل ماجرا. -#### ‫ 💡 توضیح: -- ‫ این مورد مربوط به [PEP-401](https://www.python.org/dev/peps/pep-0401/) است که در تاریخ ۱ آوریل ۲۰۰۹ منتشر شد (اکنون می‌دانید این یعنی چه!). -- ‫ نقل قولی از PEP-401: +#### 💡 توضیح: +- این مورد مربوط به [PEP-401](https://www.python.org/dev/peps/pep-0401/) است که در تاریخ ۱ آوریل ۲۰۰۹ منتشر شد (اکنون می‌دانید این یعنی چه!). +- نقل قولی از PEP-401: - > ‫ با توجه به اینکه عملگر نابرابری `!=` در پایتون ۳.۰ یک اشتباه وحشتناک و انگشت‌سوز (!) بوده است، عمو زبان مهربان برای همیشه (FLUFL) عملگر الماسی‌شکل `<>` را مجدداً به‌عنوان تنها روش درست برای این منظور بازگردانده است. + > با توجه به اینکه عملگر نابرابری `!=` در پایتون ۳.۰ یک اشتباه وحشتناک و انگشت‌سوز (!) بوده است، عمو زبان مهربان برای همیشه (FLUFL) عملگر الماسی‌شکل `<>` را مجدداً به‌عنوان تنها روش درست برای این منظور بازگردانده است. -- ‫ البته «عمو بَری» چیزهای بیشتری برای گفتن در این PEP داشت؛ می‌توانید آن‌ها را [اینجا](https://www.python.org/dev/peps/pep-0401/) مطالعه کنید. -- ‫ این قابلیت در محیط تعاملی به خوبی عمل می‌کند، اما در زمان اجرای کد از طریق فایل پایتون، با خطای `SyntaxError` روبرو خواهید شد (برای اطلاعات بیشتر به این [issue](https://github.com/satwikkansal/wtfpython/issues/94) مراجعه کنید). با این حال، می‌توانید کد خود را درون یک `eval` یا `compile` قرار دهید تا این قابلیت فعال شود. +- البته «عمو بَری» چیزهای بیشتری برای گفتن در این 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 @@ -3106,7 +3106,7 @@ True --- -### ▶ ‫ حتی پایتون هم می‌داند که عشق پیچیده است +### ▶ حتی پایتون هم می‌داند که عشق پیچیده است ```py import this @@ -3114,7 +3114,7 @@ import this Wait, what's **this**? `this` is love :heart: -‫ **خروجی:** +**خروجی:** ``` The Zen of Python, by Tim Peters @@ -3139,7 +3139,7 @@ If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ``` -‫ این ذنِ پایتون است! +این ذنِ پایتون است! ```py >>> love = this @@ -3155,17 +3155,17 @@ True True ``` -#### ‫ 💡 توضیح: +#### 💡 توضیح: -* ‫ ماژول `this` در پایتون، یک ایستر اگ برای «ذنِ پایتون» ([PEP 20](https://www.python.org/dev/peps/pep-0020)) است. -* ‫ اگر این موضوع به‌اندازه کافی جالب است، حتماً پیاده‌سازی [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py) را ببینید. نکته جالب این است که **کد مربوط به ذنِ پایتون، خودش اصول ذن را نقض کرده است** (و احتمالاً این تنها جایی است که چنین اتفاقی می‌افتد). -* ‫ درباره جمله `love is not True or False; love is love`، اگرچه طعنه‌آمیز است، اما خود گویاست. (اگر واضح نیست، لطفاً مثال‌های مربوط به عملگرهای `is` و `is not` را مشاهده کنید.) +* ماژول `this` در پایتون، یک ایستر اگ برای «ذنِ پایتون» ([PEP 20](https://www.python.org/dev/peps/pep-0020)) است. +* اگر این موضوع به‌اندازه کافی جالب است، حتماً پیاده‌سازی [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py) را ببینید. نکته جالب این است که **کد مربوط به ذنِ پایتون، خودش اصول ذن را نقض کرده است** (و احتمالاً این تنها جایی است که چنین اتفاقی می‌افتد). +* درباره جمله `love is not True or False; love is love`، اگرچه طعنه‌آمیز است، اما خود گویاست. (اگر واضح نیست، لطفاً مثال‌های مربوط به عملگرهای `is` و `is not` را مشاهده کنید.) --- -### ▶ ‫ بله، این واقعاً وجود دارد! +### ▶ بله، این واقعاً وجود دارد! -‫ **عبارت `else` برای حلقه‌ها.** یک مثال معمول آن می‌تواند چنین باشد: +**عبارت `else` برای حلقه‌ها.** یک مثال معمول آن می‌تواند چنین باشد: ```py def does_exists_num(l, to_find): @@ -3202,7 +3202,7 @@ else: Try block executed successfully... ``` -#### ‫ 💡 توضیح: +#### 💡 توضیح: - عبارت `else` بعد از حلقه‌ها تنها زمانی اجرا می‌شود که در هیچ‌کدام از تکرارها (`iterations`) از دستور `break` استفاده نشده باشد. می‌توانید آن را به عنوان یک شرط «بدون شکست» (nobreak) در نظر بگیرید. - عبارت `else` پس از بلاک `try` به عنوان «عبارت تکمیل» (`completion clause`) نیز شناخته می‌شود؛ چراکه رسیدن به عبارت `else` در ساختار `try` به این معنی است که بلاک `try` بدون رخ دادن استثنا با موفقیت تکمیل شده است. @@ -3228,15 +3228,15 @@ NameError: name 'SomeRandomString' is not defined Ellipsis ``` -#### ‫ 💡توضیح -- ‫ در پایتون، `Ellipsis` یک شیء درونی (`built-in`) است که به صورت سراسری (`global`) در دسترس است و معادل `...` است. +#### 💡توضیح +- در پایتون، `Ellipsis` یک شیء درونی (`built-in`) است که به صورت سراسری (`global`) در دسترس است و معادل `...` است. ```py >>> ... Ellipsis ``` -- ‫ `Ellipsis` می‌تواند برای چندین منظور استفاده شود: - + ‫ به عنوان یک نگه‌دارنده برای کدی که هنوز نوشته نشده است (مانند دستور `pass`) - + ‫ در سینتکس برش (`slicing`) برای نمایش برش کامل در ابعاد باقی‌مانده +- `Ellipsis` می‌تواند برای چندین منظور استفاده شود: + + به عنوان یک نگه‌دارنده برای کدی که هنوز نوشته نشده است (مانند دستور `pass`) + + در سینتکس برش (`slicing`) برای نمایش برش کامل در ابعاد باقی‌مانده ```py >>> import numpy as np @@ -3253,7 +3253,7 @@ Ellipsis ] ]) ``` - ‫ بنابراین، آرایه‌ی `three_dimensional_array` ما، آرایه‌ای از آرایه‌ها از آرایه‌ها است. فرض کنیم می‌خواهیم عنصر دوم (اندیس `1`) از تمامی آرایه‌های درونی را چاپ کنیم؛ در این حالت می‌توانیم از `Ellipsis` برای عبور از تمامی ابعاد قبلی استفاده کنیم: + بنابراین، آرایه‌ی `three_dimensional_array` ما، آرایه‌ای از آرایه‌ها از آرایه‌ها است. فرض کنیم می‌خواهیم عنصر دوم (اندیس `1`) از تمامی آرایه‌های درونی را چاپ کنیم؛ در این حالت می‌توانیم از `Ellipsis` برای عبور از تمامی ابعاد قبلی استفاده کنیم: ```py >>> three_dimensional_array[:,:,1] array([[1, 3], @@ -3262,18 +3262,18 @@ Ellipsis array([[1, 3], [5, 7]]) ``` - ‫ نکته: این روش برای آرایه‌هایی با هر تعداد بُعد کار می‌کند. حتی می‌توانید از برش (`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` ارسال شده است» تمایز قائل شوید). + نکته: این روش برای آرایه‌هایی با هر تعداد بُعد کار می‌کند. حتی می‌توانید از برش (`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`) +### ▶ بی‌نهایت (`Inpinity`) -‫ این املای کلمه تعمداً به همین شکل نوشته شده است. لطفاً برای اصلاح آن درخواست (`patch`) ارسال نکنید. +این املای کلمه تعمداً به همین شکل نوشته شده است. لطفاً برای اصلاح آن درخواست (`patch`) ارسال نکنید. -‫ **خروجی (پایتون 3.x):** +**خروجی (پایتون 3.x):** ```py >>> infinity = float('infinity') >>> hash(infinity) @@ -3282,13 +3282,13 @@ Ellipsis -314159 ``` -#### ‫ 💡 توضیح: -- ‫ هش (`hash`) مقدار بی‌نهایت برابر با 10⁵ × π است. -- ‫ نکته جالب اینکه در پایتون ۳ هشِ مقدار `float('-inf')` برابر با «-10⁵ × π» است، در حالی که در پایتون ۲ برابر با «-10⁵ × e» است. +#### 💡 توضیح: +- هش (`hash`) مقدار بی‌نهایت برابر با 10⁵ × π است. +- نکته جالب اینکه در پایتون ۳ هشِ مقدار `float('-inf')` برابر با «-10⁵ × π» است، در حالی که در پایتون ۲ برابر با «-10⁵ × e» است. --- -### ▶ ‫ بیایید خرابکاری کنیم +### ▶ بیایید خرابکاری کنیم 1\. ```py @@ -3298,7 +3298,7 @@ class Yo(object): self.bro = True ``` -‫ **خروجی:** +**خروجی:** ```py >>> Yo().bro True @@ -3317,7 +3317,7 @@ class Yo(object): self.bro = True ``` -‫ **خروجی:** +**خروجی:** ```py >>> Yo().bro True @@ -3340,7 +3340,7 @@ class A(object): return __variable # هنوز در هیچ جا مقداردهی اولیه نشده است ``` -‫ **خروجی:** +**خروجی:** ```py >>> A().__variable Traceback (most recent call last): @@ -3352,23 +3352,23 @@ AttributeError: 'A' object has no attribute '__variable' ``` -#### ‫ 💡 توضیح: +#### 💡 توضیح: -* ‫ [تغییر نام](https://en.wikipedia.org/wiki/Name_mangling) برای جلوگیری از برخورد نام‌ها بین فضاهای نام مختلف استفاده می‌شود. -* ‫ در پایتون، مفسر نام‌های اعضای کلاس که با `__` (دو آندرلاین که به عنوان "دندر" شناخته می‌شود) شروع می‌شوند و بیش از یک آندرلاین انتهایی ندارند را با اضافه کردن `_NameOfTheClass` در ابتدای آنها تغییر می‌دهد. -* ‫ بنابراین، برای دسترسی به ویژگی `__honey` در اولین قطعه کد، مجبور بودیم `_Yo` را به ابتدای آن اضافه کنیم، که از بروز تعارض با ویژگی با همان نام تعریف‌شده در هر کلاس دیگری جلوگیری می‌کند. -* ‫ اما چرا در دومین قطعه کد کار نکرد؟ زیرا تغییر نام، نام‌هایی که با دو آندرلاین خاتمه می‌یابند را شامل نمی‌شود. -* ‫ قطعه سوم نیز نتیجه تغییر نام بود. نام `__variable` در عبارت `return __variable` به `_A__variable` تغییر یافت، که همچنین همان نام متغیری است که در محدوده بیرونی تعریف کرده بودیم. -* ‫ همچنین، اگر نام تغییر یافته بیش از ۲۵۵ کاراکتر باشد، برش داده می‌شود. +* [تغییر نام](https://en.wikipedia.org/wiki/Name_mangling) برای جلوگیری از برخورد نام‌ها بین فضاهای نام مختلف استفاده می‌شود. +* در پایتون، مفسر نام‌های اعضای کلاس که با `__` (دو آندرلاین که به عنوان "دندر" شناخته می‌شود) شروع می‌شوند و بیش از یک آندرلاین انتهایی ندارند را با اضافه کردن `_NameOfTheClass` در ابتدای آنها تغییر می‌دهد. +* بنابراین، برای دسترسی به ویژگی `__honey` در اولین قطعه کد، مجبور بودیم `_Yo` را به ابتدای آن اضافه کنیم، که از بروز تعارض با ویژگی با همان نام تعریف‌شده در هر کلاس دیگری جلوگیری می‌کند. +* اما چرا در دومین قطعه کد کار نکرد؟ زیرا تغییر نام، نام‌هایی که با دو آندرلاین خاتمه می‌یابند را شامل نمی‌شود. +* قطعه سوم نیز نتیجه تغییر نام بود. نام `__variable` در عبارت `return __variable` به `_A__variable` تغییر یافت، که همچنین همان نام متغیری است که در محدوده بیرونی تعریف کرده بودیم. +* همچنین، اگر نام تغییر یافته بیش از ۲۵۵ کاراکتر باشد، برش داده می‌شود. --- --- -## ‫ بخش: ظاهرها فریبنده‌اند! +## بخش: ظاهرها فریبنده‌اند! -### ▶ ‫ خطوط را رد می‌کند؟ +### ▶ خطوط را رد می‌کند؟ -‫ **خروجی:** +**خروجی:** ```py >>> value = 11 >>> valuе = 32 @@ -3376,13 +3376,13 @@ AttributeError: 'A' object has no attribute '__variable' 11 ``` -‫ چی? +چی? -‫ **نکته:** ساده‌ترین روش برای بازتولید این رفتار، کپی کردن دستورات از کد بالا و جایگذاری (paste) آن‌ها در فایل یا محیط تعاملی (shell) خودتان است. +**نکته:** ساده‌ترین روش برای بازتولید این رفتار، کپی کردن دستورات از کد بالا و جایگذاری (paste) آن‌ها در فایل یا محیط تعاملی (shell) خودتان است. -#### ‫ 💡 توضیح +#### 💡 توضیح -‫ برخی از حروف غیرغربی کاملاً مشابه حروف الفبای انگلیسی به نظر می‌رسند، اما مفسر پایتون آن‌ها را متفاوت در نظر می‌گیرد. +برخی از حروف غیرغربی کاملاً مشابه حروف الفبای انگلیسی به نظر می‌رسند، اما مفسر پایتون آن‌ها را متفاوت در نظر می‌گیرد. ```py >>> ord('е') # حرف سیریلیک «е» (Ye) @@ -3398,11 +3398,11 @@ False 42 ``` -‫ تابع داخلی `ord()`، [کدپوینت](https://fa.wikipedia.org/wiki/کدپوینت) یونیکد مربوط به یک نویسه را برمی‌گرداند. موقعیت‌های کدی متفاوت برای حرف سیریلیک «е» و حرف لاتین «e»، علت رفتار مثال بالا را توجیه می‌کنند. +تابع داخلی `ord()`، [کدپوینت](https://fa.wikipedia.org/wiki/کدپوینت) یونیکد مربوط به یک نویسه را برمی‌گرداند. موقعیت‌های کدی متفاوت برای حرف سیریلیک «е» و حرف لاتین «e»، علت رفتار مثال بالا را توجیه می‌کنند. --- -### ▶ ‫ تله‌پورت کردن +### ▶ تله‌پورت کردن @@ -3419,23 +3419,23 @@ def energy_receive(): return np.empty((), dtype=np.float).tolist() ``` -‫ **خروجی:** +**خروجی:** ```py >>> energy_send(123.456) >>> energy_receive() 123.456 ``` -‫ جایزه نوبل کجاست؟ +جایزه نوبل کجاست؟ -#### ‫ 💡 توضیح: +#### 💡 توضیح: -* ‫ توجه کنید که آرایه‌ی numpy ایجادشده در تابع `energy_send` برگردانده نشده است، بنابراین فضای حافظه‌ی آن آزاد شده و مجدداً قابل استفاده است. -* ‫ تابع `numpy.empty()` نزدیک‌ترین فضای حافظه‌ی آزاد را بدون مقداردهی مجدد برمی‌گرداند. این فضای حافظه معمولاً همان فضایی است که به‌تازگی آزاد شده است (البته معمولاً این اتفاق می‌افتد و نه همیشه). +* توجه کنید که آرایه‌ی numpy ایجادشده در تابع `energy_send` برگردانده نشده است، بنابراین فضای حافظه‌ی آن آزاد شده و مجدداً قابل استفاده است. +* تابع `numpy.empty()` نزدیک‌ترین فضای حافظه‌ی آزاد را بدون مقداردهی مجدد برمی‌گرداند. این فضای حافظه معمولاً همان فضایی است که به‌تازگی آزاد شده است (البته معمولاً این اتفاق می‌افتد و نه همیشه). --- -### ▶ ‫ خب، یک جای کار مشکوک است... +### ▶ خب، یک جای کار مشکوک است... ```py def square(x): @@ -3448,27 +3448,27 @@ def square(x): return sum_so_far ``` -‫ **خروجی (پایتون 2.X):** +**خروجی (پایتون 2.X):** ```py >>> square(10) 10 ``` -‫ آیا این نباید ۱۰۰ باشد؟ +آیا این نباید ۱۰۰ باشد؟ -‫ **نکته:** اگر نمی‌توانید این مشکل را بازتولید کنید، سعی کنید فایل [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) را از طریق شِل اجرا کنید. +**نکته:** اگر نمی‌توانید این مشکل را بازتولید کنید، سعی کنید فایل [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) را از طریق شِل اجرا کنید. -#### ‫ 💡 توضیح +#### 💡 توضیح -* ‫ **تب‌ها و فاصله‌ها (space) را با هم ترکیب نکنید!** کاراکتری که دقیقاً قبل از دستور return آمده یک «تب» است، در حالی که در بقیۀ مثال، کد با مضربی از «۴ فاصله» تورفتگی دارد. -* ‫ نحوۀ برخورد پایتون با تب‌ها به این صورت است: +* **تب‌ها و فاصله‌ها (space) را با هم ترکیب نکنید!** کاراکتری که دقیقاً قبل از دستور return آمده یک «تب» است، در حالی که در بقیۀ مثال، کد با مضربی از «۴ فاصله» تورفتگی دارد. +* نحوۀ برخورد پایتون با تب‌ها به این صورت است: - > ‫ ابتدا تب‌ها (از چپ به راست) با یک تا هشت فاصله جایگزین می‌شوند به‌طوری که تعداد کل کاراکترها تا انتهای آن جایگزینی، مضربی از هشت باشد <...> -* ‫ بنابراین «تب» در آخرین خط تابع `square` با هشت فاصله جایگزین شده و به همین دلیل داخل حلقه قرار می‌گیرد. -* ‫ پایتون ۳ آنقدر هوشمند هست که چنین مواردی را به‌صورت خودکار با خطا اعلام کند. + > ابتدا تب‌ها (از چپ به راست) با یک تا هشت فاصله جایگزین می‌شوند به‌طوری که تعداد کل کاراکترها تا انتهای آن جایگزینی، مضربی از هشت باشد <...> +* بنابراین «تب» در آخرین خط تابع `square` با هشت فاصله جایگزین شده و به همین دلیل داخل حلقه قرار می‌گیرد. +* پایتون ۳ آنقدر هوشمند هست که چنین مواردی را به‌صورت خودکار با خطا اعلام کند. - ‫ **خروجی (Python 3.x):** + **خروجی (Python 3.x):** ```py TabError: inconsistent use of tabs and spaces in indentation @@ -3480,7 +3480,7 @@ def square(x): ## بخش: متفرقه -### ‫ ▶ `+=` سریع‌تر است +### ▶ `+=` سریع‌تر است ```py @@ -3492,12 +3492,12 @@ def square(x): 0.012188911437988281 ``` -#### ‫ 💡 توضیح: -+ ‫ استفاده از `+=` برای اتصال بیش از دو رشته سریع‌تر از `+` است، زیرا هنگام محاسبه رشته‌ی نهایی، رشته‌ی اول (به‌عنوان مثال `s1` در عبارت `s1 += s2 + s3`) از بین نمی‌رود. +#### 💡 توضیح: ++ استفاده از `+=` برای اتصال بیش از دو رشته سریع‌تر از `+` است، زیرا هنگام محاسبه رشته‌ی نهایی، رشته‌ی اول (به‌عنوان مثال `s1` در عبارت `s1 += s2 + s3`) از بین نمی‌رود. --- -### ‫ ▶ بیایید یک رشته‌ی بزرگ بسازیم! +### ▶ بیایید یک رشته‌ی بزرگ بسازیم! ```py def add_string_with_plus(iters): @@ -3529,10 +3529,10 @@ def convert_list_to_string(l, iters): assert len(s) == 3*iters ``` -‫ **خروجی:** +**خروجی:** -‫ اجرا شده در پوسته‌ی ipython با استفاده از `%timeit` برای خوانایی بهتر نتایج. -‫ همچنین می‌توانید از ماژول `timeit` در پوسته یا اسکریپت عادی پایتون استفاده کنید؛ نمونه‌ی استفاده در زیر آمده است: +اجرا شده در پوسته‌ی ipython با استفاده از `%timeit` برای خوانایی بهتر نتایج. +همچنین می‌توانید از ماژول `timeit` در پوسته یا اسکریپت عادی پایتون استفاده کنید؛ نمونه‌ی استفاده در زیر آمده است: timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) ```py @@ -3551,7 +3551,7 @@ timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) 10.1 µs ± 1.06 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` -‫ بیایید تعداد تکرارها را ۱۰ برابر افزایش دهیم. +بیایید تعداد تکرارها را ۱۰ برابر افزایش دهیم. ```py >>> NUM_ITERS = 10000 @@ -3570,11 +3570,11 @@ timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) #### 💡 توضیحات توضیحات -- ‫ برای اطلاعات بیشتر درباره‌ی [timeit](https://docs.python.org/3/library/timeit.html) یا [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit)، می‌توانید به این لینک‌ها مراجعه کنید. این توابع برای اندازه‌گیری زمان اجرای قطعه‌کدها استفاده می‌شوند. -- ‫ برای تولید رشته‌های طولانی از `+` استفاده نکنید — در پایتون، نوع داده‌ی `str` تغییرناپذیر (immutable) است؛ بنابراین برای هر الحاق (concatenation)، رشته‌ی چپ و راست باید در رشته‌ی جدید کپی شوند. اگر چهار رشته‌ی ۱۰ حرفی را متصل کنید، به‌جای کپی ۴۰ کاراکتر، باید `(10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90` کاراکتر کپی کنید. این وضعیت با افزایش تعداد و طول رشته‌ها به‌صورت درجه دو (مربعی) بدتر می‌شود (که توسط زمان اجرای تابع `add_bytes_with_plus` تأیید شده است). -- ‫ بنابراین توصیه می‌شود از `.format` یا سینتکس `%` استفاده کنید (البته این روش‌ها برای رشته‌های بسیار کوتاه کمی کندتر از `+` هستند). -- ‫ اما بهتر از آن، اگر محتوای شما از قبل به‌شکل یک شیء قابل تکرار (iterable) موجود است، از دستور `''.join(iterable_object)` استفاده کنید که بسیار سریع‌تر است. -- ‫ برخلاف تابع `add_bytes_with_plus` و به‌دلیل بهینه‌سازی‌های انجام‌شده برای عملگر `+=` (که در مثال قبلی توضیح داده شد)، تابع `add_string_with_plus` افزایشی درجه دو در زمان اجرا نشان نداد. اگر دستور به‌صورت `s = s + "x" + "y" + "z"` بود (به‌جای `s += "xyz"`)، افزایش زمان اجرا درجه دو می‌شد. +- برای اطلاعات بیشتر درباره‌ی [timeit](https://docs.python.org/3/library/timeit.html) یا [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit)، می‌توانید به این لینک‌ها مراجعه کنید. این توابع برای اندازه‌گیری زمان اجرای قطعه‌کدها استفاده می‌شوند. +- برای تولید رشته‌های طولانی از `+` استفاده نکنید — در پایتون، نوع داده‌ی `str` تغییرناپذیر (immutable) است؛ بنابراین برای هر الحاق (concatenation)، رشته‌ی چپ و راست باید در رشته‌ی جدید کپی شوند. اگر چهار رشته‌ی ۱۰ حرفی را متصل کنید، به‌جای کپی ۴۰ کاراکتر، باید `(10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90` کاراکتر کپی کنید. این وضعیت با افزایش تعداد و طول رشته‌ها به‌صورت درجه دو (مربعی) بدتر می‌شود (که توسط زمان اجرای تابع `add_bytes_with_plus` تأیید شده است). +- بنابراین توصیه می‌شود از `.format` یا سینتکس `%` استفاده کنید (البته این روش‌ها برای رشته‌های بسیار کوتاه کمی کندتر از `+` هستند). +- اما بهتر از آن، اگر محتوای شما از قبل به‌شکل یک شیء قابل تکرار (iterable) موجود است، از دستور `''.join(iterable_object)` استفاده کنید که بسیار سریع‌تر است. +- برخلاف تابع `add_bytes_with_plus` و به‌دلیل بهینه‌سازی‌های انجام‌شده برای عملگر `+=` (که در مثال قبلی توضیح داده شد)، تابع `add_string_with_plus` افزایشی درجه دو در زمان اجرا نشان نداد. اگر دستور به‌صورت `s = s + "x" + "y" + "z"` بود (به‌جای `s += "xyz"`)، افزایش زمان اجرا درجه دو می‌شد. ```py def add_string_with_plus(iters): s = "" @@ -3587,21 +3587,21 @@ timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) >>> %timeit -n100 add_string_with_plus(10000) # افزایش درجه دو در زمان اجرا 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` -- ‫ وجود راه‌های متعدد برای قالب‌بندی و ایجاد رشته‌های بزرگ تا حدودی در تضاد با [ذِن پایتون](https://www.python.org/dev/peps/pep-0020/) است که می‌گوید: +- وجود راه‌های متعدد برای قالب‌بندی و ایجاد رشته‌های بزرگ تا حدودی در تضاد با [ذِن پایتون](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)} ``` -‫ **خروجی:** +**خروجی:** ```py >>> %timeit some_dict['5'] 28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) @@ -3620,14 +3620,14 @@ KeyError: 1 ``` چرا جستجوهای یکسان کندتر می‌شوند؟ -#### ‫ 💡 توضیح: -+ ‫ در CPython یک تابع عمومی برای جستجوی کلید در دیکشنری‌ها وجود دارد که از تمام انواع کلیدها (`str`، `int` و هر شیء دیگر) پشتیبانی می‌کند؛ اما برای حالت متداولی که تمام کلیدها از نوع `str` هستند، یک تابع بهینه‌شده‌ی اختصاصی نیز وجود دارد. -+ ‫ تابع اختصاصی (که در کد منبع CPython با نام [`lookdict_unicode`](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841) شناخته می‌شود) فرض می‌کند که تمام کلیدهای موجود در دیکشنری (از جمله کلیدی که در حال جستجوی آن هستید) رشته (`str`) هستند و برای مقایسه‌ی کلیدها، به‌جای فراخوانی متد `__eq__`، از مقایسه‌ی سریع‌تر و ساده‌تر رشته‌ای استفاده می‌کند. -+ ‫ اولین باری که یک دیکشنری (`dict`) با کلیدی غیر از `str` فراخوانی شود، این حالت تغییر می‌کند و جستجوهای بعدی از تابع عمومی استفاده خواهند کرد. -+ ‫ این فرایند برای آن نمونه‌ی خاص از دیکشنری غیرقابل بازگشت است و حتی لازم نیست کلید موردنظر در دیکشنری موجود باشد. به همین دلیل است که حتی تلاش ناموفق برای دسترسی به کلیدی ناموجود نیز باعث ایجاد همین تأثیر (کند شدن جستجو) می‌شود. +#### 💡 توضیح: ++ در CPython یک تابع عمومی برای جستجوی کلید در دیکشنری‌ها وجود دارد که از تمام انواع کلیدها (`str`، `int` و هر شیء دیگر) پشتیبانی می‌کند؛ اما برای حالت متداولی که تمام کلیدها از نوع `str` هستند، یک تابع بهینه‌شده‌ی اختصاصی نیز وجود دارد. ++ تابع اختصاصی (که در کد منبع CPython با نام [`lookdict_unicode`](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841) شناخته می‌شود) فرض می‌کند که تمام کلیدهای موجود در دیکشنری (از جمله کلیدی که در حال جستجوی آن هستید) رشته (`str`) هستند و برای مقایسه‌ی کلیدها، به‌جای فراخوانی متد `__eq__`، از مقایسه‌ی سریع‌تر و ساده‌تر رشته‌ای استفاده می‌کند. ++ اولین باری که یک دیکشنری (`dict`) با کلیدی غیر از `str` فراخوانی شود، این حالت تغییر می‌کند و جستجوهای بعدی از تابع عمومی استفاده خواهند کرد. ++ این فرایند برای آن نمونه‌ی خاص از دیکشنری غیرقابل بازگشت است و حتی لازم نیست کلید موردنظر در دیکشنری موجود باشد. به همین دلیل است که حتی تلاش ناموفق برای دسترسی به کلیدی ناموجود نیز باعث ایجاد همین تأثیر (کند شدن جستجو) می‌شود. -### ‫ ▶ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) * +### ▶ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) * ```py import sys @@ -3645,7 +3645,7 @@ def dict_size(o): ``` -‫ **خروجی:** (پایتون ۳.۸؛ سایر نسخه‌های پایتون ۳ ممکن است کمی متفاوت باشند) +**خروجی:** (پایتون ۳.۸؛ سایر نسخه‌های پایتون ۳ ممکن است کمی متفاوت باشند) ```py >>> o1 = SomeClass() >>> o2 = SomeClass() @@ -3661,7 +3661,7 @@ def dict_size(o): 232 ``` -‫ بیایید دوباره امتحان کنیم... در یک مفسر (interpreter) جدید: +بیایید دوباره امتحان کنیم... در یک مفسر (interpreter) جدید: ```py >>> o1 = SomeClass() @@ -3679,28 +3679,28 @@ def dict_size(o): 232 ``` -‫ چه چیزی باعث حجیم‌شدن این دیکشنری‌ها می‌شود؟ و چرا اشیاء تازه ساخته‌شده نیز حجیم هستند؟ +چه چیزی باعث حجیم‌شدن این دیکشنری‌ها می‌شود؟ و چرا اشیاء تازه ساخته‌شده نیز حجیم هستند؟ #### 💡 توضیح: -+ ‫ در CPython، امکان استفاده‌ی مجدد از یک شیء «کلیدها» (`keys`) در چندین دیکشنری وجود دارد. این ویژگی در [PEP 412](https://www.python.org/dev/peps/pep-0412/) معرفی شد تا مصرف حافظه کاهش یابد، به‌ویژه برای دیکشنری‌هایی که به نمونه‌ها (instances) تعلق دارند و معمولاً کلیدها (نام صفات نمونه‌ها) بین آن‌ها مشترک است. -+ ‫ این بهینه‌سازی برای دیکشنری‌های نمونه‌ها کاملاً شفاف و خودکار است؛ اما اگر بعضی فرضیات نقض شوند، غیرفعال می‌شود. -+ ‫ دیکشنری‌هایی که کلیدهایشان به اشتراک گذاشته شده باشد، از حذف کلید پشتیبانی نمی‌کنند؛ بنابراین اگر صفتی از یک نمونه حذف شود، دیکشنریِ آن نمونه «غیر مشترک» (`unshared`) شده و این قابلیت اشتراک‌گذاری کلیدها برای تمام نمونه‌هایی که در آینده از آن کلاس ساخته می‌شوند، غیرفعال می‌گردد. -+ ‫ همچنین اگر اندازه‌ی دیکشنری به‌علت اضافه‌شدن کلیدهای جدید تغییر کند (`resize` شود)، اشتراک‌گذاری کلیدها تنها زمانی ادامه می‌یابد که فقط یک دیکشنری در حال استفاده از آن‌ها باشد (این اجازه می‌دهد در متد `__init__` برای اولین نمونه‌ی ساخته‌شده، صفات متعددی تعریف کنید بدون آن‌که اشتراک‌گذاری کلیدها از بین برود). اما اگر چند نمونه همزمان وجود داشته باشند و تغییر اندازه‌ی دیکشنری رخ دهد، قابلیت اشتراک‌گذاری کلیدها برای نمونه‌های بعدی همان کلاس غیرفعال خواهد شد. زیرا CPython دیگر نمی‌تواند مطمئن باشد که آیا نمونه‌های بعدی دقیقاً از مجموعه‌ی یکسانی از صفات استفاده خواهند کرد یا خیر. -+ ‫ نکته‌ای کوچک برای کاهش مصرف حافظه‌ی برنامه: هرگز صفات نمونه‌ها را حذف نکنید و حتماً تمام صفات را در متد `__init__` تعریف و مقداردهی اولیه کنید! ++ در CPython، امکان استفاده‌ی مجدد از یک شیء «کلیدها» (`keys`) در چندین دیکشنری وجود دارد. این ویژگی در [PEP 412](https://www.python.org/dev/peps/pep-0412/) معرفی شد تا مصرف حافظه کاهش یابد، به‌ویژه برای دیکشنری‌هایی که به نمونه‌ها (instances) تعلق دارند و معمولاً کلیدها (نام صفات نمونه‌ها) بین آن‌ها مشترک است. ++ این بهینه‌سازی برای دیکشنری‌های نمونه‌ها کاملاً شفاف و خودکار است؛ اما اگر بعضی فرضیات نقض شوند، غیرفعال می‌شود. ++ دیکشنری‌هایی که کلیدهایشان به اشتراک گذاشته شده باشد، از حذف کلید پشتیبانی نمی‌کنند؛ بنابراین اگر صفتی از یک نمونه حذف شود، دیکشنریِ آن نمونه «غیر مشترک» (`unshared`) شده و این قابلیت اشتراک‌گذاری کلیدها برای تمام نمونه‌هایی که در آینده از آن کلاس ساخته می‌شوند، غیرفعال می‌گردد. ++ همچنین اگر اندازه‌ی دیکشنری به‌علت اضافه‌شدن کلیدهای جدید تغییر کند (`resize` شود)، اشتراک‌گذاری کلیدها تنها زمانی ادامه می‌یابد که فقط یک دیکشنری در حال استفاده از آن‌ها باشد (این اجازه می‌دهد در متد `__init__` برای اولین نمونه‌ی ساخته‌شده، صفات متعددی تعریف کنید بدون آن‌که اشتراک‌گذاری کلیدها از بین برود). اما اگر چند نمونه همزمان وجود داشته باشند و تغییر اندازه‌ی دیکشنری رخ دهد، قابلیت اشتراک‌گذاری کلیدها برای نمونه‌های بعدی همان کلاس غیرفعال خواهد شد. زیرا CPython دیگر نمی‌تواند مطمئن باشد که آیا نمونه‌های بعدی دقیقاً از مجموعه‌ی یکسانی از صفات استفاده خواهند کرد یا خیر. ++ نکته‌ای کوچک برای کاهش مصرف حافظه‌ی برنامه: هرگز صفات نمونه‌ها را حذف نکنید و حتماً تمام صفات را در متد `__init__` تعریف و مقداردهی اولیه کنید! -### ‫ ▶ موارد جزئی * +### ▶ موارد جزئی * -* ‫ متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) +* متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) ** ‫💡 توضیح:** اگر `join()` به‌عنوان متدی روی رشته پیاده‌سازی شود، می‌تواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشونده‌ی دیگر کار کند. اگر به‌جای آن روی لیست تعریف می‌شد، باید به‌طور جداگانه برای هر نوع دیگری نیز پیاده‌سازی می‌شد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. -* ‫ تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح: - + ‫ عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی). - + ‫ عبارت `'a'[0][0][0][0][0]` نیز از نظر معنایی صحیح است، زیرا پایتون برخلاف زبان‌هایی که از C منشعب شده‌اند، نوع داده‌ای جداگانه‌ای برای کاراکتر ندارد. بنابراین انتخاب یک کاراکتر از یک رشته، منجر به بازگشت یک رشته‌ی تک‌کاراکتری می‌شود. - + ‫ عبارات `3 --0-- 5 == 8` و `--5 == 5` هر دو از لحاظ معنایی درست بوده و مقدارشان برابر `True` است. +* تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح: + + عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی). + + عبارت `'a'[0][0][0][0][0]` نیز از نظر معنایی صحیح است، زیرا پایتون برخلاف زبان‌هایی که از C منشعب شده‌اند، نوع داده‌ای جداگانه‌ای برای کاراکتر ندارد. بنابراین انتخاب یک کاراکتر از یک رشته، منجر به بازگشت یک رشته‌ی تک‌کاراکتری می‌شود. + + عبارات `3 --0-- 5 == 8` و `--5 == 5` هر دو از لحاظ معنایی درست بوده و مقدارشان برابر `True` است. -* ‫ با فرض اینکه `a` یک عدد باشد، عبارات `++a` و `--a` هر دو در پایتون معتبر هستند؛ اما رفتاری مشابه با عبارات مشابه در زبان‌هایی مانند C، ++C یا جاوا ندارند. +* با فرض اینکه `a` یک عدد باشد، عبارات `++a` و `--a` هر دو در پایتون معتبر هستند؛ اما رفتاری مشابه با عبارات مشابه در زبان‌هایی مانند C، ++C یا جاوا ندارند. ```py >>> a = 5 @@ -3712,12 +3712,12 @@ def dict_size(o): 5 ``` - ** ‫ 💡 توضیح:** - + ‫ در گرامر پایتون عملگری به‌نام `++` وجود ندارد. در واقع `++` دو عملگر `+` جداگانه است. - + ‫ عبارت `++a` به‌شکل `+(+a)` تفسیر می‌شود که معادل `a` است. به‌همین ترتیب، خروجی عبارت `--a` نیز قابل توجیه است. - + ‫ این [تاپیک در StackOverflow](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) دلایل نبودن عملگرهای افزایش (`++`) و کاهش (`--`) در پایتون را بررسی می‌کند. + ** 💡 توضیح:** + + در گرامر پایتون عملگری به‌نام `++` وجود ندارد. در واقع `++` دو عملگر `+` جداگانه است. + + عبارت `++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 @@ -3725,15 +3725,15 @@ def dict_size(o): >>> a 43 ``` -‫ از آن به‌عنوان جایگزینی برای عملگر افزایش (increment)، در ترکیب با یک عملگر دیگر استفاده می‌شود. +از آن به‌عنوان جایگزینی برای عملگر افزایش (increment)، در ترکیب با یک عملگر دیگر استفاده می‌شود. ```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) دارد. +* پایتون یک عملگر مستندنشده برای [استلزام معکوس (converse implication)](https://en.wikipedia.org/wiki/Converse_implication) دارد. ```py >>> False ** False == True @@ -3746,9 +3746,9 @@ def dict_size(o): 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 @@ -3756,16 +3756,16 @@ def dict_size(o): 46 ``` - ‫ **💡 توضیح:** عملگر `@` در پایتون ۳٫۵ با در نظر گرفتن نیازهای جامعه علمی اضافه شد. هر شی‌ای می‌تواند متد جادویی `__matmul__` را بازنویسی کند تا رفتار این عملگر را مشخص نماید. + **💡 توضیح:** عملگر `@` در پایتون ۳٫۵ با در نظر گرفتن نیازهای جامعه علمی اضافه شد. هر شی‌ای می‌تواند متد جادویی `__matmul__` را بازنویسی کند تا رفتار این عملگر را مشخص نماید. -* ‫ از پایتون ۳٫۸ به بعد می‌توانید از نحو متداول f-string مانند `f'{some_var=}'` برای اشکال‌زدایی سریع استفاده کنید. مثال, +* از پایتون ۳٫۸ به بعد می‌توانید از نحو متداول f-string مانند `f'{some_var=}'` برای اشکال‌زدایی سریع استفاده کنید. مثال, ```py >>> some_string = "wtfpython" >>> f'{some_string=}' "some_string='wtfpython'" ``` -* ‫ پایتون برای ذخیره‌سازی متغیرهای محلی در توابع از ۲ بایت استفاده می‌کند. از نظر تئوری، این به معنای امکان تعریف حداکثر ۶۵۵۳۶ متغیر در یک تابع است. با این حال، پایتون راهکار مفیدی ارائه می‌کند که می‌توان با استفاده از آن بیش از ۲^۱۶ نام متغیر را ذخیره کرد. کد زیر نشان می‌دهد وقتی بیش از ۶۵۵۳۶ متغیر محلی تعریف شود، در پشته (stack) چه اتفاقی رخ می‌دهد (هشدار: این کد تقریباً ۲^۱۸ خط متن چاپ می‌کند، بنابراین آماده باشید!): +* پایتون برای ذخیره‌سازی متغیرهای محلی در توابع از ۲ بایت استفاده می‌کند. از نظر تئوری، این به معنای امکان تعریف حداکثر ۶۵۵۳۶ متغیر در یک تابع است. با این حال، پایتون راهکار مفیدی ارائه می‌کند که می‌توان با استفاده از آن بیش از ۲^۱۶ نام متغیر را ذخیره کرد. کد زیر نشان می‌دهد وقتی بیش از ۶۵۵۳۶ متغیر محلی تعریف شود، در پشته (stack) چه اتفاقی رخ می‌دهد (هشدار: این کد تقریباً ۲^۱۸ خط متن چاپ می‌کند، بنابراین آماده باشید!): ```py import dis @@ -3779,9 +3779,9 @@ def dict_size(o): 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` ممکن است مقادیر را فوراً چاپ نکند. برای مثال، +* گاهی اوقات، متد `print` ممکن است مقادیر را فوراً چاپ نکند. برای مثال، ```py # File some_file.py @@ -3791,16 +3791,16 @@ def dict_size(o): time.sleep(3) ``` - ‫ این کد عبارت `wtfpython` را به دلیل آرگومان `end` پس از ۳ ثانیه چاپ می‌کند؛ چرا که بافر خروجی تنها پس از رسیدن به کاراکتر `\n` یا در زمان اتمام اجرای برنامه تخلیه می‌شود. برای تخلیه‌ی اجباری بافر می‌توانید از آرگومان `flush=True` استفاده کنید. + این کد عبارت `wtfpython` را به دلیل آرگومان `end` پس از ۳ ثانیه چاپ می‌کند؛ چرا که بافر خروجی تنها پس از رسیدن به کاراکتر `\n` یا در زمان اتمام اجرای برنامه تخلیه می‌شود. برای تخلیه‌ی اجباری بافر می‌توانید از آرگومان `flush=True` استفاده کنید. -* ‫ برش لیست‌ها (List slicing) با اندیس‌های خارج از محدوده، خطایی ایجاد نمی‌کند. +* برش لیست‌ها (List slicing) با اندیس‌های خارج از محدوده، خطایی ایجاد نمی‌کند. ```py >>> some_list = [1, 2, 3, 4, 5] >>> some_list[111:] [] ``` -* ‫ برش زدن (slicing) یک شئ قابل پیمایش (iterable) همیشه یک شئ جدید ایجاد نمی‌کند. به‌عنوان مثال، +* برش زدن (slicing) یک شئ قابل پیمایش (iterable) همیشه یک شئ جدید ایجاد نمی‌کند. به‌عنوان مثال، ```py >>> some_str = "wtfpython" >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n'] @@ -3810,9 +3810,9 @@ def dict_size(o): True ``` -* ‫ در پایتون ۳، فراخوانی `int('١٢٣٤٥٦٧٨٩')` مقدار `123456789` را برمی‌گرداند. در پایتون، نویسه‌های ده‌دهی (Decimal characters) شامل تمام ارقامی هستند که می‌توانند برای تشکیل اعداد در مبنای ده استفاده شوند؛ به‌عنوان مثال نویسه‌ی U+0660 که همان رقم صفر عربی-هندی است. [اینجا](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) داستان جالبی درباره این رفتار پایتون آمده است. +* در پایتون ۳، فراخوانی `int('١٢٣٤٥٦٧٨٩')` مقدار `123456789` را برمی‌گرداند. در پایتون، نویسه‌های ده‌دهی (Decimal characters) شامل تمام ارقامی هستند که می‌توانند برای تشکیل اعداد در مبنای ده استفاده شوند؛ به‌عنوان مثال نویسه‌ی U+0660 که همان رقم صفر عربی-هندی است. [اینجا](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) داستان جالبی درباره این رفتار پایتون آمده است. -* ‫ از پایتون ۳ به بعد، می‌توانید برای افزایش خوانایی، اعداد را با استفاده از زیرخط (`_`) جدا کنید. +* از پایتون ۳ به بعد، می‌توانید برای افزایش خوانایی، اعداد را با استفاده از زیرخط (`_`) جدا کنید. ```py >>> six_million = 6_000_000 @@ -3823,7 +3823,7 @@ def dict_size(o): 4027435774 ``` -* ‫ عبارت `'abc'.count('') == 4` مقدار `True` برمی‌گرداند. در اینجا یک پیاده‌سازی تقریبی از متد `count` آورده شده که این موضوع را شفاف‌تر می‌کند: +* عبارت `'abc'.count('') == 4` مقدار `True` برمی‌گرداند. در اینجا یک پیاده‌سازی تقریبی از متد `count` آورده شده که این موضوع را شفاف‌تر می‌کند: ```py def count(s, sub): result = 0 @@ -3831,31 +3831,31 @@ def dict_size(o): result += (s[i:i + len(sub)] == sub) return result ``` -‫ این رفتار به این دلیل است که زیررشته‌ی خالی (`''`) با برش‌هایی (slices) به طول صفر در رشته‌ی اصلی مطابقت پیدا می‌کند. + این رفتار به این دلیل است که زیررشته‌ی خالی (`''`) با برش‌هایی (slices) به طول صفر در رشته‌ی اصلی مطابقت پیدا می‌کند. --- --- -# ‫ مشارکت +# مشارکت ‫چند روشی که می‌توانید در wtfpython مشارکت داشته باشید: -- ‫ پیشنهاد مثال‌های جدید -- ‫ کمک به ترجمه (به [مشکلات برچسب ترجمه](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation) مراجعه کنید) -- ‫ اصلاحات جزئی مثل اشاره به تکه‌کدهای قدیمی، اشتباهات تایپی، خطاهای قالب‌بندی و غیره. -- ‫ شناسایی نواقص (مانند توضیحات ناکافی، مثال‌های تکراری و ...) -- ‫ هر پیشنهاد خلاقانه‌ای برای مفیدتر و جذاب‌تر شدن این پروژه +- پیشنهاد مثال‌های جدید +- کمک به ترجمه (به [مشکلات برچسب ترجمه](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation) مراجعه کنید) +- اصلاحات جزئی مثل اشاره به تکه‌کدهای قدیمی، اشتباهات تایپی، خطاهای قالب‌بندی و غیره. +- شناسایی نواقص (مانند توضیحات ناکافی، مثال‌های تکراری و ...) +- هر پیشنهاد خلاقانه‌ای برای مفیدتر و جذاب‌تر شدن این پروژه -‫ برای اطلاعات بیشتر [CONTRIBUTING.md](/CONTRIBUTING.md) را مشاهده کنید. برای بحث درباره موارد مختلف می‌توانید یک [مشکل جدید](https://github.com/satwikkansal/wtfpython/issues/new) ایجاد کنید. +برای اطلاعات بیشتر [CONTRIBUTING.md](/CONTRIBUTING.md) را مشاهده کنید. برای بحث درباره موارد مختلف می‌توانید یک [مشکل جدید](https://github.com/satwikkansal/wtfpython/issues/new) ایجاد کنید. -‫ نکته: لطفاً برای درخواست بک‌لینک (backlink) تماس نگیرید. هیچ لینکی اضافه نمی‌شود مگر اینکه ارتباط بسیار زیادی با پروژه داشته باشد. +نکته: لطفاً برای درخواست بک‌لینک (backlink) تماس نگیرید. هیچ لینکی اضافه نمی‌شود مگر اینکه ارتباط بسیار زیادی با پروژه داشته باشد. -# ‫ تقدیر و تشکر +# تقدیر و تشکر -‫ ایده و طراحی این مجموعه ابتدا از پروژه عالی [wtfjs](https://github.com/denysdovhan/wtfjs) توسط Denys Dovhan الهام گرفته شد. حمایت فوق‌العاده‌ جامعه پایتون باعث شد پروژه به شکل امروزی خود درآید. +ایده و طراحی این مجموعه ابتدا از پروژه عالی [wtfjs](https://github.com/denysdovhan/wtfjs) توسط Denys Dovhan الهام گرفته شد. حمایت فوق‌العاده‌ جامعه پایتون باعث شد پروژه به شکل امروزی خود درآید. -#### ‫ چند لینک جالب! +#### چند لینک جالب! * 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 @@ -3866,7 +3866,7 @@ def dict_size(o): * https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues * WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). -# ‫ 🎓 مجوز +# 🎓 مجوز [![WTFPL 2.0][license-image]][license-url] @@ -3875,16 +3875,16 @@ def dict_size(o): [license-url]: http://www.wtfpl.net [license-image]: https://img.shields.io/badge/License-WTFPL%202.0-lightgrey.svg?style=flat-square -## ‫ دوستانتان را هم شگفت‌زده کنید! +## دوستانتان را هم شگفت‌زده کنید! -‫ اگر از wtfpython خوشتان آمد، می‌توانید با این لینک‌های سریع آن را با دوستانتان به اشتراک بگذارید: +اگر از wtfpython خوشتان آمد، می‌توانید با این لینک‌های سریع آن را با دوستانتان به اشتراک بگذارید: -‫ [توییتر](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) | [لینکدین](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!) | [فیسبوک](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!) +[توییتر](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) | [لینکدین](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!) | [فیسبوک](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!) -## ‫ آیا به یک نسخه pdf نیاز دارید؟ +## آیا به یک نسخه pdf نیاز دارید؟ -‫ من چند درخواست برای نسخه PDF (و epub) کتاب wtfpython دریافت کرده‌ام. برای دریافت این نسخه‌ها به محض آماده شدن، می‌توانید اطلاعات خود را [اینجا](https://form.jotform.com/221593245656057) وارد کنید. +من چند درخواست برای نسخه PDF (و epub) کتاب wtfpython دریافت کرده‌ام. برای دریافت این نسخه‌ها به محض آماده شدن، می‌توانید اطلاعات خود را [اینجا](https://form.jotform.com/221593245656057) وارد کنید. -‫ **همین بود دوستان!** برای دریافت مطالب آینده مشابه این، می‌توانید ایمیل خود را [اینجا](https://form.jotform.com/221593598380062) اضافه کنید. +**همین بود دوستان!** برای دریافت مطالب آینده مشابه این، می‌توانید ایمیل خود را [اینجا](https://form.jotform.com/221593598380062) اضافه کنید. From 2bd726ba98a2e9f8807a1a76314998f62491744f Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sat, 5 Apr 2025 21:41:36 +0200 Subject: [PATCH 193/210] Remove RTL indicator --- translations/fa-farsi/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 376bd74a..79818e20 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -2231,7 +2231,7 @@ for idx, item in enumerate(list_4): list_4.pop(idx) ``` -‫**خروجی:** +**خروجی:** ```py >>> list_1 [1, 2, 3, 4] @@ -2790,7 +2790,7 @@ def similar_recursive_func(a): `x, y = (0, 1) if True else (None, None)` * برای مورد ۲، عبارت صحیح برای رفتار مورد انتظار این است: -‫`t = ('one',)` یا `t = 'one',` (ویرگول از قلم افتاده است). در غیر این صورت مفسر `t` را به عنوان یک `str` در نظر گرفته و به صورت کاراکتر به کاراکتر روی آن پیمایش می‌کند. +`t = ('one',)` یا `t = 'one',` (ویرگول از قلم افتاده است). در غیر این صورت مفسر `t` را به عنوان یک `str` در نظر گرفته و به صورت کاراکتر به کاراکتر روی آن پیمایش می‌کند. * علامت `()` یک توکن خاص است و نشان‌دهنده‌ی یک `tuple` خالی است. @@ -3693,7 +3693,7 @@ def dict_size(o): * متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) - ** ‫💡 توضیح:** اگر `join()` به‌عنوان متدی روی رشته پیاده‌سازی شود، می‌تواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشونده‌ی دیگر کار کند. اگر به‌جای آن روی لیست تعریف می‌شد، باید به‌طور جداگانه برای هر نوع دیگری نیز پیاده‌سازی می‌شد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. + ** 💡 توضیح:** اگر `join()` به‌عنوان متدی روی رشته پیاده‌سازی شود، می‌تواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشونده‌ی دیگر کار کند. اگر به‌جای آن روی لیست تعریف می‌شد، باید به‌طور جداگانه برای هر نوع دیگری نیز پیاده‌سازی می‌شد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. * تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح: + عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی). @@ -3838,7 +3838,7 @@ def dict_size(o): # مشارکت -‫چند روشی که می‌توانید در wtfpython مشارکت داشته باشید: +چند روشی که می‌توانید در wtfpython مشارکت داشته باشید: - پیشنهاد مثال‌های جدید - کمک به ترجمه (به [مشکلات برچسب ترجمه](https://github.com/satwikkansal/wtfpython/issues?q=is%3Aissue+is%3Aopen+label%3Atranslation) مراجعه کنید) From ebe443e0afd5cdf908d1ffe3269a691a82663456 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sat, 5 Apr 2025 21:48:15 +0200 Subject: [PATCH 194/210] Update Farsi translations by replacing bullet indicators with arrow indicators in the README.md file. --- translations/fa-farsi/README.md | 256 ++++++++++++++++---------------- 1 file changed, 128 insertions(+), 128 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 79818e20..460c3a50 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -44,73 +44,73 @@ - [استفاده](#استفاده) - [👀 مثال‌ها](#-مثالها) - [بخش: ذهن خود را به چالش بکشید!](#بخش-ذهن-خود-را-به-چالش-بکشید) - - [▶ اول از همه! \*](#-اول-از-همه-) - - [▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند](#-بعضی-وقتها-رشتهها-میتوانند-دردسرساز-شوند) - - [▶ مراقب عملیات‌های زنجیره‌ای باشید](#-مراقب-عملیاتهای-زنجیرهای-باشید) - - [▶ چطور از عملگر `is` استفاده نکنیم](#-چطور-از-عملگر-is-استفاده-نکنیم) - - [▶ کلیدهای هش](#-کلیدهای-هش) - - [▶ در عمق وجود همه ما یکسان هستیم](#-در-عمق-وجود-همه-ما-یکسان-هستیم) - - [▶ بی‌نظمی در خود نظم \*](#-بینظمی-در-خود-نظم-) - - [▶ تلاش کن... \*](#-تلاش-کن-) - - [▶ برای چی؟](#-برای-چی) - - [▶ اختلاف زمانی در محاسبه](#-اختلاف-زمانی-در-محاسبه) - - [▶ هر گردی، گردو نیست](#-هر-گردی-گردو-نیست) - - [▶ یک بازی دوز که توش X همون اول برنده میشه!](#-یک-بازی-دوز-که-توش-X-همون-اول-برنده-میشه) - - [▶ متغیر شرودینگر \*](#-متغیر-شرودینگر-) - - [▶ اول مرغ بوده یا تخم مرغ؟ \*](#-اول-مرغ-بوده-یا-تخم-مرغ-) - - [▶ روابط بین زیرمجموعه کلاس‌ها](#-روابط-بین-زیرمجموعه-کلاسها) - - [▶ ‫ برابری و هویت متدها](#--برابری-و-هویت-متدها) - - [▶ ‫ آل-ترو-یشن \*](#--آل-ترو-یشن-) - - [▶ ‫ رشته‌ها و بک‌اسلش‌ها](#--رشتهها-و-بکاسلشها) - - [▶ ‫ گره نیست، نَه!](#--گره-نیست-نَه) - - [▶ رشته‌های نیمه سه‌نقل‌قولی](#-رشتههای-نیمه-سهنقلقولی) - - [▶ ‫ مشکل بولین ها چیست؟](#--مشکل-بولین-ها-چیست) - - [▶ ‫ ویژگی‌های کلاس و ویژگی‌های نمونه](#--ویژگیهای-کلاس-و-ویژگیهای-نمونه) - - [▶ yielding None](#-yielding-none) - - [▶ Yielding from... return! \*](#-yielding-from-return-) - - [▶ ‫ بازتاب‌ناپذیری \*](#--بازتابناپذیری-) - - [▶ ‫ تغییر دادن اشیای تغییرناپذیر!](#--تغییر-دادن-اشیای-تغییرناپذیر) - - [▶ ‫ متغیری که از اسکوپ بیرونی ناپدید می‌شود](#--متغیری-که-از-اسکوپ-بیرونی-ناپدید-میشود) - - [▶ ‫ تبدیل اسرارآمیز نوع کلید](#--تبدیل-اسرارآمیز-نوع-کلید) - - [▶ ‫ ببینیم می‌توانید این را حدس بزنید؟](#--ببینیم-میتوانید-این-را-حدس-بزنید) - - [▶ ‫ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود](#--از-حد-مجاز-برای-تبدیل-رشته-به-عدد-صحیح-فراتر-میرود) + - [◀ اول از همه! \*](#-اول-از-همه-) + - [◀ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند](#-بعضی-وقتها-رشتهها-میتوانند-دردسرساز-شوند) + - [◀ مراقب عملیات‌های زنجیره‌ای باشید](#-مراقب-عملیاتهای-زنجیرهای-باشید) + - [◀ چطور از عملگر `is` استفاده نکنیم](#-چطور-از-عملگر-is-استفاده-نکنیم) + - [◀ کلیدهای هش](#-کلیدهای-هش) + - [◀ در عمق وجود همه ما یکسان هستیم](#-در-عمق-وجود-همه-ما-یکسان-هستیم) + - [◀ بی‌نظمی در خود نظم \*](#-بینظمی-در-خود-نظم-) + - [◀ تلاش کن... \*](#-تلاش-کن-) + - [◀ برای چی؟](#-برای-چی) + - [◀ اختلاف زمانی در محاسبه](#-اختلاف-زمانی-در-محاسبه) + - [◀ هر گردی، گردو نیست](#-هر-گردی-گردو-نیست) + - [◀ یک بازی دوز که توش X همون اول برنده میشه!](#-یک-بازی-دوز-که-توش-X-همون-اول-برنده-میشه) + - [◀ متغیر شرودینگر \*](#-متغیر-شرودینگر-) + - [◀ اول مرغ بوده یا تخم مرغ؟ \*](#-اول-مرغ-بوده-یا-تخم-مرغ-) + - [◀ روابط بین زیرمجموعه کلاس‌ها](#-روابط-بین-زیرمجموعه-کلاسها) + - [◀ ‫ برابری و هویت متدها](#--برابری-و-هویت-متدها) + - [◀ ‫ آل-ترو-یشن \*](#--آل-ترو-یشن-) + - [◀ ‫ رشته‌ها و بک‌اسلش‌ها](#--رشتهها-و-بکاسلشها) + - [◀ ‫ گره نیست، نَه!](#--گره-نیست-نَه) + - [◀ رشته‌های نیمه سه‌نقل‌قولی](#-رشتههای-نیمه-سهنقلقولی) + - [◀ ‫ مشکل بولین ها چیست؟](#--مشکل-بولین-ها-چیست) + - [◀ ‫ ویژگی‌های کلاس و ویژگی‌های نمونه](#--ویژگیهای-کلاس-و-ویژگیهای-نمونه) + - [◀ yielding None](#-yielding-none) + - [◀ Yielding from... return! \*](#-yielding-from-return-) + - [◀ ‫ بازتاب‌ناپذیری \*](#--بازتابناپذیری-) + - [◀ ‫ تغییر دادن اشیای تغییرناپذیر!](#--تغییر-دادن-اشیای-تغییرناپذیر) + - [◀ ‫ متغیری که از اسکوپ بیرونی ناپدید می‌شود](#--متغیری-که-از-اسکوپ-بیرونی-ناپدید-میشود) + - [◀ ‫ تبدیل اسرارآمیز نوع کلید](#--تبدیل-اسرارآمیز-نوع-کلید) + - [◀ ‫ ببینیم می‌توانید این را حدس بزنید؟](#--ببینیم-میتوانید-این-را-حدس-بزنید) + - [◀ ‫ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود](#--از-حد-مجاز-برای-تبدیل-رشته-به-عدد-صحیح-فراتر-میرود) - [‫ بخش: شیب‌های لغزنده](#-بخش-شیبهای-لغزنده) - - [▶ ‫ تغییر یک دیکشنری هنگام پیمایش روی آن](#--تغییر-یک-دیکشنری-هنگام-پیمایش-روی-آن) - - [▶ عملیات سرسختانه‌ی `del`](#-عملیات-سرسختانهی-del) - - [▶ ‫ متغیری که از حوزه خارج است](#--متغیری-که-از-حوزه-خارج-است) - - [▶ ‫ حذف المان‌های لیست در حین پیمایش](#--حذف-المانهای-لیست-در-حین-پیمایش) - - [▶ ‫ زیپِ دارای اتلاف برای پیمایشگرها \*](#--زیپِ-دارای-اتلاف-برای-پیمایشگرها-) - - [▶ ‫ نشت کردن متغیرهای حلقه!](#--نشت-کردن-متغیرهای-حلقه) - - [▶ ‫ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید!](#--مراقب-آرگومانهای-تغییرپذیر-پیشفرض-باشید) - - [▶ ‫ گرفتن استثناها (Exceptions)](#--گرفتن-استثناها-exceptions) - - [▶ ‫ عملوندهای یکسان، داستانی متفاوت!](#--عملوندهای-یکسان-داستانی-متفاوت) - - [▶ ‫ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس](#--تفکیک-نامها-با-نادیده-گرفتن-حوزهی-کلاس) - - [▶ ‫ گرد کردن به روش بانکدار \*](#--گرد-کردن-به-روش-بانکدار-) - - [▶ ‫ سوزن‌هایی در انبار کاه \*](#--سوزنهایی-در-انبار-کاه-) - - [▶ ‫ تقسیم‌ها \*](#--تقسیمها-) - - [▶ واردسازی‌های عمومی \*](#-واردسازیهای-عمومی-) - - [▶ ‫ همه چیز مرتب شده؟ \*](#--همه-چیز-مرتب-شده-) - - [▶ ‫ زمان نیمه‌شب وجود ندارد؟](#--زمان-نیمهشب-وجود-ندارد) + - [◀ ‫ تغییر یک دیکشنری هنگام پیمایش روی آن](#--تغییر-یک-دیکشنری-هنگام-پیمایش-روی-آن) + - [◀ عملیات سرسختانه‌ی `del`](#-عملیات-سرسختانهی-del) + - [◀ ‫ متغیری که از حوزه خارج است](#--متغیری-که-از-حوزه-خارج-است) + - [◀ ‫ حذف المان‌های لیست در حین پیمایش](#--حذف-المانهای-لیست-در-حین-پیمایش) + - [◀ ‫ زیپِ دارای اتلاف برای پیمایشگرها \*](#--زیپِ-دارای-اتلاف-برای-پیمایشگرها-) + - [◀ ‫ نشت کردن متغیرهای حلقه!](#--نشت-کردن-متغیرهای-حلقه) + - [◀ ‫ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید!](#--مراقب-آرگومانهای-تغییرپذیر-پیشفرض-باشید) + - [◀ ‫ گرفتن استثناها (Exceptions)](#--گرفتن-استثناها-exceptions) + - [◀ ‫ عملوندهای یکسان، داستانی متفاوت!](#--عملوندهای-یکسان-داستانی-متفاوت) + - [◀ ‫ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس](#--تفکیک-نامها-با-نادیده-گرفتن-حوزهی-کلاس) + - [◀ ‫ گرد کردن به روش بانکدار \*](#--گرد-کردن-به-روش-بانکدار-) + - [◀ ‫ سوزن‌هایی در انبار کاه \*](#--سوزنهایی-در-انبار-کاه-) + - [◀ ‫ تقسیم‌ها \*](#--تقسیمها-) + - [◀ واردسازی‌های عمومی \*](#-واردسازیهای-عمومی-) + - [◀ ‫ همه چیز مرتب شده؟ \*](#--همه-چیز-مرتب-شده-) + - [◀ ‫ زمان نیمه‌شب وجود ندارد؟](#--زمان-نیمهشب-وجود-ندارد) - [‫ بخش: گنجینه‌های پنهان!](#-بخش-گنجینههای-پنهان) - - [▶ ‫ خب پایتون، می‌توانی کاری کنی پرواز کنم؟](#--خب-پایتون-میتوانی-کاری-کنی-پرواز-کنم) - - [▶ ‫ `goto`، ولی چرا؟](#--goto-ولی-چرا) - - [▶ ‫ خودتان را آماده کنید!](#--خودتان-را-آماده-کنید) - - [▶ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم](#--بیایید-با-عمو-زبان-مهربان-برای-همیشه-آشنا-شویم) - - [▶ ‫ حتی پایتون هم می‌داند که عشق پیچیده است](#--حتی-پایتون-هم-میداند-که-عشق-پیچیده-است) - - [▶ ‫ بله، این واقعاً وجود دارد!](#--بله-این-واقعاً-وجود-دارد) - - [▶ Ellipsis \*](#-ellipsis-) - - [▶ ‫ بی‌نهایت (`Inpinity`)](#--بینهایت-inpinity) - - [▶ ‫ بیایید خرابکاری کنیم](#--بیایید-خرابکاری-کنیم) + - [◀ ‫ خب پایتون، می‌توانی کاری کنی پرواز کنم؟](#--خب-پایتون-میتوانی-کاری-کنی-پرواز-کنم) + - [◀ ‫ `goto`، ولی چرا؟](#--goto-ولی-چرا) + - [◀ ‫ خودتان را آماده کنید!](#--خودتان-را-آماده-کنید) + - [◀ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم](#--بیایید-با-عمو-زبان-مهربان-برای-همیشه-آشنا-شویم) + - [◀ ‫ حتی پایتون هم می‌داند که عشق پیچیده است](#--حتی-پایتون-هم-میداند-که-عشق-پیچیده-است) + - [◀ ‫ بله، این واقعاً وجود دارد!](#--بله-این-واقعاً-وجود-دارد) + - [◀ Ellipsis \*](#-ellipsis-) + - [◀ ‫ بی‌نهایت (`Inpinity`)](#--بینهایت-inpinity) + - [◀ ‫ بیایید خرابکاری کنیم](#--بیایید-خرابکاری-کنیم) - [‫ بخش: ظاهرها فریبنده‌اند!](#-بخش-ظاهرها-فریبندهاند) - - [▶ ‫ خطوط را رد می‌کند؟](#--خطوط-را-رد-میکند) - - [▶ ‫ تله‌پورت کردن](#--تلهپورت-کردن) - - [▶ ‫ خب، یک جای کار مشکوک است...](#--خب-یک-جای-کار-مشکوک-است) + - [◀ ‫ خطوط را رد می‌کند؟](#--خطوط-را-رد-میکند) + - [◀ ‫ تله‌پورت کردن](#--تلهپورت-کردن) + - [◀ ‫ خب، یک جای کار مشکوک است...](#--خب-یک-جای-کار-مشکوک-است) - [بخش: متفرقه](#بخش-متفرقه) - - [‫ ▶ `+=` سریع‌تر است](#---سریعتر-است) - - [‫ ▶ بیایید یک رشته‌ی بزرگ بسازیم!](#--بیایید-یک-رشتهی-بزرگ-بسازیم) - - [▶ ‫ کُند کردن جستجوها در `dict` \*](#---کُند-کردن-جستجوها-در-dict-) - - [‫ ▶ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#--حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) - - [‫ ▶ موارد جزئی \*](#---موارد-جزئی-) + - [‫ ◀ `+=` سریع‌تر است](#---سریعتر-است) + - [‫ ◀ بیایید یک رشته‌ی بزرگ بسازیم!](#--بیایید-یک-رشتهی-بزرگ-بسازیم) + - [◀ ‫ کُند کردن جستجوها در `dict` \*](#---کُند-کردن-جستجوها-در-dict-) + - [‫ ◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#--حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) + - [‫ ◀ موارد جزئی \*](#---موارد-جزئی-) - [‫ مشارکت](#-مشارکت) - [‫ تقدیر و تشکر](#-تقدیر-و-تشکر) - [‫ چند لینک جالب!](#-چند-لینک-جالب) @@ -124,7 +124,7 @@ همه مثال‌ها به صورت زیر ساخته می‌شوند: -> ### ▶ یه اسم خوشگل +> ### ◀ یه اسم خوشگل > > ```py > # راه اندازی کد @@ -175,7 +175,7 @@ ## بخش: ذهن خود را به چالش بکشید! -### ▶ اول از همه! * +### ◀ اول از همه! * @@ -298,7 +298,7 @@ if a := some_func(): --- -### ▶ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند +### ◀ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند 1\. @@ -383,7 +383,7 @@ False --- -### ▶ مراقب عملیات‌های زنجیره‌ای باشید +### ◀ مراقب عملیات‌های زنجیره‌ای باشید ```py >>> (False == False) in [False] # منطقیه @@ -427,7 +427,7 @@ False --- -### ▶ چطور از عملگر `is` استفاده نکنیم +### ◀ چطور از عملگر `is` استفاده نکنیم عبارت پایین خیلی معروفه و تو کل اینترنت موجوده. @@ -552,7 +552,7 @@ False --- -### ▶ کلیدهای هش +### ◀ کلیدهای هش 1\. ```py @@ -617,7 +617,7 @@ complex --- -### ▶ در عمق وجود همه ما یکسان هستیم +### ◀ در عمق وجود همه ما یکسان هستیم ```py class WTF: @@ -667,7 +667,7 @@ True --- -### ▶ بی‌نظمی در خود نظم * +### ◀ بی‌نظمی در خود نظم * ```py from collections import OrderedDict @@ -766,7 +766,7 @@ TypeError: unhashable type: 'dict' --- -### ▶ تلاش کن... * +### ◀ تلاش کن... * ```py def some_func(): @@ -828,7 +828,7 @@ Iteration 0 --- -### ▶ برای چی؟ +### ◀ برای چی؟ ```py some_string = "wtf" @@ -880,7 +880,7 @@ for i, some_dict[i] in enumerate(some_string): --- -### ▶ اختلاف زمانی در محاسبه +### ◀ اختلاف زمانی در محاسبه 1\. ```py @@ -949,7 +949,7 @@ array_4 = [400, 500, 600] --- -### ▶ هر گردی، گردو نیست +### ◀ هر گردی، گردو نیست ```py >>> 'something' is not None @@ -966,7 +966,7 @@ False --- -### ▶ یک بازی دوز که توش X همون اول برنده میشه! +### ◀ یک بازی دوز که توش X همون اول برنده میشه! ```py @@ -1026,7 +1026,7 @@ board = [row] * 3 --- -### ▶ متغیر شرودینگر * +### ◀ متغیر شرودینگر * @@ -1105,7 +1105,7 @@ ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) --- -### ▶ اول مرغ بوده یا تخم مرغ؟ * +### ◀ اول مرغ بوده یا تخم مرغ؟ * 1\. ```py @@ -1157,7 +1157,7 @@ False --- -### ▶ روابط بین زیرمجموعه کلاس‌ها +### ◀ روابط بین زیرمجموعه کلاس‌ها **خروجی:** ```py @@ -1181,7 +1181,7 @@ False --- -### ▶ برابری و هویت متدها +### ◀ برابری و هویت متدها 1. @@ -1270,7 +1270,7 @@ True * ایجاد شیءهای "متد" جدید در هر بار فراخوانی متدهای نمونه و نیاز به اصلاح آرگومان‌ها برای درج `self`، عملکرد را به شدت تحت تأثیر قرار می‌داد. CPython 3.7 [این مشکل را حل کرد](https://bugs.python.org/issue26110) با معرفی opcodeهای جدیدی که فراخوانی متدها را بدون ایجاد شیء متد موقتی مدیریت می‌کنند. این به شرطی است که تابع دسترسی‌یافته واقعاً فراخوانی شود، بنابراین قطعه‌کدهای اینجا تحت تأثیر قرار نمی‌گیرند و همچنان متد ایجاد می‌کنند :) -### ▶ آل-ترو-یشن * +### ◀ آل-ترو-یشن * @@ -1308,7 +1308,7 @@ True --- -### ▶ کاما‌ی شگفت‌انگیز +### ◀ کاما‌ی شگفت‌انگیز **خروجی (< 3.6):** @@ -1340,7 +1340,7 @@ SyntaxError: invalid syntax --- -### ▶ رشته‌ها و بک‌اسلش‌ها +### ◀ رشته‌ها و بک‌اسلش‌ها **خروجی:** ```py @@ -1383,7 +1383,7 @@ True --- -### ▶ گره نیست، نَه! +### ◀ گره نیست، نَه! ```py x = True @@ -1410,7 +1410,7 @@ SyntaxError: invalid syntax --- -### ▶ رشته‌های نیمه سه‌نقل‌قولی +### ◀ رشته‌های نیمه سه‌نقل‌قولی **خروجی:** ```py @@ -1439,7 +1439,7 @@ SyntaxError: EOF while scanning triple-quoted string literal --- -### ▶ مشکل بولین ها چیست؟ +### ◀ مشکل بولین ها چیست؟ 1\. @@ -1529,7 +1529,7 @@ I have lost faith in truth! --- -### ▶ ویژگی‌های کلاس و ویژگی‌های نمونه +### ◀ ویژگی‌های کلاس و ویژگی‌های نمونه 1\. ```py @@ -1600,7 +1600,7 @@ True --- -### ▶ yielding None +### ◀ yielding None ```py some_iterable = ('a', 'b') @@ -1633,7 +1633,7 @@ def some_func(val): --- -### ▶ Yielding from... return! * +### ◀ Yielding from... return! * 1\. @@ -1698,7 +1698,7 @@ def some_func(x): --- -### ▶ بازتاب‌ناپذیری * +### ◀ بازتاب‌ناپذیری * @@ -1774,7 +1774,7 @@ True --- -### ▶ تغییر دادن اشیای تغییرناپذیر! +### ◀ تغییر دادن اشیای تغییرناپذیر! @@ -1813,7 +1813,7 @@ TypeError: 'tuple' object does not support item assignment --- -### ▶ متغیری که از اسکوپ بیرونی ناپدید می‌شود +### ◀ متغیری که از اسکوپ بیرونی ناپدید می‌شود ```py @@ -1895,7 +1895,7 @@ NameError: name 'e' is not defined --- -### ▶ تبدیل اسرارآمیز نوع کلید +### ◀ تبدیل اسرارآمیز نوع کلید ```py class SomeClass(str): @@ -1951,7 +1951,7 @@ str --- -### ▶ ببینیم می‌توانید این را حدس بزنید؟ +### ◀ ببینیم می‌توانید این را حدس بزنید؟ ```py a, b = a[b] = {}, 5 @@ -2010,7 +2010,7 @@ a, b = a[b] = {}, 5 --- -### ▶ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود +### ◀ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود ```py >>> # Python 3.10.6 >>> int("2" * 5432) @@ -2049,7 +2049,7 @@ ValueError: Exceeds the limit (4300) for integer string conversion: ## بخش: شیب‌های لغزنده -### ▶ تغییر یک دیکشنری هنگام پیمایش روی آن +### ◀ تغییر یک دیکشنری هنگام پیمایش روی آن ```py x = {0: None} @@ -2085,7 +2085,7 @@ for i in x: --- -### ▶ عملیات سرسختانه‌ی `del` +### ◀ عملیات سرسختانه‌ی `del` @@ -2130,7 +2130,7 @@ Deleted! --- -### ▶ متغیری که از حوزه خارج است +### ◀ متغیری که از حوزه خارج است 1\. @@ -2210,7 +2210,7 @@ UnboundLocalError: local variable 'a' referenced before assignment --- -### ▶ حذف المان‌های لیست در حین پیمایش +### ◀ حذف المان‌های لیست در حین پیمایش ```py list_1 = [1, 2, 3, 4] @@ -2271,7 +2271,7 @@ for idx, item in enumerate(list_4): --- -### ▶ زیپِ دارای اتلاف برای پیمایشگرها * +### ◀ زیپِ دارای اتلاف برای پیمایشگرها * ```py @@ -2320,7 +2320,7 @@ for idx, item in enumerate(list_4): --- -### ▶ نشت کردن متغیرهای حلقه! +### ◀ نشت کردن متغیرهای حلقه! 1\. ```py @@ -2384,7 +2384,7 @@ print(x, ': x in global') --- -### ▶ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید! +### ◀ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید! ```py @@ -2442,7 +2442,7 @@ def some_func(default_arg=[]): --- -### ▶ گرفتن استثناها (Exceptions) +### ◀ گرفتن استثناها (Exceptions) ```py some_list = [1, 2, 3] @@ -2517,7 +2517,7 @@ SyntaxError: invalid syntax --- -### ▶ عملوندهای یکسان، داستانی متفاوت! +### ◀ عملوندهای یکسان، داستانی متفاوت! 1\. ```py @@ -2558,7 +2558,7 @@ a += [5, 6, 7, 8] --- -### ▶ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس +### ◀ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس 1\. ```py @@ -2601,7 +2601,7 @@ class SomeClass: --- -### ▶ گرد کردن به روش بانکدار * +### ◀ گرد کردن به روش بانکدار * بیایید یک تابع ساده برای به‌دست‌آوردن عنصر میانی یک لیست پیاده‌سازی کنیم: ```py @@ -2651,7 +2651,7 @@ def get_middle(some_list): --- -### ▶ سوزن‌هایی در انبار کاه * +### ◀ سوزن‌هایی در انبار کاه * @@ -2828,7 +2828,7 @@ def similar_recursive_func(a): --- -### ▶ تقسیم‌ها * +### ◀ تقسیم‌ها * ```py >>> 'a'.split() @@ -2864,7 +2864,7 @@ def similar_recursive_func(a): --- -### ▶ واردسازی‌های عمومی * +### ◀ واردسازی‌های عمومی * @@ -2923,7 +2923,7 @@ NameError: name '_another_weird_name_func' is not defined --- -### ▶ همه چیز مرتب شده؟ * +### ◀ همه چیز مرتب شده؟ * @@ -2963,7 +2963,7 @@ False --- -### ▶ زمان نیمه‌شب وجود ندارد؟ +### ◀ زمان نیمه‌شب وجود ندارد؟ ```py from datetime import datetime @@ -3001,7 +3001,7 @@ Before Python 3.5, the boolean value for `datetime.time` object was considered t این بخش شامل چند مورد جالب و کمتر شناخته‌شده درباره‌ی پایتون است که بیشتر مبتدی‌هایی مثل من از آن بی‌خبرند (البته دیگر اینطور نیست). -### ▶ خب پایتون، می‌توانی کاری کنی پرواز کنم؟ +### ◀ خب پایتون، می‌توانی کاری کنی پرواز کنم؟ خب، بفرمایید @@ -3019,7 +3019,7 @@ Sshh... It's a super-secret. --- -### ▶ `goto`، ولی چرا؟ +### ◀ `goto`، ولی چرا؟ ```py @@ -3048,7 +3048,7 @@ Freedom! --- -### ▶ خودتان را آماده کنید! +### ◀ خودتان را آماده کنید! اگر جزو افرادی هستید که دوست ندارند در پایتون برای مشخص کردن محدوده‌ها از فضای خالی (whitespace) استفاده کنند، می‌توانید با ایمپورت کردن ماژول زیر از آکولاد `{}` به سبک زبان C استفاده کنید: @@ -3073,7 +3073,7 @@ SyntaxError: not a chance --- -### ▶ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم +### ◀ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم **خروجی (Python 3.x)** ```py @@ -3106,7 +3106,7 @@ True --- -### ▶ حتی پایتون هم می‌داند که عشق پیچیده است +### ◀ حتی پایتون هم می‌داند که عشق پیچیده است ```py import this @@ -3163,7 +3163,7 @@ True --- -### ▶ بله، این واقعاً وجود دارد! +### ◀ بله، این واقعاً وجود دارد! **عبارت `else` برای حلقه‌ها.** یک مثال معمول آن می‌تواند چنین باشد: @@ -3207,7 +3207,7 @@ Try block executed successfully... - عبارت `else` پس از بلاک `try` به عنوان «عبارت تکمیل» (`completion clause`) نیز شناخته می‌شود؛ چراکه رسیدن به عبارت `else` در ساختار `try` به این معنی است که بلاک `try` بدون رخ دادن استثنا با موفقیت تکمیل شده است. --- -### ▶ Ellipsis * +### ◀ Ellipsis * ```py def some_func(): @@ -3269,7 +3269,7 @@ Ellipsis --- -### ▶ بی‌نهایت (`Inpinity`) +### ◀ بی‌نهایت (`Inpinity`) این املای کلمه تعمداً به همین شکل نوشته شده است. لطفاً برای اصلاح آن درخواست (`patch`) ارسال نکنید. @@ -3288,7 +3288,7 @@ Ellipsis --- -### ▶ بیایید خرابکاری کنیم +### ◀ بیایید خرابکاری کنیم 1\. ```py @@ -3366,7 +3366,7 @@ AttributeError: 'A' object has no attribute '__variable' ## بخش: ظاهرها فریبنده‌اند! -### ▶ خطوط را رد می‌کند؟ +### ◀ خطوط را رد می‌کند؟ **خروجی:** ```py @@ -3402,7 +3402,7 @@ False --- -### ▶ تله‌پورت کردن +### ◀ تله‌پورت کردن @@ -3435,7 +3435,7 @@ def energy_receive(): --- -### ▶ خب، یک جای کار مشکوک است... +### ◀ خب، یک جای کار مشکوک است... ```py def square(x): @@ -3480,7 +3480,7 @@ def square(x): ## بخش: متفرقه -### ▶ `+=` سریع‌تر است +### ◀ `+=` سریع‌تر است ```py @@ -3497,7 +3497,7 @@ def square(x): --- -### ▶ بیایید یک رشته‌ی بزرگ بسازیم! +### ◀ بیایید یک رشته‌ی بزرگ بسازیم! ```py def add_string_with_plus(iters): @@ -3594,7 +3594,7 @@ timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) --- -### ▶ کُند کردن جستجوها در `dict` * +### ◀ کُند کردن جستجوها در `dict` * ```py some_dict = {str(i): 1 for i in range(1_000_000)} @@ -3627,7 +3627,7 @@ KeyError: 1 + این فرایند برای آن نمونه‌ی خاص از دیکشنری غیرقابل بازگشت است و حتی لازم نیست کلید موردنظر در دیکشنری موجود باشد. به همین دلیل است که حتی تلاش ناموفق برای دسترسی به کلیدی ناموجود نیز باعث ایجاد همین تأثیر (کند شدن جستجو) می‌شود. -### ▶ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) * +### ◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) * ```py import sys @@ -3689,7 +3689,7 @@ def dict_size(o): + نکته‌ای کوچک برای کاهش مصرف حافظه‌ی برنامه: هرگز صفات نمونه‌ها را حذف نکنید و حتماً تمام صفات را در متد `__init__` تعریف و مقداردهی اولیه کنید! -### ▶ موارد جزئی * +### ◀ موارد جزئی * * متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) From 78aab13e40505ba63e3d5ac0c2230f45fd8ce4ea Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sat, 5 Apr 2025 21:51:35 +0200 Subject: [PATCH 195/210] Unify the translation of explanations --- translations/fa-farsi/README.md | 74 ++++++++++++++++----------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 460c3a50..ba541049 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -238,7 +238,7 @@ SyntaxError: invalid syntax -#### 💡 توضیحات +#### 💡 توضیح **مرور سریع بر عملگر Walrus** @@ -359,7 +359,7 @@ False منطقیه، نه؟ -#### 💡 توضیحات: +#### 💡 توضیح: + در قطعه‌کد اول و دوم، رفتار کد به دلیل یک بهینه سازی در CPython است (به نام داوطلب سازی رشته‌ها) که باعث می‌شود از برخی مقادیر غیرقابل تغییر، به جای مقداردهی مجدد، دوباره استفاده شود. + بیشتر متغیرهایی که به‌این صورت جایگزین می‌شوند، در حافظه دستگاه به مقدار داوطلب خود اشاره می‌کنند (تا از حافظه کمتری استفاده شود) + در قطعه‌کدهای بالا، رشته‌ها به‌صورت غیرمستقیم داوطلب می‌شوند. تصمیم اینکه رشته‌ها چه زمانی به صورت غیرمستقیم داوطلب شوند به نحوه پیاده‌سازی و مقداردهی آن‌ها بستگی دارد. برخی قوانین وجود دارند تا بتوانیم داوطلب شدن یا نشدن یک رشته را حدس بزنیم: @@ -406,7 +406,7 @@ False 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 است. فقط دقت کنید که هر عبارت یک بار ارزیابی می‌شود. @@ -476,7 +476,7 @@ True False ``` -#### 💡 توضیحات: +#### 💡 توضیح: **فرض بین عملگرهای `is` و `==`** @@ -582,7 +582,7 @@ complex خب، چرا Python همه جارو گرفت؟ -#### 💡 توضیحات +#### 💡 توضیح * تو دیکشنری‌های پایتون چیزی که کلیدها رو یگانه میکنه مقدار کلیدهاست، نه شناسه اون‌ها. پس با اینکه `5`، `5.0` و `5 + 0j` شیءهای متمایزی از نوع‌های متفاوتی هستند ولی از اون جایی که مقدارشون با هم برابره، نمیتونن داخل یه `dict` به عنوان کلید جدا از هم باشن (حتی به عنوان مقادیر داخل یه `set` نمیتونن باشن). وقتی بخواید داخل یه دیکشنری جست‌وجو کنید، به محض اینکه یکی از این داده‌ها رو وارد کنید، مقدار نگاشته‌شده به کلیدی که مقدار برابر با اون داده داره ولی نوعش متفاوته، با موفقیت برگردونده میشه (به جای اینکه به ارور `KeyError` بردخورد کنید.). ```py >>> 5 == 5.0 == 5 + 0j @@ -636,7 +636,7 @@ True True ``` -#### 💡 توضیحات: +#### 💡 توضیح: * وقتی `id` صدا زده شد، پایتون یک شیء با کلاس `WTF` ساخت و اون رو به تابع `id` داد. تابع `id` شناسه این شیء رو میگیره (درواقع آدرس اون شیء در حافظه دستگاه) و شیء رو حذف میکنه. * وقتی این کار رو دو بار متوالی انجام بدیم، پایتون آدرس یکسانی رو به شیء دوم اختصاص میده. از اونجایی که (در CPython) تابع `id` از آدرس شیءها توی حافظه به عنوان شناسه برای اون‌ها استفاده میکنه، پس شناسه این دو شیء یکسانه. * پس، شناسه یک شیء تا زمانی که اون شیء وجود داره، منحصربه‌فرده. بعد از اینکه اون شیء حذف میشه یا قبل از اینکه اون شیء به وجود بیاد، چیز دیگه‌ای میتونه اون شناسه رو داشته باشه. @@ -727,7 +727,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` و شیءهای قابل نگاشت دیگر به ترتیب اعضای آن‌ها بستگی ندارد و مقایسه همانند دیکشنری‌های عادی انجام می‌شود. @@ -819,7 +819,7 @@ Iteration 0 ``` -#### 💡 توضیحات: +#### 💡 توضیح: - وقتی یک عبارت `return`، `break` یا `continue` داخل بخش `try` از یک عبارت "try...finally" اجرا میشه، بخش `fianlly` هم هنگام خارج شدن اجرا میشه. - مقدار بازگشتی یک تابع از طریق آخرین عبارت `return` که داخل تابع اجرا میشه، مشخص میشه. از اونجایی که بخش `finally` همیشه اجرا میشه، عبارت `return` که داخل بخش `finally` هست آخرین عبارتیه که اجرا میشه. @@ -843,7 +843,7 @@ for i, some_dict[i] in enumerate(some_string): {0: 'w', 1: 't', 2: 'f'} ``` -#### 💡 توضیحات: +#### 💡 توضیح: * یک حلقه `for` در [گرامر پایتون](https://docs.python.org/3/reference/grammar.html) این طور تعریف میشه: ``` for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] @@ -866,7 +866,7 @@ for i, some_dict[i] in enumerate(some_string): آیا انتظار داشتید که حلقه فقط یک بار اجرا بشه؟ - **💡 توضیحات:** + **💡 توضیح:** - عبارت مقداردهی `i = 10` به خاطر نحوه کار کردن حلقه‌ها، هیچوقت باعث تغییر در تکرار حلقه نمیشه. قبل از شروع هر تکرار، مقدار بعدی که توسط شیء قابل تکرار (که در اینجا `range(4)` است) ارائه میشه، از بسته خارج میشه و به متغیرهای لیست هدف (که در اینجا `i` است) مقداردهی میشه. @@ -935,7 +935,7 @@ array_4 = [400, 500, 600] [401, 501, 601, 402, 502, 602, 403, 503, 603] ``` -#### 💡 توضیحات +#### 💡 توضیح - در یک عبارت [تولیدکننده](https://wiki.python.org/moin/Generators)، عبارت بند `in` در هنگام تعریف محاسبه میشه ولی عبارت شرطی در زمان اجرا محاسبه میشه. - پس قبل از زمان اجرا، `array` دوباره با لیست `[2, 8, 22]` مقداردهی میشه و از آن‌جایی که در مقدار جدید `array`، بین `1`، `8` و `15`، فقط تعداد `8` بزرگتر از `0` است، تولیدکننده فقط مقدار `8` رو برمیگردونه @@ -958,7 +958,7 @@ True False ``` -#### 💡 توضیحات +#### 💡 توضیح - عملگر `is not` یک عملگر باینری واحده و رفتارش متفاوت تر از استفاده `is` و `not` به صورت جداگانه‌ست. - عملگر `is not` مقدار `False` رو برمیگردونه اگر متغیرها در هردو سمت این عملگر به شیء یکسانی اشاره کنند و درغیر این صورت، مقدار `True` برمیگردونه - در مثال بالا، عبارت `(not None)` برابره با مقدار `True` از اونجایی که مقدار `None` در زمینه boolean به `False` تبدیل میشه. پس کل عبارت معادل عبارت `'something' is True` میشه. @@ -992,7 +992,7 @@ board = [row] * 3 ما که سه‌تا `"X"` نذاشتیم. گذاشتیم مگه؟ -#### 💡 توضیحات: +#### 💡 توضیح: وقتی متغیر `row` رو تشکیل میدیم، تصویر زیر نشون میده که چه اتفاقی در حافظه دستگاه میافته. @@ -1060,7 +1060,7 @@ funcs_results = [func() for func in funcs] [512, 512, 512, 512, 512, 512, 512, 512, 512, 512] ``` -#### 💡 توضیحات: +#### 💡 توضیح: * وقتی یک تابع رو در داخل یک حلقه تعریف می‌کنیم که در بدنه‌اش از متغیر اون حلقه استفاده شده، بست این تابع به *متغیر* وصله، نه *مقدار* اون. تابع به جای اینکه از مقدار `x` در زمان تعریف تابع استفاده کنه، در زمینه اطرافش دنبال `x` می‌گرده. پس همه این توابع از آخرین مقداری که به متغیر `x` مقداردهی شده برای محاسباتشون استفاده می‌کنند. ما می‌تونیم ببینیم که این توابع از متغیر `x` که در زمینه اطرافشون (*نه* از متغیر محلی) هست، استفاده می‌کنند، به این صورت: ```py @@ -1143,7 +1143,7 @@ False ``` -#### 💡 توضیحات +#### 💡 توضیح - در پایتون، `type` یک [متاکلاس](https://realpython.com/python-metaclasses/) است. - در پایتون **همه چیز** یک `object` است، که کلاس‌ها و همچنین نمونه‌هاشون (یا همان instance های کلاس‌ها) هم شامل این موضوع میشن. @@ -1172,7 +1172,7 @@ False ما انتظار داشتیم که روابط بین زیرکلاس‌ها، انتقالی باشند، درسته؟ (یعنی اگه `A` زیرکلاس `B` باشه و `B` هم زیرکلاس `C` باشه، کلس `A` __باید__ زیرکلاس `C` باشه) -#### 💡 توضیحات: +#### 💡 توضیح: * روابط بین زیرکلاس‌ها در پایتون لزوما انتقالی نیستند. همه مجازند که تابع `__subclasscheck__` دلخواه خودشون رو در یک متاکلاس تعریف کنند. * وقتی عبارت `issubclass(cls, Hashable)` اجرا میشه، برنامه دنبال یک تابع "غیر نادرست" (یا non-Falsy) در `cls` یا هرچیزی که ازش ارث‌بری می‌کنه، می‌گرده. @@ -1238,7 +1238,7 @@ True دسترسی به `classm` یا `method` دو بار، اشیایی برابر اما نه *یکسان* را برای همان نمونه از `SomeClass` ایجاد می‌کند. -#### 💡 توضیحات +#### 💡 توضیح * تابع‌ها [وصاف](https://docs.python.org/3/howto/descriptor.html) هستند. هر زمان که تابعی به عنوان یک ویژگی فراخوانی شود، وصف فعال می‌شود و یک شیء متد ایجاد می‌کند که تابع را به شیء صاحب آن ویژگی "متصل" می‌کند. اگر این متد فراخوانی شود، تابع را با ارسال ضمنی شیء متصل‌شده به عنوان اولین آرگومان صدا می‌زند (به این ترتیب است که `self` را به عنوان اولین آرگومان دریافت می‌کنیم، با وجود اینکه آن را به‌طور صریح ارسال نکرده‌ایم). ```py >>> o1.method @@ -1494,7 +1494,7 @@ I have lost faith in truth! -#### 💡 توضیحات: +#### 💡 توضیح: * در پایتون، `bool` زیرکلاسی از `int` است @@ -1751,7 +1751,7 @@ True -#### 💡 توضیحات: +#### 💡 توضیح: - `'inf'` و `'nan'` رشته‌هایی خاص هستند (نسبت به حروف بزرگ و کوچک حساس نیستند) که وقتی به‌طور صریح به نوع `float` تبدیل شوند، به ترتیب برای نمایش "بی‌نهایت" ریاضی و "عدد نیست" استفاده می‌شوند. @@ -1800,7 +1800,7 @@ TypeError: 'tuple' object does not support item assignment اما من فکر می‌کردم تاپل‌ها تغییرناپذیر هستند... -#### 💡 توضیحات: +#### 💡 توضیح: * نقل‌قول از https://docs.python.org/3/reference/datamodel.html @@ -1836,7 +1836,7 @@ except Exception as e: NameError: name 'e' is not defined ``` -#### 💡 توضیحات: +#### 💡 توضیح: * منبع: [مستندات رسمی پایتون](https://docs.python.org/3/reference/compound_stmts.html#except) هنگامی که یک استثنا (Exception) با استفاده از کلمه‌ی کلیدی `as` به متغیری تخصیص داده شود، این متغیر در انتهای بلاکِ `except` پاک می‌شود. این رفتار مشابه کد زیر است: @@ -1916,7 +1916,7 @@ str str ``` -#### 💡 توضیحات: +#### 💡 توضیح: * هر دو شیء `s` و رشته‌ی `"s"` به دلیل ارث‌بری `SomeClass` از متد `__hash__` کلاس `str`، هش یکسانی دارند. * عبارت `SomeClass("s") == "s"` به دلیل ارث‌بری `SomeClass` از متد `__eq__` کلاس `str` برابر با `True` ارزیابی می‌شود. @@ -2290,7 +2290,7 @@ for idx, item in enumerate(list_4): ``` عنصر `3` از لیست `numbers` چه شد؟ -#### 💡 توضیحات: +#### 💡 توضیح: - بر اساس [مستندات](https://docs.python.org/3.3/library/functions.html#zip) پایتون، پیاده‌سازی تقریبی تابع `zip` به شکل زیر است: ```py @@ -2374,7 +2374,7 @@ print(x, ': x in global') 1 ``` -#### 💡 توضیحات: +#### 💡 توضیح: - در پایتون، حلقه‌های `for` از حوزه (*scope*) فعلی که در آن قرار دارند استفاده می‌کنند و متغیرهای تعریف‌شده در حلقه حتی بعد از اتمام حلقه نیز باقی می‌مانند. این قاعده حتی در مواردی که متغیر حلقه پیش‌تر در فضای نام سراسری (*global namespace*) تعریف شده باشد نیز صدق می‌کند؛ در چنین حالتی، متغیر موجود مجدداً به مقدار جدید متصل می‌شود. @@ -2405,7 +2405,7 @@ def some_func(default_arg=[]): ['some_string', 'some_string', 'some_string'] ``` -#### 💡 توضیحات: +#### 💡 توضیح: - آرگومان‌های تغییرپذیر پیش‌فرض در توابع پایتون، هر بار که تابع فراخوانی می‌شود مقداردهی نمی‌شوند؛ بلکه مقداردهی آنها تنها یک بار در زمان تعریف تابع انجام می‌شود و مقدار اختصاص‌یافته به آن‌ها به عنوان مقدار پیش‌فرض برای فراخوانی‌های بعدی استفاده خواهد شد. هنگامی که به صراحت مقدار `[]` را به عنوان آرگومان به `some_func` ارسال کردیم، مقدار پیش‌فرض برای متغیر `default_arg` مورد استفاده قرار نگرفت، بنابراین تابع همان‌طور که انتظار داشتیم عمل کرد. @@ -2474,7 +2474,7 @@ ValueError: list.remove(x): x not in list SyntaxError: invalid syntax ``` -#### 💡 توضیحات +#### 💡 توضیح * To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example, ```py @@ -2549,7 +2549,7 @@ a += [5, 6, 7, 8] [1, 2, 3, 4, 5, 6, 7, 8] ``` -#### 💡 توضیحات: +#### 💡 توضیح: * عملگر `a += b` همیشه همانند `a = a + b` رفتار نمی‌کند. کلاس‌ها *ممکن است* عملگرهای *`op=`* را به گونه‌ای متفاوت پیاده‌سازی کنند، و لیست‌ها نیز چنین می‌کنند. * عبارت `a = a + [5,6,7,8]` یک لیست جدید ایجاد می‌کند و مرجع `a` را به این لیست جدید اختصاص می‌دهد، بدون آنکه `b` را تغییر دهد. @@ -2594,7 +2594,7 @@ class SomeClass: 5 ``` -#### 💡 توضیحات +#### 💡 توضیح - حوزه‌هایی که درون تعریف کلاس تو در تو هستند، نام‌های تعریف‌شده در سطح کلاس را نادیده می‌گیرند. - عبارت‌های جنراتور (generator expressions) حوزه‌ی مختص به خود دارند. - از پایتون نسخه‌ی ۳ به بعد، لیست‌های فشرده (list comprehensions) نیز حوزه‌ی مختص به خود دارند. @@ -2625,7 +2625,7 @@ def get_middle(some_list): ``` به نظر می‌رسد که پایتون عدد ۲٫۵ را به ۲ گرد کرده است. -#### 💡 توضیحات: +#### 💡 توضیح: - این یک خطای مربوط به دقت اعداد اعشاری نیست؛ بلکه این رفتار عمدی است. از پایتون نسخه 3.0 به بعد، تابع `round()` از [گرد کردن بانکی](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even) استفاده می‌کند که در آن کسرهای `.5` به نزدیک‌ترین عدد **زوج** گرد می‌شوند: @@ -2785,7 +2785,7 @@ def similar_recursive_func(a): 4 ``` -#### 💡 توضیحات: +#### 💡 توضیح: * برای مورد ۱، عبارت صحیح برای رفتار مورد انتظار این است: `x, y = (0, 1) if True else (None, None)` @@ -2847,7 +2847,7 @@ def similar_recursive_func(a): 1 ``` -#### 💡 توضیحات: +#### 💡 توضیح: - در نگاه اول ممکن است به نظر برسد جداکننده‌ی پیش‌فرض متد `split` یک فاصله‌ی تکی (`' '`) است؛ اما مطابق با [مستندات رسمی](https://docs.python.org/3/library/stdtypes.html#str.split): > اگر `sep` مشخص نشده یا برابر با `None` باشد، یک الگوریتم متفاوت برای جدا کردن اعمال می‌شود: رشته‌هایی از فاصله‌های متوالی به عنوان یک جداکننده‌ی واحد در نظر گرفته شده و در نتیجه، هیچ رشته‌ی خالی‌ای در ابتدا یا انتهای لیست خروجی قرار نمی‌گیرد، حتی اگر رشته‌ی اولیه دارای فاصله‌های اضافی در ابتدا یا انتها باشد. به همین دلیل، تقسیم یک رشته‌ی خالی یا رشته‌ای که فقط شامل فضای خالی است با جداکننده‌ی `None` باعث بازگشت یک لیست خالی `[]` می‌شود. @@ -2891,7 +2891,7 @@ Traceback (most recent call last): NameError: name '_another_weird_name_func' is not defined ``` -#### 💡 توضیحات: +#### 💡 توضیح: - اغلب توصیه می‌شود از واردسازی عمومی (wildcard imports) استفاده نکنید. اولین دلیل واضح آن این است که در این نوع واردسازی‌ها، اسامی که با زیرخط (`_`) شروع شوند، وارد نمی‌شوند. این مسئله ممکن است در زمان اجرا به خطا منجر شود. - اگر از ساختار `from ... import a, b, c` استفاده کنیم، خطای `NameError` فوق اتفاق نمی‌افتاد. @@ -2939,7 +2939,7 @@ True False ``` -#### 💡 توضیحات: +#### 💡 توضیح: - متد `sorted` همیشه یک لیست (`list`) برمی‌گرداند، و در پایتون مقایسه‌ی لیست‌ها و تاپل‌ها (`tuple`) همیشه مقدار `False` را برمی‌گرداند. @@ -2988,7 +2988,7 @@ if noon_time: ``` 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." @@ -3568,7 +3568,7 @@ timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) 86.3 µs ± 2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ``` -#### 💡 توضیحات +#### 💡 توضیح توضیحات - برای اطلاعات بیشتر درباره‌ی [timeit](https://docs.python.org/3/library/timeit.html) یا [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit)، می‌توانید به این لینک‌ها مراجعه کنید. این توابع برای اندازه‌گیری زمان اجرای قطعه‌کدها استفاده می‌شوند. - برای تولید رشته‌های طولانی از `+` استفاده نکنید — در پایتون، نوع داده‌ی `str` تغییرناپذیر (immutable) است؛ بنابراین برای هر الحاق (concatenation)، رشته‌ی چپ و راست باید در رشته‌ی جدید کپی شوند. اگر چهار رشته‌ی ۱۰ حرفی را متصل کنید، به‌جای کپی ۴۰ کاراکتر، باید `(10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90` کاراکتر کپی کنید. این وضعیت با افزایش تعداد و طول رشته‌ها به‌صورت درجه دو (مربعی) بدتر می‌شود (که توسط زمان اجرای تابع `add_bytes_with_plus` تأیید شده است). @@ -3693,7 +3693,7 @@ def dict_size(o): * متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) - ** 💡 توضیح:** اگر `join()` به‌عنوان متدی روی رشته پیاده‌سازی شود، می‌تواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشونده‌ی دیگر کار کند. اگر به‌جای آن روی لیست تعریف می‌شد، باید به‌طور جداگانه برای هر نوع دیگری نیز پیاده‌سازی می‌شد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. + **توضیح:** اگر `join()` به‌عنوان متدی روی رشته پیاده‌سازی شود، می‌تواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشونده‌ی دیگر کار کند. اگر به‌جای آن روی لیست تعریف می‌شد، باید به‌طور جداگانه برای هر نوع دیگری نیز پیاده‌سازی می‌شد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. * تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح: + عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی). @@ -3712,7 +3712,7 @@ def dict_size(o): 5 ``` - ** 💡 توضیح:** + 💡 **توضیح:** + در گرامر پایتون عملگری به‌نام `++` وجود ندارد. در واقع `++` دو عملگر `+` جداگانه است. + عبارت `++a` به‌شکل `+(+a)` تفسیر می‌شود که معادل `a` است. به‌همین ترتیب، خروجی عبارت `--a` نیز قابل توجیه است. + این [تاپیک در StackOverflow](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) دلایل نبودن عملگرهای افزایش (`++`) و کاهش (`--`) در پایتون را بررسی می‌کند. From 4ffaa0ff77f2a6ad303580619d1d64395c14f46e Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sat, 5 Apr 2025 21:58:43 +0200 Subject: [PATCH 196/210] Update ToC --- translations/fa-farsi/README.md | 105 ++++++++++++++++---------------- 1 file changed, 52 insertions(+), 53 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index ba541049..c2b82993 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -51,72 +51,71 @@ - [◀ کلیدهای هش](#-کلیدهای-هش) - [◀ در عمق وجود همه ما یکسان هستیم](#-در-عمق-وجود-همه-ما-یکسان-هستیم) - [◀ بی‌نظمی در خود نظم \*](#-بینظمی-در-خود-نظم-) - - [◀ تلاش کن... \*](#-تلاش-کن-) - [◀ برای چی؟](#-برای-چی) - [◀ اختلاف زمانی در محاسبه](#-اختلاف-زمانی-در-محاسبه) - [◀ هر گردی، گردو نیست](#-هر-گردی-گردو-نیست) - - [◀ یک بازی دوز که توش X همون اول برنده میشه!](#-یک-بازی-دوز-که-توش-X-همون-اول-برنده-میشه) + - [◀ یک بازی دوز که توش X همون اول برنده میشه!](#-یک-بازی-دوز-که-توش-x-همون-اول-برنده-میشه) - [◀ متغیر شرودینگر \*](#-متغیر-شرودینگر-) - [◀ اول مرغ بوده یا تخم مرغ؟ \*](#-اول-مرغ-بوده-یا-تخم-مرغ-) - [◀ روابط بین زیرمجموعه کلاس‌ها](#-روابط-بین-زیرمجموعه-کلاسها) - - [◀ ‫ برابری و هویت متدها](#--برابری-و-هویت-متدها) - - [◀ ‫ آل-ترو-یشن \*](#--آل-ترو-یشن-) - - [◀ ‫ رشته‌ها و بک‌اسلش‌ها](#--رشتهها-و-بکاسلشها) - - [◀ ‫ گره نیست، نَه!](#--گره-نیست-نَه) + - [◀ برابری و هویت متدها](#-برابری-و-هویت-متدها) + - [◀ آل-ترو-یشن \*](#-آل-ترو-یشن-) + - [◀ رشته‌ها و بک‌اسلش‌ها](#-رشتهها-و-بکاسلشها) + - [◀ گره نیست، نَه!](#-گره-نیست-نَه) - [◀ رشته‌های نیمه سه‌نقل‌قولی](#-رشتههای-نیمه-سهنقلقولی) - - [◀ ‫ مشکل بولین ها چیست؟](#--مشکل-بولین-ها-چیست) - - [◀ ‫ ویژگی‌های کلاس و ویژگی‌های نمونه](#--ویژگیهای-کلاس-و-ویژگیهای-نمونه) + - [◀ مشکل بولین ها چیست؟](#-مشکل-بولین-ها-چیست) + - [◀ ویژگی‌های کلاس و ویژگی‌های نمونه](#-ویژگیهای-کلاس-و-ویژگیهای-نمونه) - [◀ yielding None](#-yielding-none) - [◀ Yielding from... return! \*](#-yielding-from-return-) - - [◀ ‫ بازتاب‌ناپذیری \*](#--بازتابناپذیری-) - - [◀ ‫ تغییر دادن اشیای تغییرناپذیر!](#--تغییر-دادن-اشیای-تغییرناپذیر) - - [◀ ‫ متغیری که از اسکوپ بیرونی ناپدید می‌شود](#--متغیری-که-از-اسکوپ-بیرونی-ناپدید-میشود) - - [◀ ‫ تبدیل اسرارآمیز نوع کلید](#--تبدیل-اسرارآمیز-نوع-کلید) - - [◀ ‫ ببینیم می‌توانید این را حدس بزنید؟](#--ببینیم-میتوانید-این-را-حدس-بزنید) - - [◀ ‫ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود](#--از-حد-مجاز-برای-تبدیل-رشته-به-عدد-صحیح-فراتر-میرود) - - [‫ بخش: شیب‌های لغزنده](#-بخش-شیبهای-لغزنده) - - [◀ ‫ تغییر یک دیکشنری هنگام پیمایش روی آن](#--تغییر-یک-دیکشنری-هنگام-پیمایش-روی-آن) + - [◀ بازتاب‌ناپذیری \*](#-بازتابناپذیری-) + - [◀ تغییر دادن اشیای تغییرناپذیر!](#-تغییر-دادن-اشیای-تغییرناپذیر) + - [◀ متغیری که از اسکوپ بیرونی ناپدید می‌شود](#-متغیری-که-از-اسکوپ-بیرونی-ناپدید-میشود) + - [◀ تبدیل اسرارآمیز نوع کلید](#-تبدیل-اسرارآمیز-نوع-کلید) + - [◀ ببینیم می‌توانید این را حدس بزنید؟](#-ببینیم-میتوانید-این-را-حدس-بزنید) + - [◀ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود](#-از-حد-مجاز-برای-تبدیل-رشته-به-عدد-صحیح-فراتر-میرود) + - [بخش: شیب‌های لغزنده](#بخش-شیبهای-لغزنده) + - [◀ تغییر یک دیکشنری هنگام پیمایش روی آن](#-تغییر-یک-دیکشنری-هنگام-پیمایش-روی-آن) - [◀ عملیات سرسختانه‌ی `del`](#-عملیات-سرسختانهی-del) - - [◀ ‫ متغیری که از حوزه خارج است](#--متغیری-که-از-حوزه-خارج-است) - - [◀ ‫ حذف المان‌های لیست در حین پیمایش](#--حذف-المانهای-لیست-در-حین-پیمایش) - - [◀ ‫ زیپِ دارای اتلاف برای پیمایشگرها \*](#--زیپِ-دارای-اتلاف-برای-پیمایشگرها-) - - [◀ ‫ نشت کردن متغیرهای حلقه!](#--نشت-کردن-متغیرهای-حلقه) - - [◀ ‫ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید!](#--مراقب-آرگومانهای-تغییرپذیر-پیشفرض-باشید) - - [◀ ‫ گرفتن استثناها (Exceptions)](#--گرفتن-استثناها-exceptions) - - [◀ ‫ عملوندهای یکسان، داستانی متفاوت!](#--عملوندهای-یکسان-داستانی-متفاوت) - - [◀ ‫ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس](#--تفکیک-نامها-با-نادیده-گرفتن-حوزهی-کلاس) - - [◀ ‫ گرد کردن به روش بانکدار \*](#--گرد-کردن-به-روش-بانکدار-) - - [◀ ‫ سوزن‌هایی در انبار کاه \*](#--سوزنهایی-در-انبار-کاه-) - - [◀ ‫ تقسیم‌ها \*](#--تقسیمها-) + - [◀ متغیری که از حوزه خارج است](#-متغیری-که-از-حوزه-خارج-است) + - [◀ حذف المان‌های لیست در حین پیمایش](#-حذف-المانهای-لیست-در-حین-پیمایش) + - [◀ زیپِ دارای اتلاف برای پیمایشگرها \*](#-زیپِ-دارای-اتلاف-برای-پیمایشگرها-) + - [◀ نشت کردن متغیرهای حلقه!](#-نشت-کردن-متغیرهای-حلقه) + - [◀ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید!](#-مراقب-آرگومانهای-تغییرپذیر-پیشفرض-باشید) + - [◀ گرفتن استثناها (Exceptions)](#-گرفتن-استثناها-exceptions) + - [◀ عملوندهای یکسان، داستانی متفاوت!](#-عملوندهای-یکسان-داستانی-متفاوت) + - [◀ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس](#-تفکیک-نامها-با-نادیده-گرفتن-حوزهی-کلاس) + - [◀ گرد کردن به روش بانکدار \*](#-گرد-کردن-به-روش-بانکدار-) + - [◀ سوزن‌هایی در انبار کاه \*](#-سوزنهایی-در-انبار-کاه-) + - [◀ تقسیم‌ها \*](#-تقسیمها-) - [◀ واردسازی‌های عمومی \*](#-واردسازیهای-عمومی-) - - [◀ ‫ همه چیز مرتب شده؟ \*](#--همه-چیز-مرتب-شده-) - - [◀ ‫ زمان نیمه‌شب وجود ندارد؟](#--زمان-نیمهشب-وجود-ندارد) - - [‫ بخش: گنجینه‌های پنهان!](#-بخش-گنجینههای-پنهان) - - [◀ ‫ خب پایتون، می‌توانی کاری کنی پرواز کنم؟](#--خب-پایتون-میتوانی-کاری-کنی-پرواز-کنم) - - [◀ ‫ `goto`، ولی چرا؟](#--goto-ولی-چرا) - - [◀ ‫ خودتان را آماده کنید!](#--خودتان-را-آماده-کنید) - - [◀ ‫ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم](#--بیایید-با-عمو-زبان-مهربان-برای-همیشه-آشنا-شویم) - - [◀ ‫ حتی پایتون هم می‌داند که عشق پیچیده است](#--حتی-پایتون-هم-میداند-که-عشق-پیچیده-است) - - [◀ ‫ بله، این واقعاً وجود دارد!](#--بله-این-واقعاً-وجود-دارد) + - [◀ همه چیز مرتب شده؟ \*](#-همه-چیز-مرتب-شده-) + - [◀ زمان نیمه‌شب وجود ندارد؟](#-زمان-نیمهشب-وجود-ندارد) + - [بخش: گنجینه‌های پنهان!](#بخش-گنجینههای-پنهان) + - [◀ خب پایتون، می‌توانی کاری کنی پرواز کنم؟](#-خب-پایتون-میتوانی-کاری-کنی-پرواز-کنم) + - [◀ `goto`، ولی چرا؟](#-goto-ولی-چرا) + - [◀ خودتان را آماده کنید!](#-خودتان-را-آماده-کنید) + - [◀ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم](#-بیایید-با-عمو-زبان-مهربان-برای-همیشه-آشنا-شویم) + - [◀ حتی پایتون هم می‌داند که عشق پیچیده است](#-حتی-پایتون-هم-میداند-که-عشق-پیچیده-است) + - [◀ بله، این واقعاً وجود دارد!](#-بله-این-واقعاً-وجود-دارد) - [◀ Ellipsis \*](#-ellipsis-) - - [◀ ‫ بی‌نهایت (`Inpinity`)](#--بینهایت-inpinity) - - [◀ ‫ بیایید خرابکاری کنیم](#--بیایید-خرابکاری-کنیم) - - [‫ بخش: ظاهرها فریبنده‌اند!](#-بخش-ظاهرها-فریبندهاند) - - [◀ ‫ خطوط را رد می‌کند؟](#--خطوط-را-رد-میکند) - - [◀ ‫ تله‌پورت کردن](#--تلهپورت-کردن) - - [◀ ‫ خب، یک جای کار مشکوک است...](#--خب-یک-جای-کار-مشکوک-است) + - [◀ بی‌نهایت (`Inpinity`)](#-بینهایت-inpinity) + - [◀ بیایید خرابکاری کنیم](#-بیایید-خرابکاری-کنیم) + - [بخش: ظاهرها فریبنده‌اند!](#بخش-ظاهرها-فریبندهاند) + - [◀ خطوط را رد می‌کند؟](#-خطوط-را-رد-میکند) + - [◀ تله‌پورت کردن](#-تلهپورت-کردن) + - [◀ خب، یک جای کار مشکوک است...](#-خب-یک-جای-کار-مشکوک-است) - [بخش: متفرقه](#بخش-متفرقه) - - [‫ ◀ `+=` سریع‌تر است](#---سریعتر-است) - - [‫ ◀ بیایید یک رشته‌ی بزرگ بسازیم!](#--بیایید-یک-رشتهی-بزرگ-بسازیم) - - [◀ ‫ کُند کردن جستجوها در `dict` \*](#---کُند-کردن-جستجوها-در-dict-) - - [‫ ◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#--حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) - - [‫ ◀ موارد جزئی \*](#---موارد-جزئی-) -- [‫ مشارکت](#-مشارکت) -- [‫ تقدیر و تشکر](#-تقدیر-و-تشکر) - - [‫ چند لینک جالب!](#-چند-لینک-جالب) -- [‫ 🎓 مجوز](#--مجوز) - - [‫ دوستانتان را هم شگفت‌زده کنید!](#-دوستانتان-را-هم-شگفتزده-کنید) - - [‫ آیا به یک نسخه pdf نیاز دارید؟](#-آیا-به-یک-نسخه-pdf-نیاز-دارید) + - [◀ `+=` سریع‌تر است](#--سریعتر-است) + - [◀ بیایید یک رشته‌ی بزرگ بسازیم!](#-بیایید-یک-رشتهی-بزرگ-بسازیم) + - [◀ کُند کردن جستجوها در `dict` \*](#--کُند-کردن-جستجوها-در-dict-) + - [◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#-حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) + - [◀ موارد جزئی \*](#-موارد-جزئی-) +- [مشارکت](#مشارکت) +- [تقدیر و تشکر](#تقدیر-و-تشکر) + - [چند لینک جالب!](#چند-لینک-جالب) +- [🎓 مجوز](#-مجوز) + - [دوستانتان را هم شگفت‌زده کنید!](#دوستانتان-را-هم-شگفتزده-کنید) + - [آیا به یک نسخه pdf نیاز دارید؟](#آیا-به-یک-نسخه-pdf-نیاز-دارید) From 7a12c2ae4a871dd9dc205ecbe22f65d7a30cc620 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sun, 13 Apr 2025 15:28:26 +0200 Subject: [PATCH 197/210] Fix some typos --- translations/fa-farsi/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index c2b82993..10025163 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -17,7 +17,7 @@ پایتون، یه زبان زیبا طراحی شده، سطح بالا و مبتنی بر مفسره که قابلیت‌های بسیاری برای راحتی ما برنامه‌نویس‌ها فراهم می‌کنه. ولی گاهی اوقات قطعه‌کدهایی رو می‌بینیم که تو نگاه اول خروجی‌هاشون واضح نیست. -این یه پروژه باحاله که سعی داریم توش توضیح بدیم که پشت پرده یه سری قطعه‌کدهای غیرشهودی و فابلیت‌های کمتر شناخته شده پایتون +این یه پروژه باحاله که سعی داریم توش توضیح بدیم که پشت پرده یه سری قطعه‌کدهای غیرشهودی و قابلیت‌های کمتر شناخته شده پایتون چه خبره. درحالی که بعضی از مثال‌هایی که قراره تو این سند ببینید واقعا عجیب و غریب نیستند ولی بخش‌های جالبی از پایتون رو ظاهر می‌کنند که @@ -28,7 +28,7 @@ تو تلاش اول حدس بزنید. ممکنه شما بعضی از این مثال‌ها رو قبلا تجربه کرده باشید و من خاطراتشون رو در این سند براتون زنده کرده باشم! :sweat_smile: -پ.ن: اگه شما قبلا این سند رو خوندید، می‌تونید تغییرات جدید رو در بخش انتشار (فعلا در [اینجا](https://github.com/satwikkansal/wtfpython/)) مطالعه کنید +پ.ن: اگه شما قبلا این سند رو خوندید، می‌تونید تغییرات جدید رو در بخش انتشار (فعلا در [اینجا](https://github.com/satwikkansal/wtfpython/releases/)) مطالعه کنید (مثال‌هایی که کنارشون علامت ستاره دارند، در آخرین ویرایش اضافه شده‌اند). پس، بزن بریم... @@ -242,7 +242,7 @@ SyntaxError: invalid syntax **مرور سریع بر عملگر Walrus** عملگر Walrus همونطور که اشاره شد، در نسخه ۳.۸ پایتون معرفی -شد. این عملگر می‌تونه تو مقعیت‌هایی کاربردی باشه که شما می‌خواید داخل یه عبارت، مقادیری رو به متغیرها اختصاص بدید +شد. این عملگر می‌تونه تو موقعیت‌هایی کاربردی باشه که شما می‌خواید داخل یه عبارت، مقادیری رو به متغیرها اختصاص بدید. ```py def some_func(): From e690b4a349899af5a9ba0c329719808a2f896be9 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sun, 13 Apr 2025 15:34:58 +0200 Subject: [PATCH 198/210] Add some RTL fixings --- translations/fa-farsi/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 10025163..c02f5e19 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -275,9 +275,9 @@ if a := some_func(): این باعث میشه که یک خط کمتر کد بزنیم و از دوبار فراخوندن `some_func` جلوگیری کرد. -- "عبارت اختصاص‌دادن مقدار" بدون پرانتز (نحوه استفاده عملگر Walrus)، در سطح بالا محدود است، `SyntaxError` در عبارت `a := "wtf_walrus"` در قطعه‌کد اول به همین دلیل است. قرار دادن آن داخل پرانتز، همانطور که می‌خواستیم کار کرد و مقدار را به `a` اختصاص داد. +- ‫ "عبارت اختصاص‌دادن مقدار" بدون پرانتز (نحوه استفاده عملگر Walrus)، در سطح بالا محدود است، `SyntaxError` در عبارت `a := "wtf_walrus"` در قطعه‌کد اول به همین دلیل است. قرار دادن آن داخل پرانتز، همانطور که می‌خواستیم کار کرد و مقدار را به `a` اختصاص داد. -- به طور معمول، قرار دادن عبارتی که دارای `=` است داخل پرانتز مجاز نیست. به همین دلیل ‍عبارت `(a, b = 6, 9)` به ما خطای سینتکس داد. +- ‫ به طور معمول، قرار دادن عبارتی که دارای `=` است داخل پرانتز مجاز نیست. به همین دلیل ‍عبارت `(a, b = 6, 9)` به ما خطای سینتکس داد. - قائده استفاده از عملگر Walrus به صورت `NAME:= expr` است، به طوری که `NAME` یک شناسه صحیح و `expr` یک عبارت صحیح است. به همین دلیل باز و بسته کردن با تکرار (iterable) پشتیبانی نمی‌شوند. پس، From 385d93c40e4797f803bf1e74fd392452d318b559 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sun, 13 Apr 2025 15:36:59 +0200 Subject: [PATCH 199/210] Revert RTL fixing --- translations/fa-farsi/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index c02f5e19..10025163 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -275,9 +275,9 @@ if a := some_func(): این باعث میشه که یک خط کمتر کد بزنیم و از دوبار فراخوندن `some_func` جلوگیری کرد. -- ‫ "عبارت اختصاص‌دادن مقدار" بدون پرانتز (نحوه استفاده عملگر Walrus)، در سطح بالا محدود است، `SyntaxError` در عبارت `a := "wtf_walrus"` در قطعه‌کد اول به همین دلیل است. قرار دادن آن داخل پرانتز، همانطور که می‌خواستیم کار کرد و مقدار را به `a` اختصاص داد. +- "عبارت اختصاص‌دادن مقدار" بدون پرانتز (نحوه استفاده عملگر Walrus)، در سطح بالا محدود است، `SyntaxError` در عبارت `a := "wtf_walrus"` در قطعه‌کد اول به همین دلیل است. قرار دادن آن داخل پرانتز، همانطور که می‌خواستیم کار کرد و مقدار را به `a` اختصاص داد. -- ‫ به طور معمول، قرار دادن عبارتی که دارای `=` است داخل پرانتز مجاز نیست. به همین دلیل ‍عبارت `(a, b = 6, 9)` به ما خطای سینتکس داد. +- به طور معمول، قرار دادن عبارتی که دارای `=` است داخل پرانتز مجاز نیست. به همین دلیل ‍عبارت `(a, b = 6, 9)` به ما خطای سینتکس داد. - قائده استفاده از عملگر Walrus به صورت `NAME:= expr` است، به طوری که `NAME` یک شناسه صحیح و `expr` یک عبارت صحیح است. به همین دلیل باز و بسته کردن با تکرار (iterable) پشتیبانی نمی‌شوند. پس، From 5bf9aabd25b42779b6dedf06b4d50f15699fc14e Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sun, 13 Apr 2025 16:25:42 +0200 Subject: [PATCH 200/210] Add RTL fix for chaining --- translations/fa-farsi/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 10025163..0113a533 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -412,8 +412,8 @@ False شاید چنین رفتاری برای شما احمقانه به نظر بیاد ولی برای عملیات‌هایی مثل `a == b == c` و `0 <= x <= 100` عالی عمل می‌کنه. -* عبارت `False is False is False` معادل عبارت `(False is False) and (False is False)` است -* عبارت `True is False == False` معادل عبارت `(True is False) and (False == False)` است و از آنجایی که قسمت اول این عبارت (`True is False`) پس از ارزیابی برابر با `False` می‌شود. پس کل عبارت معادل `False` می‌شود. +* ‫ عبارت `False is False is False` معادل عبارت `(False is False) and (False is False)` است +* ‫ عبارت `True is False == False` معادل عبارت `(True is False) and (False == False)` است و از آنجایی که قسمت اول این عبارت (`True is False`) پس از ارزیابی برابر با `False` می‌شود. پس کل عبارت معادل `False` می‌شود. * عبارت `1 > 0 < 1` معادل عبارت `(1 > 0) and (0 < 1)` است. * عبارت `(1 > 0) < 1` معادل عبارت `True < 1` است و : ```py From d1c19a0d72a940817cafac88db7518faf8ee1c34 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sun, 13 Apr 2025 16:28:41 +0200 Subject: [PATCH 201/210] remove extra rtl chars --- translations/fa-farsi/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 0113a533..10025163 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -412,8 +412,8 @@ False شاید چنین رفتاری برای شما احمقانه به نظر بیاد ولی برای عملیات‌هایی مثل `a == b == c` و `0 <= x <= 100` عالی عمل می‌کنه. -* ‫ عبارت `False is False is False` معادل عبارت `(False is False) and (False is False)` است -* ‫ عبارت `True is False == False` معادل عبارت `(True is False) and (False == False)` است و از آنجایی که قسمت اول این عبارت (`True is False`) پس از ارزیابی برابر با `False` می‌شود. پس کل عبارت معادل `False` می‌شود. +* عبارت `False is False is False` معادل عبارت `(False is False) and (False is False)` است +* عبارت `True is False == False` معادل عبارت `(True is False) and (False == False)` است و از آنجایی که قسمت اول این عبارت (`True is False`) پس از ارزیابی برابر با `False` می‌شود. پس کل عبارت معادل `False` می‌شود. * عبارت `1 > 0 < 1` معادل عبارت `(1 > 0) and (0 < 1)` است. * عبارت `(1 > 0) < 1` معادل عبارت `True < 1` است و : ```py From 48b0b96193bd10aa0143b92fb4035480dd2e84d9 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Sun, 13 Apr 2025 17:27:09 +0200 Subject: [PATCH 202/210] Add missing link --- translations/fa-farsi/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 10025163..f872be43 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -612,7 +612,7 @@ complex >>> hash(5) == hash(5.0) == hash(5 + 0j) True ``` - **توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیده‌ای معروف [تصادم هش]() میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند. + **توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیده‌ای معروف [تصادف هش](https://en.wikipedia.org/wiki/Collision_(disambiguation)#Other_uses) میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند. --- From 17046d418afd00e319ea5a8fea3346d85eef8972 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Tue, 15 Apr 2025 14:57:56 +0200 Subject: [PATCH 203/210] Fix some rtl --- translations/fa-farsi/README.md | 47 +++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index f872be43..54df2c56 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -869,7 +869,7 @@ for i, some_dict[i] in enumerate(some_string): - عبارت مقداردهی `i = 10` به خاطر نحوه کار کردن حلقه‌ها، هیچوقت باعث تغییر در تکرار حلقه نمیشه. قبل از شروع هر تکرار، مقدار بعدی که توسط شیء قابل تکرار (که در اینجا `range(4)` است) ارائه میشه، از بسته خارج میشه و به متغیرهای لیست هدف (که در اینجا `i` است) مقداردهی میشه. -* تابع `enumerate(some_string)`، یک متغیر `i` (که یک شمارنده اقزایشی است) و یک حرف از حروف رشته `some_string` رو در هر تکرار برمیگردونه. و بعدش برای کلید `i` (تازه مقداردهی‌شده) در دیکشنری `some_dict`، مقدار اون حرف رو تنظیم می‌کنه. بازشده این حلقه می‌تونه مانند مثال زیر ساده بشه: +* تابع `enumerate(some_string)`، یک متغیر `i` (که یک شمارنده افزایشی است) و یک حرف از حروف رشته `some_string` رو در هر تکرار برمیگردونه. و بعدش برای کلید `i` (تازه مقداردهی‌شده) در دیکشنری `some_dict`، مقدار اون حرف رو تنظیم می‌کنه. بازشده این حلقه می‌تونه مانند مثال زیر ساده بشه: ```py >>> i, some_dict[i] = (0, 'w') >>> i, some_dict[i] = (1, 't') @@ -969,10 +969,15 @@ False ```py + # بیاید یک سطر تشکیل بدیم + row = [""] * 3 #row i['', '', ''] + # حالا بیاید تخته بازی رو ایجاد کنیم + board = [row] * 3 + ``` **خروجی:** @@ -1036,7 +1041,7 @@ for x in range(7): def some_func(): return x funcs.append(some_func) - results.append(some_func()) # note the function call here + results.append(some_func()) # به فراخوانی تابع دقت کنید. funcs_results = [func() for func in funcs] ``` @@ -1150,7 +1155,6 @@ False - هیچ کلاس پایه واقعی بین کلاس‌های `object` و `type` وجود نداره. سردرگمی که در قطعه‌کدهای بالا به وجود اومده، به خاطر اینه که ما به این روابط (یعنی `issubclass` و `isinstance`) از دیدگاه کلاس‌های پایتون فکر می‌کنیم. رابطه بین `object` و `type` رو در پایتون خالص نمیشه بازتولید کرد. برای اینکه دقیق‌تر باشیم، رابطه‌های زیر در پایتون خالص نمی‌تونند بازتولید بشن. + کلاس A یک نمونه از کلاس B، و کلاس B یک نمونه از کلاس A باشه. + کلاس A یک نمونه از خودش باشه. -- - این روابط بین `object` و `type` (که هردو نمونه یکدیگه و همچنین خودشون باشند) به خاطر "تقلب" در مرحله پیاده‌سازی، وجود دارند. --- @@ -1289,7 +1293,7 @@ True چرا این تغییر درست-نادرسته؟ -#### 💡 Explanation: +#### 💡 توضیحات: - پیاده‌سازی تابع `all` معادل است با @@ -1400,7 +1404,7 @@ True SyntaxError: invalid syntax ``` -#### 💡 Explanation: +#### 💡 توضیح: * تقدم عملگرها بر نحوه‌ی ارزیابی یک عبارت تأثیر می‌گذارد، و در پایتون، عملگر `==` تقدم بالاتری نسبت به عملگر `not` دارد. * بنابراین عبارت `not x == y` معادل `not (x == y)` است که خودش معادل `not (True == False)` بوده و در نهایت به `True` ارزیابی می‌شود. @@ -1417,7 +1421,7 @@ SyntaxError: invalid syntax wtfpython >>> print("wtfpython""") wtfpython ->>> # The following statements raise `SyntaxError` +>>> # کد های زیر خطای سینکس دارند. >>> # print('''wtfpython') >>> # print("""wtfpython") File "", line 3 @@ -1428,12 +1432,14 @@ SyntaxError: EOF while scanning triple-quoted string literal #### 💡 توضیح: + پایتون از الحاق ضمنی [رشته‌های متنی](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation) پشتیبانی می‌کند. برای مثال، + ``` >>> print("wtf" "python") wtfpython >>> print("wtf" "") # or "wtf""" wtf ``` + + `'''` و `"""` نیز جداکننده‌های رشته‌ای در پایتون هستند که باعث ایجاد SyntaxError می‌شوند، چون مفسر پایتون هنگام اسکن رشته‌ای که با سه‌نقل‌قول آغاز شده، انتظار یک سه‌نقل‌قول پایانی به‌عنوان جداکننده را دارد. --- @@ -1442,9 +1448,10 @@ SyntaxError: EOF while scanning triple-quoted string literal 1\. +‫ یک مثال ساده برای شمردن تعداد مقادیر بولی # اعداد صحیح در یک iterable با انواع داده‌ی مخلوط. + ```py -# یک مثال ساده برای شمردن تعداد مقادیر بولی و -# اعداد صحیح در یک iterable با انواع داده‌ی مخلوط. + mixed_list = [False, 1.0, "some_string", 3, True, [], False] integers_found_so_far = 0 booleans_found_so_far = 0 @@ -1528,7 +1535,7 @@ I have lost faith in truth! --- -### ◀ ویژگی‌های کلاس و ویژگی‌های نمونه +### ◀ متغیرهای کلاس و متغیرهای نمونه 1\. ```py @@ -1599,7 +1606,7 @@ True --- -### ◀ yielding None +### ◀ واگذار کردن None ```py some_iterable = ('a', 'b') @@ -1608,7 +1615,7 @@ def some_func(val): return "something" ``` -**Output (<= 3.7.x):** +**خروجی (<= 3.7.x):** ```py >>> [x for x in some_iterable] @@ -1623,16 +1630,16 @@ def some_func(val): ['a', 'something', 'b', 'something'] ``` -#### 💡 Explanation: -- This is a bug in CPython's handling of `yield` in generators and comprehensions. -- Source and explanation can be found here: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions -- Related bug report: https://bugs.python.org/issue10544 -- Python 3.8+ no longer allows `yield` inside list comprehension and will throw a `SyntaxError`. +#### 💡 توضیح: +- این یک باگ در نحوه‌ی مدیریت `yield` توسط CPython در ژنراتورها و درک لیستی (comprehensions) است. +- منبع و توضیحات را می‌توانید اینجا ببینید: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions +- گزارش باگ مرتبط: https://bugs.python.org/issue10544 +- از نسخه‌ی ۳.۸ به بعد، پایتون دیگر اجازه‌ی استفاده از `yield` در داخل درک لیستی را نمی‌دهد و خطای `SyntaxError` ایجاد خواهد کرد. --- -### ◀ Yielding from... return! * +### ◀ بازگرداندن با استفاده از `yield from`! 1\. @@ -1677,7 +1684,7 @@ def some_func(x): + از پایتون نسخه ۳.۳ به بعد، امکان استفاده از عبارت `return` همراه با مقدار در داخل ژنراتورها فراهم شد (نگاه کنید به [PEP380](https://www.python.org/dev/peps/pep-0380/)). [مستندات رسمی](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) می‌گویند: -> "... `return expr` در یک ژنراتور باعث می‌شود که هنگام خروج از ژنراتور، `StopIteration(expr)` ایجاد شود." +> دلیل: "... `return expr` در یک ژنراتور باعث می‌شود که هنگام خروج از ژنراتور، `StopIteration(expr)` ایجاد شود." + در حالت `some_func(3)`، استثنای `StopIteration` در ابتدای اجرا به دلیل وجود دستور `return` رخ می‌دهد. این استثنا به‌طور خودکار درون پوشش `list(...)` و حلقه `for` گرفته می‌شود. بنابراین، دو قطعه‌کد بالا منجر به یک لیست خالی می‌شوند. @@ -1752,7 +1759,7 @@ True #### 💡 توضیح: -- `'inf'` و `'nan'` رشته‌هایی خاص هستند (نسبت به حروف بزرگ و کوچک حساس نیستند) که وقتی به‌طور صریح به نوع `float` تبدیل شوند، به ترتیب برای نمایش "بی‌نهایت" ریاضی و "عدد نیست" استفاده می‌شوند. +- در اینجا، `'inf'` و `'nan'` رشته‌هایی خاص هستند (نسبت به حروف بزرگ و کوچک حساس نیستند) که وقتی به‌طور صریح به نوع `float` تبدیل شوند، به ترتیب برای نمایش "بی‌نهایت" ریاضی و "عدد نیست" استفاده می‌شوند. - از آنجا که طبق استاندارد IEEE، `NaN != NaN`، پایبندی به این قانون فرض بازتاب‌پذیری (reflexivity) یک عنصر در مجموعه‌ها را در پایتون نقض می‌کند؛ یعنی اگر `x` عضوی از مجموعه‌ای مثل `list` باشد، پیاده‌سازی‌هایی مانند مقایسه، بر اساس این فرض هستند که `x == x`. به دلیل همین فرض، ابتدا هویت (identity) دو عنصر مقایسه می‌شود (چون سریع‌تر است) و فقط زمانی مقادیر مقایسه می‌شوند که هویت‌ها متفاوت باشند. قطعه‌کد زیر موضوع را روشن‌تر می‌کند، @@ -2244,7 +2251,7 @@ for idx, item in enumerate(list_4): می‌توانید حدس بزنید چرا خروجی `[2, 4]` است؟ -#### 💡 Explanation: +#### 💡 توضیح: * هیچ‌وقت ایده‌ی خوبی نیست که شیئی را که روی آن پیمایش می‌کنید تغییر دهید. روش درست این است که روی یک کپی از آن شیء پیمایش کنید؛ در این‌جا `list_3[:]` دقیقاً همین کار را می‌کند. From b62ac1518013635b9173010b5e8e5d27d2677f2c Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Thu, 17 Apr 2025 17:19:29 +0200 Subject: [PATCH 204/210] Final fixes for the translations --- translations/fa-farsi/README.md | 47 ++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 54df2c56..6c924f4e 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -1916,7 +1916,7 @@ some_dict = {'s': 42} str >>> s = SomeClass('s') >>> some_dict[s] = 40 ->>> some_dict # expected: Two different keys-value pairs +>>> some_dict # دو عدد کلید-مقدار توقع می رود. {'s': 40} >>> type(list(some_dict.keys())[0]) str @@ -1972,9 +1972,11 @@ a, b = a[b] = {}, 5 #### 💡 توضیح: * طبق [مرجع زبان پایتون](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)، دستورات انتساب فرم زیر را دارند: + ``` (target_list "=")+ (expression_list | yield_expression) ``` + و > یک دستور انتساب ابتدا فهرست عبارت‌ها (expression list) را ارزیابی می‌کند (توجه کنید این عبارت می‌تواند یک عبارت تکی یا فهرستی از عبارت‌ها جداشده با ویرگول باشد که دومی به یک تاپل منجر می‌شود)، سپس شیء حاصل را به هریک از اهداف انتساب از **چپ به راست** تخصیص می‌دهد. @@ -2264,7 +2266,7 @@ for idx, item in enumerate(list_4): ``` **تفاوت بین `del`، `remove` و `pop`:** -* `del var_name` فقط اتصال `var_name` را از فضای نام محلی یا سراسری حذف می‌کند (به همین دلیل است که `list_1` تحت تأثیر قرار نمی‌گیرد). +* اینجا، `del var_name` فقط اتصال `var_name` را از فضای نام محلی یا سراسری حذف می‌کند (به همین دلیل است که `list_1` تحت تأثیر قرار نمی‌گیرد). * متد `remove` اولین مقدار مطابق را حذف می‌کند، نه یک اندیس خاص را؛ اگر مقدار مورد نظر پیدا نشود، خطای `ValueError` ایجاد می‌شود. * متد `pop` عنصری را در یک اندیس مشخص حذف کرده و آن را برمی‌گرداند؛ اگر اندیس نامعتبری مشخص شود، خطای `IndexError` ایجاد می‌شود. @@ -2290,7 +2292,7 @@ for idx, item in enumerate(list_4): >>> numbers_iter = iter(numbers) >>> list(zip(numbers_iter, first_three)) [(0, 0), (1, 1), (2, 2)] -# so far so good, let's zip the remaining +# تاحالا که خوب بوده، حالا روی باقی مانده های زیپ رو امتحان می کنیم. >>> list(zip(numbers_iter, remaining)) [(4, 3), (5, 4), (6, 5)] ``` @@ -2299,6 +2301,7 @@ for idx, item in enumerate(list_4): #### 💡 توضیح: - بر اساس [مستندات](https://docs.python.org/3.3/library/functions.html#zip) پایتون، پیاده‌سازی تقریبی تابع `zip` به شکل زیر است: + ```py def zip(*iterables): sentinel = object() @@ -2311,9 +2314,11 @@ for idx, item in enumerate(list_4): result.append(elem) yield tuple(result) ``` + - بنابراین این تابع تعداد دلخواهی از اشیای قابل پیمایش (*iterable*) را دریافت می‌کند، و با فراخوانی تابع `next` روی آن‌ها، هر یک از عناصرشان را به لیست `result` اضافه می‌کند. این فرایند زمانی متوقف می‌شود که اولین پیمایشگر به انتها برسد. - نکته مهم اینجاست که هر زمان یکی از پیمایشگرها به پایان برسد، عناصر موجود در لیست `result` نیز دور ریخته می‌شوند. این دقیقاً همان اتفاقی است که برای عدد `3` در `numbers_iter` رخ داد. - روش صحیح برای انجام عملیات بالا با استفاده از تابع `zip` چنین است: + ```py >>> numbers = list(range(7)) >>> numbers_iter = iter(numbers) @@ -2322,6 +2327,7 @@ for idx, item in enumerate(list_4): >>> list(zip(remaining, numbers_iter)) [(3, 3), (4, 4), (5, 5), (6, 6)] ``` + اولین آرگومانِ تابع `zip` باید پیمایشگری باشد که کمترین تعداد عنصر را دارد. --- @@ -2482,7 +2488,8 @@ SyntaxError: invalid syntax #### 💡 توضیح -* To add multiple Exceptions to the except clause, you need to pass them as parenthesized tuple as the first argument. The second argument is an optional name, which when supplied will bind the Exception instance that has been raised. Example, +* برای افزودن چندین استثنا به عبارت `except`، باید آن‌ها را به صورت یک تاپل پرانتزدار به عنوان آرگومان اول وارد کنید. آرگومان دوم یک نام اختیاری است که در صورت ارائه، نمونهٔ Exception ایجادشده را به آن متصل می‌کند. برای مثال: + ```py some_list = [1, 2, 3] try: @@ -2492,12 +2499,16 @@ SyntaxError: invalid syntax print("Caught again!") print(e) ``` + **خروجی (Python 2.x):** + ``` Caught again! list.remove(x): x not in list ``` + **خروجی (Python 3.x):** + ```py File "", line 4 except (IndexError, ValueError), e: @@ -2505,7 +2516,8 @@ SyntaxError: invalid syntax IndentationError: unindent does not match any outer indentation level ``` -* Separating the exception from the variable with a comma is deprecated and does not work in Python 3; the correct way is to use `as`. Example, +* جدا کردن استثنا از متغیر با استفاده از ویرگول منسوخ شده و در پایتون 3 کار نمی‌کند؛ روش صحیح استفاده از `as` است. برای مثال: + ```py some_list = [1, 2, 3] try: @@ -2515,7 +2527,9 @@ SyntaxError: invalid syntax print("Caught again!") print(e) ``` + **خروجی:** + ``` Caught again! list.remove(x): x not in list @@ -2796,7 +2810,7 @@ def similar_recursive_func(a): `x, y = (0, 1) if True else (None, None)` * برای مورد ۲، عبارت صحیح برای رفتار مورد انتظار این است: -`t = ('one',)` یا `t = 'one',` (ویرگول از قلم افتاده است). در غیر این صورت مفسر `t` را به عنوان یک `str` در نظر گرفته و به صورت کاراکتر به کاراکتر روی آن پیمایش می‌کند. +اینجا، `t = ('one',)` یا `t = 'one',` (ویرگول از قلم افتاده است). در غیر این صورت مفسر `t` را به عنوان یک `str` در نظر گرفته و به صورت کاراکتر به کاراکتر روی آن پیمایش می‌کند. * علامت `()` یک توکن خاص است و نشان‌دهنده‌ی یک `tuple` خالی است. @@ -2840,15 +2854,15 @@ def similar_recursive_func(a): >>> 'a'.split() ['a'] -# is same as +# معادل است با >>> 'a'.split(' ') ['a'] -# but +# اما >>> len(''.split()) 0 -# isn't the same as +# معادل نیست با >>> len(''.split(' ')) 1 ``` @@ -2859,6 +2873,7 @@ def similar_recursive_func(a): > اگر `sep` مشخص نشده یا برابر با `None` باشد، یک الگوریتم متفاوت برای جدا کردن اعمال می‌شود: رشته‌هایی از فاصله‌های متوالی به عنوان یک جداکننده‌ی واحد در نظر گرفته شده و در نتیجه، هیچ رشته‌ی خالی‌ای در ابتدا یا انتهای لیست خروجی قرار نمی‌گیرد، حتی اگر رشته‌ی اولیه دارای فاصله‌های اضافی در ابتدا یا انتها باشد. به همین دلیل، تقسیم یک رشته‌ی خالی یا رشته‌ای که فقط شامل فضای خالی است با جداکننده‌ی `None` باعث بازگشت یک لیست خالی `[]` می‌شود. > اگر `sep` مشخص شود، جداکننده‌های متوالی در کنار هم قرار نمی‌گیرند و هر جداکننده، یک رشته‌ی خالی جدید ایجاد می‌کند. (مثلاً `'1,,2'.split(',')` مقدار `['1', '', '2']` را برمی‌گرداند.) تقسیم یک رشته‌ی خالی با یک جداکننده‌ی مشخص‌شده نیز باعث بازگشت `['']` می‌شود. - توجه به اینکه چگونه فضای خالی در ابتدا و انتهای رشته در قطعه‌ی کد زیر مدیریت شده است، این مفهوم را روشن‌تر می‌کند: + ```py >>> ' a '.split(' ') ['', 'a', ''] @@ -2992,11 +3007,11 @@ if noon_time: ```py ('Time at noon is', datetime.time(12, 0)) ``` -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." +پیش از پایتون 3.5، مقدار بولی برای شیء `datetime.time` اگر نشان‌دهندهٔ نیمه‌شب به وقت UTC بود، برابر با `False` در نظر گرفته می‌شد. این رفتار در استفاده از دستور `if obj:` برای بررسی تهی بودن شیء یا برابر بودن آن با مقدار "خالی"، ممکن است باعث بروز خطا شود. --- --- @@ -3118,7 +3133,7 @@ True import this ``` -Wait, what's **this**? `this` is love :heart: +صبر کن، **این** چیه؟ `this` عشقه :heart: **خروجی:** ``` @@ -3213,7 +3228,7 @@ Try block executed successfully... - عبارت `else` پس از بلاک `try` به عنوان «عبارت تکمیل» (`completion clause`) نیز شناخته می‌شود؛ چراکه رسیدن به عبارت `else` در ساختار `try` به این معنی است که بلاک `try` بدون رخ دادن استثنا با موفقیت تکمیل شده است. --- -### ◀ Ellipsis * +### ◀ عملگر Ellipsis * ```py def some_func(): @@ -3240,7 +3255,7 @@ Ellipsis >>> ... Ellipsis ``` -- `Ellipsis` می‌تواند برای چندین منظور استفاده شود: +- عملگر `Ellipsis` می‌تواند برای چندین منظور استفاده شود: + به عنوان یک نگه‌دارنده برای کدی که هنوز نوشته نشده است (مانند دستور `pass`) + در سینتکس برش (`slicing`) برای نمایش برش کامل در ابعاد باقی‌مانده @@ -3810,9 +3825,9 @@ def dict_size(o): ```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. + >>> some_list is some_list[:] # انتظار می‌رود False باشد چون یک شیء جدید ایجاد شده است. False - >>> some_str is some_str[:] # True because strings are immutable, so making a new object is of not much use. + >>> some_str is some_str[:] # True چون رشته‌ها تغییرناپذیر هستند، بنابراین ساختن یک شیء جدید فایده‌ای ندارد. True ``` From f01c716e60ea66a747787b25d63654d93e64cccd Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Thu, 17 Apr 2025 17:22:06 +0200 Subject: [PATCH 205/210] Add persian link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35a9cf59..667aaeb6 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Persian فارسی](https://github.com/satwikkansal/wtfpython/tree/master/translations/fa-farsi) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) From 1e0a1ea7976668599142d1ef90a38a93aef9e294 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Tue, 22 Apr 2025 14:48:09 +0200 Subject: [PATCH 206/210] Add persian translation link --- translations/fa-farsi/README.md | 73 ++++++++++++++++++++++++++++++--- 1 file changed, 68 insertions(+), 5 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index 6c924f4e..e100c45b 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -9,7 +9,7 @@

کاوش و درک پایتون از طریق تکه‌های کد شگفت‌انگیز.

-ترجمه‌ها: [انگلیسی English](https://github.com/satwikkansal/wtfpython) | [چینی 中文](https://github.com/leisurelicht/wtfpython-cn) | [ویتنامی Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [اسپانیایی Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [کره‌ای 한국어](https://github.com/buttercrab/wtfpython-ko) | [روسی Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [آلمانی Deutsch](https://github.com/BenSt099/wtfpython) | [اضافه کردن ترجمه](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +ترجمه‌ها: [انگلیسی English](https://github.com/satwikkansal/wtfpython) | [چینی 中文](https://github.com/leisurelicht/wtfpython-cn) | [ویتنامی Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [اسپانیایی Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [کره‌ای 한국어](https://github.com/buttercrab/wtfpython-ko) | [روسی Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [آلمانی Deutsch](https://github.com/BenSt099/wtfpython) | [Persian فارسی](https://github.com/satwikkansal/wtfpython/tree/master/translations/fa-farsi) | [اضافه کردن ترجمه](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) حالت‌های دیگر: [وبسایت تعاملی](https://wtfpython-interactive.vercel.app) | [دفترچه تعاملی](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) @@ -45,70 +45,133 @@ - [👀 مثال‌ها](#-مثالها) - [بخش: ذهن خود را به چالش بکشید!](#بخش-ذهن-خود-را-به-چالش-بکشید) - [◀ اول از همه! \*](#-اول-از-همه-) + - [💡 توضیح](#-توضیح) - [◀ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند](#-بعضی-وقتها-رشتهها-میتوانند-دردسرساز-شوند) + - [💡 توضیح:](#-توضیح-1) - [◀ مراقب عملیات‌های زنجیره‌ای باشید](#-مراقب-عملیاتهای-زنجیرهای-باشید) + - [💡 توضیح:](#-توضیح-2) - [◀ چطور از عملگر `is` استفاده نکنیم](#-چطور-از-عملگر-is-استفاده-نکنیم) + - [💡 توضیح:](#-توضیح-3) - [◀ کلیدهای هش](#-کلیدهای-هش) + - [💡 توضیح](#-توضیح-4) - [◀ در عمق وجود همه ما یکسان هستیم](#-در-عمق-وجود-همه-ما-یکسان-هستیم) + - [💡 توضیح:](#-توضیح-5) - [◀ بی‌نظمی در خود نظم \*](#-بینظمی-در-خود-نظم-) + - [💡 توضیح:](#-توضیح-6) + - [💡 توضیح:](#-توضیح-7) - [◀ برای چی؟](#-برای-چی) + - [💡 توضیح:](#-توضیح-8) - [◀ اختلاف زمانی در محاسبه](#-اختلاف-زمانی-در-محاسبه) + - [💡 توضیح](#-توضیح-9) - [◀ هر گردی، گردو نیست](#-هر-گردی-گردو-نیست) + - [💡 توضیح](#-توضیح-10) - [◀ یک بازی دوز که توش X همون اول برنده میشه!](#-یک-بازی-دوز-که-توش-x-همون-اول-برنده-میشه) + - [💡 توضیح:](#-توضیح-11) - [◀ متغیر شرودینگر \*](#-متغیر-شرودینگر-) + - [💡 توضیح:](#-توضیح-12) - [◀ اول مرغ بوده یا تخم مرغ؟ \*](#-اول-مرغ-بوده-یا-تخم-مرغ-) + - [💡 توضیح](#-توضیح-13) - [◀ روابط بین زیرمجموعه کلاس‌ها](#-روابط-بین-زیرمجموعه-کلاسها) + - [💡 توضیح:](#-توضیح-14) - [◀ برابری و هویت متدها](#-برابری-و-هویت-متدها) + - [💡 توضیح](#-توضیح-15) - [◀ آل-ترو-یشن \*](#-آل-ترو-یشن-) + - [💡 توضیحات:](#-توضیحات) + - [💡 توضیح:](#-توضیح-16) - [◀ رشته‌ها و بک‌اسلش‌ها](#-رشتهها-و-بکاسلشها) + - [💡 توضیح:](#-توضیح-17) - [◀ گره نیست، نَه!](#-گره-نیست-نَه) + - [💡 توضیح:](#-توضیح-18) - [◀ رشته‌های نیمه سه‌نقل‌قولی](#-رشتههای-نیمه-سهنقلقولی) + - [💡 توضیح:](#-توضیح-19) - [◀ مشکل بولین ها چیست؟](#-مشکل-بولین-ها-چیست) - - [◀ ویژگی‌های کلاس و ویژگی‌های نمونه](#-ویژگیهای-کلاس-و-ویژگیهای-نمونه) - - [◀ yielding None](#-yielding-none) - - [◀ Yielding from... return! \*](#-yielding-from-return-) + - [💡 توضیح:](#-توضیح-20) + - [◀ متغیرهای کلاس و متغیرهای نمونه](#-متغیرهای-کلاس-و-متغیرهای-نمونه) + - [💡 توضیح:](#-توضیح-21) + - [◀ واگذار کردن None](#-واگذار-کردن-none) + - [💡 توضیح:](#-توضیح-22) + - [◀ بازگرداندن با استفاده از `yield from`!](#-بازگرداندن-با-استفاده-از-yield-from) + - [💡 توضیح:](#-توضیح-23) - [◀ بازتاب‌ناپذیری \*](#-بازتابناپذیری-) + - [💡 توضیح:](#-توضیح-24) - [◀ تغییر دادن اشیای تغییرناپذیر!](#-تغییر-دادن-اشیای-تغییرناپذیر) + - [💡 توضیح:](#-توضیح-25) - [◀ متغیری که از اسکوپ بیرونی ناپدید می‌شود](#-متغیری-که-از-اسکوپ-بیرونی-ناپدید-میشود) + - [💡 توضیح:](#-توضیح-26) - [◀ تبدیل اسرارآمیز نوع کلید](#-تبدیل-اسرارآمیز-نوع-کلید) + - [💡 توضیح:](#-توضیح-27) - [◀ ببینیم می‌توانید این را حدس بزنید؟](#-ببینیم-میتوانید-این-را-حدس-بزنید) + - [💡 توضیح:](#-توضیح-28) - [◀ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود](#-از-حد-مجاز-برای-تبدیل-رشته-به-عدد-صحیح-فراتر-میرود) + - [💡 توضیح:](#-توضیح-29) - [بخش: شیب‌های لغزنده](#بخش-شیبهای-لغزنده) - [◀ تغییر یک دیکشنری هنگام پیمایش روی آن](#-تغییر-یک-دیکشنری-هنگام-پیمایش-روی-آن) + - [💡 توضیح:](#-توضیح-30) - [◀ عملیات سرسختانه‌ی `del`](#-عملیات-سرسختانهی-del) + - [💡 توضیح:](#-توضیح-31) - [◀ متغیری که از حوزه خارج است](#-متغیری-که-از-حوزه-خارج-است) + - [💡 توضیح:](#-توضیح-32) - [◀ حذف المان‌های لیست در حین پیمایش](#-حذف-المانهای-لیست-در-حین-پیمایش) + - [💡 توضیح:](#-توضیح-33) - [◀ زیپِ دارای اتلاف برای پیمایشگرها \*](#-زیپِ-دارای-اتلاف-برای-پیمایشگرها-) + - [💡 توضیح:](#-توضیح-34) - [◀ نشت کردن متغیرهای حلقه!](#-نشت-کردن-متغیرهای-حلقه) + - [💡 توضیح:](#-توضیح-35) - [◀ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید!](#-مراقب-آرگومانهای-تغییرپذیر-پیشفرض-باشید) + - [💡 توضیح:](#-توضیح-36) - [◀ گرفتن استثناها (Exceptions)](#-گرفتن-استثناها-exceptions) + - [💡 توضیح](#-توضیح-37) - [◀ عملوندهای یکسان، داستانی متفاوت!](#-عملوندهای-یکسان-داستانی-متفاوت) + - [💡 توضیح:](#-توضیح-38) - [◀ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس](#-تفکیک-نامها-با-نادیده-گرفتن-حوزهی-کلاس) + - [💡 توضیح](#-توضیح-39) - [◀ گرد کردن به روش بانکدار \*](#-گرد-کردن-به-روش-بانکدار-) + - [💡 توضیح:](#-توضیح-40) - [◀ سوزن‌هایی در انبار کاه \*](#-سوزنهایی-در-انبار-کاه-) + - [💡 توضیح:](#-توضیح-41) - [◀ تقسیم‌ها \*](#-تقسیمها-) + - [💡 توضیح:](#-توضیح-42) - [◀ واردسازی‌های عمومی \*](#-واردسازیهای-عمومی-) + - [💡 توضیح:](#-توضیح-43) - [◀ همه چیز مرتب شده؟ \*](#-همه-چیز-مرتب-شده-) + - [💡 توضیح:](#-توضیح-44) - [◀ زمان نیمه‌شب وجود ندارد؟](#-زمان-نیمهشب-وجود-ندارد) + - [💡 توضیح:](#-توضیح-45) - [بخش: گنجینه‌های پنهان!](#بخش-گنجینههای-پنهان) - [◀ خب پایتون، می‌توانی کاری کنی پرواز کنم؟](#-خب-پایتون-میتوانی-کاری-کنی-پرواز-کنم) + - [💡 توضیح:](#-توضیح-46) - [◀ `goto`، ولی چرا؟](#-goto-ولی-چرا) + - [💡 توضیح:](#-توضیح-47) - [◀ خودتان را آماده کنید!](#-خودتان-را-آماده-کنید) + - [💡 توضیح:](#-توضیح-48) - [◀ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم](#-بیایید-با-عمو-زبان-مهربان-برای-همیشه-آشنا-شویم) + - [💡 توضیح:](#-توضیح-49) - [◀ حتی پایتون هم می‌داند که عشق پیچیده است](#-حتی-پایتون-هم-میداند-که-عشق-پیچیده-است) + - [💡 توضیح:](#-توضیح-50) - [◀ بله، این واقعاً وجود دارد!](#-بله-این-واقعاً-وجود-دارد) - - [◀ Ellipsis \*](#-ellipsis-) + - [💡 توضیح:](#-توضیح-51) + - [◀ عملگر Ellipsis \*](#-عملگر-ellipsis--) + - [💡توضیح](#توضیح) - [◀ بی‌نهایت (`Inpinity`)](#-بینهایت-inpinity) + - [💡 توضیح:](#-توضیح-52) - [◀ بیایید خرابکاری کنیم](#-بیایید-خرابکاری-کنیم) + - [💡 توضیح:](#-توضیح-53) - [بخش: ظاهرها فریبنده‌اند!](#بخش-ظاهرها-فریبندهاند) - [◀ خطوط را رد می‌کند؟](#-خطوط-را-رد-میکند) + - [💡 توضیح](#-توضیح-54) - [◀ تله‌پورت کردن](#-تلهپورت-کردن) + - [💡 توضیح:](#-توضیح-55) - [◀ خب، یک جای کار مشکوک است...](#-خب-یک-جای-کار-مشکوک-است) + - [💡 توضیح](#-توضیح-56) - [بخش: متفرقه](#بخش-متفرقه) - [◀ `+=` سریع‌تر است](#--سریعتر-است) + - [💡 توضیح:](#-توضیح-57) - [◀ بیایید یک رشته‌ی بزرگ بسازیم!](#-بیایید-یک-رشتهی-بزرگ-بسازیم) + - [💡 توضیح](#-توضیح-58) - [◀ کُند کردن جستجوها در `dict` \*](#--کُند-کردن-جستجوها-در-dict-) + - [💡 توضیح:](#-توضیح-59) - [◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*](#-حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) + - [💡 توضیح:](#-توضیح-60) - [◀ موارد جزئی \*](#-موارد-جزئی-) - [مشارکت](#مشارکت) - [تقدیر و تشکر](#تقدیر-و-تشکر) From c5e2b94ab06048784ad9b8ab1626a996228d9881 Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Tue, 29 Apr 2025 14:56:02 +0200 Subject: [PATCH 207/210] Add linting --- translations/fa-farsi/README.md | 607 ++++++++++++++++++++------------ 1 file changed, 374 insertions(+), 233 deletions(-) diff --git a/translations/fa-farsi/README.md b/translations/fa-farsi/README.md index e100c45b..22e7eb23 100644 --- a/translations/fa-farsi/README.md +++ b/translations/fa-farsi/README.md @@ -8,12 +8,10 @@

What the f*ck Python! 😱

کاوش و درک پایتون از طریق تکه‌های کد شگفت‌انگیز.

- ترجمه‌ها: [انگلیسی English](https://github.com/satwikkansal/wtfpython) | [چینی 中文](https://github.com/leisurelicht/wtfpython-cn) | [ویتنامی Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [اسپانیایی Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [کره‌ای 한국어](https://github.com/buttercrab/wtfpython-ko) | [روسی Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [آلمانی Deutsch](https://github.com/BenSt099/wtfpython) | [Persian فارسی](https://github.com/satwikkansal/wtfpython/tree/master/translations/fa-farsi) | [اضافه کردن ترجمه](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) حالت‌های دیگر: [وبسایت تعاملی](https://wtfpython-interactive.vercel.app) | [دفترچه تعاملی](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) - پایتون، یه زبان زیبا طراحی شده، سطح بالا و مبتنی بر مفسره که قابلیت‌های بسیاری برای راحتی ما برنامه‌نویس‌ها فراهم می‌کنه. ولی گاهی اوقات قطعه‌کدهایی رو می‌بینیم که تو نگاه اول خروجی‌هاشون واضح نیست. @@ -199,16 +197,19 @@ > >>> triggering_statement > یه خروجی غیرمنتظره > ``` +> > (دلخواه): توضیح یک‌خطی خروجی غیرمنتظره > > > #### 💡 توضیح: > -> * توضیح کوتاه درمورد این‌که چی داره اتفاق میافته و چرا. +> - توضیح کوتاه درمورد این‌که چی داره اتفاق میافته و چرا. +> > ```py > # راه اندازی کد > # مثال‌های بیشتر برای شفاف سازی (در صورت نیاز) > ``` +> > **خروجی (نسخه(های) پایتون):** > > ```py @@ -221,16 +222,17 @@ کنند مگراینکه به صورت جداگانه و به طور واضح نسخه مخصوص پایتون قبل از خروجی ذکر شده باشد. - # استفاده یه راه خوب برای بیشتر بهره بردن، به نظرم، اینه که مثال‌ها رو به ترتیب متوالی بخونید و برای هر مثال: + - کد ابتدایی برای راه اندازی مثال رو با دقت بخونید. اگه شما یه پایتون کار سابقه‌دار باشید، با موفقیت بیشتر اوقات اتفاق بعدی رو پیش‌بینی می‌کنید. - قطعه خروجی رو بخونید و - + بررسی کنید که آیا خروجی‌ها همونطور که انتظار دارید هستند. - + مطمئین بشید که دقیقا دلیل اینکه خروجی اون طوری هست رو می‌دونید. + - بررسی کنید که آیا خروجی‌ها همونطور که انتظار دارید هستند. + - مطمئین بشید که دقیقا دلیل اینکه خروجی اون طوری هست رو می‌دونید. - اگه نمی‌دونید (که کاملا عادیه و اصلا بد نیست)، یک نفس عمیق بکشید و توضیحات رو بخونید (و اگه نفهمیدید، داد بزنید! و [اینجا](https://github.com/emargi/wtfpython/issues/new) درموردش حرف بزنید). - اگه می‌دونید، به افتخار خودتون یه دست محکم بزنید و برید سراغ مثال بعدی. + --- # 👀 مثال‌ها @@ -298,8 +300,6 @@ SyntaxError: invalid syntax 16 ``` - - #### 💡 توضیح **مرور سریع بر عملگر Walrus** @@ -374,6 +374,7 @@ if a := some_func(): ``` 2\. + ```py >>> a = "wtf" >>> b = "wtf" @@ -422,12 +423,13 @@ False منطقیه، نه؟ #### 💡 توضیح: -+ در قطعه‌کد اول و دوم، رفتار کد به دلیل یک بهینه سازی در CPython است (به نام داوطلب سازی رشته‌ها) که باعث می‌شود از برخی مقادیر غیرقابل تغییر، به جای مقداردهی مجدد، دوباره استفاده شود. -+ بیشتر متغیرهایی که به‌این صورت جایگزین می‌شوند، در حافظه دستگاه به مقدار داوطلب خود اشاره می‌کنند (تا از حافظه کمتری استفاده شود) -+ در قطعه‌کدهای بالا، رشته‌ها به‌صورت غیرمستقیم داوطلب می‌شوند. تصمیم اینکه رشته‌ها چه زمانی به صورت غیرمستقیم داوطلب شوند به نحوه پیاده‌سازی و مقداردهی آن‌ها بستگی دارد. برخی قوانین وجود دارند تا بتوانیم داوطلب شدن یا نشدن یک رشته را حدس بزنیم: - * همه رشته‌ها با طول صفر یا یک داوطلب می‌شوند. - * رشته‌ها در زمان کامپایل داوطلب می‌شوند (`'wtf'` داوطلب می‌شود اما `''.join(['w', 't', 'f'])` داوطلب نمی‌شود) - * رشته‌هایی که از حروف ASCII ، اعداد صحیح و آندرلاین تشکیل نشده‌باشند داوطلب نمی‌شود. به همین دلیل `'wtf!'` به خاطر وجود `'!'` داوطلب نشد. پیاده‌سازی این قانون در CPython در [اینجا](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) قرار دارد. + +- در قطعه‌کد اول و دوم، رفتار کد به دلیل یک بهینه سازی در CPython است (به نام داوطلب سازی رشته‌ها) که باعث می‌شود از برخی مقادیر غیرقابل تغییر، به جای مقداردهی مجدد، دوباره استفاده شود. +- بیشتر متغیرهایی که به‌این صورت جایگزین می‌شوند، در حافظه دستگاه به مقدار داوطلب خود اشاره می‌کنند (تا از حافظه کمتری استفاده شود) +- در قطعه‌کدهای بالا، رشته‌ها به‌صورت غیرمستقیم داوطلب می‌شوند. تصمیم اینکه رشته‌ها چه زمانی به صورت غیرمستقیم داوطلب شوند به نحوه پیاده‌سازی و مقداردهی آن‌ها بستگی دارد. برخی قوانین وجود دارند تا بتوانیم داوطلب شدن یا نشدن یک رشته را حدس بزنیم: + - همه رشته‌ها با طول صفر یا یک داوطلب می‌شوند. + - رشته‌ها در زمان کامپایل داوطلب می‌شوند (`'wtf'` داوطلب می‌شود اما `''.join(['w', 't', 'f'])` داوطلب نمی‌شود) + - رشته‌هایی که از حروف ASCII ، اعداد صحیح و آندرلاین تشکیل نشده‌باشند داوطلب نمی‌شود. به همین دلیل `'wtf!'` به خاطر وجود `'!'` داوطلب نشد. پیاده‌سازی این قانون در CPython در [اینجا](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) قرار دارد.

@@ -437,14 +439,13 @@ False

-+ زمانی که `"wtf!"` را در یک خط به `a` و `b` اختصاص می‌دهیم، مفسر پایتون شیء جدید می‌سازد و متغیر دوم را به آن ارجاع می‌دهد. اگر مقدار دهی در خط‌های جدا از هم انجام شود، در واقع مفسر "خبر ندارد" که یک شیء مختص به `"wtf!"` از قبل در برنامه وجود دارد (زیرا `"wtf!"` به دلایلی که در بالا گفته شد، به‌صورت غیرمستقیم داوطلب نمی‌شود). این بهینه سازی در زمان کامپایل انجام می‌شود. این بهینه سازی همچنین برای نسخه های (x).۳.۷ وجود ندارد (برای گفت‌وگوی بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) را ببینید). -+ یک واحد کامپایل در یک محیط تعاملی مانند IPython از یک عبارت تشکیل می‌شود، در حالی که برای ماژول‌ها شامل کل ماژول می‌شود. `a, b = "wtf!", "wtf!"` یک عبارت است. در حالی که `a = "wtf!"; b = "wtf!"` دو عبارت در یک خط است. به همین دلیل شناسه‌ها در `a = "wtf!"; b = "wtf!"` متفاوتند و همین‌طور وقتی با مفسر پایتون داخل فایل `some_file.py` اجرا می‌شوند، شناسه‌ها یکسانند. -+ تغییر ناگهانی در خروجی قطعه‌کد چهارم به دلیل [بهینه‌سازی پنجره‌ای](https://en.wikipedia.org/wiki/Peephole_optimization) است که تکنیکی معروف به جمع آوری ثابت‌ها است. به همین خاطر عبارت `'a'*20` با `'aaaaaaaaaaaaaaaaaaaa'` در هنگام کامپایل جایگزین می‌شود تا کمی بار از دوش چرخه‌ساعتی پردازنده کم شود. تکنیک جمع آوری ثابت‌ها فقط مخصوص رشته‌هایی با طول کمتر از 21 است. (چرا؟ فرض کنید که فایل `.pyc` که توسط کامپایلر ساخته می‌شود چقدر بزرگ می‌شد اگر عبارت `'a'*10**10`). [این](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) هم کد پیاده‌سازی این تکنیک در CPython. -+ توجه: در پایتون ۳.۷، جمع آوری ثابت‌ها از بهینه‌ساز پنجره‌ای به بهینه‌ساز AST جدید انتقال داده شد همراه با تغییراتی در منطق آن. پس چهارمین قطعه‌کد در پایتون نسخه ۳.۷ کار نمی‌کند. شما می‌توانید در [اینجا](https://bugs.python.org/issue11549) بیشتر درمورد این تغییرات بخوانید. +- زمانی که `"wtf!"` را در یک خط به `a` و `b` اختصاص می‌دهیم، مفسر پایتون شیء جدید می‌سازد و متغیر دوم را به آن ارجاع می‌دهد. اگر مقدار دهی در خط‌های جدا از هم انجام شود، در واقع مفسر "خبر ندارد" که یک شیء مختص به `"wtf!"` از قبل در برنامه وجود دارد (زیرا `"wtf!"` به دلایلی که در بالا گفته شد، به‌صورت غیرمستقیم داوطلب نمی‌شود). این بهینه سازی در زمان کامپایل انجام می‌شود. این بهینه سازی همچنین برای نسخه های (x).۳.۷ وجود ندارد (برای گفت‌وگوی بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) را ببینید). +- یک واحد کامپایل در یک محیط تعاملی مانند IPython از یک عبارت تشکیل می‌شود، در حالی که برای ماژول‌ها شامل کل ماژول می‌شود. `a, b = "wtf!", "wtf!"` یک عبارت است. در حالی که `a = "wtf!"; b = "wtf!"` دو عبارت در یک خط است. به همین دلیل شناسه‌ها در `a = "wtf!"; b = "wtf!"` متفاوتند و همین‌طور وقتی با مفسر پایتون داخل فایل `some_file.py` اجرا می‌شوند، شناسه‌ها یکسانند. +- تغییر ناگهانی در خروجی قطعه‌کد چهارم به دلیل [بهینه‌سازی پنجره‌ای](https://en.wikipedia.org/wiki/Peephole_optimization) است که تکنیکی معروف به جمع آوری ثابت‌ها است. به همین خاطر عبارت `'a'*20` با `'aaaaaaaaaaaaaaaaaaaa'` در هنگام کامپایل جایگزین می‌شود تا کمی بار از دوش چرخه‌ساعتی پردازنده کم شود. تکنیک جمع آوری ثابت‌ها فقط مخصوص رشته‌هایی با طول کمتر از 21 است. (چرا؟ فرض کنید که فایل `.pyc` که توسط کامپایلر ساخته می‌شود چقدر بزرگ می‌شد اگر عبارت `'a'*10**10`). [این](https://github.com/python/cpython/blob/3.6/Python/peephole.c#L288) هم کد پیاده‌سازی این تکنیک در CPython. +- توجه: در پایتون ۳.۷، جمع آوری ثابت‌ها از بهینه‌ساز پنجره‌ای به بهینه‌ساز AST جدید انتقال داده شد همراه با تغییراتی در منطق آن. پس چهارمین قطعه‌کد در پایتون نسخه ۳.۷ کار نمی‌کند. شما می‌توانید در [اینجا](https://bugs.python.org/issue11549) بیشتر درمورد این تغییرات بخوانید. --- - ### ◀ مراقب عملیات‌های زنجیره‌ای باشید ```py @@ -475,16 +476,18 @@ False شاید چنین رفتاری برای شما احمقانه به نظر بیاد ولی برای عملیات‌هایی مثل `a == b == c` و `0 <= x <= 100` عالی عمل می‌کنه. -* عبارت `False is False is False` معادل عبارت `(False is False) and (False is False)` است -* عبارت `True is False == False` معادل عبارت `(True is False) and (False == False)` است و از آنجایی که قسمت اول این عبارت (`True is False`) پس از ارزیابی برابر با `False` می‌شود. پس کل عبارت معادل `False` می‌شود. -* عبارت `1 > 0 < 1` معادل عبارت `(1 > 0) and (0 < 1)` است. -* عبارت `(1 > 0) < 1` معادل عبارت `True < 1` است و : +- عبارت `False is False is False` معادل عبارت `(False is False) and (False is False)` است +- عبارت `True is False == False` معادل عبارت `(True is False) and (False == False)` است و از آنجایی که قسمت اول این عبارت (`True is False`) پس از ارزیابی برابر با `False` می‌شود. پس کل عبارت معادل `False` می‌شود. +- عبارت `1 > 0 < 1` معادل عبارت `(1 > 0) and (0 < 1)` است. +- عبارت `(1 > 0) < 1` معادل عبارت `True < 1` است و : + ```py >>> int(True) 1 >>> True + 1 # مربوط به این بخش نیست ولی همینجوری گذاشتم 2 ``` + پس عبارت `True < 1` معادل عبارت `1 < 1` می‌شود که در کل معادل `False` است. --- @@ -542,9 +545,10 @@ False **فرض بین عملگرهای `is` و `==`** -* عملگر `is` بررسی میکنه که دو متغیر در حافظه دستگاه به یک شیء اشاره میکنند یا نه (یعنی شناسه متغیرها رو با هم تطبیق میده). -* عملگر `==` مقدار متغیرها رو با هم مقایسه میکنه و یکسان بودنشون رو بررسی میکنه. -* پس `is` برای معادل بودن متغیرها در حافظه دستگاه و `==` برای معادل بودن مقادیر استفاده میشه. یه مثال برای شفاف سازی بیشتر: +- عملگر `is` بررسی میکنه که دو متغیر در حافظه دستگاه به یک شیء اشاره میکنند یا نه (یعنی شناسه متغیرها رو با هم تطبیق میده). +- عملگر `==` مقدار متغیرها رو با هم مقایسه میکنه و یکسان بودنشون رو بررسی میکنه. +- پس `is` برای معادل بودن متغیرها در حافظه دستگاه و `==` برای معادل بودن مقادیر استفاده میشه. یه مثال برای شفاف سازی بیشتر: + ```py >>> class A: pass >>> A() is A() # این‌ها دو شیء خالی هستند که در دو جای مختلف در حافظه قرار دارند. @@ -599,9 +603,9 @@ False 140640774013488 ``` -* وقتی a و b در یک خط با `257` مقداردهی میشن، مفسر پایتون یک شیء برای یکی از متغیرها در حافظه میسازه و متغیر دوم رو در حافظه به اون ارجاع میده. اگه این کار رو تو دو خط جدا از هم انجام بدید، درواقع مفسر پایتون از وجود مقدار `257` به عنوان یک شیء، "خبر نداره". +- وقتی a و b در یک خط با `257` مقداردهی میشن، مفسر پایتون یک شیء برای یکی از متغیرها در حافظه میسازه و متغیر دوم رو در حافظه به اون ارجاع میده. اگه این کار رو تو دو خط جدا از هم انجام بدید، درواقع مفسر پایتون از وجود مقدار `257` به عنوان یک شیء، "خبر نداره". -* این یک بهینه سازی توسط کامپایلر هست و مخصوصا در محیط تعاملی به کار برده میشه. وقتی شما دو خط رو در یک مفسر زنده وارد می‌کنید، اون‌ها به صورت جداگانه کامپایل میشن، به همین دلیل بهینه سازی به صورت جداگانه برای هرکدوم اعمال میشه. اگر بخواهید این مثال رو در یک فایل `.py` امتحان کنید، رفتار متفاوتی می‌بینید زیرا فایل به صورت کلی و یک‌جا کامپایل میشه. این بهینه سازی محدود به اعداد صحیح نیست و برای انواع داده‌های غیرقابل تغییر دیگه مانند رشته‌ها (مثال "رشته‌ها می‌توانند دردسرساز شوند" رو ببینید) و اعداد اعشاری هم اعمال میشه. +- این یک بهینه سازی توسط کامپایلر هست و مخصوصا در محیط تعاملی به کار برده میشه. وقتی شما دو خط رو در یک مفسر زنده وارد می‌کنید، اون‌ها به صورت جداگانه کامپایل میشن، به همین دلیل بهینه سازی به صورت جداگانه برای هرکدوم اعمال میشه. اگر بخواهید این مثال رو در یک فایل `.py` امتحان کنید، رفتار متفاوتی می‌بینید زیرا فایل به صورت کلی و یک‌جا کامپایل میشه. این بهینه سازی محدود به اعداد صحیح نیست و برای انواع داده‌های غیرقابل تغییر دیگه مانند رشته‌ها (مثال "رشته‌ها می‌توانند دردسرساز شوند" رو ببینید) و اعداد اعشاری هم اعمال میشه. ```py >>> a, b = 257.0, 257.0 @@ -609,14 +613,14 @@ False True ``` -* چرا این برای پایتون ۳.۷ کار نکرد؟ دلیل انتزاعیش اینه که چنین بهینه‌سازی‌های کامپایلری وابسته به پیاده‌سازی هستن (یعنی بسته به نسخه، و نوع سیستم‌عامل و چیزهای دیگه تغییر میکنن). من هنوز پیگیرم که بدونم که کدوم تغییر تو پیاده‌سازی باعث همچین مشکلاتی میشه، می‌تونید برای خبرهای بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) رو نگاه کنید. +- چرا این برای پایتون ۳.۷ کار نکرد؟ دلیل انتزاعیش اینه که چنین بهینه‌سازی‌های کامپایلری وابسته به پیاده‌سازی هستن (یعنی بسته به نسخه، و نوع سیستم‌عامل و چیزهای دیگه تغییر میکنن). من هنوز پیگیرم که بدونم که کدوم تغییر تو پیاده‌سازی باعث همچین مشکلاتی میشه، می‌تونید برای خبرهای بیشتر این [موضوع](https://github.com/satwikkansal/wtfpython/issues/100) رو نگاه کنید. --- - ### ◀ کلیدهای هش 1\. + ```py some_dict = {} some_dict[5.5] = "JavaScript" @@ -643,9 +647,10 @@ complex خب، چرا Python همه جارو گرفت؟ - #### 💡 توضیح -* تو دیکشنری‌های پایتون چیزی که کلیدها رو یگانه میکنه مقدار کلیدهاست، نه شناسه اون‌ها. پس با اینکه `5`، `5.0` و `5 + 0j` شیءهای متمایزی از نوع‌های متفاوتی هستند ولی از اون جایی که مقدارشون با هم برابره، نمیتونن داخل یه `dict` به عنوان کلید جدا از هم باشن (حتی به عنوان مقادیر داخل یه `set` نمیتونن باشن). وقتی بخواید داخل یه دیکشنری جست‌وجو کنید، به محض اینکه یکی از این داده‌ها رو وارد کنید، مقدار نگاشته‌شده به کلیدی که مقدار برابر با اون داده داره ولی نوعش متفاوته، با موفقیت برگردونده میشه (به جای اینکه به ارور `KeyError` بردخورد کنید.). + +- تو دیکشنری‌های پایتون چیزی که کلیدها رو یگانه میکنه مقدار کلیدهاست، نه شناسه اون‌ها. پس با اینکه `5`، `5.0` و `5 + 0j` شیءهای متمایزی از نوع‌های متفاوتی هستند ولی از اون جایی که مقدارشون با هم برابره، نمیتونن داخل یه `dict` به عنوان کلید جدا از هم باشن (حتی به عنوان مقادیر داخل یه `set` نمیتونن باشن). وقتی بخواید داخل یه دیکشنری جست‌وجو کنید، به محض اینکه یکی از این داده‌ها رو وارد کنید، مقدار نگاشته‌شده به کلیدی که مقدار برابر با اون داده داره ولی نوعش متفاوته، با موفقیت برگردونده میشه (به جای اینکه به ارور `KeyError` بردخورد کنید.). + ```py >>> 5 == 5.0 == 5 + 0j True @@ -658,7 +663,9 @@ complex >>> (5 in some_dict) and (5 + 0j in some_dict) True ``` -* همچنین این قانون برای مقداردهی توی دیکشنری هم اعمال میشه. وقتی شما عبارت `some_dict[5] = "Python"` رو اجرا می‌کنید، پایتون دنبال کلیدی با مقدار یکسان می‌گرده که اینجا ما داریم `5.0 -> "Ruby"` و مقدار نگاشته‌شده به این کلید در دیکشنری رو با مقدار جدید جایگزین میکنه و کلید رو همونجوری که هست باقی میذاره. + +- همچنین این قانون برای مقداردهی توی دیکشنری هم اعمال میشه. وقتی شما عبارت `some_dict[5] = "Python"` رو اجرا می‌کنید، پایتون دنبال کلیدی با مقدار یکسان می‌گرده که اینجا ما داریم `5.0 -> "Ruby"` و مقدار نگاشته‌شده به این کلید در دیکشنری رو با مقدار جدید جایگزین میکنه و کلید رو همونجوری که هست باقی میذاره. + ```py >>> some_dict {5.0: 'Ruby'} @@ -666,15 +673,18 @@ complex >>> some_dict {5.0: 'Python'} ``` -* خب پس چطوری میتونیم مقدار خود کلید رو به `5` تغییر بدیم (جای `5.0`)؟ راستش ما نمیتونیم این کار رو درجا انجام بدیم، ولی میتونیم اول اون کلید رو پاک کنیم (`del some_dict[5.0]`) و بعد کلیدی که میخوایم رو قرار بدیم (`some_dict[5]`) تا بتونیم عدد صحیح `5` رو به جای عدد اعشاری `5.0` به عنوان کلید داخل دیکشنری داشته باشیم. درکل خیلی کم پیش میاد که بخوایم چنین کاری کنیم. -* پایتون چطوری توی دیکشنری که کلید `5.0` رو داره، کلید `5` رو پیدا کرد؟ پایتون این کار رو توی زمان ثابتی توسط توابع هش انجام میده بدون اینکه مجبور باشه همه کلیدها رو بررسی کنه. وقتی پایتون دنبال کلیدی مثل `foo` داخل یه `dict` میگرده، اول مقدار `hash(foo)` رو محاسبه میکنه (که توی زمان ثابتی انجام میشه). از اونجایی که توی پایتون برای مقایسه برابری مقدار دو شیء لازمه که هش یکسانی هم داشته باشند ([مستندات](https://docs.python.org/3/reference/datamodel.html#object.__hash__)). `5`، `5.0` و `5 + 0j` مقدار هش یکسانی دارند. +- خب پس چطوری میتونیم مقدار خود کلید رو به `5` تغییر بدیم (جای `5.0`)؟ راستش ما نمیتونیم این کار رو درجا انجام بدیم، ولی میتونیم اول اون کلید رو پاک کنیم (`del some_dict[5.0]`) و بعد کلیدی که میخوایم رو قرار بدیم (`some_dict[5]`) تا بتونیم عدد صحیح `5` رو به جای عدد اعشاری `5.0` به عنوان کلید داخل دیکشنری داشته باشیم. درکل خیلی کم پیش میاد که بخوایم چنین کاری کنیم. + +- پایتون چطوری توی دیکشنری که کلید `5.0` رو داره، کلید `5` رو پیدا کرد؟ پایتون این کار رو توی زمان ثابتی توسط توابع هش انجام میده بدون اینکه مجبور باشه همه کلیدها رو بررسی کنه. وقتی پایتون دنبال کلیدی مثل `foo` داخل یه `dict` میگرده، اول مقدار `hash(foo)` رو محاسبه میکنه (که توی زمان ثابتی انجام میشه). از اونجایی که توی پایتون برای مقایسه برابری مقدار دو شیء لازمه که هش یکسانی هم داشته باشند ([مستندات](https://docs.python.org/3/reference/datamodel.html#object.__hash__)). `5`، `5.0` و `5 + 0j` مقدار هش یکسانی دارند. + ```py >>> 5 == 5.0 == 5 + 0j True >>> hash(5) == hash(5.0) == hash(5 + 0j) True ``` + **توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیده‌ای معروف [تصادف هش](https://en.wikipedia.org/wiki/Collision_(disambiguation)#Other_uses) میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند. --- @@ -687,6 +697,7 @@ class WTF: ``` **خروجی:** + ```py >>> WTF() == WTF() # دو نمونه متفاوت از یک کلاس نمیتونند برابر هم باشند False @@ -699,10 +710,12 @@ True ``` #### 💡 توضیح: -* وقتی `id` صدا زده شد، پایتون یک شیء با کلاس `WTF` ساخت و اون رو به تابع `id` داد. تابع `id` شناسه این شیء رو میگیره (درواقع آدرس اون شیء در حافظه دستگاه) و شیء رو حذف میکنه. -* وقتی این کار رو دو بار متوالی انجام بدیم، پایتون آدرس یکسانی رو به شیء دوم اختصاص میده. از اونجایی که (در CPython) تابع `id` از آدرس شیءها توی حافظه به عنوان شناسه برای اون‌ها استفاده میکنه، پس شناسه این دو شیء یکسانه. -* پس، شناسه یک شیء تا زمانی که اون شیء وجود داره، منحصربه‌فرده. بعد از اینکه اون شیء حذف میشه یا قبل از اینکه اون شیء به وجود بیاد، چیز دیگه‌ای میتونه اون شناسه رو داشته باشه. -* ولی چرا با عملگر `is` مقدار `False` رو دریافت کردیم؟ بیاید با یه قطعه‌کد ببینیم دلیلش رو. + +- وقتی `id` صدا زده شد، پایتون یک شیء با کلاس `WTF` ساخت و اون رو به تابع `id` داد. تابع `id` شناسه این شیء رو میگیره (درواقع آدرس اون شیء در حافظه دستگاه) و شیء رو حذف میکنه. +- وقتی این کار رو دو بار متوالی انجام بدیم، پایتون آدرس یکسانی رو به شیء دوم اختصاص میده. از اونجایی که (در CPython) تابع `id` از آدرس شیءها توی حافظه به عنوان شناسه برای اون‌ها استفاده میکنه، پس شناسه این دو شیء یکسانه. +- پس، شناسه یک شیء تا زمانی که اون شیء وجود داره، منحصربه‌فرده. بعد از اینکه اون شیء حذف میشه یا قبل از اینکه اون شیء به وجود بیاد، چیز دیگه‌ای میتونه اون شناسه رو داشته باشه. +- ولی چرا با عملگر `is` مقدار `False` رو دریافت کردیم؟ بیاید با یه قطعه‌کد ببینیم دلیلش رو. + ```py class WTF(object): def __init__(self): print("I") @@ -710,6 +723,7 @@ True ``` **خروجی:** + ```py >>> WTF() is WTF() I @@ -724,11 +738,11 @@ True D True ``` + همونطور که مشاهده می‌کنید، ترتیب حذف شدن شیءها باعث تفاوت میشه. --- - ### ◀ بی‌نظمی در خود نظم * ```py @@ -757,6 +771,7 @@ class OrderedDictWithHash(OrderedDict): ``` **خروجی** + ```py >>> dictionary == ordered_dict # اگر مقدار اولی با دومی برابره True @@ -795,6 +810,7 @@ TypeError: unhashable type: 'dict' > مقایسه برابری بین شیءهایی از نوع OrderedDict به ترتیب اعضای آن‌ها هم بستگی دارد و به صورت `list(od1.items())==list(od2.items())` پیاده سازی شده است. مقایسه برابری بین شیءهای `OrderedDict` و شیءهای قابل نگاشت دیگر به ترتیب اعضای آن‌ها بستگی ندارد و مقایسه همانند دیکشنری‌های عادی انجام می‌شود. - این رفتار باعث میشه که بتونیم `OrderedDict` ها رو هرجایی که یک دیکشنری عادی کاربرد داره، جایگزین کنیم و استفاده کنیم. - خب، حالا چرا تغییر ترتیب روی طول مجموعه‌ای که از دیکشنری‌ها ساختیم، تاثیر گذاشت؟ جوابش همین رفتار مقایسه‌ای غیرانتقالی بین این شیءهاست. از اونجایی که `set` ها مجموعه‌ای از عناصر غیرتکراری و بدون نظم هستند، ترتیبی که عناصر تو این مجموعه‌ها درج میشن نباید مهم باشه. ولی در این مورد، مهم هست. بیاید کمی تجزیه و تحلیلش کنیم. + ```py >>> some_set = set() >>> some_set.add(dictionary) # این شیء‌ها از قطعه‌کدهای بالا هستند. @@ -827,7 +843,6 @@ TypeError: unhashable type: 'dict' --- - ### ◀ تلاش کن... * ```py @@ -889,7 +904,6 @@ Iteration 0 --- - ### ◀ برای چی؟ ```py @@ -900,18 +914,23 @@ for i, some_dict[i] in enumerate(some_string): ``` **خروجی:** + ```py >>> some_dict # یک دیکشنری مرتب‌شده نمایان میشه. {0: 'w', 1: 't', 2: 'f'} ``` -#### 💡 توضیح: -* یک حلقه `for` در [گرامر پایتون](https://docs.python.org/3/reference/grammar.html) این طور تعریف میشه: +#### 💡 توضیح: + +- یک حلقه `for` در [گرامر پایتون](https://docs.python.org/3/reference/grammar.html) این طور تعریف میشه: + ``` for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] ``` + به طوری که `exprlist` یک هدف برای مقداردهیه. این یعنی، معادل عبارت `{exprlist} = {next_value}` **برای هر شیء داخل `testlist` اجرا می‌شود**. یک مثال جالب برای نشون دادن این تعریف: + ```py for i in range(4): print(i) @@ -919,6 +938,7 @@ for i, some_dict[i] in enumerate(some_string): ``` **خروجی:** + ``` 0 1 @@ -932,7 +952,8 @@ for i, some_dict[i] in enumerate(some_string): - عبارت مقداردهی `i = 10` به خاطر نحوه کار کردن حلقه‌ها، هیچوقت باعث تغییر در تکرار حلقه نمیشه. قبل از شروع هر تکرار، مقدار بعدی که توسط شیء قابل تکرار (که در اینجا `range(4)` است) ارائه میشه، از بسته خارج میشه و به متغیرهای لیست هدف (که در اینجا `i` است) مقداردهی میشه. -* تابع `enumerate(some_string)`، یک متغیر `i` (که یک شمارنده افزایشی است) و یک حرف از حروف رشته `some_string` رو در هر تکرار برمیگردونه. و بعدش برای کلید `i` (تازه مقداردهی‌شده) در دیکشنری `some_dict`، مقدار اون حرف رو تنظیم می‌کنه. بازشده این حلقه می‌تونه مانند مثال زیر ساده بشه: +- تابع `enumerate(some_string)`، یک متغیر `i` (که یک شمارنده افزایشی است) و یک حرف از حروف رشته `some_string` رو در هر تکرار برمیگردونه. و بعدش برای کلید `i` (تازه مقداردهی‌شده) در دیکشنری `some_dict`، مقدار اون حرف رو تنظیم می‌کنه. بازشده این حلقه می‌تونه مانند مثال زیر ساده بشه: + ```py >>> i, some_dict[i] = (0, 'w') >>> i, some_dict[i] = (1, 't') @@ -945,6 +966,7 @@ for i, some_dict[i] in enumerate(some_string): ### ◀ اختلاف زمانی در محاسبه 1\. + ```py array = [1, 8, 15] # یک عبارت تولیدکننده عادی @@ -972,6 +994,7 @@ array_2[:] = [1,2,3,4,5] ``` **خروجی:** + ```py >>> print(list(gen_1)) [1, 2, 3, 4] @@ -992,6 +1015,7 @@ array_4 = [400, 500, 600] ``` **خروجی:** + ```py >>> print(list(gen)) [401, 501, 601, 402, 502, 602, 403, 503, 603] @@ -1010,7 +1034,6 @@ array_4 = [400, 500, 600] --- - ### ◀ هر گردی، گردو نیست ```py @@ -1021,13 +1044,13 @@ False ``` #### 💡 توضیح + - عملگر `is not` یک عملگر باینری واحده و رفتارش متفاوت تر از استفاده `is` و `not` به صورت جداگانه‌ست. - عملگر `is not` مقدار `False` رو برمیگردونه اگر متغیرها در هردو سمت این عملگر به شیء یکسانی اشاره کنند و درغیر این صورت، مقدار `True` برمیگردونه - در مثال بالا، عبارت `(not None)` برابره با مقدار `True` از اونجایی که مقدار `None` در زمینه boolean به `False` تبدیل میشه. پس کل عبارت معادل عبارت `'something' is True` میشه. --- - ### ◀ یک بازی دوز که توش X همون اول برنده میشه! @@ -1092,11 +1115,9 @@ board = [row] * 3 --- - ### ◀ متغیر شرودینگر * - ```py funcs = [] results = [] @@ -1110,6 +1131,7 @@ funcs_results = [func() for func in funcs] ``` **خروجی:** + ```py >>> results [0, 1, 2, 3, 4, 5, 6] @@ -1128,7 +1150,8 @@ funcs_results = [func() for func in funcs] ``` #### 💡 توضیح: -* وقتی یک تابع رو در داخل یک حلقه تعریف می‌کنیم که در بدنه‌اش از متغیر اون حلقه استفاده شده، بست این تابع به *متغیر* وصله، نه *مقدار* اون. تابع به جای اینکه از مقدار `x` در زمان تعریف تابع استفاده کنه، در زمینه اطرافش دنبال `x` می‌گرده. پس همه این توابع از آخرین مقداری که به متغیر `x` مقداردهی شده برای محاسباتشون استفاده می‌کنند. ما می‌تونیم ببینیم که این توابع از متغیر `x` که در زمینه اطرافشون (*نه* از متغیر محلی) هست، استفاده می‌کنند، به این صورت: + +- وقتی یک تابع رو در داخل یک حلقه تعریف می‌کنیم که در بدنه‌اش از متغیر اون حلقه استفاده شده، بست این تابع به *متغیر* وصله، نه *مقدار* اون. تابع به جای اینکه از مقدار `x` در زمان تعریف تابع استفاده کنه، در زمینه اطرافش دنبال `x` می‌گرده. پس همه این توابع از آخرین مقداری که به متغیر `x` مقداردهی شده برای محاسباتشون استفاده می‌کنند. ما می‌تونیم ببینیم که این توابع از متغیر `x` که در زمینه اطرافشون (*نه* از متغیر محلی) هست، استفاده می‌کنند، به این صورت: ```py >>> import inspect @@ -1144,7 +1167,7 @@ ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) [42, 42, 42, 42, 42, 42, 42] ``` -* برای رسیدن به رفتار موردنظر شما می‌تونید متغیر حلقه رو به عنوان یک متغیر اسم‌دار به تابع بدید. **چرا در این صورت کار می‌کنه؟** چون اینجوری یک متغیر در دامنه خود تابع تعریف میشه. تابع دیگه دنبال مقدار `x` در دامنه اطراف (سراسری) نمی‌گرده ولی یک متغیر محلی برای ذخیره کردن مقدار `x` در اون لحظه می‌سازه. +- برای رسیدن به رفتار موردنظر شما می‌تونید متغیر حلقه رو به عنوان یک متغیر اسم‌دار به تابع بدید. **چرا در این صورت کار می‌کنه؟** چون اینجوری یک متغیر در دامنه خود تابع تعریف میشه. تابع دیگه دنبال مقدار `x` در دامنه اطراف (سراسری) نمی‌گرده ولی یک متغیر محلی برای ذخیره کردن مقدار `x` در اون لحظه می‌سازه. ```py funcs = [] @@ -1171,10 +1194,10 @@ ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) --- - ### ◀ اول مرغ بوده یا تخم مرغ؟ * 1\. + ```py >>> isinstance(3, int) True @@ -1186,7 +1209,7 @@ True پس کدوم کلاس پایه "نهایی" هست؟ راستی سردرگمی بیشتری هم تو راهه. -2\. +2\. ```py >>> class A: pass @@ -1209,23 +1232,22 @@ True False ``` - #### 💡 توضیح - در پایتون، `type` یک [متاکلاس](https://realpython.com/python-metaclasses/) است. - در پایتون **همه چیز** یک `object` است، که کلاس‌ها و همچنین نمونه‌هاشون (یا همان instance های کلاس‌ها) هم شامل این موضوع میشن. - کلاس `type` یک متاکلاسه برای کلاس `object` و همه کلاس‌ها (همچنین کلاس `type`) به صورت مستقیم یا غیرمستقیم از کلاس `object` ارث بری کرده است. - هیچ کلاس پایه واقعی بین کلاس‌های `object` و `type` وجود نداره. سردرگمی که در قطعه‌کدهای بالا به وجود اومده، به خاطر اینه که ما به این روابط (یعنی `issubclass` و `isinstance`) از دیدگاه کلاس‌های پایتون فکر می‌کنیم. رابطه بین `object` و `type` رو در پایتون خالص نمیشه بازتولید کرد. برای اینکه دقیق‌تر باشیم، رابطه‌های زیر در پایتون خالص نمی‌تونند بازتولید بشن. - + کلاس A یک نمونه از کلاس B، و کلاس B یک نمونه از کلاس A باشه. - + کلاس A یک نمونه از خودش باشه. + - کلاس A یک نمونه از کلاس B، و کلاس B یک نمونه از کلاس A باشه. + - کلاس A یک نمونه از خودش باشه. - این روابط بین `object` و `type` (که هردو نمونه یکدیگه و همچنین خودشون باشند) به خاطر "تقلب" در مرحله پیاده‌سازی، وجود دارند. --- - ### ◀ روابط بین زیرمجموعه کلاس‌ها **خروجی:** + ```py >>> from collections.abc import Hashable >>> issubclass(list, object) @@ -1236,14 +1258,14 @@ True False ``` -ما انتظار داشتیم که روابط بین زیرکلاس‌ها، انتقالی باشند، درسته؟ (یعنی اگه `A` زیرکلاس `B` باشه و `B` هم زیرکلاس `C` باشه، کلس `A` __باید__ زیرکلاس `C` باشه) +ما انتظار داشتیم که روابط بین زیرکلاس‌ها، انتقالی باشند، درسته؟ (یعنی اگه `A` زیرکلاس `B` باشه و `B` هم زیرکلاس `C` باشه، کلس `A` **باید** زیرکلاس `C` باشه) #### 💡 توضیح: -* روابط بین زیرکلاس‌ها در پایتون لزوما انتقالی نیستند. همه مجازند که تابع `__subclasscheck__` دلخواه خودشون رو در یک متاکلاس تعریف کنند. -* وقتی عبارت `issubclass(cls, Hashable)` اجرا میشه، برنامه دنبال یک تابع "غیر نادرست" (یا non-Falsy) در `cls` یا هرچیزی که ازش ارث‌بری می‌کنه، می‌گرده. -* از اونجایی که `object` قابل هش شدنه، ولی `list` این‌طور نیست، رابطه انتقالی شکسته میشه. -* توضیحات با جزئیات بیشتر [اینجا](https://www.naftaliharris.com/blog/python-subclass-intransitivity/) پیدا میشه. +- روابط بین زیرکلاس‌ها در پایتون لزوما انتقالی نیستند. همه مجازند که تابع `__subclasscheck__` دلخواه خودشون رو در یک متاکلاس تعریف کنند. +- وقتی عبارت `issubclass(cls, Hashable)` اجرا میشه، برنامه دنبال یک تابع "غیر نادرست" (یا non-Falsy) در `cls` یا هرچیزی که ازش ارث‌بری می‌کنه، می‌گرده. +- از اونجایی که `object` قابل هش شدنه، ولی `list` این‌طور نیست، رابطه انتقالی شکسته میشه. +- توضیحات با جزئیات بیشتر [اینجا](https://www.naftaliharris.com/blog/python-subclass-intransitivity/) پیدا میشه. --- @@ -1251,6 +1273,7 @@ False 1. + ```py class SomeClass: def method(self): @@ -1266,6 +1289,7 @@ class SomeClass: ``` **خروجی:** + ```py >>> print(SomeClass.method is SomeClass.method) True @@ -1281,12 +1305,14 @@ True چه اتفاقی برای نمونه‌های `SomeClass` می‌افتد: 2. + ```py o1 = SomeClass() o2 = SomeClass() ``` **خروجی:** + ```py >>> print(o1.method == o2.method) False @@ -1305,35 +1331,46 @@ True دسترسی به `classm` یا `method` دو بار، اشیایی برابر اما نه *یکسان* را برای همان نمونه از `SomeClass` ایجاد می‌کند. #### 💡 توضیح -* تابع‌ها [وصاف](https://docs.python.org/3/howto/descriptor.html) هستند. هر زمان که تابعی به عنوان یک ویژگی فراخوانی شود، وصف فعال می‌شود و یک شیء متد ایجاد می‌کند که تابع را به شیء صاحب آن ویژگی "متصل" می‌کند. اگر این متد فراخوانی شود، تابع را با ارسال ضمنی شیء متصل‌شده به عنوان اولین آرگومان صدا می‌زند (به این ترتیب است که `self` را به عنوان اولین آرگومان دریافت می‌کنیم، با وجود اینکه آن را به‌طور صریح ارسال نکرده‌ایم). + +- تابع‌ها [وصاف](https://docs.python.org/3/howto/descriptor.html) هستند. هر زمان که تابعی به عنوان یک ویژگی فراخوانی شود، وصف فعال می‌شود و یک شیء متد ایجاد می‌کند که تابع را به شیء صاحب آن ویژگی "متصل" می‌کند. اگر این متد فراخوانی شود، تابع را با ارسال ضمنی شیء متصل‌شده به عنوان اولین آرگومان صدا می‌زند (به این ترتیب است که `self` را به عنوان اولین آرگومان دریافت می‌کنیم، با وجود اینکه آن را به‌طور صریح ارسال نکرده‌ایم). + ```py >>> o1.method > ``` -* دسترسی به ویژگی چندین بار، هر بار یک شیء متد جدید ایجاد می‌کند! بنابراین عبارت `o1.method is o1.method` هرگز درست (truthy) نیست. با این حال، دسترسی به تابع‌ها به عنوان ویژگی‌های کلاس (و نه نمونه) متد ایجاد نمی‌کند؛ بنابراین عبارت `SomeClass.method is SomeClass.method` درست است. + +- دسترسی به ویژگی چندین بار، هر بار یک شیء متد جدید ایجاد می‌کند! بنابراین عبارت `o1.method is o1.method` هرگز درست (truthy) نیست. با این حال، دسترسی به تابع‌ها به عنوان ویژگی‌های کلاس (و نه نمونه) متد ایجاد نمی‌کند؛ بنابراین عبارت `SomeClass.method is SomeClass.method` درست است. + ```py >>> SomeClass.method ``` -* `classmethod` توابع را به متدهای کلاس تبدیل می‌کند. متدهای کلاس وصاف‌هایی هستند که هنگام دسترسی، یک شیء متد ایجاد می‌کنند که به *کلاس* (نوع) شیء متصل می‌شود، نه خود شیء. + +- `classmethod` توابع را به متدهای کلاس تبدیل می‌کند. متدهای کلاس وصاف‌هایی هستند که هنگام دسترسی، یک شیء متد ایجاد می‌کنند که به *کلاس* (نوع) شیء متصل می‌شود، نه خود شیء. + ```py >>> o1.classm > ``` -* برخلاف توابع، `classmethod`‌ها هنگام دسترسی به عنوان ویژگی‌های کلاس نیز یک شیء متد ایجاد می‌کنند (که در این حالت به خود کلاس متصل می‌شوند، نه نوع آن). بنابراین عبارت `SomeClass.classm is SomeClass.classm` نادرست (falsy) است. + +- برخلاف توابع، `classmethod`‌ها هنگام دسترسی به عنوان ویژگی‌های کلاس نیز یک شیء متد ایجاد می‌کنند (که در این حالت به خود کلاس متصل می‌شوند، نه نوع آن). بنابراین عبارت `SomeClass.classm is SomeClass.classm` نادرست (falsy) است. + ```py >>> SomeClass.classm > ``` -* یک شیء متد زمانی برابر در نظر گرفته می‌شود که هم تابع‌ها برابر باشند و هم شیءهای متصل‌شده یکسان باشند. بنابراین عبارت `o1.method == o1.method` درست (truthy) است، هرچند که آن‌ها در حافظه شیء یکسانی نیستند. -* `staticmethod` توابع را به یک وصف "بدون عملیات" (no-op) تبدیل می‌کند که تابع را به همان صورت بازمی‌گرداند. هیچ شیء متدی ایجاد نمی‌شود، بنابراین مقایسه با `is` نیز درست (truthy) است. + +- یک شیء متد زمانی برابر در نظر گرفته می‌شود که هم تابع‌ها برابر باشند و هم شیءهای متصل‌شده یکسان باشند. بنابراین عبارت `o1.method == o1.method` درست (truthy) است، هرچند که آن‌ها در حافظه شیء یکسانی نیستند. +- `staticmethod` توابع را به یک وصف "بدون عملیات" (no-op) تبدیل می‌کند که تابع را به همان صورت بازمی‌گرداند. هیچ شیء متدی ایجاد نمی‌شود، بنابراین مقایسه با `is` نیز درست (truthy) است. + ```py >>> o1.staticm >>> SomeClass.staticm ``` -* ایجاد شیءهای "متد" جدید در هر بار فراخوانی متدهای نمونه و نیاز به اصلاح آرگومان‌ها برای درج `self`، عملکرد را به شدت تحت تأثیر قرار می‌داد. + +- ایجاد شیءهای "متد" جدید در هر بار فراخوانی متدهای نمونه و نیاز به اصلاح آرگومان‌ها برای درج `self`، عملکرد را به شدت تحت تأثیر قرار می‌داد. CPython 3.7 [این مشکل را حل کرد](https://bugs.python.org/issue26110) با معرفی opcodeهای جدیدی که فراخوانی متدها را بدون ایجاد شیء متد موقتی مدیریت می‌کنند. این به شرطی است که تابع دسترسی‌یافته واقعاً فراخوانی شود، بنابراین قطعه‌کدهای اینجا تحت تأثیر قرار نمی‌گیرند و همچنان متد ایجاد می‌کنند :) ### ◀ آل-ترو-یشن * @@ -1409,6 +1446,7 @@ SyntaxError: invalid syntax ### ◀ رشته‌ها و بک‌اسلش‌ها **خروجی:** + ```py >>> print("\"") " @@ -1429,11 +1467,14 @@ True #### 💡 توضیح: - در یک رشته‌ی معمولی در پایتون، بک‌اسلش برای فرار دادن (escape) نویسه‌هایی استفاده می‌شود که ممکن است معنای خاصی داشته باشند (مانند تک‌نقل‌قول، دوتا‌نقل‌قول، و خودِ بک‌اسلش). + ```py >>> "wt\"f" 'wt"f' ``` + - در یک رشته‌ی خام (raw string literal) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان شکل منتقل می‌شوند، به‌همراه رفتار فرار دادن نویسه‌ی بعدی. + ```py >>> r'wt\"f' == 'wt\\"f' True @@ -1445,6 +1486,7 @@ True >>> print(r"\\n") '\\n' ``` + - در یک رشته‌ی خام (raw string) که با پیشوند `r` مشخص می‌شود، بک‌اسلش‌ها خودشان به همان صورت منتقل می‌شوند، همراه با رفتاری که کاراکتر بعدی را فرار می‌دهد (escape می‌کند). --- @@ -1457,6 +1499,7 @@ y = False ``` **خروجی:** + ```py >>> not x == y True @@ -1469,16 +1512,17 @@ SyntaxError: invalid syntax #### 💡 توضیح: -* تقدم عملگرها بر نحوه‌ی ارزیابی یک عبارت تأثیر می‌گذارد، و در پایتون، عملگر `==` تقدم بالاتری نسبت به عملگر `not` دارد. -* بنابراین عبارت `not x == y` معادل `not (x == y)` است که خودش معادل `not (True == False)` بوده و در نهایت به `True` ارزیابی می‌شود. -* اما `x == not y` یک `SyntaxError` ایجاد می‌کند، چون می‌توان آن را به صورت `(x == not) y` تفسیر کرد، نه آن‌طور که در نگاه اول انتظار می‌رود یعنی `x == (not y)`. -* تجزیه‌گر (parser) انتظار دارد که توکن `not` بخشی از عملگر `not in` باشد (چون هر دو عملگر `==` و `not in` تقدم یکسانی دارند)، اما پس از اینکه توکن `in` بعد از `not` پیدا نمی‌شود، خطای `SyntaxError` صادر می‌شود. +- تقدم عملگرها بر نحوه‌ی ارزیابی یک عبارت تأثیر می‌گذارد، و در پایتون، عملگر `==` تقدم بالاتری نسبت به عملگر `not` دارد. +- بنابراین عبارت `not x == y` معادل `not (x == y)` است که خودش معادل `not (True == False)` بوده و در نهایت به `True` ارزیابی می‌شود. +- اما `x == not y` یک `SyntaxError` ایجاد می‌کند، چون می‌توان آن را به صورت `(x == not) y` تفسیر کرد، نه آن‌طور که در نگاه اول انتظار می‌رود یعنی `x == (not y)`. +- تجزیه‌گر (parser) انتظار دارد که توکن `not` بخشی از عملگر `not in` باشد (چون هر دو عملگر `==` و `not in` تقدم یکسانی دارند)، اما پس از اینکه توکن `in` بعد از `not` پیدا نمی‌شود، خطای `SyntaxError` صادر می‌شود. --- ### ◀ رشته‌های نیمه سه‌نقل‌قولی **خروجی:** + ```py >>> print('wtfpython''') wtfpython @@ -1494,7 +1538,8 @@ SyntaxError: EOF while scanning triple-quoted string literal ``` #### 💡 توضیح: -+ پایتون از الحاق ضمنی [رشته‌های متنی](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation) پشتیبانی می‌کند. برای مثال، + +- پایتون از الحاق ضمنی [رشته‌های متنی](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation) پشتیبانی می‌کند. برای مثال، ``` >>> print("wtf" "python") @@ -1503,7 +1548,7 @@ SyntaxError: EOF while scanning triple-quoted string literal wtf ``` -+ `'''` و `"""` نیز جداکننده‌های رشته‌ای در پایتون هستند که باعث ایجاد SyntaxError می‌شوند، چون مفسر پایتون هنگام اسکن رشته‌ای که با سه‌نقل‌قول آغاز شده، انتظار یک سه‌نقل‌قول پایانی به‌عنوان جداکننده را دارد. +- `'''` و `"""` نیز جداکننده‌های رشته‌ای در پایتون هستند که باعث ایجاد SyntaxError می‌شوند، چون مفسر پایتون هنگام اسکن رشته‌ای که با سه‌نقل‌قول آغاز شده، انتظار یک سه‌نقل‌قول پایانی به‌عنوان جداکننده را دارد. --- @@ -1527,6 +1572,7 @@ for item in mixed_list: ``` **خروجی:** + ```py >>> integers_found_so_far 4 @@ -1534,8 +1580,8 @@ for item in mixed_list: 0 ``` - 2\. + ```py >>> some_bool = True >>> "wtf" * some_bool @@ -1561,20 +1607,19 @@ def tell_truth(): I have lost faith in truth! ``` - - #### 💡 توضیح: -* در پایتون، `bool` زیرکلاسی از `int` است - +- در پایتون، `bool` زیرکلاسی از `int` است + ```py >>> issubclass(bool, int) True >>> issubclass(int, bool) False ``` - -* و بنابراین، `True` و `False` نمونه‌هایی از `int` هستند + +- و بنابراین، `True` و `False` نمونه‌هایی از `int` هستند + ```py >>> isinstance(True, int) True @@ -1582,7 +1627,8 @@ I have lost faith in truth! True ``` -* مقدار عددی `True` برابر با `1` و مقدار عددی `False` برابر با `0` است. +- مقدار عددی `True` برابر با `1` و مقدار عددی `False` برابر با `0` است. + ```py >>> int(True) 1 @@ -1590,17 +1636,18 @@ I have lost faith in truth! 0 ``` -* این پاسخ در StackOverflow را ببینید: [answer](https://stackoverflow.com/a/8169049/4354153) برای توضیح منطقی پشت این موضوع. +- این پاسخ در StackOverflow را ببینید: [answer](https://stackoverflow.com/a/8169049/4354153) برای توضیح منطقی پشت این موضوع. -* در ابتدا، پایتون نوع `bool` نداشت (کاربران از 0 برای false و مقادیر غیر صفر مثل 1 برای true استفاده می‌کردند). `True`، `False` و نوع `bool` در نسخه‌های 2.x اضافه شدند، اما برای سازگاری با نسخه‌های قبلی، `True` و `False` نمی‌توانستند به عنوان ثابت تعریف شوند. آن‌ها فقط متغیرهای توکار (built-in) بودند و امکان تغییر مقدارشان وجود داشت. +- در ابتدا، پایتون نوع `bool` نداشت (کاربران از 0 برای false و مقادیر غیر صفر مثل 1 برای true استفاده می‌کردند). `True`، `False` و نوع `bool` در نسخه‌های 2.x اضافه شدند، اما برای سازگاری با نسخه‌های قبلی، `True` و `False` نمی‌توانستند به عنوان ثابت تعریف شوند. آن‌ها فقط متغیرهای توکار (built-in) بودند و امکان تغییر مقدارشان وجود داشت. -* پایتون ۳ با نسخه‌های قبلی ناسازگار بود، این مشکل سرانجام رفع شد، و بنابراین قطعه‌کد آخر در نسخه‌های Python 3.x کار نخواهد کرد! +- پایتون ۳ با نسخه‌های قبلی ناسازگار بود، این مشکل سرانجام رفع شد، و بنابراین قطعه‌کد آخر در نسخه‌های Python 3.x کار نخواهد کرد! --- ### ◀ متغیرهای کلاس و متغیرهای نمونه 1\. + ```py class A: x = 1 @@ -1613,6 +1660,7 @@ class C(A): ``` **Output:** + ```py >>> A.x, B.x, C.x (1, 1, 1) @@ -1631,6 +1679,7 @@ class C(A): ``` 2\. + ```py class SomeClass: some_var = 15 @@ -1663,9 +1712,8 @@ True #### 💡 توضیح: -* متغیرهای کلاس و متغیرهای نمونه‌های کلاس درونی به‌صورت دیکشنری‌هایی از شیء کلاس مدیریت می‌شوند. اگر نام متغیری در دیکشنری کلاس جاری پیدا نشود، کلاس‌های والد برای آن جست‌وجو می‌شوند. -* عملگر `+=` شیء قابل‌تغییر (mutable) را به‌صورت درجا (in-place) تغییر می‌دهد بدون اینکه شیء جدیدی ایجاد کند. بنابراین، تغییر ویژگی یک نمونه بر نمونه‌های دیگر و همچنین ویژگی کلاس تأثیر می‌گذارد. - +- متغیرهای کلاس و متغیرهای نمونه‌های کلاس درونی به‌صورت دیکشنری‌هایی از شیء کلاس مدیریت می‌شوند. اگر نام متغیری در دیکشنری کلاس جاری پیدا نشود، کلاس‌های والد برای آن جست‌وجو می‌شوند. +- عملگر `+=` شیء قابل‌تغییر (mutable) را به‌صورت درجا (in-place) تغییر می‌دهد بدون اینکه شیء جدیدی ایجاد کند. بنابراین، تغییر ویژگی یک نمونه بر نمونه‌های دیگر و همچنین ویژگی کلاس تأثیر می‌گذارد. --- @@ -1694,6 +1742,7 @@ def some_func(val): ``` #### 💡 توضیح: + - این یک باگ در نحوه‌ی مدیریت `yield` توسط CPython در ژنراتورها و درک لیستی (comprehensions) است. - منبع و توضیحات را می‌توانید اینجا ببینید: https://stackoverflow.com/questions/32139885/yield-in-list-comprehensions-and-generator-expressions - گزارش باگ مرتبط: https://bugs.python.org/issue10544 @@ -1701,7 +1750,6 @@ def some_func(val): --- - ### ◀ بازگرداندن با استفاده از `yield from`! 1\. @@ -1745,13 +1793,13 @@ def some_func(x): #### 💡 توضیح: -+ از پایتون نسخه ۳.۳ به بعد، امکان استفاده از عبارت `return` همراه با مقدار در داخل ژنراتورها فراهم شد (نگاه کنید به [PEP380](https://www.python.org/dev/peps/pep-0380/)). [مستندات رسمی](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) می‌گویند: +- از پایتون نسخه ۳.۳ به بعد، امکان استفاده از عبارت `return` همراه با مقدار در داخل ژنراتورها فراهم شد (نگاه کنید به [PEP380](https://www.python.org/dev/peps/pep-0380/)). [مستندات رسمی](https://www.python.org/dev/peps/pep-0380/#enhancements-to-stopiteration) می‌گویند: > دلیل: "... `return expr` در یک ژنراتور باعث می‌شود که هنگام خروج از ژنراتور، `StopIteration(expr)` ایجاد شود." -+ در حالت `some_func(3)`، استثنای `StopIteration` در ابتدای اجرا به دلیل وجود دستور `return` رخ می‌دهد. این استثنا به‌طور خودکار درون پوشش `list(...)` و حلقه `for` گرفته می‌شود. بنابراین، دو قطعه‌کد بالا منجر به یک لیست خالی می‌شوند. +- در حالت `some_func(3)`، استثنای `StopIteration` در ابتدای اجرا به دلیل وجود دستور `return` رخ می‌دهد. این استثنا به‌طور خودکار درون پوشش `list(...)` و حلقه `for` گرفته می‌شود. بنابراین، دو قطعه‌کد بالا منجر به یک لیست خالی می‌شوند. -+ برای اینکه مقدار `["wtf"]` را از ژنراتور `some_func` بگیریم، باید استثنای `StopIteration` را خودمان مدیریت کنیم، +- برای اینکه مقدار `["wtf"]` را از ژنراتور `some_func` بگیریم، باید استثنای `StopIteration` را خودمان مدیریت کنیم، ```py try: @@ -1818,8 +1866,6 @@ False True ``` - - #### 💡 توضیح: - در اینجا، `'inf'` و `'nan'` رشته‌هایی خاص هستند (نسبت به حروف بزرگ و کوچک حساس نیستند) که وقتی به‌طور صریح به نوع `float` تبدیل شوند، به ترتیب برای نمایش "بی‌نهایت" ریاضی و "عدد نیست" استفاده می‌شوند. @@ -1855,6 +1901,7 @@ another_tuple = ([1, 2], [3, 4], [5, 6]) ``` **خروجی:** + ```py >>> some_tuple[2] = "change this" TypeError: 'tuple' object does not support item assignment @@ -1871,14 +1918,13 @@ TypeError: 'tuple' object does not support item assignment #### 💡 توضیح: -* نقل‌قول از https://docs.python.org/3/reference/datamodel.html +- نقل‌قول از https://docs.python.org/3/reference/datamodel.html > دنباله‌های تغییرناپذیر شیئی از نوع دنباله‌ی تغییرناپذیر، پس از ایجاد دیگر قابل تغییر نیست. (اگر شیء شامل ارجاع‌هایی به اشیای دیگر باشد، این اشیای دیگر ممکن است قابل تغییر باشند و تغییر کنند؛ اما مجموعه‌ی اشیایی که مستقیماً توسط یک شیء تغییرناپذیر ارجاع داده می‌شوند، نمی‌تواند تغییر کند.) -* عملگر `+=` لیست را به‌صورت درجا (in-place) تغییر می‌دهد. تخصیص به یک عضو کار نمی‌کند، اما زمانی که استثنا ایجاد می‌شود، عضو موردنظر پیش از آن به‌صورت درجا تغییر کرده است. -* همچنین توضیحی در [پرسش‌های متداول رسمی پایتون](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works) وجود دارد. - +- عملگر `+=` لیست را به‌صورت درجا (in-place) تغییر می‌دهد. تخصیص به یک عضو کار نمی‌کند، اما زمانی که استثنا ایجاد می‌شود، عضو موردنظر پیش از آن به‌صورت درجا تغییر کرده است. +- همچنین توضیحی در [پرسش‌های متداول رسمی پایتون](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works) وجود دارد. --- @@ -1894,19 +1940,22 @@ except Exception as e: ``` **Output (Python 2.x):** + ```py >>> print(e) # چیزی چاپ نمی شود. ``` **Output (Python 3.x):** + ```py >>> print(e) NameError: name 'e' is not defined ``` #### 💡 توضیح: -* منبع: [مستندات رسمی پایتون](https://docs.python.org/3/reference/compound_stmts.html#except) + +- منبع: [مستندات رسمی پایتون](https://docs.python.org/3/reference/compound_stmts.html#except) هنگامی که یک استثنا (Exception) با استفاده از کلمه‌ی کلیدی `as` به متغیری تخصیص داده شود، این متغیر در انتهای بلاکِ `except` پاک می‌شود. این رفتار مشابه کد زیر است: @@ -1927,8 +1976,7 @@ NameError: name 'e' is not defined این بدان معناست که استثنا باید به نام دیگری انتساب داده شود تا بتوان پس از پایان بند `except` به آن ارجاع داد. استثناها پاک می‌شوند چون با داشتن «ردیابی» (traceback) ضمیمه‌شده، یک چرخه‌ی مرجع (reference cycle) با قاب پشته (stack frame) تشکیل می‌دهند که باعث می‌شود تمام متغیرهای محلی (locals) در آن قاب تا زمان پاکسازی حافظه (garbage collection) باقی بمانند. -* در پایتون، بندها (`clauses`) حوزه‌ی مستقل ندارند. در مثال بالا، همه‌چیز در یک حوزه‌ی واحد قرار دارد، و متغیر `e` در اثر اجرای بند `except` حذف می‌شود. این موضوع در مورد توابع صادق نیست، زیرا توابع حوزه‌های داخلی جداگانه‌ای دارند. مثال زیر این نکته را نشان می‌دهد: - +- در پایتون، بندها (`clauses`) حوزه‌ی مستقل ندارند. در مثال بالا، همه‌چیز در یک حوزه‌ی واحد قرار دارد، و متغیر `e` در اثر اجرای بند `except` حذف می‌شود. این موضوع در مورد توابع صادق نیست، زیرا توابع حوزه‌های داخلی جداگانه‌ای دارند. مثال زیر این نکته را نشان می‌دهد: ```py def f(x): @@ -1940,6 +1988,7 @@ NameError: name 'e' is not defined ``` **خروجی:** + ```py >>> f(x) UnboundLocalError: local variable 'x' referenced before assignment @@ -1951,9 +2000,10 @@ NameError: name 'e' is not defined [5, 4, 3] ``` -* در پایتون نسخه‌ی ۲.x، نام متغیر `e` به یک نمونه از `Exception()` انتساب داده می‌شود، بنابراین وقتی سعی کنید آن را چاپ کنید، چیزی نمایش داده نمی‌شود. +- در پایتون نسخه‌ی ۲.x، نام متغیر `e` به یک نمونه از `Exception()` انتساب داده می‌شود، بنابراین وقتی سعی کنید آن را چاپ کنید، چیزی نمایش داده نمی‌شود. **خروجی (Python 2.x):** + ```py >>> e Exception() @@ -1963,7 +2013,6 @@ NameError: name 'e' is not defined --- - ### ◀ تبدیل اسرارآمیز نوع کلید ```py @@ -1974,6 +2023,7 @@ some_dict = {'s': 42} ``` **خروجی:** + ```py >>> type(list(some_dict.keys())[0]) str @@ -1987,10 +2037,11 @@ str #### 💡 توضیح: -* هر دو شیء `s` و رشته‌ی `"s"` به دلیل ارث‌بری `SomeClass` از متد `__hash__` کلاس `str`، هش یکسانی دارند. -* عبارت `SomeClass("s") == "s"` به دلیل ارث‌بری `SomeClass` از متد `__eq__` کلاس `str` برابر با `True` ارزیابی می‌شود. -* از آنجا که این دو شیء هش یکسان و برابری دارند، به عنوان یک کلید مشترک در دیکشنری در نظر گرفته می‌شوند. -* برای رسیدن به رفتار دلخواه، می‌توانیم متد `__eq__` را در کلاس `SomeClass` بازتعریف کنیم. +- هر دو شیء `s` و رشته‌ی `"s"` به دلیل ارث‌بری `SomeClass` از متد `__hash__` کلاس `str`، هش یکسانی دارند. +- عبارت `SomeClass("s") == "s"` به دلیل ارث‌بری `SomeClass` از متد `__eq__` کلاس `str` برابر با `True` ارزیابی می‌شود. +- از آنجا که این دو شیء هش یکسان و برابری دارند، به عنوان یک کلید مشترک در دیکشنری در نظر گرفته می‌شوند. +- برای رسیدن به رفتار دلخواه، می‌توانیم متد `__eq__` را در کلاس `SomeClass` بازتعریف کنیم. + ```py class SomeClass(str): def __eq__(self, other): @@ -2008,6 +2059,7 @@ str ``` **خروجی:** + ```py >>> s = SomeClass('s') >>> some_dict[s] = 40 @@ -2027,6 +2079,7 @@ a, b = a[b] = {}, 5 ``` **خروجی:** + ```py >>> a {5: ({...}, 5)} @@ -2034,7 +2087,7 @@ a, b = a[b] = {}, 5 #### 💡 توضیح: -* طبق [مرجع زبان پایتون](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)، دستورات انتساب فرم زیر را دارند: +- طبق [مرجع زبان پایتون](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)، دستورات انتساب فرم زیر را دارند: ``` (target_list "=")+ (expression_list | yield_expression) @@ -2044,15 +2097,16 @@ a, b = a[b] = {}, 5 > یک دستور انتساب ابتدا فهرست عبارت‌ها (expression list) را ارزیابی می‌کند (توجه کنید این عبارت می‌تواند یک عبارت تکی یا فهرستی از عبارت‌ها جداشده با ویرگول باشد که دومی به یک تاپل منجر می‌شود)، سپس شیء حاصل را به هریک از اهداف انتساب از **چپ به راست** تخصیص می‌دهد. -* علامت `+` در `(target_list "=")+` به این معناست که می‌توان **یک یا چند** هدف انتساب داشت. در این حالت، اهداف انتساب ما `a, b` و `a[b]` هستند (توجه کنید که عبارت ارزیابی‌شده دقیقاً یکی است، که در اینجا `{}` و `5` است). +- علامت `+` در `(target_list "=")+` به این معناست که می‌توان **یک یا چند** هدف انتساب داشت. در این حالت، اهداف انتساب ما `a, b` و `a[b]` هستند (توجه کنید که عبارت ارزیابی‌شده دقیقاً یکی است، که در اینجا `{}` و `5` است). + +- پس از ارزیابی عبارت، نتیجه از **چپ به راست** به اهداف انتساب داده می‌شود. در این مثال ابتدا تاپل `({}, 5)` به `a, b` باز می‌شود، بنابراین `a = {}` و `b = 5` خواهیم داشت. -* پس از ارزیابی عبارت، نتیجه از **چپ به راست** به اهداف انتساب داده می‌شود. در این مثال ابتدا تاپل `({}, 5)` به `a, b` باز می‌شود، بنابراین `a = {}` و `b = 5` خواهیم داشت. +- حالا `a` یک شیء قابل تغییر (mutable) است (`{}`). -* حالا `a` یک شیء قابل تغییر (mutable) است (`{}`). +- هدف انتساب بعدی `a[b]` است (شاید انتظار داشته باشید که اینجا خطا بگیریم زیرا پیش از این هیچ مقداری برای `a` و `b` مشخص نشده است؛ اما به یاد داشته باشید که در گام قبل به `a` مقدار `{}` و به `b` مقدار `5` دادیم). -* هدف انتساب بعدی `a[b]` است (شاید انتظار داشته باشید که اینجا خطا بگیریم زیرا پیش از این هیچ مقداری برای `a` و `b` مشخص نشده است؛ اما به یاد داشته باشید که در گام قبل به `a` مقدار `{}` و به `b` مقدار `5` دادیم). +- اکنون، کلید `5` در دیکشنری به تاپل `({}, 5)` مقداردهی می‌شود و یک مرجع دوری (Circular Reference) ایجاد می‌کند (علامت `{...}` در خروجی به همان شیئی اشاره دارد که قبلاً توسط `a` به آن ارجاع داده شده است). یک مثال ساده‌تر از مرجع دوری می‌تواند به این صورت باشد: -* اکنون، کلید `5` در دیکشنری به تاپل `({}, 5)` مقداردهی می‌شود و یک مرجع دوری (Circular Reference) ایجاد می‌کند (علامت `{...}` در خروجی به همان شیئی اشاره دارد که قبلاً توسط `a` به آن ارجاع داده شده است). یک مثال ساده‌تر از مرجع دوری می‌تواند به این صورت باشد: ```py >>> some_list = some_list[0] = [0] >>> some_list @@ -2064,24 +2118,27 @@ a, b = a[b] = {}, 5 >>> some_list[0][0][0][0][0][0] == some_list True ``` + در مثال ما نیز شرایط مشابه است (`a[b][0]` همان شیئی است که `a` به آن اشاره دارد). +- بنابراین برای جمع‌بندی، می‌توانید مثال بالا را به این صورت ساده کنید: -* بنابراین برای جمع‌بندی، می‌توانید مثال بالا را به این صورت ساده کنید: ```py a, b = {}, 5 a[b] = a, b ``` + و مرجع دوری به این دلیل قابل توجیه است که `a[b][0]` همان شیئی است که `a` به آن اشاره دارد. + ```py >>> a[b][0] is a True ``` - --- ### ◀ از حد مجاز برای تبدیل رشته به عدد صحیح فراتر می‌رود + ```py >>> # Python 3.10.6 >>> int("2" * 5432) @@ -2091,6 +2148,7 @@ a, b = a[b] = {}, 5 ``` **خروجی:** + ```py >>> # Python 3.10.6 222222222222222222222222222222222222222222222222222222222222222... @@ -2104,6 +2162,7 @@ ValueError: Exceeds the limit (4300) for integer string conversion: ``` #### 💡 توضیح: + فراخوانی تابع `int()` در نسخه‌ی Python 3.10.6 به‌خوبی کار می‌کند اما در نسخه‌ی Python 3.10.8 منجر به خطای `ValueError` می‌شود. توجه کنید که پایتون همچنان قادر به کار با اعداد صحیح بزرگ است. این خطا تنها هنگام تبدیل اعداد صحیح به رشته یا برعکس رخ می‌دهد. خوشبختانه می‌توانید در صورت انتظار عبور از این حد مجاز، مقدار آن را افزایش دهید. برای انجام این کار می‌توانید از یکی از روش‌های زیر استفاده کنید: @@ -2114,10 +2173,8 @@ ValueError: Exceeds the limit (4300) for integer string conversion: برای جزئیات بیشتر درباره‌ی تغییر مقدار پیش‌فرض این حد مجاز، [مستندات رسمی پایتون](https://docs.python.org/3/library/stdtypes.html#int-max-str-digits) را مشاهده کنید. - --- - ## بخش: شیب‌های لغزنده ### ◀ تغییر یک دیکشنری هنگام پیمایش روی آن @@ -2168,6 +2225,7 @@ class SomeClass: **خروجی:** 1\. + ```py >>> x = SomeClass() >>> y = x @@ -2179,6 +2237,7 @@ Deleted! «خُب، بالاخره حذف شد.» احتمالاً حدس زده‌اید چه چیزی جلوی فراخوانی `__del__` را در اولین تلاشی که برای حذف `x` داشتیم، گرفته بود. بیایید مثال را پیچیده‌تر کنیم. 2\. + ```py >>> x = SomeClass() >>> y = x @@ -2194,6 +2253,7 @@ Deleted! «باشه، حالا حذف شد» :confused: #### 💡 توضیح: + - عبارت `del x` مستقیماً باعث فراخوانی `x.__del__()` نمی‌شود. - وقتی به دستور `del x` می‌رسیم، پایتون نام `x` را از حوزه‌ی فعلی حذف کرده و شمارنده‌ی مراجع شیٔ‌ای که `x` به آن اشاره می‌کرد را یک واحد کاهش می‌دهد. فقط وقتی شمارنده‌ی مراجع شیٔ به صفر برسد، تابع `__del__()` فراخوانی می‌شود. - در خروجی دوم، متد `__del__()` فراخوانی نشد چون دستور قبلی (`>>> y`) در مفسر تعاملی یک ارجاع دیگر به شیٔ ایجاد کرده بود (به صورت خاص، متغیر جادویی `_` به مقدار آخرین عبارت غیر `None` در REPL اشاره می‌کند). بنابراین مانع از رسیدن شمارنده‌ی مراجع به صفر در هنگام اجرای `del y` شد. @@ -2205,6 +2265,7 @@ Deleted! 1\. + ```py a = 1 def some_func(): @@ -2216,6 +2277,7 @@ def another_func(): ``` 2\. + ```py def some_closure_func(): a = 1 @@ -2232,6 +2294,7 @@ def another_closure_func(): ``` **خروجی:** + ```py >>> some_func() 1 @@ -2245,8 +2308,10 @@ UnboundLocalError: local variable 'a' referenced before assignment ``` #### 💡 توضیح: -* وقتی در محدوده (Scope) یک تابع به متغیری مقداردهی می‌کنید، آن متغیر در همان حوزه محلی تعریف می‌شود. بنابراین `a` در تابع `another_func` تبدیل به متغیر محلی می‌شود، اما پیش‌تر در همان حوزه مقداردهی نشده است، و این باعث خطا می‌شود. -* برای تغییر متغیر سراسری `a` در تابع `another_func`، باید از کلیدواژه‌ی `global` استفاده کنیم. + +- وقتی در محدوده (Scope) یک تابع به متغیری مقداردهی می‌کنید، آن متغیر در همان حوزه محلی تعریف می‌شود. بنابراین `a` در تابع `another_func` تبدیل به متغیر محلی می‌شود، اما پیش‌تر در همان حوزه مقداردهی نشده است، و این باعث خطا می‌شود. +- برای تغییر متغیر سراسری `a` در تابع `another_func`، باید از کلیدواژه‌ی `global` استفاده کنیم. + ```py def another_func() global a @@ -2255,12 +2320,15 @@ UnboundLocalError: local variable 'a' referenced before assignment ``` **خروجی:** + ```py >>> another_func() 2 ``` -* در تابع `another_closure_func`، متغیر `a` در حوزه‌ی `another_inner_func` محلی می‌شود ولی پیش‌تر در آن حوزه مقداردهی نشده است. به همین دلیل خطا می‌دهد. -* برای تغییر متغیر حوزه‌ی بیرونی `a` در `another_inner_func`، باید از کلیدواژه‌ی `nonlocal` استفاده کنیم. دستور `nonlocal` به مفسر می‌گوید که متغیر را در نزدیک‌ترین حوزه‌ی بیرونی (به‌جز حوزه‌ی global) جستجو کند. + +- در تابع `another_closure_func`، متغیر `a` در حوزه‌ی `another_inner_func` محلی می‌شود ولی پیش‌تر در آن حوزه مقداردهی نشده است. به همین دلیل خطا می‌دهد. +- برای تغییر متغیر حوزه‌ی بیرونی `a` در `another_inner_func`، باید از کلیدواژه‌ی `nonlocal` استفاده کنیم. دستور `nonlocal` به مفسر می‌گوید که متغیر را در نزدیک‌ترین حوزه‌ی بیرونی (به‌جز حوزه‌ی global) جستجو کند. + ```py def another_func(): a = 1 @@ -2272,12 +2340,14 @@ UnboundLocalError: local variable 'a' referenced before assignment ``` **خروجی:** + ```py >>> another_func() 2 ``` -* کلیدواژه‌های `global` و `nonlocal` به مفسر پایتون می‌گویند که متغیر جدیدی را تعریف نکند و به جای آن در حوزه‌های بیرونی (سراسری یا میانجی) آن را بیابد. -* برای مطالعه‌ی بیشتر در مورد نحوه‌ی کار فضای نام‌ها و مکانیزم تعیین حوزه‌ها در پایتون، می‌توانید این [مقاله کوتاه ولی عالی](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) را بخوانید. + +- کلیدواژه‌های `global` و `nonlocal` به مفسر پایتون می‌گویند که متغیر جدیدی را تعریف نکند و به جای آن در حوزه‌های بیرونی (سراسری یا میانجی) آن را بیابد. +- برای مطالعه‌ی بیشتر در مورد نحوه‌ی کار فضای نام‌ها و مکانیزم تعیین حوزه‌ها در پایتون، می‌توانید این [مقاله کوتاه ولی عالی](https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) را بخوانید. --- @@ -2303,6 +2373,7 @@ for idx, item in enumerate(list_4): ``` **خروجی:** + ```py >>> list_1 [1, 2, 3, 4] @@ -2318,7 +2389,7 @@ for idx, item in enumerate(list_4): #### 💡 توضیح: -* هیچ‌وقت ایده‌ی خوبی نیست که شیئی را که روی آن پیمایش می‌کنید تغییر دهید. روش درست این است که روی یک کپی از آن شیء پیمایش کنید؛ در این‌جا `list_3[:]` دقیقاً همین کار را می‌کند. +- هیچ‌وقت ایده‌ی خوبی نیست که شیئی را که روی آن پیمایش می‌کنید تغییر دهید. روش درست این است که روی یک کپی از آن شیء پیمایش کنید؛ در این‌جا `list_3[:]` دقیقاً همین کار را می‌کند. ```py >>> some_list = [1, 2, 3, 4] @@ -2329,19 +2400,20 @@ for idx, item in enumerate(list_4): ``` **تفاوت بین `del`، `remove` و `pop`:** -* اینجا، `del var_name` فقط اتصال `var_name` را از فضای نام محلی یا سراسری حذف می‌کند (به همین دلیل است که `list_1` تحت تأثیر قرار نمی‌گیرد). -* متد `remove` اولین مقدار مطابق را حذف می‌کند، نه یک اندیس خاص را؛ اگر مقدار مورد نظر پیدا نشود، خطای `ValueError` ایجاد می‌شود. -* متد `pop` عنصری را در یک اندیس مشخص حذف کرده و آن را برمی‌گرداند؛ اگر اندیس نامعتبری مشخص شود، خطای `IndexError` ایجاد می‌شود. + +- اینجا، `del var_name` فقط اتصال `var_name` را از فضای نام محلی یا سراسری حذف می‌کند (به همین دلیل است که `list_1` تحت تأثیر قرار نمی‌گیرد). +- متد `remove` اولین مقدار مطابق را حذف می‌کند، نه یک اندیس خاص را؛ اگر مقدار مورد نظر پیدا نشود، خطای `ValueError` ایجاد می‌شود. +- متد `pop` عنصری را در یک اندیس مشخص حذف کرده و آن را برمی‌گرداند؛ اگر اندیس نامعتبری مشخص شود، خطای `IndexError` ایجاد می‌شود. **چرا خروجی `[2, 4]` است؟** + - پیمایش لیست به صورت اندیس به اندیس انجام می‌شود، و هنگامی که عدد `1` را از `list_2` یا `list_4` حذف می‌کنیم، محتوای لیست به `[2, 3, 4]` تغییر می‌کند. در این حالت عناصر باقی‌مانده به سمت چپ جابه‌جا شده و جایگاهشان تغییر می‌کند؛ یعنی عدد `2` در اندیس 0 و عدد `3` در اندیس 1 قرار می‌گیرد. از آنجا که در مرحله بعدی حلقه به سراغ اندیس 1 می‌رود (که اکنون مقدار آن `3` است)، عدد `2` به طور کامل نادیده گرفته می‌شود. این اتفاق مشابه برای هر عنصر یک‌درمیان در طول پیمایش لیست رخ خواهد داد. -* برای توضیح بیشتر این مثال، این [تاپیک StackOverflow](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) را ببینید. -* همچنین برای نمونه مشابهی مربوط به دیکشنری‌ها در پایتون، این [تاپیک مفید StackOverflow](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) را ببینید. +- برای توضیح بیشتر این مثال، این [تاپیک StackOverflow](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) را ببینید. +- همچنین برای نمونه مشابهی مربوط به دیکشنری‌ها در پایتون، این [تاپیک مفید StackOverflow](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) را ببینید. --- - ### ◀ زیپِ دارای اتلاف برای پیمایشگرها * @@ -2359,6 +2431,7 @@ for idx, item in enumerate(list_4): >>> list(zip(numbers_iter, remaining)) [(4, 3), (5, 4), (6, 5)] ``` + عنصر `3` از لیست `numbers` چه شد؟ #### 💡 توضیح: @@ -2398,6 +2471,7 @@ for idx, item in enumerate(list_4): ### ◀ نشت کردن متغیرهای حلقه! 1\. + ```py for x in range(7): if x == 6: @@ -2406,6 +2480,7 @@ print(x, ': x in global') ``` **خروجی:** + ```py 6 : for x inside loop 6 : x in global @@ -2414,6 +2489,7 @@ print(x, ': x in global') اما متغیر `x` هرگز خارج از محدوده (scope) حلقه `for` تعریف نشده بود... 2\. + ```py # این دفعه، مقدار ایکس را در ابتدا مقداردهی اولیه میکنیم. x = -1 @@ -2424,6 +2500,7 @@ print(x, ': x in global') ``` **خروجی:** + ```py 6 : for x inside loop 6 : x in global @@ -2432,6 +2509,7 @@ print(x, ': x in global') 3\. **خروجی (Python 2.x):** + ```py >>> x = 1 >>> print([x for x in range(5)]) @@ -2441,6 +2519,7 @@ print(x, ': x in global') ``` **خروجی (Python 3.x):** + ```py >>> x = 1 >>> print([x for x in range(5)]) @@ -2469,6 +2548,7 @@ def some_func(default_arg=[]): ``` **خروجی:** + ```py >>> some_func() ['some_string'] @@ -2491,6 +2571,7 @@ def some_func(default_arg=[]): ``` **خروجی:** + ```py >>> some_func.__defaults__ # مقادیر پیشفرض این تابع را نمایش می دهد. ([],) @@ -2535,6 +2616,7 @@ except IndexError, ValueError: ``` **خروجی (Python 2.x):** + ```py Caught! @@ -2542,6 +2624,7 @@ ValueError: list.remove(x): x not in list ``` **خروجی (Python 3.x):** + ```py File "", line 3 except IndexError, ValueError: @@ -2551,7 +2634,7 @@ SyntaxError: invalid syntax #### 💡 توضیح -* برای افزودن چندین استثنا به عبارت `except`، باید آن‌ها را به صورت یک تاپل پرانتزدار به عنوان آرگومان اول وارد کنید. آرگومان دوم یک نام اختیاری است که در صورت ارائه، نمونهٔ Exception ایجادشده را به آن متصل می‌کند. برای مثال: +- برای افزودن چندین استثنا به عبارت `except`، باید آن‌ها را به صورت یک تاپل پرانتزدار به عنوان آرگومان اول وارد کنید. آرگومان دوم یک نام اختیاری است که در صورت ارائه، نمونهٔ Exception ایجادشده را به آن متصل می‌کند. برای مثال: ```py some_list = [1, 2, 3] @@ -2579,7 +2662,7 @@ SyntaxError: invalid syntax IndentationError: unindent does not match any outer indentation level ``` -* جدا کردن استثنا از متغیر با استفاده از ویرگول منسوخ شده و در پایتون 3 کار نمی‌کند؛ روش صحیح استفاده از `as` است. برای مثال: +- جدا کردن استثنا از متغیر با استفاده از ویرگول منسوخ شده و در پایتون 3 کار نمی‌کند؛ روش صحیح استفاده از `as` است. برای مثال: ```py some_list = [1, 2, 3] @@ -2603,6 +2686,7 @@ SyntaxError: invalid syntax ### ◀ عملوندهای یکسان، داستانی متفاوت! 1\. + ```py a = [1, 2, 3, 4] b = a @@ -2610,6 +2694,7 @@ a = a + [5, 6, 7, 8] ``` **خروجی:** + ```py >>> a [1, 2, 3, 4, 5, 6, 7, 8] @@ -2618,6 +2703,7 @@ a = a + [5, 6, 7, 8] ``` 2\. + ```py a = [1, 2, 3, 4] b = a @@ -2625,6 +2711,7 @@ a += [5, 6, 7, 8] ``` **خروجی:** + ```py >>> a [1, 2, 3, 4, 5, 6, 7, 8] @@ -2633,17 +2720,19 @@ a += [5, 6, 7, 8] ``` #### 💡 توضیح: -* عملگر `a += b` همیشه همانند `a = a + b` رفتار نمی‌کند. کلاس‌ها *ممکن است* عملگرهای *`op=`* را به گونه‌ای متفاوت پیاده‌سازی کنند، و لیست‌ها نیز چنین می‌کنند. -* عبارت `a = a + [5,6,7,8]` یک لیست جدید ایجاد می‌کند و مرجع `a` را به این لیست جدید اختصاص می‌دهد، بدون آنکه `b` را تغییر دهد. +- عملگر `a += b` همیشه همانند `a = a + b` رفتار نمی‌کند. کلاس‌ها *ممکن است* عملگرهای *`op=`* را به گونه‌ای متفاوت پیاده‌سازی کنند، و لیست‌ها نیز چنین می‌کنند. -* عبارت `a += [5,6,7,8]` در واقع به تابعی معادل «extend» ترجمه می‌شود که روی لیست اصلی عمل می‌کند؛ بنابراین `a` و `b` همچنان به همان لیست اشاره می‌کنند که به‌صورت درجا (in-place) تغییر کرده است. +- عبارت `a = a + [5,6,7,8]` یک لیست جدید ایجاد می‌کند و مرجع `a` را به این لیست جدید اختصاص می‌دهد، بدون آنکه `b` را تغییر دهد. + +- عبارت `a += [5,6,7,8]` در واقع به تابعی معادل «extend» ترجمه می‌شود که روی لیست اصلی عمل می‌کند؛ بنابراین `a` و `b` همچنان به همان لیست اشاره می‌کنند که به‌صورت درجا (in-place) تغییر کرده است. --- ### ◀ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس 1\. + ```py x = 5 class SomeClass: @@ -2652,12 +2741,14 @@ class SomeClass: ``` **خروجی:** + ```py >>> list(SomeClass.y)[0] 5 ``` 2\. + ```py x = 5 class SomeClass: @@ -2666,18 +2757,21 @@ class SomeClass: ``` **خروجی (Python 2.x):** + ```py >>> SomeClass.y[0] 17 ``` **خروجی (Python 3.x):** + ```py >>> SomeClass.y[0] 5 ``` #### 💡 توضیح + - حوزه‌هایی که درون تعریف کلاس تو در تو هستند، نام‌های تعریف‌شده در سطح کلاس را نادیده می‌گیرند. - عبارت‌های جنراتور (generator expressions) حوزه‌ی مختص به خود دارند. - از پایتون نسخه‌ی ۳ به بعد، لیست‌های فشرده (list comprehensions) نیز حوزه‌ی مختص به خود دارند. @@ -2687,6 +2781,7 @@ class SomeClass: ### ◀ گرد کردن به روش بانکدار * بیایید یک تابع ساده برای به‌دست‌آوردن عنصر میانی یک لیست پیاده‌سازی کنیم: + ```py def get_middle(some_list): mid_index = round(len(some_list) / 2) @@ -2694,6 +2789,7 @@ def get_middle(some_list): ``` **Python 3.x:** + ```py >>> get_middle([1]) # خوب به نظر می رسد. 1 @@ -2706,6 +2802,7 @@ def get_middle(some_list): >>> round(len([1,2,3,4,5]) / 2) # چرا? 2 ``` + به نظر می‌رسد که پایتون عدد ۲٫۵ را به ۲ گرد کرده است. #### 💡 توضیح: @@ -2869,21 +2966,23 @@ def similar_recursive_func(a): ``` #### 💡 توضیح: -* برای مورد ۱، عبارت صحیح برای رفتار مورد انتظار این است: + +- برای مورد ۱، عبارت صحیح برای رفتار مورد انتظار این است: `x, y = (0, 1) if True else (None, None)` -* برای مورد ۲، عبارت صحیح برای رفتار مورد انتظار این است: +- برای مورد ۲، عبارت صحیح برای رفتار مورد انتظار این است: اینجا، `t = ('one',)` یا `t = 'one',` (ویرگول از قلم افتاده است). در غیر این صورت مفسر `t` را به عنوان یک `str` در نظر گرفته و به صورت کاراکتر به کاراکتر روی آن پیمایش می‌کند. -* علامت `()` یک توکن خاص است و نشان‌دهنده‌ی یک `tuple` خالی است. +- علامت `()` یک توکن خاص است و نشان‌دهنده‌ی یک `tuple` خالی است. + +- در مورد ۳، همان‌طور که احتمالاً متوجه شدید، بعد از عنصر پنجم (`"that"`) یک ویرگول از قلم افتاده است. بنابراین با الحاق ضمنی رشته‌ها، -* در مورد ۳، همان‌طور که احتمالاً متوجه شدید، بعد از عنصر پنجم (`"that"`) یک ویرگول از قلم افتاده است. بنابراین با الحاق ضمنی رشته‌ها، ```py >>> ten_words_list ['some', 'very', 'big', 'list', 'thatconsists', 'of', 'exactly', 'ten', 'words'] ``` -* در قطعه‌ی چهارم هیچ `AssertionError`ای رخ نداد؛ زیرا به جای ارزیابی عبارت تکی `a == b`، کل یک تاپل ارزیابی شده است. قطعه‌ی کد زیر این موضوع را روشن‌تر می‌کند: +- در قطعه‌ی چهارم هیچ `AssertionError`ای رخ نداد؛ زیرا به جای ارزیابی عبارت تکی `a == b`، کل یک تاپل ارزیابی شده است. قطعه‌ی کد زیر این موضوع را روشن‌تر می‌کند: ```py >>> a = "python" @@ -2902,15 +3001,14 @@ def similar_recursive_func(a): AssertionError: Values are not equal ``` -* در قطعه‌ی پنجم، بیشتر متدهایی که اشیای ترتیبی (Sequence) یا نگاشت‌ها (Mapping) را تغییر می‌دهند (مانند `list.append`، `dict.update`، `list.sort` و غیره)، شیء اصلی را به‌صورت درجا (in-place) تغییر داده و مقدار `None` برمی‌گردانند. منطق پشت این تصمیم، بهبود عملکرد با جلوگیری از کپی کردن شیء است (به این [منبع](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list) مراجعه کنید). +- در قطعه‌ی پنجم، بیشتر متدهایی که اشیای ترتیبی (Sequence) یا نگاشت‌ها (Mapping) را تغییر می‌دهند (مانند `list.append`، `dict.update`، `list.sort` و غیره)، شیء اصلی را به‌صورت درجا (in-place) تغییر داده و مقدار `None` برمی‌گردانند. منطق پشت این تصمیم، بهبود عملکرد با جلوگیری از کپی کردن شیء است (به این [منبع](https://docs.python.org/3/faq/design.html#why-doesn-t-list-sort-return-the-sorted-list) مراجعه کنید). -* قطعه‌ی آخر نیز نسبتاً واضح است؛ شیء تغییرپذیر (mutable)، مثل `list`، می‌تواند در داخل تابع تغییر کند، درحالی‌که انتساب دوباره‌ی یک شیء تغییرناپذیر (مانند `a -= 1`) باعث تغییر مقدار اصلی آن نخواهد شد. +- قطعه‌ی آخر نیز نسبتاً واضح است؛ شیء تغییرپذیر (mutable)، مثل `list`، می‌تواند در داخل تابع تغییر کند، درحالی‌که انتساب دوباره‌ی یک شیء تغییرناپذیر (مانند `a -= 1`) باعث تغییر مقدار اصلی آن نخواهد شد. -* آگاهی از این نکات ظریف در بلندمدت می‌تواند ساعت‌ها از زمان شما برای رفع اشکال را صرفه‌جویی کند. +- آگاهی از این نکات ظریف در بلندمدت می‌تواند ساعت‌ها از زمان شما برای رفع اشکال را صرفه‌جویی کند. --- - ### ◀ تقسیم‌ها * ```py @@ -2979,12 +3077,15 @@ 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! ``` + - اگر واقعاً تمایل دارید از واردسازی عمومی استفاده کنید، لازم است فهرستی به نام `__all__` را در ماژول خود تعریف کنید که شامل نام اشیاء عمومی (public) قابل‌دسترس هنگام واردسازی عمومی است. + ```py __all__ = ['_another_weird_name_func'] @@ -2994,6 +3095,7 @@ NameError: name '_another_weird_name_func' is not defined def _another_weird_name_func(): print("works!") ``` + **خروجی** ```py @@ -3034,6 +3136,7 @@ False >>> type(x), type(sorted(x)) (tuple, list) ``` + - برخلاف متد `sorted`، متد `reversed` یک تکرارکننده (iterator) برمی‌گرداند. چرا؟ زیرا مرتب‌سازی نیاز به تغییر درجا (in-place) یا استفاده از ظرف جانبی (مانند یک لیست اضافی) دارد، در حالی که معکوس کردن می‌تواند به‌سادگی با پیمایش از اندیس آخر به اول انجام شود. - بنابراین در مقایسه‌ی `sorted(y) == sorted(y)`، فراخوانی اولِ `sorted()` تمام عناصرِ تکرارکننده‌ی `y` را مصرف می‌کند، و فراخوانی بعدی یک لیست خالی برمی‌گرداند. @@ -3070,6 +3173,7 @@ if noon_time: ```py ('Time at noon is', datetime.time(12, 0)) ``` + زمان نیمه‌شب چاپ نمی‌شود. #### 💡 توضیح: @@ -3079,8 +3183,6 @@ if noon_time: --- --- - - ## بخش: گنجینه‌های پنهان! این بخش شامل چند مورد جالب و کمتر شناخته‌شده درباره‌ی پایتون است که بیشتر مبتدی‌هایی مثل من از آن بی‌خبرند (البته دیگر اینطور نیست). @@ -3097,9 +3199,10 @@ import antigravity Sshh... It's a super-secret. #### 💡 توضیح: -+ ماژول `antigravity` یکی از معدود ایستر اِگ‌هایی است که توسط توسعه‌دهندگان پایتون ارائه شده است. -+ دستور `import antigravity` باعث می‌شود مرورگر وب به سمت [کمیک کلاسیک XKCD](https://xkcd.com/353/) در مورد پایتون باز شود. -+ البته موضوع عمیق‌تر است؛ در واقع یک **ایستر اگ دیگر داخل این ایستر اگ** وجود دارد. اگر به [کد منبع](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17) نگاه کنید، یک تابع تعریف شده که ادعا می‌کند [الگوریتم جئوهشینگ XKCD](https://xkcd.com/426/) را پیاده‌سازی کرده است. + +- ماژول `antigravity` یکی از معدود ایستر اِگ‌هایی است که توسط توسعه‌دهندگان پایتون ارائه شده است. +- دستور `import antigravity` باعث می‌شود مرورگر وب به سمت [کمیک کلاسیک XKCD](https://xkcd.com/353/) در مورد پایتون باز شود. +- البته موضوع عمیق‌تر است؛ در واقع یک **ایستر اگ دیگر داخل این ایستر اگ** وجود دارد. اگر به [کد منبع](https://github.com/python/cpython/blob/master/Lib/antigravity.py#L7-L17) نگاه کنید، یک تابع تعریف شده که ادعا می‌کند [الگوریتم جئوهشینگ XKCD](https://xkcd.com/426/) را پیاده‌سازی کرده است. --- @@ -3119,6 +3222,7 @@ print("Freedom!") ``` **خروجی (پایتون ۲.۳):** + ```py I am trapped, please rescue! I am trapped, please rescue! @@ -3126,6 +3230,7 @@ Freedom! ``` #### 💡 توضیح: + - نسخه‌ی قابل استفاده‌ای از `goto` در پایتون به عنوان یک شوخی [در اول آوریل ۲۰۰۴ معرفی شد](https://mail.python.org/pipermail/python-announce-list/2004-April/002982.html). - نسخه‌های فعلی پایتون فاقد این ماژول هستند. - اگرچه این ماژول واقعاً کار می‌کند، ولی لطفاً از آن استفاده نکنید. در [این صفحه](https://docs.python.org/3/faq/design.html#why-is-there-no-goto) می‌توانید دلیل عدم حضور دستور `goto` در پایتون را مطالعه کنید. @@ -3141,6 +3246,7 @@ from __future__ import braces ``` **خروجی:** + ```py File "some_file.py", line 1 from __future__ import braces @@ -3150,16 +3256,18 @@ SyntaxError: not a chance آکولاد؟ هرگز! اگر از این بابت ناامید شدید، بهتر است از جاوا استفاده کنید. خب، یک چیز شگفت‌آور دیگر؛ آیا می‌توانید تشخیص دهید که ارور `SyntaxError` در کجای کد ماژول `__future__` [اینجا](https://github.com/python/cpython/blob/master/Lib/__future__.py) ایجاد می‌شود؟ #### 💡 توضیح: -+ ماژول `__future__` معمولاً برای ارائه قابلیت‌هایی از نسخه‌های آینده پایتون به کار می‌رود. اما کلمه «future» (آینده) در این زمینه خاص، حالت طنز و کنایه دارد. -+ این مورد یک «ایستر اگ» (easter egg) است که به احساسات جامعه برنامه‌نویسان پایتون در این خصوص اشاره دارد. -+ کد مربوط به این موضوع در واقع [اینجا](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) در فایل `future.c` قرار دارد. -+ زمانی که کامپایلر CPython با یک [عبارت future](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements) مواجه می‌شود، ابتدا کد مرتبط در `future.c` را اجرا کرده و سپس آن را همانند یک دستور ایمپورت عادی در نظر می‌گیرد. + +- ماژول `__future__` معمولاً برای ارائه قابلیت‌هایی از نسخه‌های آینده پایتون به کار می‌رود. اما کلمه «future» (آینده) در این زمینه خاص، حالت طنز و کنایه دارد. +- این مورد یک «ایستر اگ» (easter egg) است که به احساسات جامعه برنامه‌نویسان پایتون در این خصوص اشاره دارد. +- کد مربوط به این موضوع در واقع [اینجا](https://github.com/python/cpython/blob/025eb98dc0c1dc27404df6c544fc2944e0fa9f3a/Python/future.c#L49) در فایل `future.c` قرار دارد. +- زمانی که کامپایلر CPython با یک [عبارت future](https://docs.python.org/3.3/reference/simple_stmts.html#future-statements) مواجه می‌شود، ابتدا کد مرتبط در `future.c` را اجرا کرده و سپس آن را همانند یک دستور ایمپورت عادی در نظر می‌گیرد. --- ### ◀ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم **خروجی (Python 3.x)** + ```py >>> from __future__ import barry_as_FLUFL >>> "Ruby" != "Python" # شکی در این نیست. @@ -3175,6 +3283,7 @@ True حالا می‌رسیم به اصل ماجرا. #### 💡 توضیح: + - این مورد مربوط به [PEP-401](https://www.python.org/dev/peps/pep-0401/) است که در تاریخ ۱ آوریل ۲۰۰۹ منتشر شد (اکنون می‌دانید این یعنی چه!). - نقل قولی از PEP-401: @@ -3199,6 +3308,7 @@ import this صبر کن، **این** چیه؟ `this` عشقه :heart: **خروجی:** + ``` The Zen of Python, by Tim Peters @@ -3241,9 +3351,9 @@ True #### 💡 توضیح: -* ماژول `this` در پایتون، یک ایستر اگ برای «ذنِ پایتون» ([PEP 20](https://www.python.org/dev/peps/pep-0020)) است. -* اگر این موضوع به‌اندازه کافی جالب است، حتماً پیاده‌سازی [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py) را ببینید. نکته جالب این است که **کد مربوط به ذنِ پایتون، خودش اصول ذن را نقض کرده است** (و احتمالاً این تنها جایی است که چنین اتفاقی می‌افتد). -* درباره جمله `love is not True or False; love is love`، اگرچه طعنه‌آمیز است، اما خود گویاست. (اگر واضح نیست، لطفاً مثال‌های مربوط به عملگرهای `is` و `is not` را مشاهده کنید.) +- ماژول `this` در پایتون، یک ایستر اگ برای «ذنِ پایتون» ([PEP 20](https://www.python.org/dev/peps/pep-0020)) است. +- اگر این موضوع به‌اندازه کافی جالب است، حتماً پیاده‌سازی [this.py](https://hg.python.org/cpython/file/c3896275c0f6/Lib/this.py) را ببینید. نکته جالب این است که **کد مربوط به ذنِ پایتون، خودش اصول ذن را نقض کرده است** (و احتمالاً این تنها جایی است که چنین اتفاقی می‌افتد). +- درباره جمله `love is not True or False; love is love`، اگرچه طعنه‌آمیز است، اما خود گویاست. (اگر واضح نیست، لطفاً مثال‌های مربوط به عملگرهای `is` و `is not` را مشاهده کنید.) --- @@ -3262,6 +3372,7 @@ True ``` **خروجی:** + ```py >>> some_list = [1, 2, 3, 4, 5] >>> does_exists_num(some_list, 4) @@ -3282,15 +3393,18 @@ else: ``` **خروجی:** + ```py Try block executed successfully... ``` #### 💡 توضیح: + - عبارت `else` بعد از حلقه‌ها تنها زمانی اجرا می‌شود که در هیچ‌کدام از تکرارها (`iterations`) از دستور `break` استفاده نشده باشد. می‌توانید آن را به عنوان یک شرط «بدون شکست» (nobreak) در نظر بگیرید. - عبارت `else` پس از بلاک `try` به عنوان «عبارت تکمیل» (`completion clause`) نیز شناخته می‌شود؛ چراکه رسیدن به عبارت `else` در ساختار `try` به این معنی است که بلاک `try` بدون رخ دادن استثنا با موفقیت تکمیل شده است. --- + ### ◀ عملگر Ellipsis * ```py @@ -3299,6 +3413,7 @@ def some_func(): ``` **خروجی** + ```py >>> some_func() # بدون خروجی و بدون خطا @@ -3313,14 +3428,17 @@ Ellipsis ``` #### 💡توضیح + - در پایتون، `Ellipsis` یک شیء درونی (`built-in`) است که به صورت سراسری (`global`) در دسترس است و معادل `...` است. + ```py >>> ... Ellipsis ``` + - عملگر `Ellipsis` می‌تواند برای چندین منظور استفاده شود: - + به عنوان یک نگه‌دارنده برای کدی که هنوز نوشته نشده است (مانند دستور `pass`) - + در سینتکس برش (`slicing`) برای نمایش برش کامل در ابعاد باقی‌مانده + - به عنوان یک نگه‌دارنده برای کدی که هنوز نوشته نشده است (مانند دستور `pass`) + - در سینتکس برش (`slicing`) برای نمایش برش کامل در ابعاد باقی‌مانده ```py >>> import numpy as np @@ -3337,7 +3455,9 @@ Ellipsis ] ]) ``` + بنابراین، آرایه‌ی `three_dimensional_array` ما، آرایه‌ای از آرایه‌ها از آرایه‌ها است. فرض کنیم می‌خواهیم عنصر دوم (اندیس `1`) از تمامی آرایه‌های درونی را چاپ کنیم؛ در این حالت می‌توانیم از `Ellipsis` برای عبور از تمامی ابعاد قبلی استفاده کنیم: + ```py >>> three_dimensional_array[:,:,1] array([[1, 3], @@ -3346,10 +3466,10 @@ Ellipsis array([[1, 3], [5, 7]]) ``` - نکته: این روش برای آرایه‌هایی با هر تعداد بُعد کار می‌کند. حتی می‌توانید از برش (`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` ارسال شده است» تمایز قائل شوید). + نکته: این روش برای آرایه‌هایی با هر تعداد بُعد کار می‌کند. حتی می‌توانید از برش (`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` ارسال شده است» تمایز قائل شوید). --- @@ -3358,6 +3478,7 @@ Ellipsis این املای کلمه تعمداً به همین شکل نوشته شده است. لطفاً برای اصلاح آن درخواست (`patch`) ارسال نکنید. **خروجی (پایتون 3.x):** + ```py >>> infinity = float('infinity') >>> hash(infinity) @@ -3367,6 +3488,7 @@ Ellipsis ``` #### 💡 توضیح: + - هش (`hash`) مقدار بی‌نهایت برابر با 10⁵ × π است. - نکته جالب اینکه در پایتون ۳ هشِ مقدار `float('-inf')` برابر با «-10⁵ × π» است، در حالی که در پایتون ۲ برابر با «-10⁵ × e» است. @@ -3375,6 +3497,7 @@ Ellipsis ### ◀ بیایید خرابکاری کنیم 1\. + ```py class Yo(object): def __init__(self): @@ -3383,6 +3506,7 @@ class Yo(object): ``` **خروجی:** + ```py >>> Yo().bro True @@ -3393,6 +3517,7 @@ True ``` 2\. + ```py class Yo(object): def __init__(self): @@ -3402,6 +3527,7 @@ class Yo(object): ``` **خروجی:** + ```py >>> Yo().bro True @@ -3425,6 +3551,7 @@ class A(object): ``` **خروجی:** + ```py >>> A().__variable Traceback (most recent call last): @@ -3435,15 +3562,14 @@ AttributeError: 'A' object has no attribute '__variable' 'Some value' ``` - #### 💡 توضیح: -* [تغییر نام](https://en.wikipedia.org/wiki/Name_mangling) برای جلوگیری از برخورد نام‌ها بین فضاهای نام مختلف استفاده می‌شود. -* در پایتون، مفسر نام‌های اعضای کلاس که با `__` (دو آندرلاین که به عنوان "دندر" شناخته می‌شود) شروع می‌شوند و بیش از یک آندرلاین انتهایی ندارند را با اضافه کردن `_NameOfTheClass` در ابتدای آنها تغییر می‌دهد. -* بنابراین، برای دسترسی به ویژگی `__honey` در اولین قطعه کد، مجبور بودیم `_Yo` را به ابتدای آن اضافه کنیم، که از بروز تعارض با ویژگی با همان نام تعریف‌شده در هر کلاس دیگری جلوگیری می‌کند. -* اما چرا در دومین قطعه کد کار نکرد؟ زیرا تغییر نام، نام‌هایی که با دو آندرلاین خاتمه می‌یابند را شامل نمی‌شود. -* قطعه سوم نیز نتیجه تغییر نام بود. نام `__variable` در عبارت `return __variable` به `_A__variable` تغییر یافت، که همچنین همان نام متغیری است که در محدوده بیرونی تعریف کرده بودیم. -* همچنین، اگر نام تغییر یافته بیش از ۲۵۵ کاراکتر باشد، برش داده می‌شود. +- [تغییر نام](https://en.wikipedia.org/wiki/Name_mangling) برای جلوگیری از برخورد نام‌ها بین فضاهای نام مختلف استفاده می‌شود. +- در پایتون، مفسر نام‌های اعضای کلاس که با `__` (دو آندرلاین که به عنوان "دندر" شناخته می‌شود) شروع می‌شوند و بیش از یک آندرلاین انتهایی ندارند را با اضافه کردن `_NameOfTheClass` در ابتدای آنها تغییر می‌دهد. +- بنابراین، برای دسترسی به ویژگی `__honey` در اولین قطعه کد، مجبور بودیم `_Yo` را به ابتدای آن اضافه کنیم، که از بروز تعارض با ویژگی با همان نام تعریف‌شده در هر کلاس دیگری جلوگیری می‌کند. +- اما چرا در دومین قطعه کد کار نکرد؟ زیرا تغییر نام، نام‌هایی که با دو آندرلاین خاتمه می‌یابند را شامل نمی‌شود. +- قطعه سوم نیز نتیجه تغییر نام بود. نام `__variable` در عبارت `return __variable` به `_A__variable` تغییر یافت، که همچنین همان نام متغیری است که در محدوده بیرونی تعریف کرده بودیم. +- همچنین، اگر نام تغییر یافته بیش از ۲۵۵ کاراکتر باشد، برش داده می‌شود. --- --- @@ -3453,6 +3579,7 @@ AttributeError: 'A' object has no attribute '__variable' ### ◀ خطوط را رد می‌کند؟ **خروجی:** + ```py >>> value = 11 >>> valuе = 32 @@ -3504,6 +3631,7 @@ def energy_receive(): ``` **خروجی:** + ```py >>> energy_send(123.456) >>> energy_receive() @@ -3514,8 +3642,8 @@ def energy_receive(): #### 💡 توضیح: -* توجه کنید که آرایه‌ی numpy ایجادشده در تابع `energy_send` برگردانده نشده است، بنابراین فضای حافظه‌ی آن آزاد شده و مجدداً قابل استفاده است. -* تابع `numpy.empty()` نزدیک‌ترین فضای حافظه‌ی آزاد را بدون مقداردهی مجدد برمی‌گرداند. این فضای حافظه معمولاً همان فضایی است که به‌تازگی آزاد شده است (البته معمولاً این اتفاق می‌افتد و نه همیشه). +- توجه کنید که آرایه‌ی numpy ایجادشده در تابع `energy_send` برگردانده نشده است، بنابراین فضای حافظه‌ی آن آزاد شده و مجدداً قابل استفاده است. +- تابع `numpy.empty()` نزدیک‌ترین فضای حافظه‌ی آزاد را بدون مقداردهی مجدد برمی‌گرداند. این فضای حافظه معمولاً همان فضایی است که به‌تازگی آزاد شده است (البته معمولاً این اتفاق می‌افتد و نه همیشه). --- @@ -3545,12 +3673,12 @@ def square(x): #### 💡 توضیح -* **تب‌ها و فاصله‌ها (space) را با هم ترکیب نکنید!** کاراکتری که دقیقاً قبل از دستور return آمده یک «تب» است، در حالی که در بقیۀ مثال، کد با مضربی از «۴ فاصله» تورفتگی دارد. -* نحوۀ برخورد پایتون با تب‌ها به این صورت است: +- **تب‌ها و فاصله‌ها (space) را با هم ترکیب نکنید!** کاراکتری که دقیقاً قبل از دستور return آمده یک «تب» است، در حالی که در بقیۀ مثال، کد با مضربی از «۴ فاصله» تورفتگی دارد. +- نحوۀ برخورد پایتون با تب‌ها به این صورت است: > ابتدا تب‌ها (از چپ به راست) با یک تا هشت فاصله جایگزین می‌شوند به‌طوری که تعداد کل کاراکترها تا انتهای آن جایگزینی، مضربی از هشت باشد <...> -* بنابراین «تب» در آخرین خط تابع `square` با هشت فاصله جایگزین شده و به همین دلیل داخل حلقه قرار می‌گیرد. -* پایتون ۳ آنقدر هوشمند هست که چنین مواردی را به‌صورت خودکار با خطا اعلام کند. +- بنابراین «تب» در آخرین خط تابع `square` با هشت فاصله جایگزین شده و به همین دلیل داخل حلقه قرار می‌گیرد. +- پایتون ۳ آنقدر هوشمند هست که چنین مواردی را به‌صورت خودکار با خطا اعلام کند. **خروجی (Python 3.x):** @@ -3563,7 +3691,6 @@ def square(x): ## بخش: متفرقه - ### ◀ `+=` سریع‌تر است @@ -3576,8 +3703,9 @@ def square(x): 0.012188911437988281 ``` -#### 💡 توضیح: -+ استفاده از `+=` برای اتصال بیش از دو رشته سریع‌تر از `+` است، زیرا هنگام محاسبه رشته‌ی نهایی، رشته‌ی اول (به‌عنوان مثال `s1` در عبارت `s1 += s2 + s3`) از بین نمی‌رود. +#### 💡 توضیح: + +- استفاده از `+=` برای اتصال بیش از دو رشته سریع‌تر از `+` است، زیرا هنگام محاسبه رشته‌ی نهایی، رشته‌ی اول (به‌عنوان مثال `s1` در عبارت `s1 += s2 + s3`) از بین نمی‌رود. --- @@ -3653,12 +3781,15 @@ timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) ``` #### 💡 توضیح + توضیحات -- برای اطلاعات بیشتر درباره‌ی [timeit](https://docs.python.org/3/library/timeit.html) یا [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit)، می‌توانید به این لینک‌ها مراجعه کنید. این توابع برای اندازه‌گیری زمان اجرای قطعه‌کدها استفاده می‌شوند. -- برای تولید رشته‌های طولانی از `+` استفاده نکنید — در پایتون، نوع داده‌ی `str` تغییرناپذیر (immutable) است؛ بنابراین برای هر الحاق (concatenation)، رشته‌ی چپ و راست باید در رشته‌ی جدید کپی شوند. اگر چهار رشته‌ی ۱۰ حرفی را متصل کنید، به‌جای کپی ۴۰ کاراکتر، باید `(10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90` کاراکتر کپی کنید. این وضعیت با افزایش تعداد و طول رشته‌ها به‌صورت درجه دو (مربعی) بدتر می‌شود (که توسط زمان اجرای تابع `add_bytes_with_plus` تأیید شده است). -- بنابراین توصیه می‌شود از `.format` یا سینتکس `%` استفاده کنید (البته این روش‌ها برای رشته‌های بسیار کوتاه کمی کندتر از `+` هستند). -- اما بهتر از آن، اگر محتوای شما از قبل به‌شکل یک شیء قابل تکرار (iterable) موجود است، از دستور `''.join(iterable_object)` استفاده کنید که بسیار سریع‌تر است. -- برخلاف تابع `add_bytes_with_plus` و به‌دلیل بهینه‌سازی‌های انجام‌شده برای عملگر `+=` (که در مثال قبلی توضیح داده شد)، تابع `add_string_with_plus` افزایشی درجه دو در زمان اجرا نشان نداد. اگر دستور به‌صورت `s = s + "x" + "y" + "z"` بود (به‌جای `s += "xyz"`)، افزایش زمان اجرا درجه دو می‌شد. + +- برای اطلاعات بیشتر درباره‌ی [timeit](https://docs.python.org/3/library/timeit.html) یا [%timeit](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit)، می‌توانید به این لینک‌ها مراجعه کنید. این توابع برای اندازه‌گیری زمان اجرای قطعه‌کدها استفاده می‌شوند. +- برای تولید رشته‌های طولانی از `+` استفاده نکنید — در پایتون، نوع داده‌ی `str` تغییرناپذیر (immutable) است؛ بنابراین برای هر الحاق (concatenation)، رشته‌ی چپ و راست باید در رشته‌ی جدید کپی شوند. اگر چهار رشته‌ی ۱۰ حرفی را متصل کنید، به‌جای کپی ۴۰ کاراکتر، باید `(10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90` کاراکتر کپی کنید. این وضعیت با افزایش تعداد و طول رشته‌ها به‌صورت درجه دو (مربعی) بدتر می‌شود (که توسط زمان اجرای تابع `add_bytes_with_plus` تأیید شده است). +- بنابراین توصیه می‌شود از `.format` یا سینتکس `%` استفاده کنید (البته این روش‌ها برای رشته‌های بسیار کوتاه کمی کندتر از `+` هستند). +- اما بهتر از آن، اگر محتوای شما از قبل به‌شکل یک شیء قابل تکرار (iterable) موجود است، از دستور `''.join(iterable_object)` استفاده کنید که بسیار سریع‌تر است. +- برخلاف تابع `add_bytes_with_plus` و به‌دلیل بهینه‌سازی‌های انجام‌شده برای عملگر `+=` (که در مثال قبلی توضیح داده شد)، تابع `add_string_with_plus` افزایشی درجه دو در زمان اجرا نشان نداد. اگر دستور به‌صورت `s = s + "x" + "y" + "z"` بود (به‌جای `s += "xyz"`)، افزایش زمان اجرا درجه دو می‌شد. + ```py def add_string_with_plus(iters): s = "" @@ -3671,10 +3802,10 @@ timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals()) >>> %timeit -n100 add_string_with_plus(10000) # افزایش درجه دو در زمان اجرا 9 ms ± 298 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` + - وجود راه‌های متعدد برای قالب‌بندی و ایجاد رشته‌های بزرگ تا حدودی در تضاد با [ذِن پایتون](https://www.python.org/dev/peps/pep-0020/) است که می‌گوید: - - > «باید یک راه — و ترجیحاً فقط یک راه — واضح برای انجام آن وجود داشته باشد.» + > «باید یک راه — و ترجیحاً فقط یک راه — واضح برای انجام آن وجود داشته باشد.» --- @@ -3686,6 +3817,7 @@ another_dict = {str(i): 1 for i in range(1_000_000)} ``` **خروجی:** + ```py >>> %timeit some_dict['5'] 28.6 ns ± 0.115 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) @@ -3702,14 +3834,15 @@ KeyError: 1 >>> %timeit another_dict['5'] 38.5 ns ± 0.0913 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) ``` + چرا جستجوهای یکسان کندتر می‌شوند؟ -#### 💡 توضیح: -+ در CPython یک تابع عمومی برای جستجوی کلید در دیکشنری‌ها وجود دارد که از تمام انواع کلیدها (`str`، `int` و هر شیء دیگر) پشتیبانی می‌کند؛ اما برای حالت متداولی که تمام کلیدها از نوع `str` هستند، یک تابع بهینه‌شده‌ی اختصاصی نیز وجود دارد. -+ تابع اختصاصی (که در کد منبع CPython با نام [`lookdict_unicode`](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841) شناخته می‌شود) فرض می‌کند که تمام کلیدهای موجود در دیکشنری (از جمله کلیدی که در حال جستجوی آن هستید) رشته (`str`) هستند و برای مقایسه‌ی کلیدها، به‌جای فراخوانی متد `__eq__`، از مقایسه‌ی سریع‌تر و ساده‌تر رشته‌ای استفاده می‌کند. -+ اولین باری که یک دیکشنری (`dict`) با کلیدی غیر از `str` فراخوانی شود، این حالت تغییر می‌کند و جستجوهای بعدی از تابع عمومی استفاده خواهند کرد. -+ این فرایند برای آن نمونه‌ی خاص از دیکشنری غیرقابل بازگشت است و حتی لازم نیست کلید موردنظر در دیکشنری موجود باشد. به همین دلیل است که حتی تلاش ناموفق برای دسترسی به کلیدی ناموجود نیز باعث ایجاد همین تأثیر (کند شدن جستجو) می‌شود. +#### 💡 توضیح: +- در CPython یک تابع عمومی برای جستجوی کلید در دیکشنری‌ها وجود دارد که از تمام انواع کلیدها (`str`، `int` و هر شیء دیگر) پشتیبانی می‌کند؛ اما برای حالت متداولی که تمام کلیدها از نوع `str` هستند، یک تابع بهینه‌شده‌ی اختصاصی نیز وجود دارد. +- تابع اختصاصی (که در کد منبع CPython با نام [`lookdict_unicode`](https://github.com/python/cpython/blob/522691c46e2ae51faaad5bbbce7d959dd61770df/Objects/dictobject.c#L841) شناخته می‌شود) فرض می‌کند که تمام کلیدهای موجود در دیکشنری (از جمله کلیدی که در حال جستجوی آن هستید) رشته (`str`) هستند و برای مقایسه‌ی کلیدها، به‌جای فراخوانی متد `__eq__`، از مقایسه‌ی سریع‌تر و ساده‌تر رشته‌ای استفاده می‌کند. +- اولین باری که یک دیکشنری (`dict`) با کلیدی غیر از `str` فراخوانی شود، این حالت تغییر می‌کند و جستجوهای بعدی از تابع عمومی استفاده خواهند کرد. +- این فرایند برای آن نمونه‌ی خاص از دیکشنری غیرقابل بازگشت است و حتی لازم نیست کلید موردنظر در دیکشنری موجود باشد. به همین دلیل است که حتی تلاش ناموفق برای دسترسی به کلیدی ناموجود نیز باعث ایجاد همین تأثیر (کند شدن جستجو) می‌شود. ### ◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) * @@ -3730,6 +3863,7 @@ def dict_size(o): ``` **خروجی:** (پایتون ۳.۸؛ سایر نسخه‌های پایتون ۳ ممکن است کمی متفاوت باشند) + ```py >>> o1 = SomeClass() >>> o2 = SomeClass() @@ -3766,25 +3900,25 @@ def dict_size(o): چه چیزی باعث حجیم‌شدن این دیکشنری‌ها می‌شود؟ و چرا اشیاء تازه ساخته‌شده نیز حجیم هستند؟ #### 💡 توضیح: -+ در CPython، امکان استفاده‌ی مجدد از یک شیء «کلیدها» (`keys`) در چندین دیکشنری وجود دارد. این ویژگی در [PEP 412](https://www.python.org/dev/peps/pep-0412/) معرفی شد تا مصرف حافظه کاهش یابد، به‌ویژه برای دیکشنری‌هایی که به نمونه‌ها (instances) تعلق دارند و معمولاً کلیدها (نام صفات نمونه‌ها) بین آن‌ها مشترک است. -+ این بهینه‌سازی برای دیکشنری‌های نمونه‌ها کاملاً شفاف و خودکار است؛ اما اگر بعضی فرضیات نقض شوند، غیرفعال می‌شود. -+ دیکشنری‌هایی که کلیدهایشان به اشتراک گذاشته شده باشد، از حذف کلید پشتیبانی نمی‌کنند؛ بنابراین اگر صفتی از یک نمونه حذف شود، دیکشنریِ آن نمونه «غیر مشترک» (`unshared`) شده و این قابلیت اشتراک‌گذاری کلیدها برای تمام نمونه‌هایی که در آینده از آن کلاس ساخته می‌شوند، غیرفعال می‌گردد. -+ همچنین اگر اندازه‌ی دیکشنری به‌علت اضافه‌شدن کلیدهای جدید تغییر کند (`resize` شود)، اشتراک‌گذاری کلیدها تنها زمانی ادامه می‌یابد که فقط یک دیکشنری در حال استفاده از آن‌ها باشد (این اجازه می‌دهد در متد `__init__` برای اولین نمونه‌ی ساخته‌شده، صفات متعددی تعریف کنید بدون آن‌که اشتراک‌گذاری کلیدها از بین برود). اما اگر چند نمونه همزمان وجود داشته باشند و تغییر اندازه‌ی دیکشنری رخ دهد، قابلیت اشتراک‌گذاری کلیدها برای نمونه‌های بعدی همان کلاس غیرفعال خواهد شد. زیرا CPython دیگر نمی‌تواند مطمئن باشد که آیا نمونه‌های بعدی دقیقاً از مجموعه‌ی یکسانی از صفات استفاده خواهند کرد یا خیر. -+ نکته‌ای کوچک برای کاهش مصرف حافظه‌ی برنامه: هرگز صفات نمونه‌ها را حذف نکنید و حتماً تمام صفات را در متد `__init__` تعریف و مقداردهی اولیه کنید! +- در CPython، امکان استفاده‌ی مجدد از یک شیء «کلیدها» (`keys`) در چندین دیکشنری وجود دارد. این ویژگی در [PEP 412](https://www.python.org/dev/peps/pep-0412/) معرفی شد تا مصرف حافظه کاهش یابد، به‌ویژه برای دیکشنری‌هایی که به نمونه‌ها (instances) تعلق دارند و معمولاً کلیدها (نام صفات نمونه‌ها) بین آن‌ها مشترک است. +- این بهینه‌سازی برای دیکشنری‌های نمونه‌ها کاملاً شفاف و خودکار است؛ اما اگر بعضی فرضیات نقض شوند، غیرفعال می‌شود. +- دیکشنری‌هایی که کلیدهایشان به اشتراک گذاشته شده باشد، از حذف کلید پشتیبانی نمی‌کنند؛ بنابراین اگر صفتی از یک نمونه حذف شود، دیکشنریِ آن نمونه «غیر مشترک» (`unshared`) شده و این قابلیت اشتراک‌گذاری کلیدها برای تمام نمونه‌هایی که در آینده از آن کلاس ساخته می‌شوند، غیرفعال می‌گردد. +- همچنین اگر اندازه‌ی دیکشنری به‌علت اضافه‌شدن کلیدهای جدید تغییر کند (`resize` شود)، اشتراک‌گذاری کلیدها تنها زمانی ادامه می‌یابد که فقط یک دیکشنری در حال استفاده از آن‌ها باشد (این اجازه می‌دهد در متد `__init__` برای اولین نمونه‌ی ساخته‌شده، صفات متعددی تعریف کنید بدون آن‌که اشتراک‌گذاری کلیدها از بین برود). اما اگر چند نمونه همزمان وجود داشته باشند و تغییر اندازه‌ی دیکشنری رخ دهد، قابلیت اشتراک‌گذاری کلیدها برای نمونه‌های بعدی همان کلاس غیرفعال خواهد شد. زیرا CPython دیگر نمی‌تواند مطمئن باشد که آیا نمونه‌های بعدی دقیقاً از مجموعه‌ی یکسانی از صفات استفاده خواهند کرد یا خیر. +- نکته‌ای کوچک برای کاهش مصرف حافظه‌ی برنامه: هرگز صفات نمونه‌ها را حذف نکنید و حتماً تمام صفات را در متد `__init__` تعریف و مقداردهی اولیه کنید! -### ◀ موارد جزئی * +### ◀ موارد جزئی * -* متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) +- متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) **توضیح:** اگر `join()` به‌عنوان متدی روی رشته پیاده‌سازی شود، می‌تواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشونده‌ی دیگر کار کند. اگر به‌جای آن روی لیست تعریف می‌شد، باید به‌طور جداگانه برای هر نوع دیگری نیز پیاده‌سازی می‌شد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. -* تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح: - + عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی). - + عبارت `'a'[0][0][0][0][0]` نیز از نظر معنایی صحیح است، زیرا پایتون برخلاف زبان‌هایی که از C منشعب شده‌اند، نوع داده‌ای جداگانه‌ای برای کاراکتر ندارد. بنابراین انتخاب یک کاراکتر از یک رشته، منجر به بازگشت یک رشته‌ی تک‌کاراکتری می‌شود. - + عبارات `3 --0-- 5 == 8` و `--5 == 5` هر دو از لحاظ معنایی درست بوده و مقدارشان برابر `True` است. +- تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح: + - عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی). + - عبارت `'a'[0][0][0][0][0]` نیز از نظر معنایی صحیح است، زیرا پایتون برخلاف زبان‌هایی که از C منشعب شده‌اند، نوع داده‌ای جداگانه‌ای برای کاراکتر ندارد. بنابراین انتخاب یک کاراکتر از یک رشته، منجر به بازگشت یک رشته‌ی تک‌کاراکتری می‌شود. + - عبارات `3 --0-- 5 == 8` و `--5 == 5` هر دو از لحاظ معنایی درست بوده و مقدارشان برابر `True` است. -* با فرض اینکه `a` یک عدد باشد، عبارات `++a` و `--a` هر دو در پایتون معتبر هستند؛ اما رفتاری مشابه با عبارات مشابه در زبان‌هایی مانند C، ++C یا جاوا ندارند. +- با فرض اینکه `a` یک عدد باشد، عبارات `++a` و `--a` هر دو در پایتون معتبر هستند؛ اما رفتاری مشابه با عبارات مشابه در زبان‌هایی مانند C، ++C یا جاوا ندارند. ```py >>> a = 5 @@ -3797,11 +3931,12 @@ 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 (مهاجم فضایی)* شنیده‌اید؟ +- در گرامر پایتون عملگری به‌نام `++` وجود ندارد. در واقع `++` دو عملگر `+` جداگانه است. +- عبارت `++a` به‌شکل `+(+a)` تفسیر می‌شود که معادل `a` است. به‌همین ترتیب، خروجی عبارت `--a` نیز قابل توجیه است. +- این [تاپیک در StackOverflow](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) دلایل نبودن عملگرهای افزایش (`++`) و کاهش (`--`) در پایتون را بررسی می‌کند. + +- احتمالاً با عملگر Walrus (گراز دریایی) در پایتون آشنا هستید؛ اما تا به حال در مورد *عملگر Space-invader (مهاجم فضایی)* شنیده‌اید؟ ```py >>> a = 42 @@ -3809,16 +3944,19 @@ def dict_size(o): >>> a 43 ``` + از آن به‌عنوان جایگزینی برای عملگر افزایش (increment)، در ترکیب با یک عملگر دیگر استفاده می‌شود. + ```py >>> a +=+ 1 >>> a >>> 44 ``` + **💡 توضیح:** این شوخی از [توییت 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) دارد. - +- پایتون یک عملگر مستندنشده برای [استلزام معکوس (converse implication)](https://en.wikipedia.org/wiki/Converse_implication) دارد. + ```py >>> False ** False == True True @@ -3832,7 +3970,7 @@ def dict_size(o): **💡 توضیح:** اگر مقادیر `False` و `True` را به‌ترتیب با اعداد ۰ و ۱ جایگزین کرده و محاسبات را انجام دهید، جدول درستی حاصل، معادل یک عملگر استلزام معکوس خواهد بود. ([منبع](https://github.com/cosmologicon/pywat/blob/master/explanation.md#the-undocumented-converse-implication-operator)) -* حالا که صحبت از عملگرها شد، عملگر `@` نیز برای ضرب ماتریسی در پایتون وجود دارد (نگران نباشید، این بار واقعی است). +- حالا که صحبت از عملگرها شد، عملگر `@` نیز برای ضرب ماتریسی در پایتون وجود دارد (نگران نباشید، این بار واقعی است). ```py >>> import numpy as np @@ -3842,15 +3980,16 @@ def dict_size(o): **💡 توضیح:** عملگر `@` در پایتون ۳٫۵ با در نظر گرفتن نیازهای جامعه علمی اضافه شد. هر شی‌ای می‌تواند متد جادویی `__matmul__` را بازنویسی کند تا رفتار این عملگر را مشخص نماید. -* از پایتون ۳٫۸ به بعد می‌توانید از نحو متداول f-string مانند `f'{some_var=}'` برای اشکال‌زدایی سریع استفاده کنید. مثال, +- از پایتون ۳٫۸ به بعد می‌توانید از نحو متداول f-string مانند `f'{some_var=}'` برای اشکال‌زدایی سریع استفاده کنید. مثال, + ```py >>> some_string = "wtfpython" >>> f'{some_string=}' "some_string='wtfpython'" - ``` + ``` + +- پایتون برای ذخیره‌سازی متغیرهای محلی در توابع از ۲ بایت استفاده می‌کند. از نظر تئوری، این به معنای امکان تعریف حداکثر ۶۵۵۳۶ متغیر در یک تابع است. با این حال، پایتون راهکار مفیدی ارائه می‌کند که می‌توان با استفاده از آن بیش از ۲^۱۶ نام متغیر را ذخیره کرد. کد زیر نشان می‌دهد وقتی بیش از ۶۵۵۳۶ متغیر محلی تعریف شود، در پشته (stack) چه اتفاقی رخ می‌دهد (هشدار: این کد تقریباً ۲^۱۸ خط متن چاپ می‌کند، بنابراین آماده باشید!): -* پایتون برای ذخیره‌سازی متغیرهای محلی در توابع از ۲ بایت استفاده می‌کند. از نظر تئوری، این به معنای امکان تعریف حداکثر ۶۵۵۳۶ متغیر در یک تابع است. با این حال، پایتون راهکار مفیدی ارائه می‌کند که می‌توان با استفاده از آن بیش از ۲^۱۶ نام متغیر را ذخیره کرد. کد زیر نشان می‌دهد وقتی بیش از ۶۵۵۳۶ متغیر محلی تعریف شود، در پشته (stack) چه اتفاقی رخ می‌دهد (هشدار: این کد تقریباً ۲^۱۸ خط متن چاپ می‌کند، بنابراین آماده باشید!): - ```py import dis exec(""" @@ -3862,10 +4001,10 @@ def dict_size(o): 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) در پایتون استفاده کنید. -* گاهی اوقات، متد `print` ممکن است مقادیر را فوراً چاپ نکند. برای مثال، +- چندین رشته (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 @@ -3877,14 +4016,16 @@ def dict_size(o): این کد عبارت `wtfpython` را به دلیل آرگومان `end` پس از ۳ ثانیه چاپ می‌کند؛ چرا که بافر خروجی تنها پس از رسیدن به کاراکتر `\n` یا در زمان اتمام اجرای برنامه تخلیه می‌شود. برای تخلیه‌ی اجباری بافر می‌توانید از آرگومان `flush=True` استفاده کنید. -* برش لیست‌ها (List slicing) با اندیس‌های خارج از محدوده، خطایی ایجاد نمی‌کند. +- برش لیست‌ها (List slicing) با اندیس‌های خارج از محدوده، خطایی ایجاد نمی‌کند. + ```py >>> some_list = [1, 2, 3, 4, 5] >>> some_list[111:] [] ``` -* برش زدن (slicing) یک شئ قابل پیمایش (iterable) همیشه یک شئ جدید ایجاد نمی‌کند. به‌عنوان مثال، +- برش زدن (slicing) یک شئ قابل پیمایش (iterable) همیشه یک شئ جدید ایجاد نمی‌کند. به‌عنوان مثال، + ```py >>> some_str = "wtfpython" >>> some_list = ['w', 't', 'f', 'p', 'y', 't', 'h', 'o', 'n'] @@ -3894,9 +4035,9 @@ def dict_size(o): True ``` -* در پایتون ۳، فراخوانی `int('١٢٣٤٥٦٧٨٩')` مقدار `123456789` را برمی‌گرداند. در پایتون، نویسه‌های ده‌دهی (Decimal characters) شامل تمام ارقامی هستند که می‌توانند برای تشکیل اعداد در مبنای ده استفاده شوند؛ به‌عنوان مثال نویسه‌ی U+0660 که همان رقم صفر عربی-هندی است. [اینجا](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) داستان جالبی درباره این رفتار پایتون آمده است. +- در پایتون ۳، فراخوانی `int('١٢٣٤٥٦٧٨٩')` مقدار `123456789` را برمی‌گرداند. در پایتون، نویسه‌های ده‌دهی (Decimal characters) شامل تمام ارقامی هستند که می‌توانند برای تشکیل اعداد در مبنای ده استفاده شوند؛ به‌عنوان مثال نویسه‌ی U+0660 که همان رقم صفر عربی-هندی است. [اینجا](https://chris.improbable.org/2014/8/25/adventures-in-unicode-digits/) داستان جالبی درباره این رفتار پایتون آمده است. -* از پایتون ۳ به بعد، می‌توانید برای افزایش خوانایی، اعداد را با استفاده از زیرخط (`_`) جدا کنید. +- از پایتون ۳ به بعد، می‌توانید برای افزایش خوانایی، اعداد را با استفاده از زیرخط (`_`) جدا کنید. ```py >>> six_million = 6_000_000 @@ -3907,7 +4048,8 @@ def dict_size(o): 4027435774 ``` -* عبارت `'abc'.count('') == 4` مقدار `True` برمی‌گرداند. در اینجا یک پیاده‌سازی تقریبی از متد `count` آورده شده که این موضوع را شفاف‌تر می‌کند: +- عبارت `'abc'.count('') == 4` مقدار `True` برمی‌گرداند. در اینجا یک پیاده‌سازی تقریبی از متد `count` آورده شده که این موضوع را شفاف‌تر می‌کند: + ```py def count(s, sub): result = 0 @@ -3915,6 +4057,7 @@ def dict_size(o): result += (s[i:i + len(sub)] == sub) return result ``` + این رفتار به این دلیل است که زیررشته‌ی خالی (`''`) با برش‌هایی (slices) به طول صفر در رشته‌ی اصلی مطابقت پیدا می‌کند. --- @@ -3938,17 +4081,17 @@ def dict_size(o): ایده و طراحی این مجموعه ابتدا از پروژه عالی [wtfjs](https://github.com/denysdovhan/wtfjs) توسط Denys Dovhan الهام گرفته شد. حمایت فوق‌العاده‌ جامعه پایتون باعث شد پروژه به شکل امروزی خود درآید. - #### چند لینک جالب! -* 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 -* https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines -* https://stackoverflow.com/questions/1011431/common-pitfalls-in-python -* https://www.python.org/doc/humor/ -* https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator -* https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues -* WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). + +- 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 +- https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines +- https://stackoverflow.com/questions/1011431/common-pitfalls-in-python +- https://www.python.org/doc/humor/ +- https://github.com/cosmologicon/pywat#the-undocumented-converse-implication-operator +- https://github.com/wemake-services/wemake-python-styleguide/search?q=wtfpython&type=Issues +- WFTPython discussion threads on [Hacker News](https://news.ycombinator.com/item?id=21862073) and [Reddit](https://www.reddit.com/r/programming/comments/edsh3q/what_the_fck_python_30_exploring_and/). # 🎓 مجوز @@ -3965,10 +4108,8 @@ def dict_size(o): [توییتر](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) | [لینکدین](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!) | [فیسبوک](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!) - ## آیا به یک نسخه pdf نیاز دارید؟ - من چند درخواست برای نسخه PDF (و epub) کتاب wtfpython دریافت کرده‌ام. برای دریافت این نسخه‌ها به محض آماده شدن، می‌توانید اطلاعات خود را [اینجا](https://form.jotform.com/221593245656057) وارد کنید. **همین بود دوستان!** برای دریافت مطالب آینده مشابه این، می‌توانید ایمیل خود را [اینجا](https://form.jotform.com/221593598380062) اضافه کنید. From 55e5ae206a1b66049226dc8948e601f36da91d9e Mon Sep 17 00:00:00 2001 From: Leo Alavi Date: Tue, 29 Apr 2025 16:11:30 +0200 Subject: [PATCH 208/210] 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 a82e11ef..e1114cc7 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 - - >>> 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 - ``` + ```py + >>> some_set = set() + >>> some_set.add(dictionary) # these are the mapping objects from the snippets above + >>> ordered_dict in some_set + True + >>> some_set.add(ordered_dict) + >>> len(some_set) + 1 + >>> another_ordered_dict in some_set + True + >>> some_set.add(another_ordered_dict) + >>> len(some_set) + 1 + + >>> another_set = set() + >>> another_set.add(ordered_dict) + >>> another_ordered_dict in another_set + False + >>> another_set.add(another_ordered_dict) + >>> len(another_set) + 2 + >>> dictionary in another_set + True + >>> another_set.add(another_ordered_dict) + >>> len(another_set) + 2 + ``` - So the inconsistency is due to `another_ordered_dict in another_set` being `False` because `ordered_dict` was already present in `another_set` and as observed before, `ordered_dict == another_ordered_dict` is `False`. + 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 :) + 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 * +### ▶ 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 + + 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. + 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 22e7eb23..cddeb0b7 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 + + print("wtfpython", end="_") + time.sleep(3) + ``` - این کد عبارت `wtfpython` را به دلیل آرگومان `end` پس از ۳ ثانیه چاپ می‌کند؛ چرا که بافر خروجی تنها پس از رسیدن به کاراکتر `\n` یا در زمان اتمام اجرای برنامه تخلیه می‌شود. برای تخلیه‌ی اجباری بافر می‌توانید از آرگومان `flush=True` استفاده کنید. + این کد عبارت `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) اضافه کنید. From 0a9f1dbaaa63459494edcc5ead0fc5de87c9db0d Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 6 May 2025 16:46:26 +0300 Subject: [PATCH 209/210] Fix markdownlint errors part 1 --- .github/workflows/pr.yml | 3 +- .pre-commit-config.yaml | 2 +- README.md | 116 +++++++++++++++++++++++++++------------ 3 files changed, 83 insertions(+), 38 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 2120da77..034e50c5 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -17,7 +17,8 @@ jobs: - name: Write git diff to temp file run: | git fetch origin - git diff origin/${{ github.base_ref }} --unified=0 *.md translations/*/*.md \ + git diff origin/${{ github.base_ref }} *.md translations/*/*.md \ + | sed -n '/^+/p' | sed '/^+++/d' | sed 's/^+//' \ > ${{ runner.temp }}/diff.md - uses: DavidAnson/markdownlint-cli2-action@v17 with: diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8813a02d..8c241c39 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,6 +2,6 @@ default_language_version: python: python3.12 repos: - repo: https://github.com/DavidAnson/markdownlint-cli2 - rev: v0.14.0 + rev: v0.17.0 hooks: - id: markdownlint-cli2 diff --git a/README.md b/README.md index e1114cc7..e4afe016 100644 --- a/README.md +++ b/README.md @@ -9,19 +9,33 @@

What the f*ck Python! 😱

Exploring and understanding Python through surprising snippets.

-Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | [Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | [Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | [Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | [Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | [German Deutsch](https://github.com/BenSt099/wtfpython) | [Persian فارسی](https://github.com/satwikkansal/wtfpython/tree/master/translations/fa-farsi) | [Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) +Translations: [Chinese 中文](https://github.com/leisurelicht/wtfpython-cn) | +[Vietnamese Tiếng Việt](https://github.com/vuduclyunitn/wtfptyhon-vi) | +[Spanish Español](https://web.archive.org/web/20220511161045/https://github.com/JoseDeFreitas/wtfpython-es) | +[Korean 한국어](https://github.com/buttercrab/wtfpython-ko) | +[Russian Русский](https://github.com/satwikkansal/wtfpython/tree/master/translations/ru-russian) | +[German Deutsch](https://github.com/BenSt099/wtfpython) | +[Persian فارسی](https://github.com/satwikkansal/wtfpython/tree/master/translations/fa-farsi) | +[Add translation](https://github.com/satwikkansal/wtfpython/issues/new?title=Add%20translation%20for%20[LANGUAGE]&body=Expected%20time%20to%20finish:%20[X]%20weeks.%20I%27ll%20start%20working%20on%20it%20from%20[Y].) Other modes: [Interactive Website](https://wtfpython-interactive.vercel.app) | [Interactive Notebook](https://colab.research.google.com/github/satwikkansal/wtfpython/blob/master/irrelevant/wtf.ipynb) -Python, being a beautifully designed high-level and interpreter-based programming language, provides us with many features for the programmer's comfort. But sometimes, the outcomes of a Python snippet may not seem obvious at first sight. +Python, being a beautifully designed high-level and interpreter-based programming language, +provides us with many features for the programmer's comfort. +But sometimes, the outcomes of a Python snippet may not seem obvious at first sight. -Here's a fun project attempting to explain what exactly is happening under the hood for some counter-intuitive snippets and lesser-known features in Python. +Here's a fun project attempting to explain what exactly is happening under the hood for some counter-intuitive snippets +and lesser-known features in Python. -While some of the examples you see below may not be WTFs in the truest sense, but they'll reveal some of the interesting parts of Python that you might be unaware of. I find it a nice way to learn the internals of a programming language, and I believe that you'll find it interesting too! +While some of the examples you see below may not be WTFs in the truest sense, +but they'll reveal some of the interesting parts of Python that you might be unaware of. +I find it a nice way to learn the internals of a programming language, and I believe that you'll find it interesting too! -If you're an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt. You may have already experienced some of them before, and I might be able to revive sweet old memories of yours! :sweat_smile: +If you're an experienced Python programmer, you can take it as a challenge to get most of them right in the first attempt +You may have already experienced some of them before, and I might be able to revive sweet old memories of yours! :sweat_smile: -PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) (the examples marked with asterisk are the ones added in the latest major revision). +PS: If you're a returning reader, you can learn about the new modifications [here](https://github.com/satwikkansal/wtfpython/releases/) +(the examples marked with asterisk are the ones added in the latest major revision). So, here we go... @@ -116,6 +130,8 @@ So, here we go... All the examples are structured like below: +> ## Section: (if necessary) +> > ### ▶ Some fancy Title > > ```py @@ -148,17 +164,20 @@ All the examples are structured like below: > # some justified output > ``` -**Note:** All the examples are tested on Python 3.5.2 interactive interpreter, and they should work for all the Python versions unless explicitly specified before the output. +**Note:** All the examples are tested on Python 3.5.2 interactive interpreter, +and they should work for all the Python versions unless explicitly specified before the output. # Usage A nice way to get the most out of these examples, in my opinion, is to read them in sequential order, and for every example: -- Carefully read the initial code for setting up the example. If you're an experienced Python programmer, you'll successfully anticipate what's going to happen next most of the time. +- Carefully read the initial code for setting up the example. + If you're an experienced Python programmer, you'll successfully anticipate what's going to happen next most of the time. - Read the output snippets and, - Check if the outputs are the same as you'd expect. - Make sure if you know the exact reason behind the output being the way it is. - - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfpython/issues/new)). + - If the answer is no (which is perfectly okay), take a deep breath, and read the explanation + (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfpython/issues/new)). - If yes, give a gentle pat on your back, and you may skip to the next example. --- @@ -170,7 +189,6 @@ A nice way to get the most out of these examples, in my opinion, is to read them ### ▶ First things first! \* - For some reason, the Python 3.8's "Walrus" operator (`:=`) has become quite popular. Let's check it out, @@ -230,9 +248,8 @@ SyntaxError: invalid syntax #### 💡 Explanation -**Quick walrus operator refresher** - -The Walrus operator (`:=`) was introduced in Python 3.8, it can be useful in situations where you'd want to assign values to variables within an expression. +The Walrus operator (`:=`) was introduced in Python 3.8, +it can be useful in situations where you'd want to assign values to variables within an expression. ```py def some_func(): @@ -264,12 +281,13 @@ 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`. - -- As usual, parenthesizing of an expression containing `=` operator is not allowed. Hence the syntax error in `(a, b = 6, 9)`. - -- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier, and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, - +- 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)`. +- The syntax of the Walrus operator is of the form `NAME:= expr`, where `NAME` is a valid identifier, + and `expr` is a valid expression. Hence, iterable packing and unpacking are not supported which means, - `(a := 6, 9)` is equivalent to `((a := 6), 9)` and ultimately `(a, 9)` (where `a`'s value is 6') ```py @@ -319,7 +337,7 @@ a = "wtf!"; b = "wtf!" assert a is b ``` -4\. **Disclaimer - snippet is not relavant in modern Python versions** +4\. **Disclaimer - snippet is not relevant in modern Python versions** **Output (< Python3.7 )** @@ -334,12 +352,15 @@ Makes sense, right? #### 💡 Explanation: -- The behavior in first and second snippets is due to a CPython optimization (called string interning) that tries to use existing immutable objects in some cases rather than creating a new object every time. +- 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: +- In the snippets above, strings are implicitly interned. The decision of when to implicitly intern a string is + implementation-dependent. There are some rules that can be used to guess if a string will be interned or not: - All length 0 and length 1 strings are interned. - Strings are interned at compile time (`'wtf'` will be interned but `''.join(['w', 't', 'f'])` will not be interned) - - Strings that are not composed of ASCII letters, digits or underscores, are not interned. This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19) + - Strings that are not composed of ASCII letters, digits or underscores, are not interned. + This explains why `'wtf!'` was not interned due to `!`. CPython implementation of this rule can be found [here](https://github.com/python/cpython/blob/3.6/Objects/codeobject.c#L19)

@@ -349,10 +370,25 @@ 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. -- 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). +- 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. +- 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). --- @@ -385,19 +421,23 @@ False As per https://docs.python.org/3/reference/expressions.html#comparisons -> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once. +> Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, + then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, + except that each expression is evaluated at most once. -While such behavior might seem silly to you in the above examples, it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. +While such behavior might seem silly to you in the above examples, +it's fantastic with stuff like `a == b == c` and `0 <= x <= 100`. - `False is False is False` is equivalent to `(False is False) and (False is False)` -- `True is False == False` is equivalent to `(True is False) and (False == False)` and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. +- `True is False == False` is equivalent to `(True is False) and (False == False)` + and since the first part of the statement (`True is False`) evaluates to `False`, the overall expression evaluates to `False`. - `1 > 0 < 1` is equivalent to `(1 > 0) and (0 < 1)` which evaluates to `True`. - The expression `(1 > 0) < 1` is equivalent to `True < 1` and ```py >>> int(True) 1 - >>> True + 1 #not relevant for this example, but just for fun + >>> True + 1 # not relevant for this example, but just for fun 2 ``` @@ -1079,7 +1119,11 @@ 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 @@ -1313,10 +1357,10 @@ Accessing `classm` or `method` twice, creates equal but not _same_ objects for t ``` - 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 :) +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 \* From a6a64732553f91229457dcb05f1e0c905c822656 Mon Sep 17 00:00:00 2001 From: Vadim Nifadev <36514612+nifadyev@users.noreply.github.com> Date: Tue, 6 May 2025 16:48:44 +0300 Subject: [PATCH 210/210] Fix markdownlint errors part 1 --- .github/workflows/pr.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 034e50c5..8356b6f8 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -20,6 +20,9 @@ jobs: git diff origin/${{ github.base_ref }} *.md translations/*/*.md \ | sed -n '/^+/p' | sed '/^+++/d' | sed 's/^+//' \ > ${{ runner.temp }}/diff.md - - uses: DavidAnson/markdownlint-cli2-action@v17 + - name: Output diff + run: cat ${{ runner.temp }}/diff.md + - name: Check diff with markdownlint + uses: DavidAnson/markdownlint-cli2-action@v17 with: globs: "${{ runner.temp }}/diff.md"