forked from satwikkansal/wtfpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.md
executable file
·1687 lines (1309 loc) · 47.8 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<h1 align="center"> What the f*ck Python? 🐍 </h1>
<p align="center"> A collection of interesting and tricky Python examples. </p>
[![WTFPL 2.0][license-image]][license-url]
Python, being awesome by design high-level and interpreter-based programming language, provides us with many features for the programmer's comfort. But sometimes, the outcomes of a Python snippet may not seem obvious to a regular user at first sight.
Here is a fun project attempting to collect such classic and tricky examples of unexpected behaviors in Python and discuss what exactly is happening under the hood!
While some of the examples you see below may not be WTFs in the truest sense, but they'll reveal some of the interesting parts of Python that you might be unaware of. I find it a nice way to learn the internals of a programming language, and I think you'll find them interesting as well!
If you're an experienced Python programmer, you might be familiar with most of these examples, and I might be able to revive some sweet old memories of yours being bitten by these gotchas :sweat_smile:
So, here ya go...
# Table of Contents
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [Structure of the Examples](#structure-of-the-examples)
- [Some fancy Title](#some-fancy-title)
- [💡 Explanation:](#-explanation)
- [Usage](#usage)
- [👀 Examples](#-examples)
- [Skipping lines?](#skipping-lines)
- [💡 Explanation](#-explanation)
- [Well, something is fishy...](#well-something-is-fishy)
- [💡 Explanation](#-explanation-1)
- [Time for some hash brownies!](#time-for-some-hash-brownies)
- [💡 Explanation](#-explanation-2)
- [Evaluation time discrepancy](#evaluation-time-discrepancy)
- [💡 Explanation](#-explanation-3)
- [Modifying a dictionary while iterating over it](#modifying-a-dictionary-while-iterating-over-it)
- [💡 Explanation:](#-explanation-1)
- [Deleting a list item while iterating over it](#deleting-a-list-item-while-iterating-over-it)
- [💡 Explanation:](#-explanation-2)
- [Backslashes at the end of string](#backslashes-at-the-end-of-string)
- [💡 Explanation](#-explanation-4)
- [Let's make a giant string!](#lets-make-a-giant-string)
- [💡 Explanation](#-explanation-5)
- [String concatenation interpreter optimizations.](#string-concatenation-interpreter-optimizations)
- [💡 Explanation:](#-explanation-3)
- [Yes, it exists!](#yes-it-exists)
- [💡 Explanation:](#-explanation-4)
- [`is` is not what it is!](#is-is-not-what-it-is)
- [💡 Explanation:](#-explanation-5)
- [`is not ...` is different from `is (not ...)`](#is-not--is-different-from-is-not-)
- [💡 Explanation](#-explanation-6)
- [The function inside loop sticks to the same output](#the-function-inside-loop-sticks-to-the-same-output)
- [💡 Explanation](#-explanation-7)
- [Loop variables leaking out of local scope!](#loop-variables-leaking-out-of-local-scope)
- [💡 Explanation:](#-explanation-6)
- [A tic-tac-toe where X wins in the first attempt!](#a-tic-tac-toe-where-x-wins-in-the-first-attempt)
- [💡 Explanation:](#-explanation-7)
- [Beware of default mutable arguments!](#beware-of-default-mutable-arguments)
- [💡 Explanation:](#-explanation-8)
- [Same operands, different story!](#same-operands-different-story)
- [💡 Explanation:](#-explanation-9)
- [Mutating the immutable!](#mutating-the-immutable)
- [💡 Explanation:](#-explanation-10)
- [Using a variable not defined in scope](#using-a-variable-not-defined-in-scope)
- [💡 Explanation:](#-explanation-11)
- [The disappearing variable from outer scope](#the-disappearing-variable-from-outer-scope)
- [💡 Explanation:](#-explanation-12)
- [Return return everywhere!](#return-return-everywhere)
- [💡 Explanation:](#-explanation-13)
- [When True is actually False](#when-true-is-actually-false)
- [💡 Explanation:](#-explanation-14)
- [Be careful with chained operations](#be-careful-with-chained-operations)
- [💡 Explanation:](#-explanation-15)
- [Name resolution ignoring class scope](#name-resolution-ignoring-class-scope)
- [💡 Explanation](#-explanation-8)
- [From filled to None in one instruction...](#from-filled-to-none-in-one-instruction)
- [💡 Explanation](#-explanation-9)
- [Explicit typecast of strings](#explicit-typecast-of-strings)
- [💡 Explanation:](#-explanation-16)
- [Class attributes and instance attributes](#class-attributes-and-instance-attributes)
- [💡 Explanation:](#-explanation-17)
- [Catching the Exceptions!](#catching-the-exceptions)
- [💡 Explanation](#-explanation-10)
- [Midnight time doesn't exist?](#midnight-time-doesnt-exist)
- [💡 Explanation:](#-explanation-18)
- [What's wrong with booleans?](#whats-wrong-with-booleans)
- [💡 Explanation:](#-explanation-19)
- [Needle in a Haystack](#needle-in-a-haystack)
- [💡 Explanation:](#-explanation-20)
- [For what?](#for-what)
- [💡 Explanation:](#-explanation-21)
- [not knot!](#not-knot)
- [💡 Explanation:](#-explanation-22)
- [Let's see if you can guess this?](#lets-see-if-you-can-guess-this)
- [💡 Explanation:](#-explanation-23)
- [Minor Ones](#minor-ones)
- [TODO: Hell of an example!](#todo-hell-of-an-example)
- [Contributing](#contributing)
- [Acknowledgements](#acknowledgements)
- [Some nice Links!](#some-nice-links)
- [🎓 License](#-license)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
# Structure of the Examples
**Note:** All the examples mentioned below are tested on Python 3.5.2 interactive interpreter, and they should work for all the Python versions unless explicitly specified in the example description.
All the examples are structured like below:
### Some fancy Title
```py
# Setting up the code.
# Preparation for the magic...
```
**Output (Python version):**
```py
>>> triggering_statement
Probably unexpected output
```
(Optional): One line describing the unexpected output.
#### 💡 Explanation:
* Brief explanation of what's happening and why is it happening.
```py
Setting up examples for clarification (if necessary)
```
**Output:**
```py
>>> trigger # some example that makes it easy to unveil the magic
# some justified output
```
# Usage
A good way to get the most out of these examples, in my opinion, will be just to read the examples chronologically, and for every example:
- Carefully read the initial code for setting up the example. If you're an experienced Python programmer, most of the times you will successfully anticipate what's gonna happen next.
- Read the output snippets and
+ Check if the outputs are the same as you'd expect.
+ Make sure know the exact reason behind the output being the way it is.
- If no, read the explanation (and if you still don't understand, shout out! and create an issue [here](https://github.com/satwikkansal/wtfPython)).
- If yes, give a gentle pat on your back, and you may skip to the next example.
PS: You can also read these examples at the command line. First install the npm package `wtfpython`,
```sh
$ npm install -g wtfpython
```
Now, just run `wtfpython` at the command line which will open this collection in your selected `$PAGER`.
#TODO: Add pypi package for reading via command line
# 👀 Examples
### Skipping lines?
**Output:**
```py
>>> value = 11
>>> valuе = 32
>>> value
11
```
Wut?
**Note:** The easiest way to reproduce this is to simply copy the statements from the above snippet and paste them into your file/shell.
#### 💡 Explanation
Some Unicode characters look identical to ASCII ones, but are considered distinct by the interpreter.
```py
>>> value = 42 #ascii e
>>> valuе = 23 #cyrillic e, Python 2.x interpreter would raise a `SyntaxError` here
>>> value
42
```
---
### Well, something is fishy...
```py
def square(x):
"""
A simple function to calculate square of a number by addition.
"""
sum_so_far = 0
for counter in range(x):
sum_so_far = sum_so_far + x
return sum_so_far
```
**Output (Python 2.x):**
```py
>>> square(10)
10
```
Shouldn't that be 100?
**Note:** If you're not able to reproduce this, try running the file [mixed_tabs_and_spaces.py](/mixed_tabs_and_spaces.py) via the shell.
#### 💡 Explanation
* **Don't mix tabs and spaces!** The character just preceding return is a "tab", and the code is indented by multiple of "4 spaces" elsewhere in the example.
* This is how Python handles tabs:
> First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>
* So the "tab" at the last line of `square` function is replaced with eight spaces, and it gets into the loop.
* Python 3 is nice enough to automatically throw an error for such cases.
**Output (Python 3.x):**
```py
TabError: inconsistent use of tabs and spaces in indentation
```
---
### Time for some hash brownies!
1\.
```py
some_dict = {}
some_dict[5.5] = "Ruby"
some_dict[5.0] = "JavaScript"
some_dict[5] = "Python"
```
**Output:**
```py
>>> some_dict[5.5]
"Ruby"
>>> some_dict[5.0]
"Python"
>>> some_dict[5]
"Python"
```
"Python" destroyed the existence of "JavaScript"?
#### 💡 Explanation
* Python dictionaries check for equality and compare the hash value to determine if two keys are the same.
* Immutable objects with same value always have a same hash in Python.
```py
>>> 5 == 5.0
True
>>> hash(5) == hash(5.0)
True
```
**Note:** Objects with different values may also have same hash (known as hash collision).
* When the statement `some_dict[5] = "Python"` is executed, the existing value "JavaScript" is overwritten with "Python" because Python recongnizes `5` and `5.0` as the same keys of the dictionary `some_dict`.
* This StackOverflow [answer](https://stackoverflow.com/a/32211042/4354153) explains beautifully the rationale behind it.
---
### Evaluation time discrepancy
```py
array = [1, 8, 15]
g = (x for x in array if array.count(x) > 0)
array = [2, 8, 22]
```
**Output:**
```py
>>> print(list(g))
[8]
```
#### 💡 Explanation
- In a [generator](https://wiki.python.org/moin/Generators) expression, the `in` clause is evaluated at declaration time, but the conditional clause is evaluated at run time.
- So before run time, `array` is re-assigned to the list `[2, 8, 22]`, and since out of `1`, `8` and `15`, only the count of `8` is greater than `0`, the generator only yields `8`.
---
### Modifying a dictionary while iterating over it
```py
x = {0: None}
for i in x:
del x[i]
x[i+1] = None
print(i)
```
**Output:**
```
0
1
2
3
4
5
6
7
```
Yes, it runs for exactly **eight** times and stops.
#### 💡 Explanation:
* Iteration over a dictionary that you edit at the same time is not supported.
* It runs eight times because that's the point at which the dictionary resizes to hold more keys (we have eight deletion entries, so a resize is needed). This is actually an implementation detail.
* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/44763802/bug-in-python-dict) explaining a similar example.
---
### Deleting a list item while iterating over it
```py
list_1 = [1, 2, 3, 4]
list_2 = [1, 2, 3, 4]
list_3 = [1, 2, 3, 4]
list_4 = [1, 2, 3, 4]
for idx, item in enumerate(list_1):
del item
for idx, item in enumerate(list_2):
list_2.remove(item)
for idx, item in enumerate(list_3[:]):
list_3.remove(item)
for idx, item in enumerate(list_4):
list_4.pop(idx)
```
**Output:**
```py
>>> list_1
[1, 2, 3, 4]
>>> list_2
[2, 4]
>>> list_3
[]
>>> list_4
[2, 4]
```
Can you guess why the output is `[2, 4]`?
#### 💡 Explanation:
* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.
```py
>>> some_list = [1, 2, 3, 4]
>>> id(some_list)
139798789457608
>>> id(some_list[:]) # Notice that python creates new object for sliced list.
139798779601192
```
**Difference between `del`, `remove`, and `pop`:**
* `del var_name` just removes the binding of the `var_name` from the local or global namespace (That's why the `list_1` is unaffected).
* `remove` removes the first matching value, not a specific index, raises `ValueError` if the value is not found.
* `pop` removes element at a specific index and returns it, raises `IndexError` if an invalid index is specified.
**Why the output is `[2, 4]`?**
- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e. `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.
* See this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.
---
### Backslashes at the end of string
**Output:**
```
>>> print("\\ some string \\")
>>> print(r"\ some string")
>>> print(r"\ some string \")
File "<stdin>", line 1
print(r"\ some string \")
^
SyntaxError: EOL while scanning string literal
```
#### 💡 Explanation
- In a raw string literal, as indicated by the prefix `r`, the backslash doesn't have the special meaning.
- What the interpreter actually does, though, is simply change the behavior of backslashes, so they pass themselves and the following character through. That's why backslashes don't work at the end of a raw string.
---
### Let's make a giant string!
This is not a WTF at all, just some nice things to be aware of :)
```py
def add_string_with_plus(iters):
s = ""
for i in range(iters):
s += "xyz"
assert len(s) == 3*iters
def add_string_with_format(iters):
fs = "{}"*iters
s = fs.format(*(["xyz"]*iters))
assert len(s) == 3*iters
def add_string_with_join(iters):
l = []
for i in range(iters):
l.append("xyz")
s = "".join(l)
assert len(s) == 3*iters
def convert_list_to_string(l, iters):
s = "".join(l)
assert len(s) == 3*iters
```
**Output:**
```py
>>> timeit(add_string_with_plus(10000))
100 loops, best of 3: 9.73 ms per loop
>>> timeit(add_string_with_format(10000))
100 loops, best of 3: 5.47 ms per loop
>>> timeit(add_string_with_join(10000))
100 loops, best of 3: 10.1 ms per loop
>>> l = ["xyz"]*10000
>>> timeit(convert_list_to_string(l, 10000))
10000 loops, best of 3: 75.3 µs per loop
```
#### 💡 Explanation
- You can read more about [timeit](https://docs.python.org/3/library/timeit.html) from here. It is generally used to measure the execution time of snippets.
- Don't use `+` for generating long strings — In Python, `str` is immutable, so the left and right strings have to be copied into the new string for every pair of concatenations. If you concatenate four strings of length 10, you'll be copying (10+10) + ((10+10)+10) + (((10+10)+10)+10) = 90 characters instead of just 40 characters. Things get quadratically worse as the number and size of the string increases.
- Therefore, it's advised to use `.format.` or `%` syntax (however, they are slightly slower than `+` for short strings).
- Or better, if already you've contents available in the form of an iterable object, then use `''.join(iterable_object)` which is much faster.
---
### String concatenation interpreter optimizations.
```py
>>> a = "some_string"
>>> id(a)
140420665652016
>>> id("some" + "_" + "string") # Notice that both the ids are same.
140420665652016
# using "+", three strings:
>>> timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100)
0.25748300552368164
# using "+=", three strings:
>>> timeit.timeit("s1 += s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100)
0.012188911437988281
```
#### 💡 Explanation:
+ `+=` is faster than `+` for concatenating more than two strings because the first string (example, `s1` for `s1 += s2 + s3`) is not destroyed while calculating the complete string.
+ Both the strings refer to the same object because of CPython optimization hat tries to use existing immutable objects in some cases (implementation specific) rather than creating a new object every time. You can read more about this [here](https://stackoverflow.com/questions/24245324/about-the-changing-id-of-an-immutable-string)
---
### Yes, it exists!
**The `else` clause for loops.** One typical example might be:
```py
def does_exists_num(l, to_find):
for num in l:
if num == to_find:
print("Exists!")
break
else:
print("Does not exist")
```
**Output:**
```py
>>> some_list = [1, 2, 3, 4, 5]
>>> does_exists_num(some_list, 4)
Exists!
>>> does_exists_num(some_list, -1)
Does not exist
```
**The `else` clause in exception handling.** An example,
```py
try:
pass
except:
print("Exception occurred!!!")
else:
print("Try block executed successfully...")
```
**Output:**
```py
Try block executed successfully...
```
#### 💡 Explanation:
- The `else` clause after a loop is executed only when there's no explicit `break` after all the iterations.
- `else` clause after try block is also called "completion clause" as reaching the `else` clause in a `try` statement means that the try block actually completed successfully.
---
### `is` is not what it is!
The following is a very famous example present all over the internet.
```py
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
>>> a = 257; b = 257
>>> a is b
True
```
#### 💡 Explanation:
**The difference between `is` and `==`**
* `is` operator checks if both the operands refer to the same object (i.e. it checks if the identity of the operands matches or not).
* `==` operator compares the values of both the operands and checks if they are the same.
* So `is` is for reference equality and `==` is for value equality. An example to clear things up,
```py
>>> [] == []
True
>>> [] is [] # These are two empty lists at two different memory locations.
False
```
**`256` is an existing object but `257` isn't**
When you start up python the numbers from `-5` to `256` will be allocated. These numbers are used a lot, so it makes sense just to have them ready.
Quoting from https://docs.python.org/3/c-api/long.html
> The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behavior of Python, in this case, is undefined. :-)
```py
>>> id(256)
10922528
>>> a = 256
>>> b = 256
>>> id(a)
10922528
>>> id(b)
10922528
>>> id(257)
140084850247312
>>> x = 257
>>> y = 257
>>> id(x)
140084850247440
>>> id(y)
140084850247344
```
Here the interpreter isn't smart enough while executing `y = 257` to recognize that we've already created an integer of the value `257` and so it goes on to create another object in the memory.
**Both `a` and `b` refer to the same object, when initialized with same value in the same line.**
```py
>>> a, b = 257, 257
>>> id(a)
140640774013296
>>> id(b)
140640774013296
>>> a = 257
>>> b = 257
>>> id(a)
140640774013392
>>> id(b)
140640774013488
```
* When a and b are set to `257` in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already `257` as an object.
* It's a compiler optimization and specifically applies to the interactive environment. When you enter two lines in a live interpreter, they're compiled separately, therefore optimized separately. If you were to try this example in a `.py` file, you would not see the same behavior, because the file is compiled all at once.
---
### `is not ...` is different from `is (not ...)`
```py
>>> 'something' is not None
True
>>> 'something' is (not None)
False
```
#### 💡 Explanation
- `is not` is a single binary operator, and has behavior different than using `is` and `not` separated.
- `is not` evaluates to `False` if the variables on either side of the operator point to the same object and `True` otherwise.
---
### The function inside loop sticks to the same output
```py
funcs = []
results = []
for x in range(7):
def some_func():
return x
funcs.append(some_func)
results.append(some_func())
funcs_results = [func() for func in funcs]
```
**Output:**
```py
>>> results
[0, 1, 2, 3, 4, 5, 6]
>>> funcs_results
[6, 6, 6, 6, 6, 6, 6]
```
Even when the values of `x` were different in every iteration prior to appending `some_func` to `funcs`, all the functions return 6.
//OR
```py
>>> powers_of_x = [lambda x: x**i for i in range(10)]
>>> [f(2) for f in powers_of_x]
[512, 512, 512, 512, 512, 512, 512, 512, 512, 512]
```
#### 💡 Explanation
- When defining a function inside a loop that uses the loop variable in its body, the loop function's closure is bound to the variable, not its value. So all of the functions use the latest value assigned to the variable for computation.
- To get the desired behavior you can pass in the loop variable as a named variable to the function. **Why this works?** Because this will define the variable again within the function's scope.
```py
funcs = []
for x in range(7):
def some_func(x=x):
return x
funcs.append(some_func)
```
**Output:**
```py
>>> funcs_results = [func() for func in funcs]
>>> funcs_results
[0, 1, 2, 3, 4, 5, 6]
```
---
### Loop variables leaking out of local scope!
1\.
```py
for x in range(7):
if x == 6:
print(x, ': for x inside loop')
print(x, ': x in global')
```
**Output:**
```py
6 : for x inside loop
6 : x in global
```
But `x` was never defined outside the scope of for loop...
2\.
```py
# This time let's initialize x first
x = -1
for x in range(7):
if x == 6:
print(x, ': for x inside loop')
print(x, ': x in global')
```
**Output:**
```py
6 : for x inside loop
6 : x in global
```
3\.
```
x = 1
print([x for x in range(5)])
print(x, ': x in global')
```
**Output (on Python 2.x):**
```
[0, 1, 2, 3, 4]
(4, ': x in global')
```
**Output (on Python 3.x):**
```
[0, 1, 2, 3, 4]
1 : x in global
```
#### 💡 Explanation:
- In Python, for-loops use the scope they exist in and leave their defined loop-variable behind. This also applies if we explicitly defined the for-loop variable in the global namespace before. In this case, it will rebind the existing variable.
- The differences in the output of Python 2.x and Python 3.x interpreters for list comprehension example can be explained by following change documented in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) documentation:
> "List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also, note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular the loop control variables are no longer leaked into the surrounding scope."
---
### A tic-tac-toe where X wins in the first attempt!
```py
# Let's initialize a row
row = [""]*3 #row i['', '', '']
# Let's make a board
board = [row]*3
```
**Output:**
```py
>>> board
[['', '', ''], ['', '', ''], ['', '', '']]
>>> board[0]
['', '', '']
>>> board[0][0]
''
>>> board[0][0] = "X"
>>> board
[['X', '', ''], ['X', '', ''], ['X', '', '']]
```
We didn't assigned 3 "X"s or did we?
#### 💡 Explanation:
When we initialize `row` variable, this visualization explains what happens in the memory
![image](/images/tic-tac-toe/after_row_initialized.png)
And when the `board` is initialized by multiplying the `row`, this is what happens inside the memory (each of the elements `board[0]`, `board[1]` and `board[2]` is a reference to the same list referred by `row`)
![image](/images/tic-tac-toe/after_board_initialized.png)
---
### Beware of default mutable arguments!
```py
def some_func(default_arg=[]):
default_arg.append("some_string")
return default_arg
```
**Output:**
```py
>>> some_func()
['some_string']
>>> some_func()
['some_string', 'some_string']
>>> some_func([])
['some_string']
>>> some_func()
['some_string', 'some_string', 'some_string']
```
#### 💡 Explanation:
- The default mutable arguments of functions in Python aren't really initialized every time you call the function. Instead, the recently assigned value to them is used as the default value. When we explicitly passed `[]` to `some_func` as the argument, the default value of the `default_arg` variable was not used, so the function returned as expected.
```py
def some_func(default_arg=[]):
default_arg.append("some_string")
return default_arg
```
**Output:**
```py
>>> some_func.__defaults__ #This will show the default argument values for the function
([],)
>>> some_func()
>>> some_func.__defaults__
(['some_string'],)
>>> some_func()
>>> some_func.__defaults__
(['some_string', 'some_string'],)
>>> some_func([])
>>> some_func.__defaults__
(['some_string', 'some_string'],)
```
- A common practice to avoid bugs due to mutable arguments is to assign `None` as the default value and later check if any value is passed to the function corresponding to that argument. Example:
```py
def some_func(default_arg=None):
if not default_arg:
default_arg = []
default_arg.append("some_string")
return default_arg
```
---
### Same operands, different story!
1\.
```py
a = [1, 2, 3, 4]
b = a
a = a + [5, 6, 7, 8]
```
**Output:**
```py
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4]
```
2\.
```py
a = [1, 2, 3, 4]
b = a
a += [5, 6, 7, 8]
```
**Output:**
```py
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4, 5, 6, 7, 8]
```
#### 💡 Explanation:
* a += b doesn't behave the same way as a = a + b
* The expression `a = a + [5,6,7,8]` generates a new object and sets `a`'s reference to that new object, leaving `b` unchanged.
* The expression `a + =[5,6,7,8]` is actually mapped to an "extend" function that operates on the object such that `a` and `b` still point to the same object that has been modified in-place.
---
### Mutating the immutable!
```py
some_tuple = ("A", "tuple", "with", "values")
another_tuple = ([1, 2], [3, 4], [5, 6])
```
**Output:**
```py
>>> some_tuple[2] = "change this"
TypeError: 'tuple' object does not support item assignment
>>> another_tuple[2].append(1000) #This throws no error
>>> another_tuple
([1, 2], [3, 4], [5, 6, 1000])
>>> another_tuple[2] += [99, 999]
TypeError: 'tuple' object does not support item assignment
>>> another_tuple
([1, 2], [3, 4], [5, 6, 1000, 99, 999])
```
But I thought tuples were immutable...
#### 💡 Explanation:
* Quoting from https://docs.python.org/2/reference/datamodel.html
> Immutable sequences
An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.)
* `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place.
---
### Using a variable not defined in scope
```py
a = 1
def some_func():
return a
def another_func():
a += 1
return a
```
**Output:**
```py
>>> some_func()
1
>>> another_func()
UnboundLocalError: local variable 'a' referenced before assignment
```
#### 💡 Explanation:
* When you make an assignment to a variable in a scope, it becomes local to that scope. So `a` becomes local to the scope of `another_func`, but it has not been initialized previously in the same scope which throws an error.
* Read [this](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html) short but an awesome guide to learn more about how namespaces and scope resolution works in Python.
* To modify the outer scope variable `a` in `another_func`, use `global` keyword.
```py
def another_func()
global a
a += 1
return a
```
**Output:**
```py
>>> another_func()
2
```
---
### The disappearing variable from outer scope
```py
e = 7
try:
raise Exception()
except Exception as e:
pass
```
**Output (Python 2.x):**
```py
>>> print(e)
# prints nothing
```
**Output (Python 3.x):**
```py
>>> print(e)
NameError: name 'e' is not defined
```
#### 💡 Explanation:
* Source: https://docs.python.org/3/reference/compound_stmts.html#except
When an exception has been assigned using `as` target, it is cleared at the end of the except clause. This is as if
```py
except E as N:
foo
```
was translated to
```py
except E as N:
try:
foo
finally:
del N
```
This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because, with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.
* The clauses are not scoped in Python. Everything in the example is present in the same scope, and the variable `e` got removed due to the execution of the `except` clause. The same is not the case with functions which have their separate inner-scopes. The example below illustrates this:
```py
def f(x):
del(x)
print(x)
x = 5
y = [5, 4, 3]
```
**Output:**
```py
>>>f(x)
UnboundLocalError: local variable 'x' referenced before assignment