You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
-[Let's see if you can guess this?](#lets-see-if-you-can-guess-this)
109
+
-[💡 Explanation:](#-explanation-31)
108
110
-[Minor Ones](#minor-ones)
109
111
-[TODO: Hell of an example!](#todo-hell-of-an-example)
110
112
-[Contributing](#contributing)
@@ -1931,6 +1933,53 @@ str
1931
1933
(__main__.SomeClass, str)
1932
1934
```
1933
1935
1936
+
---
1937
+
1938
+
### Stubborn `del` operator
1939
+
1940
+
Suggested by @tukkek in [this](https://github.com/satwikkansal/wtfpython/issues/26) issue.
1941
+
1942
+
```py
1943
+
class SomeClass:
1944
+
def __del__(self):
1945
+
print("Deleted!")
1946
+
```
1947
+
1948
+
**Output:**
1949
+
1\.
1950
+
```py
1951
+
>>> x = SomeClass()
1952
+
>>> y = x
1953
+
>>> del x # this should print "Deleted!"
1954
+
>>> del y
1955
+
Deleted!
1956
+
```
1957
+
1958
+
Phew, deleted at last. You might have guessed what saved from `__del__` being called in our first attempt to delete `x`. Let's add more twist ro the example.
1959
+
1960
+
2\.
1961
+
```py
1962
+
>>> x = SomeClass()
1963
+
>>> y = x
1964
+
>>> del x
1965
+
>>> y # check if y exists
1966
+
<__main__.SomeClass instance at 0x7f98a1a67fc8>
1967
+
>>> del y # Like previously, this should print "Deleted!"
1968
+
>>> globals() # oh, it didn't. Let's check all our global variables and confirm
+ Whenever `del x` is encountered, Python decrements the reference count for `x` by one, and `x.__del__()` when x’s reference count reaches zero.
1978
+
+ In the second output snippet, `y.__del__()` was not called because the previous statement (`>>> y`) in the interactive interpreter created another reference to the same object, thus preventing the reference count to reach zero when `del y` was encountered.
1979
+
+ Calling `globals` caused the existing reference to be destroyed and hence we can see "Deleted!" being printed (finally!).
1980
+
1981
+
---
1982
+
1934
1983
### Let's see if you can guess this?
1935
1984
1936
1985
Suggested by @PiaFraus in [this](https://github.com/satwikkansal/wtfPython/issues/9) issue.
0 commit comments