Skip to content

Commit 669ff8c

Browse files
authored
Merge pull request satwikkansal#192 from Jongy/correctify-stubborn-del-explanation
Correctify explanation of "Stubborn `del` operation"
2 parents e9b04d3 + 67f743e commit 669ff8c

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

README.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -1954,7 +1954,7 @@ class SomeClass:
19541954
Deleted!
19551955
```
19561956
1957-
Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twists to the example.
1957+
Phew, deleted at last. You might have guessed what saved `__del__` from being called in our first attempt to delete `x`. Let's add more twists to the example.
19581958
19591959
2\.
19601960
```py
@@ -1973,9 +1973,9 @@ Okay, now it's deleted :confused:
19731973
19741974
#### 💡 Explanation:
19751975
+ `del x` doesn’t directly call `x.__del__()`.
1976-
+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero.
1977-
+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count from reaching zero when `del y` was encountered.
1978-
+ Calling `globals` caused the existing reference to be destroyed, and hence we can see "Deleted!" being printed (finally!).
1976+
+ 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.
1977+
+ 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.
1978+
+ Calling `globals` (or really, executing anything that will have a non `None` result) caused `_` to reference the new result, dropping the existing reference. Now the reference count reached 0 and we can see "Deleted!" being printed (finally!).
19791979
19801980
---
19811981

0 commit comments

Comments
 (0)