1
0
mirror of https://github.com/satwikkansal/wtfpython synced 2025-05-19 18:53:46 +02:00

Fix liniting issues

This commit is contained in:
Leo Alavi 2025-04-29 16:11:30 +02:00
parent c5e2b94ab0
commit 55e5ae206a
2 changed files with 844 additions and 597 deletions

231
README.md vendored
View File

@ -1,3 +1,4 @@
<!-- markdownlint-disable MD013 -->
<p align="center"> <p align="center">
<picture> <picture>
<source media="(prefers-color-scheme: dark)" srcset="/images/logo_dark_theme.svg"> <source media="(prefers-color-scheme: dark)" srcset="/images/logo_dark_theme.svg">
@ -35,23 +36,23 @@ So, here we go...
- [Usage](#usage) - [Usage](#usage)
- [👀 Examples](#-examples) - [👀 Examples](#-examples)
- [Section: Strain your brain!](#section-strain-your-brain) - [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) - [ Strings can be tricky sometimes](#-strings-can-be-tricky-sometimes)
- [ Be careful with chained operations](#-be-careful-with-chained-operations) - [ Be careful with chained operations](#-be-careful-with-chained-operations)
- [ How not to use `is` operator](#-how-not-to-use-is-operator) - [ How not to use `is` operator](#-how-not-to-use-is-operator)
- [ Hash brownies](#-hash-brownies) - [ Hash brownies](#-hash-brownies)
- [ Deep down, we're all the same.](#-deep-down-were-all-the-same) - [ Deep down, we're all the same.](#-deep-down-were-all-the-same)
- [ Disorder within order *](#-disorder-within-order-) - [ Disorder within order \*](#-disorder-within-order-)
- [ Keep trying... *](#-keep-trying-) - [ Keep trying... \*](#-keep-trying-)
- [ For what?](#-for-what) - [ For what?](#-for-what)
- [ Evaluation time discrepancy](#-evaluation-time-discrepancy) - [ Evaluation time discrepancy](#-evaluation-time-discrepancy)
- [ `is not ...` is not `is (not ...)`](#-is-not--is-not-is-not-) - [ `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) - [ 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-) - [ 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) - [ Subclass relationships](#-subclass-relationships)
- [ Methods equality and identity](#-methods-equality-and-identity) - [ 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) - [ The surprising comma](#-the-surprising-comma)
- [ Strings and the backslashes](#-strings-and-the-backslashes) - [ Strings and the backslashes](#-strings-and-the-backslashes)
- [ not knot!](#-not-knot) - [ not knot!](#-not-knot)
@ -59,8 +60,8 @@ So, here we go...
- [ What's wrong with booleans?](#-whats-wrong-with-booleans) - [ What's wrong with booleans?](#-whats-wrong-with-booleans)
- [ Class attributes and instance attributes](#-class-attributes-and-instance-attributes) - [ Class attributes and instance attributes](#-class-attributes-and-instance-attributes)
- [ yielding None](#-yielding-none) - [ yielding None](#-yielding-none)
- [ Yielding from... return! *](#-yielding-from-return-) - [ Yielding from... return! \*](#-yielding-from-return-)
- [ Nan-reflexivity *](#-nan-reflexivity-) - [ Nan-reflexivity \*](#-nan-reflexivity-)
- [ Mutating the immutable!](#-mutating-the-immutable) - [ Mutating the immutable!](#-mutating-the-immutable)
- [ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope) - [ The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope)
- [ The mysterious key type conversion](#-the-mysterious-key-type-conversion) - [ The mysterious key type conversion](#-the-mysterious-key-type-conversion)
@ -71,17 +72,17 @@ So, here we go...
- [ Stubborn `del` operation](#-stubborn-del-operation) - [ Stubborn `del` operation](#-stubborn-del-operation)
- [ The out of scope variable](#-the-out-of-scope-variable) - [ The out of scope variable](#-the-out-of-scope-variable)
- [ Deleting a list item while iterating](#-deleting-a-list-item-while-iterating) - [ 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) - [ Loop variables leaking out!](#-loop-variables-leaking-out)
- [ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments) - [ Beware of default mutable arguments!](#-beware-of-default-mutable-arguments)
- [ Catching the Exceptions](#-catching-the-exceptions) - [ Catching the Exceptions](#-catching-the-exceptions)
- [ Same operands, different story!](#-same-operands-different-story) - [ Same operands, different story!](#-same-operands-different-story)
- [ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope) - [ Name resolution ignoring class scope](#-name-resolution-ignoring-class-scope)
- [ Rounding like a banker *](#-rounding-like-a-banker-) - [ Rounding like a banker \*](#-rounding-like-a-banker-)
- [ Needles in a Haystack *](#-needles-in-a-haystack-) - [ Needles in a Haystack \*](#-needles-in-a-haystack-)
- [ Splitsies *](#-splitsies-) - [ Splitsies \*](#-splitsies-)
- [ Wild imports *](#-wild-imports-) - [ Wild imports \*](#-wild-imports-)
- [ All sorted? *](#-all-sorted-) - [ All sorted? \*](#-all-sorted-)
- [ Midnight time doesn't exist?](#-midnight-time-doesnt-exist) - [ Midnight time doesn't exist?](#-midnight-time-doesnt-exist)
- [Section: The Hidden treasures!](#section-the-hidden-treasures) - [Section: The Hidden treasures!](#section-the-hidden-treasures)
- [ Okay Python, Can you make me fly?](#-okay-python-can-you-make-me-fly) - [ 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) - [ 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) - [ Even Python understands that love is complicated](#-even-python-understands-that-love-is-complicated)
- [ Yes, it exists!](#-yes-it-exists) - [ Yes, it exists!](#-yes-it-exists)
- [ Ellipsis *](#-ellipsis-) - [ Ellipsis \*](#-ellipsis-)
- [ Inpinity](#-inpinity) - [ Inpinity](#-inpinity)
- [ Let's mangle](#-lets-mangle) - [ Let's mangle](#-lets-mangle)
- [Section: Appearances are deceptive!](#section-appearances-are-deceptive) - [Section: Appearances are deceptive!](#section-appearances-are-deceptive)
@ -100,9 +101,9 @@ So, here we go...
- [Section: Miscellaneous](#section-miscellaneous) - [Section: Miscellaneous](#section-miscellaneous)
- [ `+=` is faster](#--is-faster) - [ `+=` is faster](#--is-faster)
- [ Let's make a giant string!](#-lets-make-a-giant-string) - [ 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-) - [ Bloating instance `dict`s \*](#-bloating-instance-dicts-)
- [ Minor Ones *](#-minor-ones-) - [ Minor Ones \*](#-minor-ones-)
- [Contributing](#contributing) - [Contributing](#contributing)
- [Acknowledgements](#acknowledgements) - [Acknowledgements](#acknowledgements)
- [🎓 License](#-license) - [🎓 License](#-license)
@ -131,7 +132,6 @@ All the examples are structured like below:
> >
> (Optional): One line describing the unexpected output. > (Optional): One line describing the unexpected output.
> >
>
> #### 💡 Explanation: > #### 💡 Explanation:
> >
> - Brief explanation of what's happening and why is it happening. > - 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! ## Section: Strain your brain!
### ▶ First things first! * ### ▶ First things first! \*
<!-- Example ID: d3d73936-3cf1-4632-b5ab-817981338863 --> <!-- Example ID: d3d73936-3cf1-4632-b5ab-817981338863 -->
<!-- read-only --> <!-- read-only -->
@ -319,7 +319,7 @@ a = "wtf!"; b = "wtf!"
assert a is b 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 )** **Output (< Python3.7 )**
@ -333,6 +333,7 @@ False
Makes sense, right? Makes sense, right?
#### 💡 Explanation: #### 💡 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). - 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:
@ -356,7 +357,9 @@ Makes sense, right?
--- ---
### ▶ Be careful with chained operations ### ▶ Be careful with chained operations
<!-- Example ID: 07974979-9c86-4720-80bd-467aa19470d9 ---> <!-- Example ID: 07974979-9c86-4720-80bd-467aa19470d9 --->
```py ```py
>>> (False == False) in [False] # makes sense >>> (False == False) in [False] # makes sense
False 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 ### ▶ How not to use `is` operator
<!-- Example ID: 230fa2ac-ab36-4ad1-b675-5f5a1c1a6217 ---> <!-- Example ID: 230fa2ac-ab36-4ad1-b675-5f5a1c1a6217 --->
The following is a very famous example present all over the internet. The following is a very famous example present all over the internet.
1\. 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. 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 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. :-) > 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 ```py
@ -528,7 +534,9 @@ Similar optimization applies to other **immutable** objects like empty tuples as
--- ---
### ▶ Hash brownies ### ▶ Hash brownies
<!-- Example ID: eb17db53-49fd-4b61-85d6-345c5ca213ff ---> <!-- Example ID: eb17db53-49fd-4b61-85d6-345c5ca213ff --->
1\. 1\.
```py ```py
@ -559,7 +567,7 @@ So, why is Python all over the place?
#### 💡 Explanation #### 💡 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 ```py
>>> 5 == 5.0 == 5 + 0j >>> 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) >>> (5 in some_dict) and (5 + 0j in some_dict)
True 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 ```py
@ -582,6 +591,7 @@ So, why is Python all over the place?
>>> some_dict >>> some_dict
{5.0: 'Python'} {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.
@ -593,12 +603,14 @@ So, why is Python all over the place?
True 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](<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. ### ▶ Deep down, we're all the same.
<!-- Example ID: 8f99a35f-1736-43e2-920d-3b78ec35da9b ---> <!-- Example ID: 8f99a35f-1736-43e2-920d-3b78ec35da9b --->
```py ```py
class WTF: class WTF:
pass pass
@ -651,8 +663,10 @@ True
--- ---
### ▶ Disorder within order * ### ▶ Disorder within order \*
<!-- Example ID: 91bff1f8-541d-455a-9de4-6cd8ff00ea66 ---> <!-- Example ID: 91bff1f8-541d-455a-9de4-6cd8ff00ea66 --->
```py ```py
from collections import OrderedDict from collections import OrderedDict
@ -717,6 +731,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) - 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. - 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, - 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,
@ -752,8 +767,10 @@ What is going on here?
--- ---
### ▶ Keep trying... * ### ▶ Keep trying... \*
<!-- Example ID: b4349443-e89f-4d25-a109-82616be9d41a ---> <!-- Example ID: b4349443-e89f-4d25-a109-82616be9d41a --->
```py ```py
def some_func(): def some_func():
try: try:
@ -813,7 +830,9 @@ Iteration 0
--- ---
### ▶ For what? ### ▶ For what?
<!-- Example ID: 64a9dccf-5083-4bc9-98aa-8aeecde4f210 ---> <!-- Example ID: 64a9dccf-5083-4bc9-98aa-8aeecde4f210 --->
```py ```py
some_string = "wtf" some_string = "wtf"
some_dict = {} some_dict = {}
@ -872,7 +891,9 @@ for i, some_dict[i] in enumerate(some_string):
--- ---
### ▶ Evaluation time discrepancy ### ▶ Evaluation time discrepancy
<!-- Example ID: 6aa11a4b-4cf1-467a-b43a-810731517e98 ---> <!-- Example ID: 6aa11a4b-4cf1-467a-b43a-810731517e98 --->
1\. 1\.
```py ```py
@ -943,7 +964,9 @@ array_4 = [400, 500, 600]
--- ---
### ▶ `is not ...` is not `is (not ...)` ### ▶ `is not ...` is not `is (not ...)`
<!-- Example ID: b26fb1ed-0c7d-4b9c-8c6d-94a58a055c0d ---> <!-- Example ID: b26fb1ed-0c7d-4b9c-8c6d-94a58a055c0d --->
```py ```py
>>> 'something' is not None >>> 'something' is not None
True True
@ -960,6 +983,7 @@ False
--- ---
### ▶ A tic-tac-toe where X wins in the first attempt! ### ▶ A tic-tac-toe where X wins in the first attempt!
<!-- Example ID: 69329249-bdcb-424f-bd09-cca2e6705a7a ---> <!-- Example ID: 69329249-bdcb-424f-bd09-cca2e6705a7a --->
```py ```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 \*
<!-- Example ID: 4dc42f77-94cb-4eb5-a120-8203d3ed7604 ---> <!-- Example ID: 4dc42f77-94cb-4eb5-a120-8203d3ed7604 --->
```py ```py
@ -1053,7 +1078,8 @@ The values of `x` were different in every iteration prior to appending `some_fun
``` ```
#### 💡 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:
- 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 ```py
>>> import inspect >>> 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] [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 ```py
funcs = [] funcs = []
@ -1096,8 +1122,10 @@ ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set())
--- ---
### ▶ The chicken-egg problem * ### ▶ The chicken-egg problem \*
<!-- Example ID: 60730dc2-0d79-4416-8568-2a63323b3ce8 ---> <!-- Example ID: 60730dc2-0d79-4416-8568-2a63323b3ce8 --->
1\. 1\.
```py ```py
@ -1147,7 +1175,9 @@ False
--- ---
### ▶ Subclass relationships ### ▶ Subclass relationships
<!-- Example ID: 9f6d8cf0-e1b5-42d0-84a0-4cfab25a0bc0 ---> <!-- Example ID: 9f6d8cf0-e1b5-42d0-84a0-4cfab25a0bc0 --->
**Output:** **Output:**
```py ```py
@ -1160,7 +1190,7 @@ True
False 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: #### 💡 Explanation:
@ -1172,6 +1202,7 @@ The Subclass relationships were expected to be transitive, right? (i.e., if `A`
--- ---
### ▶ Methods equality and identity ### ▶ Methods equality and identity
<!-- Example ID: 94802911-48fe-4242-defa-728ae893fa32 ---> <!-- Example ID: 94802911-48fe-4242-defa-728ae893fa32 --->
1. 1.
@ -1203,7 +1234,7 @@ True
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`: with instances of `SomeClass`:
2. 2.
@ -1230,9 +1261,10 @@ True
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 #### 💡 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, 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 attribute. If called, the method calls the function, implicitly passing the bound object as the first argument
@ -1242,6 +1274,7 @@ attribute. If called, the method calls the function, implicitly passing the boun
>>> o1.method >>> o1.method
<bound method SomeClass.method of <__main__.SomeClass object at ...>> <bound method SomeClass.method of <__main__.SomeClass object at ...>>
``` ```
- 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 never truthy. Accessing functions as class attributes (as opposed to instance) does not create methods, however; so
`SomeClass.method is SomeClass.method` is truthy. `SomeClass.method is SomeClass.method` is truthy.
@ -1250,13 +1283,15 @@ never truthy. Accessing functions as class attributes (as opposed to instance) d
>>> SomeClass.method >>> SomeClass.method
<function SomeClass.method at ...> <function SomeClass.method at ...>
``` ```
- `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. a method object which binds the _class_ (type) of the object, instead of the object itself.
```py ```py
>>> o1.classm >>> o1.classm
<bound method SomeClass.classm of <class '__main__.SomeClass'>> <bound method SomeClass.classm of <class '__main__.SomeClass'>>
``` ```
- 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. bind the class, not to the type of it). So `SomeClass.classm is SomeClass.classm` is falsy.
@ -1264,6 +1299,7 @@ bind the class, not to the type of it). So `SomeClass.classm is SomeClass.classm
>>> SomeClass.classm >>> SomeClass.classm
<bound method SomeClass.classm of <class '__main__.SomeClass'>> <bound method SomeClass.classm of <class '__main__.SomeClass'>>
``` ```
- 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. `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
@ -1275,13 +1311,14 @@ objects are ever created, so comparison with `is` is truthy.
>>> SomeClass.staticm >>> SomeClass.staticm
<function SomeClass.staticm at ...> <function SomeClass.staticm at ...>
``` ```
- 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. 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 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 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 :) snippets here are not affected, and still generate methods :)
### ▶ All-true-ation * ### ▶ All-true-ation \*
<!-- Example ID: dfe6d845-e452-48fe-a2da-0ed3869a8042 --> <!-- Example ID: dfe6d845-e452-48fe-a2da-0ed3869a8042 -->
@ -1320,7 +1357,9 @@ Why's this True-False alteration?
--- ---
### ▶ The surprising comma ### ▶ The surprising comma
<!-- Example ID: 31a819c8-ed73-4dcc-84eb-91bedbb51e58 ---> <!-- Example ID: 31a819c8-ed73-4dcc-84eb-91bedbb51e58 --->
**Output (< 3.6):** **Output (< 3.6):**
```py ```py
@ -1352,7 +1391,9 @@ SyntaxError: invalid syntax
--- ---
### ▶ Strings and the backslashes ### ▶ Strings and the backslashes
<!-- Example ID: 6ae622c3-6d99-4041-9b33-507bd1a4407b ---> <!-- Example ID: 6ae622c3-6d99-4041-9b33-507bd1a4407b --->
**Output:** **Output:**
```py ```py
@ -1400,7 +1441,9 @@ True
--- ---
### ▶ not knot! ### ▶ not knot!
<!-- Example ID: 7034deb1-7443-417d-94ee-29a800524de8 ---> <!-- Example ID: 7034deb1-7443-417d-94ee-29a800524de8 --->
```py ```py
x = True x = True
y = False y = False
@ -1428,7 +1471,9 @@ SyntaxError: invalid syntax
--- ---
### ▶ Half triple-quoted strings ### ▶ Half triple-quoted strings
<!-- Example ID: c55da3e2-1034-43b9-abeb-a7a970a2ad9e ---> <!-- Example ID: c55da3e2-1034-43b9-abeb-a7a970a2ad9e --->
**Output:** **Output:**
```py ```py
@ -1446,6 +1491,7 @@ SyntaxError: EOF while scanning triple-quoted string literal
``` ```
#### 💡 Explanation: #### 💡 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,
``` ```
@ -1454,12 +1500,15 @@ SyntaxError: EOF while scanning triple-quoted string literal
>>> print("wtf" "") # or "wtf""" >>> print("wtf" "") # or "wtf"""
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.
--- ---
### ▶ What's wrong with booleans? ### ▶ What's wrong with booleans?
<!-- Example ID: 0bba5fa7-9e6d-4cd2-8b94-952d061af5dd ---> <!-- Example ID: 0bba5fa7-9e6d-4cd2-8b94-952d061af5dd --->
1\. 1\.
```py ```py
@ -1550,7 +1599,9 @@ I have lost faith in truth!
--- ---
### ▶ Class attributes and instance attributes ### ▶ Class attributes and instance attributes
<!-- Example ID: 6f332208-33bd-482d-8106-42863b739ed9 ---> <!-- Example ID: 6f332208-33bd-482d-8106-42863b739ed9 --->
1\. 1\.
```py ```py
@ -1623,7 +1674,9 @@ True
--- ---
### ▶ yielding None ### ▶ yielding None
<!-- Example ID: 5a40c241-2c30-40d0-8ba9-cf7e097b3b53 ---> <!-- Example ID: 5a40c241-2c30-40d0-8ba9-cf7e097b3b53 --->
```py ```py
some_iterable = ('a', 'b') some_iterable = ('a', 'b')
@ -1655,8 +1708,10 @@ def some_func(val):
--- ---
### ▶ Yielding from... return! * ### ▶ Yielding from... return! \*
<!-- Example ID: 5626d8ef-8802-49c2-adbc-7cda5c550816 ---> <!-- Example ID: 5626d8ef-8802-49c2-adbc-7cda5c550816 --->
1\. 1\.
```py ```py
@ -1720,7 +1775,7 @@ The same result, this didn't work either.
--- ---
### ▶ Nan-reflexivity * ### ▶ Nan-reflexivity \*
<!-- Example ID: 59bee91a-36e0-47a4-8c7d-aa89bf1d3976 ---> <!-- Example ID: 59bee91a-36e0-47a4-8c7d-aa89bf1d3976 --->
@ -1826,6 +1881,7 @@ But I thought tuples were immutable...
- Quoting from https://docs.python.org/3/reference/datamodel.html - 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.) 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. - `+=` 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 ### ▶ The disappearing variable from outer scope
<!-- Example ID: 7f1e71b6-cb3e-44fb-aa47-87ef1b7decc8 ---> <!-- Example ID: 7f1e71b6-cb3e-44fb-aa47-87ef1b7decc8 --->
```py ```py
@ -1919,7 +1976,9 @@ NameError: name 'e' is not defined
--- ---
### ▶ The mysterious key type conversion ### ▶ The mysterious key type conversion
<!-- Example ID: 00f42dd0-b9ef-408d-9e39-1bc209ce3f36 ---> <!-- Example ID: 00f42dd0-b9ef-408d-9e39-1bc209ce3f36 --->
```py ```py
class SomeClass(str): class SomeClass(str):
pass pass
@ -1978,7 +2037,9 @@ str
--- ---
### ▶ Let's see if you can guess this? ### ▶ Let's see if you can guess this?
<!-- Example ID: 81aa9fbe-bd63-4283-b56d-6fdd14c9105e ---> <!-- Example ID: 81aa9fbe-bd63-4283-b56d-6fdd14c9105e --->
```py ```py
a, b = a[b] = {}, 5 a, b = a[b] = {}, 5
``` ```
@ -2083,7 +2144,9 @@ Fortunately, you can increase the limit for the allowed number of digits when yo
## Section: Slippery Slopes ## Section: Slippery Slopes
### ▶ Modifying a dictionary while iterating over it ### ▶ Modifying a dictionary while iterating over it
<!-- Example ID: b4e5cdfb-c3a8-4112-bd38-e2356d801c41 ---> <!-- Example ID: b4e5cdfb-c3a8-4112-bd38-e2356d801c41 --->
```py ```py
x = {0: None} x = {0: None}
@ -2119,6 +2182,7 @@ Yes, it runs for exactly **eight** times and stops.
--- ---
### ▶ Stubborn `del` operation ### ▶ Stubborn `del` operation
<!-- Example ID: 777ed4fd-3a2d-466f-95e7-c4058e61d78e ---> <!-- Example ID: 777ed4fd-3a2d-466f-95e7-c4058e61d78e --->
<!-- read-only --> <!-- read-only -->
@ -2158,6 +2222,7 @@ Deleted!
Okay, now it's deleted :confused: Okay, now it's deleted :confused:
#### 💡 Explanation: #### 💡 Explanation:
- `del x` doesnt directly call `x.__del__()`. - `del x` doesnt 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. - 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. - 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 ### ▶ The out of scope variable
<!-- Example ID: 75c03015-7be9-4289-9e22-4f5fdda056f7 ---> <!-- Example ID: 75c03015-7be9-4289-9e22-4f5fdda056f7 --->
1\. 1\.
@ -2212,6 +2278,7 @@ UnboundLocalError: local variable 'a' referenced before assignment
``` ```
#### 💡 Explanation: #### 💡 Explanation:
- When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error. - When you make an assignment to a variable in scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope, which throws an error.
- To modify the outer scope variable `a` in `another_func`, we have to use the `global` keyword. - 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() >>> another_func()
2 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. - 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. - 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() >>> another_func()
2 2
``` ```
- The keywords `global` and `nonlocal` tell the python interpreter to not declare 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. - 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 ### ▶ Deleting a list item while iterating
<!-- Example ID: 4cc52d4e-d42b-4e09-b25f-fbf5699b7d4e ---> <!-- Example ID: 4cc52d4e-d42b-4e09-b25f-fbf5699b7d4e --->
```py ```py
list_1 = [1, 2, 3, 4] list_1 = [1, 2, 3, 4]
list_2 = [1, 2, 3, 4] list_2 = [1, 2, 3, 4]
@ -2301,6 +2372,7 @@ Can you guess why the output is `[2, 4]`?
``` ```
**Difference between `del`, `remove`, and `pop`:** **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). - `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. - `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. - `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 \*
<!-- Example ID: c28ed154-e59f-4070-8eb6-8967a4acac6d ---> <!-- Example ID: c28ed154-e59f-4070-8eb6-8967a4acac6d --->
```py ```py
@ -2369,7 +2442,9 @@ Where did element `3` go from the `numbers` list?
--- ---
### ▶ Loop variables leaking out! ### ▶ Loop variables leaking out!
<!-- Example ID: ccec7bf6-7679-4963-907a-1cd8587be9ea ---> <!-- Example ID: ccec7bf6-7679-4963-907a-1cd8587be9ea --->
1\. 1\.
```py ```py
@ -2439,6 +2514,7 @@ print(x, ': x in global')
--- ---
### ▶ Beware of default mutable arguments! ### ▶ Beware of default mutable arguments!
<!-- Example ID: 7d42dade-e20d-4a7b-9ed7-16fb58505fe9 ---> <!-- Example ID: 7d42dade-e20d-4a7b-9ed7-16fb58505fe9 --->
```py ```py
@ -2499,7 +2575,9 @@ def some_func(default_arg=[]):
--- ---
### ▶ Catching the Exceptions ### ▶ Catching the Exceptions
<!-- Example ID: b5ca5e6a-47b9-4f69-9375-cda0f8c6755d ---> <!-- Example ID: b5ca5e6a-47b9-4f69-9375-cda0f8c6755d --->
```py ```py
some_list = [1, 2, 3] some_list = [1, 2, 3]
try: try:
@ -2584,7 +2662,9 @@ SyntaxError: invalid syntax
--- ---
### ▶ Same operands, different story! ### ▶ Same operands, different story!
<!-- Example ID: ca052cdf-dd2d-4105-b936-65c28adc18a0 ---> <!-- Example ID: ca052cdf-dd2d-4105-b936-65c28adc18a0 --->
1\. 1\.
```py ```py
@ -2621,7 +2701,7 @@ a += [5, 6, 7, 8]
#### 💡 Explanation: #### 💡 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.
@ -2630,7 +2710,9 @@ a += [5, 6, 7, 8]
--- ---
### ▶ Name resolution ignoring class scope ### ▶ Name resolution ignoring class scope
<!-- Example ID: 03f73d96-151c-4929-b0a8-f74430788324 ---> <!-- Example ID: 03f73d96-151c-4929-b0a8-f74430788324 --->
1\. 1\.
```py ```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: 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 \*
<!-- Example ID: 52a199b1-989a-4b28-8910-dff562cebba9 ---> <!-- Example ID: 52a199b1-989a-4b28-8910-dff562cebba9 --->
@ -2907,8 +2989,10 @@ def similar_recursive_func(a):
--- ---
### ▶ Splitsies * ### ▶ Splitsies \*
<!-- Example ID: ec3168ba-a81a-4482-afb0-691f1cc8d65a ---> <!-- Example ID: ec3168ba-a81a-4482-afb0-691f1cc8d65a --->
```py ```py
>>> 'a'.split() >>> 'a'.split()
['a'] ['a']
@ -2944,7 +3028,8 @@ def similar_recursive_func(a):
--- ---
### ▶ Wild imports * ### ▶ Wild imports \*
<!-- Example ID: 83deb561-bd55-4461-bb5e-77dd7f411e1c ---> <!-- Example ID: 83deb561-bd55-4461-bb5e-77dd7f411e1c --->
<!-- read-only --> <!-- read-only -->
@ -3007,7 +3092,7 @@ NameError: name '_another_weird_name_func' is not defined
--- ---
### ▶ All sorted? * ### ▶ All sorted? \*
<!-- Example ID: e5ff1eaf-8823-4738-b4ce-b73f7c9d5511 --> <!-- Example ID: e5ff1eaf-8823-4738-b4ce-b73f7c9d5511 -->
@ -3049,7 +3134,9 @@ False
--- ---
### ▶ Midnight time doesn't exist? ### ▶ Midnight time doesn't exist?
<!-- Example ID: 1bce8294-5619-4d70-8ce3-fe0bade690d1 ---> <!-- Example ID: 1bce8294-5619-4d70-8ce3-fe0bade690d1 --->
```py ```py
from datetime import datetime 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." 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! ## 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). 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? ### ▶ Okay Python, Can you make me fly?
<!-- Example ID: a92f3645-1899-4d50-9721-0031be4aec3f ---> <!-- Example ID: a92f3645-1899-4d50-9721-0031be4aec3f --->
Well, here you go Well, here you go
```py ```py
@ -3097,6 +3187,7 @@ import antigravity
Sshh... It's a super-secret. Sshh... It's a super-secret.
#### 💡 Explanation: #### 💡 Explanation:
- `antigravity` module is one of the few easter eggs released by Python developers. - `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. - `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/). - 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? ### ▶ `goto`, but why?
<!-- Example ID: 2aff961e-7fa5-4986-a18a-9e5894bd89fe ---> <!-- Example ID: 2aff961e-7fa5-4986-a18a-9e5894bd89fe --->
```py ```py
@ -3135,7 +3227,9 @@ Freedom!
--- ---
### ▶ Brace yourself! ### ▶ Brace yourself!
<!-- Example ID: 5c0c75f2-ddd9-4da3-ba49-c4be7ec39acf ---> <!-- Example ID: 5c0c75f2-ddd9-4da3-ba49-c4be7ec39acf --->
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, 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 ```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)? 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: #### 💡 Explanation:
- The `__future__` module is normally used to provide features from future versions of Python. The "future" in this specific context is however, ironic. - The `__future__` module is normally used to provide features from future versions of Python. The "future" in this specific context is however, ironic.
- This is an easter egg concerned with the community's feelings on this issue. - 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. - 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 ### ▶ Let's meet Friendly Language Uncle For Life
<!-- Example ID: 6427fae6-e959-462d-85da-ce4c94ce41be ---> <!-- Example ID: 6427fae6-e959-462d-85da-ce4c94ce41be --->
**Output (Python 3.x)** **Output (Python 3.x)**
```py ```py
@ -3184,6 +3281,7 @@ There we go.
- Quoting from the PEP-401 - Quoting from the PEP-401
> Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling. > Recognized that the != inequality operator in Python 3.0 was a horrible, finger-pain inducing mistake, the FLUFL reinstates the <> diamond operator as the sole spelling.
- There were more things that Uncle Barry had to share in the PEP; you can read them [here](https://www.python.org/dev/peps/pep-0401/). - 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, - 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,
@ -3195,7 +3293,9 @@ There we go.
--- ---
### ▶ Even Python understands that love is complicated ### ▶ Even Python understands that love is complicated
<!-- Example ID: b93cad9e-d341-45d1-999c-fcdce65bed25 ---> <!-- Example ID: b93cad9e-d341-45d1-999c-fcdce65bed25 --->
```py ```py
import this import this
``` ```
@ -3253,7 +3353,9 @@ True
--- ---
### ▶ Yes, it exists! ### ▶ Yes, it exists!
<!-- Example ID: 4286db3d-1ea7-47c9-8fb6-a9a04cac6e49 ---> <!-- Example ID: 4286db3d-1ea7-47c9-8fb6-a9a04cac6e49 --->
**The `else` clause for loops.** One typical example might be: **The `else` clause for loops.** One typical example might be:
```py ```py
@ -3300,8 +3402,10 @@ Try block executed successfully...
--- ---
### ▶ Ellipsis * ### ▶ Ellipsis \*
<!-- Example ID: 969b7100-ab3d-4a7d-ad7d-a6be16181b2b ---> <!-- Example ID: 969b7100-ab3d-4a7d-ad7d-a6be16181b2b --->
```py ```py
def some_func(): def some_func():
Ellipsis Ellipsis
@ -3332,6 +3436,7 @@ Ellipsis
``` ```
- Ellipsis 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) - 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 - 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]`) 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, ...]`)) - 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). - 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 ### ▶ Inpinity
<!-- Example ID: ff473ea8-a3b1-4876-a6f0-4378aff790c1 ---> <!-- Example ID: ff473ea8-a3b1-4876-a6f0-4378aff790c1 --->
The spelling is intended. Please, don't submit a patch for this. The spelling is intended. Please, don't submit a patch for this.
**Output (Python 3.x):** **Output (Python 3.x):**
@ -3390,7 +3498,9 @@ The spelling is intended. Please, don't submit a patch for this.
--- ---
### ▶ Let's mangle ### ▶ Let's mangle
<!-- Example ID: 37146d2d-9e67-43a9-8729-3c17934b910c ---> <!-- Example ID: 37146d2d-9e67-43a9-8729-3c17934b910c --->
1\. 1\.
```py ```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. - Also, if the mangled name is longer than 255 characters, truncation will happen.
--- ---
--- ---
## Section: Appearances are deceptive! ## Section: Appearances are deceptive!
### ▶ Skipping lines? ### ▶ Skipping lines?
<!-- Example ID: d50bbde1-fb9d-4735-9633-3444b9d2f417 ---> <!-- Example ID: d50bbde1-fb9d-4735-9633-3444b9d2f417 --->
**Output:** **Output:**
```py ```py
@ -3543,7 +3656,9 @@ Where's the Nobel Prize?
--- ---
### ▶ Well, something is fishy... ### ▶ Well, something is fishy...
<!-- Example ID: cb6a37c5-74f7-44ca-b58c-3b902419b362 ---> <!-- Example ID: cb6a37c5-74f7-44ca-b58c-3b902419b362 --->
```py ```py
def square(x): def square(x):
""" """
@ -3572,6 +3687,7 @@ Shouldn't that be 100?
- This is how Python handles tabs: - 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 <...> > 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. - 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. - Python 3 is kind enough to throw an error for such cases automatically.
@ -3582,11 +3698,13 @@ Shouldn't that be 100?
``` ```
--- ---
--- ---
## Section: Miscellaneous ## Section: Miscellaneous
### ▶ `+=` is faster ### ▶ `+=` is faster
<!-- Example ID: bfd19c60-a807-4a26-9598-4912b86ddb36 ---> <!-- Example ID: bfd19c60-a807-4a26-9598-4912b86ddb36 --->
```py ```py
@ -3599,12 +3717,15 @@ Shouldn't that be 100?
``` ```
#### 💡 Explanation: #### 💡 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.
--- ---
### ▶ Let's make a giant string! ### ▶ Let's make a giant string!
<!-- Example ID: c7a07424-63fe-4504-9842-8f3d334f28fc ---> <!-- Example ID: c7a07424-63fe-4504-9842-8f3d334f28fc --->
```py ```py
def add_string_with_plus(iters): def add_string_with_plus(iters):
s = "" s = ""
@ -3700,8 +3821,10 @@ Let's increase the number of iterations by a factor of 10.
--- ---
### ▶ Slowing down `dict` lookups * ### ▶ Slowing down `dict` lookups \*
<!-- Example ID: c9c26ce6-df0c-47f7-af0b-966b9386d4c3 ---> <!-- Example ID: c9c26ce6-df0c-47f7-af0b-966b9386d4c3 --->
```py ```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)} another_dict = {str(i): 1 for i in range(1_000_000)}
@ -3729,13 +3852,16 @@ KeyError: 1
Why are same lookups becoming slower? Why are same lookups becoming slower?
#### 💡 Explanation: #### 💡 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. - 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 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. - 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. - 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 \*
<!-- Example ID: fe706ab4-1615-c0ba-a078-76c98cbe3f48 ---> <!-- Example ID: fe706ab4-1615-c0ba-a078-76c98cbe3f48 --->
```py ```py
import sys 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? What makes those dictionaries become bloated? And why are newly created objects bloated as well?
#### 💡 Explanation: #### 💡 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. - 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. - 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. - 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__`! - 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 \*
<!-- Example ID: f885cb82-f1e4-4daa-9ff3-972b14cb1324 ---> <!-- Example ID: f885cb82-f1e4-4daa-9ff3-972b14cb1324 --->
- `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. **💡 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: - Few weird looking but semantically correct statements:
- `[] = ()` is a semantically correct statement (unpacking an empty `tuple` into an empty `list`) - `[] = ()` 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. - `'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`. - `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:** **💡 Explanation:**
- There is no `++` operator in Python grammar. It is actually two `+` operators. - 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. - `++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. - 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 ```py
>>> a = 42 >>> a = 42
@ -3890,7 +4021,7 @@ What makes those dictionaries become bloated? And why are newly created objects
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, - Sometimes, the `print` method might not print values immediately. For example,
@ -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. The behavior is due to the matching of empty substring(`''`) with slices of length 0 in the original string.
--- ---
--- ---
# Contributing # 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. 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! #### Some nice Links!
- https://www.youtube.com/watch?v=sH4XF6pKKmk - https://www.youtube.com/watch?v=sH4XF6pKKmk
- https://www.reddit.com/r/Python/comments/3cu6ej/what_are_some_wtf_things_about_python - https://www.reddit.com/r/Python/comments/3cu6ej/what_are_some_wtf_things_about_python
- https://sopython.com/wiki/Common_Gotchas_In_Python - https://sopython.com/wiki/Common_Gotchas_In_Python

View File

@ -1,3 +1,6 @@
<!-- markdownlint-disable MD001 -->
<!-- markdownlint-disable MD013 -->
<!-- markdownlint-disable MD036 -->
<p align="center"> <p align="center">
<picture> <picture>
<source media="(prefers-color-scheme: dark)" srcset="/images/logo_dark_theme.svg"> <source media="(prefers-color-scheme: dark)" srcset="/images/logo_dark_theme.svg">
@ -148,7 +151,7 @@
- [💡 توضیح:](#-توضیح-50) - [💡 توضیح:](#-توضیح-50)
- [ بله، این واقعاً وجود دارد!](#-بله-این-واقعاً-وجود-دارد) - [ بله، این واقعاً وجود دارد!](#-بله-این-واقعاً-وجود-دارد)
- [💡 توضیح:](#-توضیح-51) - [💡 توضیح:](#-توضیح-51)
- [ عملگر Ellipsis \*](#-عملگر-ellipsis--) - [ عملگر Ellipsis \*](#-عملگر-ellipsis-)
- [💡توضیح](#توضیح) - [💡توضیح](#توضیح)
- [ بینهایت (`Inpinity`)](#-بینهایت-inpinity) - [ بینهایت (`Inpinity`)](#-بینهایت-inpinity)
- [💡 توضیح:](#-توضیح-52) - [💡 توضیح:](#-توضیح-52)
@ -166,14 +169,13 @@
- [💡 توضیح:](#-توضیح-57) - [💡 توضیح:](#-توضیح-57)
- [ بیایید یک رشتهی بزرگ بسازیم!](#-بیایید-یک-رشتهی-بزرگ-بسازیم) - [ بیایید یک رشتهی بزرگ بسازیم!](#-بیایید-یک-رشتهی-بزرگ-بسازیم)
- [💡 توضیح](#-توضیح-58) - [💡 توضیح](#-توضیح-58)
- [ کُند کردن جستجوها در `dict` \*](#--کُند-کردن-جستجوها-در-dict-) - [ کُند کردن جستجوها در `dict` \*](#-کُند-کردن-جستجوها-در-dict-)
- [💡 توضیح:](#-توضیح-59) - [💡 توضیح:](#-توضیح-59)
- [ حجیم کردن دیکشنری نمونهها (`instance dicts`) \*](#-حجیم-کردن-دیکشنری-نمونهها-instance-dicts-) - [ حجیم کردن دیکشنری نمونهها (`instance dicts`) \*](#-حجیم-کردن-دیکشنری-نمونهها-instance-dicts-)
- [💡 توضیح:](#-توضیح-60) - [💡 توضیح:](#-توضیح-60)
- [ موارد جزئی \*](#-موارد-جزئی-) - [ موارد جزئی \*](#-موارد-جزئی-)
- [مشارکت](#مشارکت) - [مشارکت](#مشارکت)
- [تقدیر و تشکر](#تقدیر-و-تشکر) - [تقدیر و تشکر](#تقدیر-و-تشکر) - [چند لینک جالب!](#چند-لینک-جالب)
- [چند لینک جالب!](#چند-لینک-جالب)
- [🎓 مجوز](#-مجوز) - [🎓 مجوز](#-مجوز)
- [دوستانتان را هم شگفتزده کنید!](#دوستانتان-را-هم-شگفتزده-کنید) - [دوستانتان را هم شگفتزده کنید!](#دوستانتان-را-هم-شگفتزده-کنید)
- [آیا به یک نسخه pdf نیاز دارید؟](#آیا-به-یک-نسخه-pdf-نیاز-دارید) - [آیا به یک نسخه pdf نیاز دارید؟](#آیا-به-یک-نسخه-pdf-نیاز-دارید)
@ -200,7 +202,6 @@
> >
> (دلخواه): توضیح یکخطی خروجی غیرمنتظره > (دلخواه): توضیح یکخطی خروجی غیرمنتظره
> >
>
> #### 💡 توضیح: > #### 💡 توضیح:
> >
> - توضیح کوتاه درمورد اینکه چی داره اتفاق میافته و چرا. > - توضیح کوتاه درمورد اینکه چی داره اتفاق میافته و چرا.
@ -239,7 +240,7 @@
## بخش: ذهن خود را به چالش بکشید! ## بخش: ذهن خود را به چالش بکشید!
### ◀ اول از همه! * ### ◀ اول از همه! \*
<!-- Example ID: d3d73936-3cf1-4632-b5ab-817981338863 --> <!-- Example ID: d3d73936-3cf1-4632-b5ab-817981338863 -->
<!-- read-only --> <!-- read-only -->
@ -363,6 +364,7 @@ if a := some_func():
### ◀ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند ### ◀ بعضی وقت‌ها رشته‌ها می‌توانند دردسرساز شوند
<!-- Example ID: 30f1d3fc-e267-4b30-84ef-4d9e7091ac1a ---> <!-- Example ID: 30f1d3fc-e267-4b30-84ef-4d9e7091ac1a --->
1\. 1\.
```py ```py
@ -447,7 +449,9 @@ False
--- ---
### ◀ مراقب عملیات‌های زنجیره‌ای باشید ### ◀ مراقب عملیات‌های زنجیره‌ای باشید
<!-- Example ID: 07974979-9c86-4720-80bd-467aa19470d9 ---> <!-- Example ID: 07974979-9c86-4720-80bd-467aa19470d9 --->
```py ```py
>>> (False == False) in [False] # منطقیه >>> (False == False) in [False] # منطقیه
False False
@ -472,6 +476,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 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` عالی عمل میکنه. شاید چنین رفتاری برای شما احمقانه به نظر بیاد ولی برای عملیاتهایی مثل `a == b == c` و `0 <= x <= 100` عالی عمل میکنه.
@ -493,7 +498,9 @@ False
--- ---
### ◀ چطور از عملگر `is` استفاده نکنیم ### ◀ چطور از عملگر `is` استفاده نکنیم
<!-- Example ID: 230fa2ac-ab36-4ad1-b675-5f5a1c1a6217 ---> <!-- Example ID: 230fa2ac-ab36-4ad1-b675-5f5a1c1a6217 --->
عبارت پایین خیلی معروفه و تو کل اینترنت موجوده. عبارت پایین خیلی معروفه و تو کل اینترنت موجوده.
1\. 1\.
@ -560,6 +567,7 @@ False
وقتی پایتون رو اجرا میکنید اعداد از `-5` تا `256` در حافظه ذخیره میشن. چون این اعداد خیلی پرکاربرد هستند پس منطقیه که اونها رو در حافظه دستگاه، آماده داشته باشیم. وقتی پایتون رو اجرا میکنید اعداد از `-5` تا `256` در حافظه ذخیره میشن. چون این اعداد خیلی پرکاربرد هستند پس منطقیه که اونها رو در حافظه دستگاه، آماده داشته باشیم.
نقل قول از https://docs.python.org/3/c-api/long.html نقل قول از https://docs.python.org/3/c-api/long.html
> در پیاده سازی فعلی یک آرایه از اشیاء عددی صحیح برای تمام اعداد صحیح بین `-5` تا `256` نگهداری میشود. وقتی شما یک عدد صحیح در این بازه به مقداردهی میکنید، فقط یک ارجاع به آن عدد که از قبل در حافظه ذخیره شده است دریافت میکنید. پس تغییر مقدار عدد 1 باید ممکن باشد. که در این مورد من به رفتار پایتون شک دارم تعریفنشده است. :-) > در پیاده سازی فعلی یک آرایه از اشیاء عددی صحیح برای تمام اعداد صحیح بین `-5` تا `256` نگهداری میشود. وقتی شما یک عدد صحیح در این بازه به مقداردهی میکنید، فقط یک ارجاع به آن عدد که از قبل در حافظه ذخیره شده است دریافت میکنید. پس تغییر مقدار عدد 1 باید ممکن باشد. که در این مورد من به رفتار پایتون شک دارم تعریفنشده است. :-)
```py ```py
@ -618,7 +626,9 @@ False
--- ---
### ◀ کلیدهای هش ### ◀ کلیدهای هش
<!-- Example ID: eb17db53-49fd-4b61-85d6-345c5ca213ff ---> <!-- Example ID: eb17db53-49fd-4b61-85d6-345c5ca213ff --->
1\. 1\.
```py ```py
@ -685,12 +695,14 @@ complex
True True
``` ```
**توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیدهای معروف [تصادف هش](https://en.wikipedia.org/wiki/Collision_(disambiguation)#Other_uses) میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند. **توجه:** برعکس این قضیه لزوما درست نیست. شیءهای میتونن هش های یکسانی داشته باشند ولی مقادیر نابرابری داشته باشند. (این باعث به وجود اومدن پدیدهای معروف [تصادف هش](<https://en.wikipedia.org/wiki/Collision_(disambiguation)#Other_uses>) میشه)، در این صورت توابع هش عملکرد خودشون رو کندتر از حالت عادی انجام می‌دهند.
--- ---
### ◀ در عمق وجود همه ما یکسان هستیم ### ◀ در عمق وجود همه ما یکسان هستیم
<!-- Example ID: 8f99a35f-1736-43e2-920d-3b78ec35da9b ---> <!-- Example ID: 8f99a35f-1736-43e2-920d-3b78ec35da9b --->
```py ```py
class WTF: class WTF:
pass pass
@ -743,8 +755,10 @@ True
--- ---
### ◀ بی‌نظمی در خود نظم * ### ◀ بی‌نظمی در خود نظم \*
<!-- Example ID: 91bff1f8-541d-455a-9de4-6cd8ff00ea66 ---> <!-- Example ID: 91bff1f8-541d-455a-9de4-6cd8ff00ea66 --->
```py ```py
from collections import OrderedDict from collections import OrderedDict
@ -843,8 +857,10 @@ TypeError: unhashable type: 'dict'
--- ---
### ◀ تلاش کن... * ### ◀ تلاش کن... \*
<!-- Example ID: b4349443-e89f-4d25-a109-82616be9d41a ---> <!-- Example ID: b4349443-e89f-4d25-a109-82616be9d41a --->
```py ```py
def some_func(): def some_func():
try: try:
@ -905,7 +921,9 @@ Iteration 0
--- ---
### ◀ برای چی؟ ### ◀ برای چی؟
<!-- Example ID: 64a9dccf-5083-4bc9-98aa-8aeecde4f210 ---> <!-- Example ID: 64a9dccf-5083-4bc9-98aa-8aeecde4f210 --->
```py ```py
some_string = "wtf" some_string = "wtf"
some_dict = {} some_dict = {}
@ -924,7 +942,7 @@ for i, some_dict[i] in enumerate(some_string):
- یک حلقه `for` در [گرامر پایتون](https://docs.python.org/3/reference/grammar.html) این طور تعریف میشه: - یک حلقه `for` در [گرامر پایتون](https://docs.python.org/3/reference/grammar.html) این طور تعریف میشه:
``` ```bash
for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
``` ```
@ -939,7 +957,7 @@ for i, some_dict[i] in enumerate(some_string):
**خروجی:** **خروجی:**
``` ```bash
0 0
1 1
2 2
@ -964,7 +982,9 @@ for i, some_dict[i] in enumerate(some_string):
--- ---
### ◀ اختلاف زمانی در محاسبه ### ◀ اختلاف زمانی در محاسبه
<!-- Example ID: 6aa11a4b-4cf1-467a-b43a-810731517e98 ---> <!-- Example ID: 6aa11a4b-4cf1-467a-b43a-810731517e98 --->
1\. 1\.
```py ```py
@ -1035,7 +1055,9 @@ array_4 = [400, 500, 600]
--- ---
### ◀ هر گردی، گردو نیست ### ◀ هر گردی، گردو نیست
<!-- Example ID: b26fb1ed-0c7d-4b9c-8c6d-94a58a055c0d ---> <!-- Example ID: b26fb1ed-0c7d-4b9c-8c6d-94a58a055c0d --->
```py ```py
>>> 'something' is not None >>> 'something' is not None
True True
@ -1052,6 +1074,7 @@ False
--- ---
### ◀ یک بازی دوز که توش X همون اول برنده میشه! ### ◀ یک بازی دوز که توش X همون اول برنده میشه!
<!-- Example ID: 69329249-bdcb-424f-bd09-cca2e6705a7a ---> <!-- Example ID: 69329249-bdcb-424f-bd09-cca2e6705a7a --->
```py ```py
@ -1115,9 +1138,12 @@ board = [row] * 3
--- ---
### ◀ متغیر شرودینگر * ### ◀ متغیر شرودینگر \*
<!-- Example ID: 4dc42f77-94cb-4eb5-a120-8203d3ed7604 ---> <!-- Example ID: 4dc42f77-94cb-4eb5-a120-8203d3ed7604 --->
مثال اول:
```py ```py
funcs = [] funcs = []
results = [] results = []
@ -1141,7 +1167,7 @@ funcs_results = [func() for func in funcs]
مقدار `x` در هر تکرار حلقه قبل از اضافه کردن `some_func` به لیست `funcs` متفاوت بود، ولی همه توابع در خارج از حلقه مقدار `6` رو برمیگردونند. مقدار `x` در هر تکرار حلقه قبل از اضافه کردن `some_func` به لیست `funcs` متفاوت بود، ولی همه توابع در خارج از حلقه مقدار `6` رو برمیگردونند.
2. مثال دوم:
```py ```py
>>> powers_of_x = [lambda x: x**i for i in range(10)] >>> 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 ```py
>>> import inspect >>> import inspect
@ -1194,8 +1220,10 @@ ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set())
--- ---
### ◀ اول مرغ بوده یا تخم مرغ؟ * ### ◀ اول مرغ بوده یا تخم مرغ؟ \*
<!-- Example ID: 60730dc2-0d79-4416-8568-2a63323b3ce8 ---> <!-- Example ID: 60730dc2-0d79-4416-8568-2a63323b3ce8 --->
1\. 1\.
```py ```py
@ -1245,7 +1273,9 @@ False
--- ---
### ◀ روابط بین زیرمجموعه کلاس‌ها ### ◀ روابط بین زیرمجموعه کلاس‌ها
<!-- Example ID: 9f6d8cf0-e1b5-42d0-84a0-4cfab25a0bc0 ---> <!-- Example ID: 9f6d8cf0-e1b5-42d0-84a0-4cfab25a0bc0 --->
**خروجی:** **خروجی:**
```py ```py
@ -1270,9 +1300,10 @@ False
--- ---
### ◀ برابری و هویت متدها ### ◀ برابری و هویت متدها
<!-- Example ID: 94802911-48fe-4242-defa-728ae893fa32 ---> <!-- Example ID: 94802911-48fe-4242-defa-728ae893fa32 --->
1. مثال اول
```py ```py
class SomeClass: class SomeClass:
@ -1301,10 +1332,10 @@ True
True True
``` ```
با دوبار دسترسی به `classm`، یک شیء برابر دریافت میکنیم، اما *همان* شیء نیست؟ بیایید ببینیم با دوبار دسترسی به `classm`، یک شیء برابر دریافت میکنیم، اما _همان_ شیء نیست؟ بیایید ببینیم
چه اتفاقی برای نمونههای `SomeClass` میافتد: چه اتفاقی برای نمونههای `SomeClass` میافتد:
2. مثال دوم
```py ```py
o1 = SomeClass() o1 = SomeClass()
@ -1328,7 +1359,7 @@ True
True True
``` ```
دسترسی به `classm` یا `method` دو بار، اشیایی برابر اما نه *یکسان* را برای همان نمونه از `SomeClass` ایجاد میکند. دسترسی به `classm` یا `method` دو بار، اشیایی برابر اما نه _یکسان_ را برای همان نمونه از `SomeClass` ایجاد میکند.
#### 💡 توضیح #### 💡 توضیح
@ -1346,7 +1377,7 @@ True
<function SomeClass.method at ...> <function SomeClass.method at ...>
``` ```
- `classmethod` توابع را به متدهای کلاس تبدیل میکند. متدهای کلاس وصافهایی هستند که هنگام دسترسی، یک شیء متد ایجاد میکنند که به *کلاس* (نوع) شیء متصل میشود، نه خود شیء. - `classmethod` توابع را به متدهای کلاس تبدیل میکند. متدهای کلاس وصافهایی هستند که هنگام دسترسی، یک شیء متد ایجاد میکنند که به _کلاس_ (نوع) شیء متصل میشود، نه خود شیء.
```py ```py
>>> o1.classm >>> o1.classm
@ -1373,7 +1404,7 @@ True
- ایجاد شیءهای "متد" جدید در هر بار فراخوانی متدهای نمونه و نیاز به اصلاح آرگومانها برای درج `self`، عملکرد را به شدت تحت تأثیر قرار میداد. - ایجاد شیءهای "متد" جدید در هر بار فراخوانی متدهای نمونه و نیاز به اصلاح آرگومانها برای درج `self`، عملکرد را به شدت تحت تأثیر قرار میداد.
CPython 3.7 [این مشکل را حل کرد](https://bugs.python.org/issue26110) با معرفی opcodeهای جدیدی که فراخوانی متدها را بدون ایجاد شیء متد موقتی مدیریت میکنند. این به شرطی است که تابع دسترسییافته واقعاً فراخوانی شود، بنابراین قطعهکدهای اینجا تحت تأثیر قرار نمیگیرند و همچنان متد ایجاد میکنند :) CPython 3.7 [این مشکل را حل کرد](https://bugs.python.org/issue26110) با معرفی opcodeهای جدیدی که فراخوانی متدها را بدون ایجاد شیء متد موقتی مدیریت میکنند. این به شرطی است که تابع دسترسییافته واقعاً فراخوانی شود، بنابراین قطعهکدهای اینجا تحت تأثیر قرار نمیگیرند و همچنان متد ایجاد میکنند :)
### ◀ آل-ترو-یشن * ### ◀ آل-ترو-یشن \*
<!-- Example ID: dfe6d845-e452-48fe-a2da-0ed3869a8042 --> <!-- Example ID: dfe6d845-e452-48fe-a2da-0ed3869a8042 -->
@ -1412,7 +1443,9 @@ True
--- ---
### ◀ کاما‌ی شگفت‌انگیز ### ◀ کاما‌ی شگفت‌انگیز
<!-- Example ID: 31a819c8-ed73-4dcc-84eb-91bedbb51e58 ---> <!-- Example ID: 31a819c8-ed73-4dcc-84eb-91bedbb51e58 --->
**خروجی (< 3.6):** **خروجی (< 3.6):**
```py ```py
@ -1444,7 +1477,9 @@ SyntaxError: invalid syntax
--- ---
### ◀ رشته‌ها و بک‌اسلش‌ها ### ◀ رشته‌ها و بک‌اسلش‌ها
<!-- Example ID: 6ae622c3-6d99-4041-9b33-507bd1a4407b ---> <!-- Example ID: 6ae622c3-6d99-4041-9b33-507bd1a4407b --->
**خروجی:** **خروجی:**
```py ```py
@ -1492,7 +1527,9 @@ True
--- ---
### ◀ گره نیست، نَه! ### ◀ گره نیست، نَه!
<!-- Example ID: 7034deb1-7443-417d-94ee-29a800524de8 ---> <!-- Example ID: 7034deb1-7443-417d-94ee-29a800524de8 --->
```py ```py
x = True x = True
y = False y = False
@ -1520,7 +1557,9 @@ SyntaxError: invalid syntax
--- ---
### ◀ رشته‌های نیمه سه‌نقل‌قولی ### ◀ رشته‌های نیمه سه‌نقل‌قولی
<!-- Example ID: c55da3e2-1034-43b9-abeb-a7a970a2ad9e ---> <!-- Example ID: c55da3e2-1034-43b9-abeb-a7a970a2ad9e --->
**خروجی:** **خروجی:**
```py ```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) پشتیبانی می‌کند. برای مثال، - پایتون از الحاق ضمنی [رشتههای متنی](https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation) پشتیبانی می‌کند. برای مثال،
``` ```python
>>> print("wtf" "python") >>> print("wtf" "python")
wtfpython wtfpython
>>> print("wtf" "") # or "wtf""" >>> print("wtf" "") # or "wtf"""
@ -1553,7 +1592,9 @@ SyntaxError: EOF while scanning triple-quoted string literal
--- ---
### ◀ مشکل بولین ها چیست؟ ### ◀ مشکل بولین ها چیست؟
<!-- Example ID: 0bba5fa7-9e6d-4cd2-8b94-952d061af5dd ---> <!-- Example ID: 0bba5fa7-9e6d-4cd2-8b94-952d061af5dd --->
1\. 1\.
&#x202b; یک مثال ساده برای شمردن تعداد مقادیر بولی # اعداد صحیح در یک iterable با انواع داده‌ی مخلوط. &#x202b; یک مثال ساده برای شمردن تعداد مقادیر بولی # اعداد صحیح در یک iterable با انواع داده‌ی مخلوط.
@ -1645,7 +1686,9 @@ I have lost faith in truth!
--- ---
### ◀ متغیرهای کلاس و متغیرهای نمونه ### ◀ متغیرهای کلاس و متغیرهای نمونه
<!-- Example ID: 6f332208-33bd-482d-8106-42863b739ed9 ---> <!-- Example ID: 6f332208-33bd-482d-8106-42863b739ed9 --->
1\. 1\.
```py ```py
@ -1718,7 +1761,9 @@ True
--- ---
### ◀ واگذار کردن None ### ◀ واگذار کردن None
<!-- Example ID: 5a40c241-2c30-40d0-8ba9-cf7e097b3b53 ---> <!-- Example ID: 5a40c241-2c30-40d0-8ba9-cf7e097b3b53 --->
```py ```py
some_iterable = ('a', 'b') some_iterable = ('a', 'b')
@ -1751,7 +1796,9 @@ def some_func(val):
--- ---
### ◀ بازگرداندن با استفاده از `yield from`! ### ◀ بازگرداندن با استفاده از `yield from`!
<!-- Example ID: 5626d8ef-8802-49c2-adbc-7cda5c550816 ---> <!-- Example ID: 5626d8ef-8802-49c2-adbc-7cda5c550816 --->
1\. 1\.
```py ```py
@ -1815,7 +1862,7 @@ def some_func(x):
--- ---
### ◀ بازتاب‌ناپذیری * ### ◀ بازتاب‌ناپذیری \*
<!-- Example ID: 59bee91a-36e0-47a4-8c7d-aa89bf1d3976 ---> <!-- Example ID: 59bee91a-36e0-47a4-8c7d-aa89bf1d3976 --->
@ -1921,7 +1968,10 @@ TypeError: 'tuple' object does not support item assignment
- نقلقول از https://docs.python.org/3/reference/datamodel.html - نقلقول از https://docs.python.org/3/reference/datamodel.html
> دنبالههای تغییرناپذیر > دنبالههای تغییرناپذیر
```text
شیئی از نوع دنبالهی تغییرناپذیر، پس از ایجاد دیگر قابل تغییر نیست. (اگر شیء شامل ارجاعهایی به اشیای دیگر باشد، این اشیای دیگر ممکن است قابل تغییر باشند و تغییر کنند؛ اما مجموعهی اشیایی که مستقیماً توسط یک شیء تغییرناپذیر ارجاع داده میشوند، نمیتواند تغییر کند.) شیئی از نوع دنبالهی تغییرناپذیر، پس از ایجاد دیگر قابل تغییر نیست. (اگر شیء شامل ارجاعهایی به اشیای دیگر باشد، این اشیای دیگر ممکن است قابل تغییر باشند و تغییر کنند؛ اما مجموعهی اشیایی که مستقیماً توسط یک شیء تغییرناپذیر ارجاع داده میشوند، نمیتواند تغییر کند.)
```
- عملگر `+=` لیست را بهصورت درجا (in-place) تغییر میدهد. تخصیص به یک عضو کار نمیکند، اما زمانی که استثنا ایجاد میشود، عضو موردنظر پیش از آن بهصورت درجا تغییر کرده است. - عملگر `+=` لیست را بهصورت درجا (in-place) تغییر میدهد. تخصیص به یک عضو کار نمیکند، اما زمانی که استثنا ایجاد میشود، عضو موردنظر پیش از آن بهصورت درجا تغییر کرده است.
- همچنین توضیحی در [پرسشهای متداول رسمی پایتون](https://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works) وجود دارد. - همچنین توضیحی در [پرسشهای متداول رسمی پایتون](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
--- ---
### ◀ متغیری که از اسکوپ بیرونی ناپدید می‌شود ### ◀ متغیری که از اسکوپ بیرونی ناپدید می‌شود
<!-- Example ID: 7f1e71b6-cb3e-44fb-aa47-87ef1b7decc8 ---> <!-- Example ID: 7f1e71b6-cb3e-44fb-aa47-87ef1b7decc8 --->
```py ```py
@ -2014,7 +2065,9 @@ NameError: name 'e' is not defined
--- ---
### ◀ تبدیل اسرارآمیز نوع کلید ### ◀ تبدیل اسرارآمیز نوع کلید
<!-- Example ID: 00f42dd0-b9ef-408d-9e39-1bc209ce3f36 ---> <!-- Example ID: 00f42dd0-b9ef-408d-9e39-1bc209ce3f36 --->
```py ```py
class SomeClass(str): class SomeClass(str):
pass pass
@ -2073,7 +2126,9 @@ str
--- ---
### ◀ ببینیم می‌توانید این را حدس بزنید؟ ### ◀ ببینیم می‌توانید این را حدس بزنید؟
<!-- Example ID: 81aa9fbe-bd63-4283-b56d-6fdd14c9105e ---> <!-- Example ID: 81aa9fbe-bd63-4283-b56d-6fdd14c9105e --->
```py ```py
a, b = a[b] = {}, 5 a, b = a[b] = {}, 5
``` ```
@ -2089,7 +2144,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)، دستورات انتساب فرم زیر را دارند:
``` ```text
(target_list "=")+ (expression_list | yield_expression) (target_list "=")+ (expression_list | yield_expression)
``` ```
@ -2178,7 +2233,9 @@ ValueError: Exceeds the limit (4300) for integer string conversion:
## بخش: شیب‌های لغزنده ## بخش: شیب‌های لغزنده
### ◀ تغییر یک دیکشنری هنگام پیمایش روی آن ### ◀ تغییر یک دیکشنری هنگام پیمایش روی آن
<!-- Example ID: b4e5cdfb-c3a8-4112-bd38-e2356d801c41 ---> <!-- Example ID: b4e5cdfb-c3a8-4112-bd38-e2356d801c41 --->
```py ```py
x = {0: None} x = {0: None}
@ -2190,7 +2247,7 @@ for i in x:
**خروجی (پایتون 2.7تا پایتون 3.5):** **خروجی (پایتون 2.7تا پایتون 3.5):**
``` ```text
0 0
1 1
2 2
@ -2214,6 +2271,7 @@ for i in x:
--- ---
### ◀ عملیات سرسختانه‌ی `del` ### ◀ عملیات سرسختانه‌ی `del`
<!-- Example ID: 777ed4fd-3a2d-466f-95e7-c4058e61d78e ---> <!-- Example ID: 777ed4fd-3a2d-466f-95e7-c4058e61d78e --->
<!-- read-only --> <!-- read-only -->
@ -2262,6 +2320,7 @@ Deleted!
--- ---
### ◀ متغیری که از حوزه خارج است ### ◀ متغیری که از حوزه خارج است
<!-- Example ID: 75c03015-7be9-4289-9e22-4f5fdda056f7 ---> <!-- Example ID: 75c03015-7be9-4289-9e22-4f5fdda056f7 --->
1\. 1\.
@ -2352,7 +2411,9 @@ UnboundLocalError: local variable 'a' referenced before assignment
--- ---
### ◀ حذف المان‌های لیست در حین پیمایش ### ◀ حذف المان‌های لیست در حین پیمایش
<!-- Example ID: 4cc52d4e-d42b-4e09-b25f-fbf5699b7d4e ---> <!-- Example ID: 4cc52d4e-d42b-4e09-b25f-fbf5699b7d4e --->
```py ```py
list_1 = [1, 2, 3, 4] list_1 = [1, 2, 3, 4]
list_2 = [1, 2, 3, 4] list_2 = [1, 2, 3, 4]
@ -2414,7 +2475,8 @@ for idx, item in enumerate(list_4):
--- ---
### ◀ زیپِ دارای اتلاف برای پیمایشگرها * ### ◀ زیپِ دارای اتلاف برای پیمایشگرها \*
<!-- Example ID: c28ed154-e59f-4070-8eb6-8967a4acac6d ---> <!-- Example ID: c28ed154-e59f-4070-8eb6-8967a4acac6d --->
```py ```py
@ -2451,7 +2513,7 @@ for idx, item in enumerate(list_4):
yield tuple(result) yield tuple(result)
``` ```
- بنابراین این تابع تعداد دلخواهی از اشیای قابل پیمایش (*iterable*) را دریافت میکند، و با فراخوانی تابع `next` روی آنها، هر یک از عناصرشان را به لیست `result` اضافه میکند. این فرایند زمانی متوقف میشود که اولین پیمایشگر به انتها برسد. - بنابراین این تابع تعداد دلخواهی از اشیای قابل پیمایش (_iterable_) را دریافت میکند، و با فراخوانی تابع `next` روی آنها، هر یک از عناصرشان را به لیست `result` اضافه میکند. این فرایند زمانی متوقف میشود که اولین پیمایشگر به انتها برسد.
- نکته مهم اینجاست که هر زمان یکی از پیمایشگرها به پایان برسد، عناصر موجود در لیست `result` نیز دور ریخته میشوند. این دقیقاً همان اتفاقی است که برای عدد `3` در `numbers_iter` رخ داد. - نکته مهم اینجاست که هر زمان یکی از پیمایشگرها به پایان برسد، عناصر موجود در لیست `result` نیز دور ریخته میشوند. این دقیقاً همان اتفاقی است که برای عدد `3` در `numbers_iter` رخ داد.
- روش صحیح برای انجام عملیات بالا با استفاده از تابع `zip` چنین است: - روش صحیح برای انجام عملیات بالا با استفاده از تابع `zip` چنین است:
@ -2469,7 +2531,9 @@ for idx, item in enumerate(list_4):
--- ---
### ◀ نشت کردن متغیرهای حلقه! ### ◀ نشت کردن متغیرهای حلقه!
<!-- Example ID: ccec7bf6-7679-4963-907a-1cd8587be9ea ---> <!-- Example ID: ccec7bf6-7679-4963-907a-1cd8587be9ea --->
1\. 1\.
```py ```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()` هستند و در نتیجه، متغیرهای کنترل حلقه دیگر به فضای نام بیرونی نشت نمیکنند.»
--- ---
### ◀ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید! ### ◀ مراقب آرگومان‌های تغییرپذیر پیش‌فرض باشید!
<!-- Example ID: 7d42dade-e20d-4a7b-9ed7-16fb58505fe9 ---> <!-- Example ID: 7d42dade-e20d-4a7b-9ed7-16fb58505fe9 --->
```py ```py
@ -2599,7 +2664,9 @@ def some_func(default_arg=[]):
--- ---
### ◀ گرفتن استثناها (Exceptions) ### ◀ گرفتن استثناها (Exceptions)
<!-- Example ID: b5ca5e6a-47b9-4f69-9375-cda0f8c6755d ---> <!-- Example ID: b5ca5e6a-47b9-4f69-9375-cda0f8c6755d --->
```py ```py
some_list = [1, 2, 3] some_list = [1, 2, 3]
try: try:
@ -2648,7 +2715,7 @@ SyntaxError: invalid syntax
**خروجی (Python 2.x):** **خروجی (Python 2.x):**
``` ```text
Caught again! Caught again!
list.remove(x): x not in list list.remove(x): x not in list
``` ```
@ -2676,7 +2743,7 @@ SyntaxError: invalid syntax
**خروجی:** **خروجی:**
``` ```text
Caught again! Caught again!
list.remove(x): x not in list list.remove(x): x not in list
``` ```
@ -2684,7 +2751,9 @@ SyntaxError: invalid syntax
--- ---
### ◀ عملوندهای یکسان، داستانی متفاوت! ### ◀ عملوندهای یکسان، داستانی متفاوت!
<!-- Example ID: ca052cdf-dd2d-4105-b936-65c28adc18a0 ---> <!-- Example ID: ca052cdf-dd2d-4105-b936-65c28adc18a0 --->
1\. 1\.
```py ```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` را تغییر دهد. - عبارت `a = a + [5,6,7,8]` یک لیست جدید ایجاد میکند و مرجع `a` را به این لیست جدید اختصاص میدهد، بدون آنکه `b` را تغییر دهد.
@ -2730,7 +2799,9 @@ a += [5, 6, 7, 8]
--- ---
### ◀ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس ### ◀ تفکیک نام‌ها با نادیده گرفتن حوزه‌ی کلاس
<!-- Example ID: 03f73d96-151c-4929-b0a8-f74430788324 ---> <!-- Example ID: 03f73d96-151c-4929-b0a8-f74430788324 --->
1\. 1\.
```py ```py
@ -2778,7 +2849,7 @@ class SomeClass:
--- ---
### ◀ گرد کردن به روش بانکدار * ### ◀ گرد کردن به روش بانکدار \*
بیایید یک تابع ساده برای بهدستآوردن عنصر میانی یک لیست پیادهسازی کنیم: بیایید یک تابع ساده برای بهدستآوردن عنصر میانی یک لیست پیادهسازی کنیم:
@ -2831,7 +2902,7 @@ def get_middle(some_list):
--- ---
### ◀ سوزن‌هایی در انبار کاه * ### ◀ سوزن‌هایی در انبار کاه \*
<!-- Example ID: 52a199b1-989a-4b28-8910-dff562cebba9 ---> <!-- Example ID: 52a199b1-989a-4b28-8910-dff562cebba9 --->
@ -2878,7 +2949,7 @@ tuple()
3\. 3\.
``` ```python
ten_words_list = [ ten_words_list = [
"some", "some",
"very", "very",
@ -3009,8 +3080,10 @@ def similar_recursive_func(a):
--- ---
### ◀ تقسیم‌ها * ### ◀ تقسیم‌ها \*
<!-- Example ID: ec3168ba-a81a-4482-afb0-691f1cc8d65a ---> <!-- Example ID: ec3168ba-a81a-4482-afb0-691f1cc8d65a --->
```py ```py
>>> 'a'.split() >>> 'a'.split()
['a'] ['a']
@ -3046,7 +3119,8 @@ def similar_recursive_func(a):
--- ---
### ◀ واردسازی‌های عمومی * ### ◀ واردسازی‌های عمومی \*
<!-- Example ID: 83deb561-bd55-4461-bb5e-77dd7f411e1c ---> <!-- Example ID: 83deb561-bd55-4461-bb5e-77dd7f411e1c --->
<!-- read-only --> <!-- read-only -->
@ -3109,7 +3183,7 @@ NameError: name '_another_weird_name_func' is not defined
--- ---
### ◀ همه چیز مرتب شده؟ * ### ◀ همه چیز مرتب شده؟ \*
<!-- Example ID: e5ff1eaf-8823-4738-b4ce-b73f7c9d5511 --> <!-- Example ID: e5ff1eaf-8823-4738-b4ce-b73f7c9d5511 -->
@ -3151,7 +3225,9 @@ False
--- ---
### ◀ زمان نیمه‌شب وجود ندارد؟ ### ◀ زمان نیمه‌شب وجود ندارد؟
<!-- Example ID: 1bce8294-5619-4d70-8ce3-fe0bade690d1 ---> <!-- Example ID: 1bce8294-5619-4d70-8ce3-fe0bade690d1 --->
```py ```py
from datetime import datetime from datetime import datetime
@ -3181,6 +3257,7 @@ if noon_time:
پیش از پایتون 3.5، مقدار بولی برای شیء `datetime.time` اگر نشاندهندهٔ نیمهشب به وقت UTC بود، برابر با `False` در نظر گرفته میشد. این رفتار در استفاده از دستور `if obj:` برای بررسی تهی بودن شیء یا برابر بودن آن با مقدار "خالی"، ممکن است باعث بروز خطا شود. پیش از پایتون 3.5، مقدار بولی برای شیء `datetime.time` اگر نشاندهندهٔ نیمهشب به وقت UTC بود، برابر با `False` در نظر گرفته میشد. این رفتار در استفاده از دستور `if obj:` برای بررسی تهی بودن شیء یا برابر بودن آن با مقدار "خالی"، ممکن است باعث بروز خطا شود.
--- ---
--- ---
## بخش: گنجینه‌های پنهان! ## بخش: گنجینه‌های پنهان!
@ -3188,7 +3265,9 @@ if noon_time:
این بخش شامل چند مورد جالب و کمتر شناختهشده دربارهی پایتون است که بیشتر مبتدیهایی مثل من از آن بیخبرند (البته دیگر اینطور نیست). این بخش شامل چند مورد جالب و کمتر شناختهشده دربارهی پایتون است که بیشتر مبتدیهایی مثل من از آن بیخبرند (البته دیگر اینطور نیست).
### ◀ خب پایتون، می‌توانی کاری کنی پرواز کنم؟ ### ◀ خب پایتون، می‌توانی کاری کنی پرواز کنم؟
<!-- Example ID: a92f3645-1899-4d50-9721-0031be4aec3f ---> <!-- Example ID: a92f3645-1899-4d50-9721-0031be4aec3f --->
خب، بفرمایید خب، بفرمایید
```py ```py
@ -3207,6 +3286,7 @@ Sshh... It's a super-secret.
--- ---
### ◀ `goto`، ولی چرا؟ ### ◀ `goto`، ولی چرا؟
<!-- Example ID: 2aff961e-7fa5-4986-a18a-9e5894bd89fe ---> <!-- Example ID: 2aff961e-7fa5-4986-a18a-9e5894bd89fe --->
```py ```py
@ -3238,7 +3318,9 @@ Freedom!
--- ---
### ◀ خودتان را آماده کنید! ### ◀ خودتان را آماده کنید!
<!-- Example ID: 5c0c75f2-ddd9-4da3-ba49-c4be7ec39acf ---> <!-- Example ID: 5c0c75f2-ddd9-4da3-ba49-c4be7ec39acf --->
اگر جزو افرادی هستید که دوست ندارند در پایتون برای مشخص کردن محدودهها از فضای خالی (whitespace) استفاده کنند، میتوانید با ایمپورت کردن ماژول زیر از آکولاد `{}` به سبک زبان C استفاده کنید: اگر جزو افرادی هستید که دوست ندارند در پایتون برای مشخص کردن محدودهها از فضای خالی (whitespace) استفاده کنند، میتوانید با ایمپورت کردن ماژول زیر از آکولاد `{}` به سبک زبان C استفاده کنید:
```py ```py
@ -3265,7 +3347,9 @@ SyntaxError: not a chance
--- ---
### ◀ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم ### ◀ بیایید با «عمو زبان مهربان برای همیشه» آشنا شویم
<!-- Example ID: 6427fae6-e959-462d-85da-ce4c94ce41be ---> <!-- Example ID: 6427fae6-e959-462d-85da-ce4c94ce41be --->
**خروجی (Python 3.x)** **خروجی (Python 3.x)**
```py ```py
@ -3300,7 +3384,9 @@ True
--- ---
### ◀ حتی پایتون هم می‌داند که عشق پیچیده است ### ◀ حتی پایتون هم می‌داند که عشق پیچیده است
<!-- Example ID: b93cad9e-d341-45d1-999c-fcdce65bed25 ---> <!-- Example ID: b93cad9e-d341-45d1-999c-fcdce65bed25 --->
```py ```py
import this import this
``` ```
@ -3309,7 +3395,7 @@ import this
**خروجی:** **خروجی:**
``` ```text
The Zen of Python, by Tim Peters The Zen of Python, by Tim Peters
Beautiful is better than ugly. Beautiful is better than ugly.
@ -3358,7 +3444,9 @@ True
--- ---
### ◀ بله، این واقعاً وجود دارد! ### ◀ بله، این واقعاً وجود دارد!
<!-- Example ID: 4286db3d-1ea7-47c9-8fb6-a9a04cac6e49 ---> <!-- Example ID: 4286db3d-1ea7-47c9-8fb6-a9a04cac6e49 --->
**عبارت `else` برای حلقهها.** یک مثال معمول آن میتواند چنین باشد: **عبارت `else` برای حلقهها.** یک مثال معمول آن میتواند چنین باشد:
```py ```py
@ -3405,8 +3493,10 @@ Try block executed successfully...
--- ---
### ◀ عملگر Ellipsis * ### ◀ عملگر Ellipsis \*
<!-- Example ID: 969b7100-ab3d-4a7d-ad7d-a6be16181b2b ---> <!-- Example ID: 969b7100-ab3d-4a7d-ad7d-a6be16181b2b --->
```py ```py
def some_func(): def some_func():
Ellipsis Ellipsis
@ -3437,6 +3527,7 @@ Ellipsis
``` ```
- عملگر `Ellipsis` میتواند برای چندین منظور استفاده شود: - عملگر `Ellipsis` میتواند برای چندین منظور استفاده شود:
- به عنوان یک نگهدارنده برای کدی که هنوز نوشته نشده است (مانند دستور `pass`) - به عنوان یک نگهدارنده برای کدی که هنوز نوشته نشده است (مانند دستور `pass`)
- در سینتکس برش (`slicing`) برای نمایش برش کامل در ابعاد باقیمانده - در سینتکس برش (`slicing`) برای نمایش برش کامل در ابعاد باقیمانده
@ -3468,13 +3559,16 @@ Ellipsis
``` ```
نکته: این روش برای آرایههایی با هر تعداد بُعد کار میکند. حتی میتوانید از برش (`slice`) در بُعد اول و آخر استفاده کرده و ابعاد میانی را نادیده بگیرید (به صورت `n_dimensional_array[first_dim_slice, ..., last_dim_slice]`). نکته: این روش برای آرایههایی با هر تعداد بُعد کار میکند. حتی میتوانید از برش (`slice`) در بُعد اول و آخر استفاده کرده و ابعاد میانی را نادیده بگیرید (به صورت `n_dimensional_array[first_dim_slice, ..., last_dim_slice]`).
- در [نوعدهی (`type hinting`)](https://docs.python.org/3/library/typing.html) برای اشاره به بخشی از نوع (مانند `Callable[..., int]` یا `Tuple[str, ...]`) استفاده میشود. - در [نوعدهی (`type hinting`)](https://docs.python.org/3/library/typing.html) برای اشاره به بخشی از نوع (مانند `Callable[..., int]` یا `Tuple[str, ...]`) استفاده میشود.
- همچنین میتوانید از `Ellipsis` به عنوان آرگومان پیشفرض تابع استفاده کنید (برای مواردی که میخواهید میان «آرگومانی ارسال نشده است» و «مقدار `None` ارسال شده است» تمایز قائل شوید). - همچنین میتوانید از `Ellipsis` به عنوان آرگومان پیشفرض تابع استفاده کنید (برای مواردی که میخواهید میان «آرگومانی ارسال نشده است» و «مقدار `None` ارسال شده است» تمایز قائل شوید).
--- ---
### ◀ بی‌نهایت (`Inpinity`) ### ◀ بی‌نهایت (`Inpinity`)
<!-- Example ID: ff473ea8-a3b1-4876-a6f0-4378aff790c1 ---> <!-- Example ID: ff473ea8-a3b1-4876-a6f0-4378aff790c1 --->
این املای کلمه تعمداً به همین شکل نوشته شده است. لطفاً برای اصلاح آن درخواست (`patch`) ارسال نکنید. این املای کلمه تعمداً به همین شکل نوشته شده است. لطفاً برای اصلاح آن درخواست (`patch`) ارسال نکنید.
**خروجی (پایتون 3.x):** **خروجی (پایتون 3.x):**
@ -3495,7 +3589,9 @@ Ellipsis
--- ---
### ◀ بیایید خرابکاری کنیم ### ◀ بیایید خرابکاری کنیم
<!-- Example ID: 37146d2d-9e67-43a9-8729-3c17934b910c ---> <!-- Example ID: 37146d2d-9e67-43a9-8729-3c17934b910c --->
1\. 1\.
```py ```py
@ -3572,12 +3668,15 @@ AttributeError: 'A' object has no attribute '__variable'
- همچنین، اگر نام تغییر یافته بیش از ۲۵۵ کاراکتر باشد، برش داده میشود. - همچنین، اگر نام تغییر یافته بیش از ۲۵۵ کاراکتر باشد، برش داده میشود.
--- ---
--- ---
## بخش: ظاهرها فریبنده‌اند! ## بخش: ظاهرها فریبنده‌اند!
### ◀ خطوط را رد می‌کند؟ ### ◀ خطوط را رد می‌کند؟
<!-- Example ID: d50bbde1-fb9d-4735-9633-3444b9d2f417 ---> <!-- Example ID: d50bbde1-fb9d-4735-9633-3444b9d2f417 --->
**خروجی:** **خروجی:**
```py ```py
@ -3648,7 +3747,9 @@ def energy_receive():
--- ---
### ◀ خب، یک جای کار مشکوک است... ### ◀ خب، یک جای کار مشکوک است...
<!-- Example ID: cb6a37c5-74f7-44ca-b58c-3b902419b362 ---> <!-- Example ID: cb6a37c5-74f7-44ca-b58c-3b902419b362 --->
```py ```py
def square(x): def square(x):
""" """
@ -3677,6 +3778,7 @@ def square(x):
- نحوۀ برخورد پایتون با تبها به این صورت است: - نحوۀ برخورد پایتون با تبها به این صورت است:
> ابتدا تبها (از چپ به راست) با یک تا هشت فاصله جایگزین میشوند بهطوری که تعداد کل کاراکترها تا انتهای آن جایگزینی، مضربی از هشت باشد <...> > ابتدا تبها (از چپ به راست) با یک تا هشت فاصله جایگزین میشوند بهطوری که تعداد کل کاراکترها تا انتهای آن جایگزینی، مضربی از هشت باشد <...>
- بنابراین «تب» در آخرین خط تابع `square` با هشت فاصله جایگزین شده و به همین دلیل داخل حلقه قرار میگیرد. - بنابراین «تب» در آخرین خط تابع `square` با هشت فاصله جایگزین شده و به همین دلیل داخل حلقه قرار میگیرد.
- پایتون ۳ آنقدر هوشمند هست که چنین مواردی را بهصورت خودکار با خطا اعلام کند. - پایتون ۳ آنقدر هوشمند هست که چنین مواردی را بهصورت خودکار با خطا اعلام کند.
@ -3687,11 +3789,13 @@ def square(x):
``` ```
--- ---
--- ---
## بخش: متفرقه ## بخش: متفرقه
### ◀ `+=` سریع‌تر است ### ◀ `+=` سریع‌تر است
<!-- Example ID: bfd19c60-a807-4a26-9598-4912b86ddb36 ---> <!-- Example ID: bfd19c60-a807-4a26-9598-4912b86ddb36 --->
```py ```py
@ -3710,7 +3814,9 @@ def square(x):
--- ---
### ◀ بیایید یک رشته‌ی بزرگ بسازیم! ### ◀ بیایید یک رشته‌ی بزرگ بسازیم!
<!-- Example ID: c7a07424-63fe-4504-9842-8f3d334f28fc ---> <!-- Example ID: c7a07424-63fe-4504-9842-8f3d334f28fc --->
```py ```py
def add_string_with_plus(iters): def add_string_with_plus(iters):
s = "" s = ""
@ -3809,8 +3915,10 @@ timeit.timeit('add_string_with_plus(10000)', number=1000, globals=globals())
--- ---
### ◀ کُند کردن جستجوها در `dict` * ### ◀ کُند کردن جستجوها در `dict` \*
<!-- Example ID: c9c26ce6-df0c-47f7-af0b-966b9386d4c3 ---> <!-- Example ID: c9c26ce6-df0c-47f7-af0b-966b9386d4c3 --->
```py ```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)} another_dict = {str(i): 1 for i in range(1_000_000)}
@ -3844,8 +3952,10 @@ KeyError: 1
- اولین باری که یک دیکشنری (`dict`) با کلیدی غیر از `str` فراخوانی شود، این حالت تغییر میکند و جستجوهای بعدی از تابع عمومی استفاده خواهند کرد. - اولین باری که یک دیکشنری (`dict`) با کلیدی غیر از `str` فراخوانی شود، این حالت تغییر میکند و جستجوهای بعدی از تابع عمومی استفاده خواهند کرد.
- این فرایند برای آن نمونهی خاص از دیکشنری غیرقابل بازگشت است و حتی لازم نیست کلید موردنظر در دیکشنری موجود باشد. به همین دلیل است که حتی تلاش ناموفق برای دسترسی به کلیدی ناموجود نیز باعث ایجاد همین تأثیر (کند شدن جستجو) میشود. - این فرایند برای آن نمونهی خاص از دیکشنری غیرقابل بازگشت است و حتی لازم نیست کلید موردنظر در دیکشنری موجود باشد. به همین دلیل است که حتی تلاش ناموفق برای دسترسی به کلیدی ناموجود نیز باعث ایجاد همین تأثیر (کند شدن جستجو) میشود.
### ◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) * ### ◀ حجیم کردن دیکشنری نمونه‌ها (`instance dicts`) \*
<!-- Example ID: fe706ab4-1615-c0ba-a078-76c98cbe3f48 ---> <!-- Example ID: fe706ab4-1615-c0ba-a078-76c98cbe3f48 --->
```py ```py
import sys import sys
@ -3907,13 +4017,16 @@ def dict_size(o):
- همچنین اگر اندازهی دیکشنری بهعلت اضافهشدن کلیدهای جدید تغییر کند (`resize` شود)، اشتراکگذاری کلیدها تنها زمانی ادامه مییابد که فقط یک دیکشنری در حال استفاده از آنها باشد (این اجازه میدهد در متد `__init__` برای اولین نمونهی ساختهشده، صفات متعددی تعریف کنید بدون آنکه اشتراکگذاری کلیدها از بین برود). اما اگر چند نمونه همزمان وجود داشته باشند و تغییر اندازهی دیکشنری رخ دهد، قابلیت اشتراکگذاری کلیدها برای نمونههای بعدی همان کلاس غیرفعال خواهد شد. زیرا CPython دیگر نمیتواند مطمئن باشد که آیا نمونههای بعدی دقیقاً از مجموعهی یکسانی از صفات استفاده خواهند کرد یا خیر. - همچنین اگر اندازهی دیکشنری بهعلت اضافهشدن کلیدهای جدید تغییر کند (`resize` شود)، اشتراکگذاری کلیدها تنها زمانی ادامه مییابد که فقط یک دیکشنری در حال استفاده از آنها باشد (این اجازه میدهد در متد `__init__` برای اولین نمونهی ساختهشده، صفات متعددی تعریف کنید بدون آنکه اشتراکگذاری کلیدها از بین برود). اما اگر چند نمونه همزمان وجود داشته باشند و تغییر اندازهی دیکشنری رخ دهد، قابلیت اشتراکگذاری کلیدها برای نمونههای بعدی همان کلاس غیرفعال خواهد شد. زیرا CPython دیگر نمیتواند مطمئن باشد که آیا نمونههای بعدی دقیقاً از مجموعهی یکسانی از صفات استفاده خواهند کرد یا خیر.
- نکتهای کوچک برای کاهش مصرف حافظهی برنامه: هرگز صفات نمونهها را حذف نکنید و حتماً تمام صفات را در متد `__init__` تعریف و مقداردهی اولیه کنید! - نکتهای کوچک برای کاهش مصرف حافظهی برنامه: هرگز صفات نمونهها را حذف نکنید و حتماً تمام صفات را در متد `__init__` تعریف و مقداردهی اولیه کنید!
### ◀ موارد جزئی * ### ◀ موارد جزئی \*
<!-- Example ID: f885cb82-f1e4-4daa-9ff3-972b14cb1324 ---> <!-- Example ID: f885cb82-f1e4-4daa-9ff3-972b14cb1324 --->
- متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.) - متد `join()` عملیاتی مربوط به رشته (`str`) است، نه لیست (`list`). (در نگاه اول کمی برخلاف انتظار است.)
**توضیح:** اگر `join()` بهعنوان متدی روی رشته پیادهسازی شود، میتواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشوندهی دیگر کار کند. اگر بهجای آن روی لیست تعریف میشد، باید بهطور جداگانه برای هر نوع دیگری نیز پیادهسازی میشد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود. **توضیح:** اگر `join()` بهعنوان متدی روی رشته پیادهسازی شود، میتواند روی هر شیء قابل پیمایش (`iterable`) از جمله لیست، تاپل و هر نوع تکرارشوندهی دیگر کار کند. اگر بهجای آن روی لیست تعریف میشد، باید بهطور جداگانه برای هر نوع دیگری نیز پیادهسازی میشد. همچنین منطقی نیست که یک متد مختص رشته روی یک شیء عمومی مانند `list` پیاده شود.
- تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح: - تعدادی عبارت با ظاهری عجیب اما از نظر معنا صحیح:
- عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی). - عبارت `[] = ()` از نظر معنایی صحیح است (باز کردن یا `unpack` کردن یک تاپل خالی درون یک لیست خالی).
- عبارت `'a'[0][0][0][0][0]` نیز از نظر معنایی صحیح است، زیرا پایتون برخلاف زبانهایی که از C منشعب شدهاند، نوع دادهای جداگانهای برای کاراکتر ندارد. بنابراین انتخاب یک کاراکتر از یک رشته، منجر به بازگشت یک رشتهی تککاراکتری میشود. - عبارت `'a'[0][0][0][0][0]` نیز از نظر معنایی صحیح است، زیرا پایتون برخلاف زبانهایی که از C منشعب شدهاند، نوع دادهای جداگانهای برای کاراکتر ندارد. بنابراین انتخاب یک کاراکتر از یک رشته، منجر به بازگشت یک رشتهی تککاراکتری میشود.
- عبارات `3 --0-- 5 == 8` و `--5 == 5` هر دو از لحاظ معنایی درست بوده و مقدارشان برابر `True` است. - عبارات `3 --0-- 5 == 8` و `--5 == 5` هر دو از لحاظ معنایی درست بوده و مقدارشان برابر `True` است.
@ -3936,7 +4049,7 @@ def dict_size(o):
- عبارت `++a` بهشکل `+(+a)` تفسیر میشود که معادل `a` است. بههمین ترتیب، خروجی عبارت `--a` نیز قابل توجیه است. - عبارت `++a` بهشکل `+(+a)` تفسیر میشود که معادل `a` است. بههمین ترتیب، خروجی عبارت `--a` نیز قابل توجیه است.
- این [تاپیک در StackOverflow](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) دلایل نبودن عملگرهای افزایش (`++`) و کاهش (`--`) در پایتون را بررسی میکند. - این [تاپیک در StackOverflow](https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python) دلایل نبودن عملگرهای افزایش (`++`) و کاهش (`--`) در پایتون را بررسی میکند.
- احتمالاً با عملگر Walrus (گراز دریایی) در پایتون آشنا هستید؛ اما تا به حال در مورد *عملگر Space-invader (مهاجم فضایی)* شنیدهاید؟ - احتمالاً با عملگر Walrus (گراز دریایی) در پایتون آشنا هستید؛ اما تا به حال در مورد _عملگر Space-invader (مهاجم فضایی)_ شنیدهاید؟
```py ```py
>>> a = 42 >>> a = 42
@ -4002,7 +4115,7 @@ def dict_size(o):
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` ممکن است مقادیر را فوراً چاپ نکند. برای مثال، - گاهی اوقات، متد `print` ممکن است مقادیر را فوراً چاپ نکند. برای مثال،
@ -4061,6 +4174,7 @@ def dict_size(o):
این رفتار به این دلیل است که زیررشتهی خالی (`''`) با برشهایی (slices) به طول صفر در رشتهی اصلی مطابقت پیدا میکند. این رفتار به این دلیل است که زیررشتهی خالی (`''`) با برشهایی (slices) به طول صفر در رشتهی اصلی مطابقت پیدا میکند.
--- ---
--- ---
# مشارکت # مشارکت