forked from cirosantilli/python-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·3282 lines (2274 loc) · 82.2 KB
/
main.py
File metadata and controls
executable file
·3282 lines (2274 loc) · 82.2 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
TODO: split this up into smaller files.
Major cheat on the Python language and stdlibs.
Contains every test that does not:
- produces too much stdout, or one that is too complex to assert, e.g. human readable
- takes a perceptible ammount of time to run
- cannot be contained on a single file
"""
import re
import sys
import shutil
import tempfile
import itertools
if '## whitespace':
# Python forces certain indentations
# Use backslash '\' for line continuation of long commands:
assert \
1+\
1\
== 2
# Parenthesis also work:
assert (
1+
1 ==
2
)
if '## whitespace and functions':
# Cannot separate `(` from function def:
#def f
#(x,y):
#pass
# Everything else works.
# Good:
def f(x,y):
"""
docstrings must be indented
"""
pass
# My favorite format for lots of args:
def f(
x,
y,
z,
w
):
pass
# Ugly but works:
def f(
x
,y,
z
):
pass
# Single line only
def f(): pass
#def f(): pass
#pass
def f(x,y):
pass
f(1,2)
f(1,
2)
f(
1,
2
)
def f():
g(
1,
2
)
# Anything that has `:` like `if`, `while` and `class` works like function.
if '## multiple commands on a single line':
# <http://stackoverflow.com/questions/6167127/how-to-put-multiple-statements-in-one-line>
# Only possible for multiple simple statements.
i = 0; i += 1; assert i == 1
# Only use this for bash one liners.
if '## built-in':
"""
Python has three kinds of built-ins:
- functions
- constants
- types
Built-ins add insanity to the language, but allow us to write much shorter
and more readable code. It is the classical sanity / sugarness tradeoff of language design.
Those built-ins are mostly just like user defined types except for some points.
Notable differences include:
- they do not need to be imported: they are always available on any scope.
- some (but not all) built-in types have nice looking literals such as `1`, `[1]` or `{1: 2}`
It is however be possible to create any type with a built-in factory function.
- most built-in types are lower case words by convention, while classes usually start with Upper case.
"""
if 'It is not possible to set attributes of built-in types.':
class C: pass
C.i = 1
try:
int.i = 1
except TypeError:
pass
else:
assert False
if '## built-in constants':
"""
Python has the following built-in constants:
- `True`
- `False`
- `None`
- ##NotImplemented
Vs. `NotImplementedError` built-in exception:
<http://stackoverflow.com/questions/878943/why-return-notimplemented-instead-of-raising-notimplementederror>
- `Ellipsis`
- `__debug__`
Besides those, there are also builtin exception objects.
"""
# Can be reassigned in Python 2.
def f():
False = 10
assert False == 10
f()
if '## built-in functions':
if '## help':
"""
Intended for interactive usage documentation retrieval.
If linked to a tty, opens the doc of the given object in a pager.
Else, does nothing.
"""
def f():
"""doc"""
#help(f)
if '## locals':
# TODO
pass
if '## globals':
# TODO
pass
# Built-in functions:
assert abs(-1) == 1
if '## max':
# Returns the first max item according to some metric:
assert max(1, -2, 0) == 1
assert max([1, -2, 0]) == 1
assert max([1, -2, 0, 2], key=lambda x: x*x) == -2
# TODO best way to get the value of key withtout recalculating?
def f(x): return x*x
assert f(max([1, -2, 0, 2], key=f)) == 4
if '## exec':
# Interpret a string at given point.
a = 0
exec('a = 1')
assert a == 1
if '## built-in types ## types':
"""
<http://docs.python.org/3.3/reference/datamodel.html>
Types which are already defined by the interpreter,
and do not need to be imported from the stdlib.
They may have special (non-class-like) literals like ints `1` and lists: `[1, 2]`.
All have global function constructors like `list()` or `set()`,
The built-in types can be classified based on which ABCs they implement.
All the Python 2 built-in types are:
- numbers: implement the `numbers.Number` ABC or its derived classes.
All immutable.
- integers: `numbers.Integral`
- int
- long
- bool
- real: `numbers.Real`
- float
- complex: `numbers.Complex`
- complex
- sequences:
It seems that in Python 2 there is not a fixed ABC for them.
In Python 3 they implement `collections.abc.Sequence`. Much saner.
- immutable:
- str
- unicode
- tuple
- mutable:
- list
- bytearray
- memoryview
- sets: in Python 3 they implement `collections.abc.Set`
- set
- frozenset
- mappings:
Only one:
- dict
- super
"""
assert(type(int()) == type(0))
assert(type(float()) == type(0.0))
assert(type(long()) == type(0L))
assert(type(complex()) == type(1j))
if '## bytearray':
"""
Mutable version of `str`.
"""
ba = bytearray(b'ab')
ba2 = ba
ba2[0] = ord(b'b')
assert ba == bytearray(b'bb')
if '## branching':
if '## if':
if False:
assert False
elif False:
assert False
else:
pass
if '## multiline condition':
# Multiline conditions must have parenthesis:
if (a
and b
and c
and d):
pass
if '## single line':
# Behaves like the C question mark `?` operator.
# Must have the else part:
a = 1 if True else 2
assert a == 1
a = 1 if False else 2
assert a == 2
if '## is':
# `is` checks for equality of reference equality instead of using __equals__
class C(object):
def __eq__(self, other): True
assert C() != C()
assert not C() is C()
c = C()
assert c is c
# In Python 2, not guaranteed because True and False can be reassigned.
# In Python 3, guaranteed.
# http://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail-or-is-it-guarante
assert 1 == True
assert not 1 is True
assert 0 == False
assert not 0 is False
assert not None == False
assert not None is False
assert not '' == False
assert not '' is False
assert not '' == None
assert not [] == False
assert not [] is False
if '## truth value testing for objects':
"""
Any object can be used on an if or while.
In Python 2, an object evaluates to false iff:
- it implements `__nonzero__` and `__nonzero__()` if False.
- else if it impements `__len__`, and `__len__() == 0`
Any other object evaluates to True.
For the built-in types, the only the following are test False:
- None
- False
- zero of any numeric type, for example, 0, 0L, 0.0, 0j.
- any empty sequence, for example, '', (), [], set().
- any empty mapping, for example, {}.
"""
if '':
assert False
if ' ':
pass
else:
assert False
if []:
assert False
if [False]:
pass
else:
assert False
if None:
assert False
"""
Truth value testing can differ from `__eq__` to True or false!
Something that is not equal to True can still works for an if!
"""
assert -1 != True
if -1:
pass
else:
assert False
if '## while':
i = 0
while i < 10:
print i
i += 1
i = 0
while i < 10:
print i
if i == 5:
break
i += 1
i = 0
while i < 10:
print i
i += 1
if i == 5:
continue
if '## for':
for i in [1, 3, 2]:
print i
for i in [1, 3, 2]:
print i
if i == 3:
break
for i in [1, 3, 2]:
print i
if i == 3:
continue
"""
# Modify list while itearting it
Just don't do it. Make a copy instead. There is no decent efficient way like in Java:
http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python/34238688#34238688
"""
if '## and ## or':
"""
And and or are actually branching instructions:
analogous to ``&&`` and ``||`` in bash.
- and evaluates the first expression. If False return it, if true return the second.
- or evaluates the first expression. If True return it, if false return the second one.
"""
assert (True and 1) == 1
assert (False and 1) == False
assert (True or 1) == True
assert (False or 1) == 1
if '## Function':
if '## Arguments':
def f(a, b = 0, *args, **kwargs):
"""
args is a tuple
kwargs a dicdt
those names are just a convention,
any name can be used, ex:
def g(*myArgs, **myEtraKwargs)
"""
#args is a tuple.
for arg in list(args):
pass
#you can iterate over it.
#this is a standard way to give default values:
kw1 = kwargs.get(1, "default1")
kw2 = kwargs.get(2, "default2")
kw2 = kwargs.get(3, "default3")
return a, b, list(args), kwargs
#ERROR: argument a has no value
#f()
assert f(1) == (1, 0, [] , {} )
assert f(1, 2) == (1, 2, [] , {} )
assert f(1, 2, 3) == (1, 2, [3], {} )
assert f(1, 2, 3, 4) == (1, 2, [3, 4], {} )
assert f(1, 2, 3, 4, c=5, d=6) == (1, 2, [3, 4], {'c':5, 'd':6} )
assert f(1, 2, c=5, d=6) == (1, 2, [], {'c':5, 'd':6} )
# If a named parameter exists already, it does not go into kwargs:
assert f(a = 1) == (1, 0, [], {} )
assert f(a = 1, b = 2) == (1, 2, [], {} )
assert f(b = 2, a = 1) == (1, 2, [], {} )
assert f(a = 1, b = 2, c = 5) == (1, 2, [], {'c':5} )
if '## Unpack argument lists ## Splat':
# Splat is the Rubish term for it.
# Transform list or dictionnaries into function arguments.
assert f(*[0, 1]) == (0, 1, [], {})
assert f(0, 1, *[2, 3]) == (0, 1, [2, 3], {})
# Part of them may be named arguments, part may be *args.
assert f(0, *[1, 2, 3]) == (0, 1, [2, 3], {})
# ERROR: only named arguments may follow unpacked list
assert f(0, 1, *[2, 3], c=4) == (0, 1, [2, 3], {'c':4})
#assert f(0, 1, *[2, 3], 4) == (0, 1, [2, 3, 4], {})
# Also possible with dictionnaries:
assert f(1, 2, 3, 4, **{'c': 5, 'd': 6}) == (1, 2, [3, 4], {'c': 5, 'd': 6} )
assert f(1, 2, **{'c': 5, 'd': 6}) == (1, 2, [], {'c': 5, 'd': 6} )
# Can combine dict unpack with named arguments:
assert f(1, 2, d=6, **{'c': 5} ) == (1, 2, [], {'c': 5, 'd': 6} )
# ERROR: dict unpack must be the last thing:
#assert f(1, 2, **{'c': 5}, d=6 ) == (1, 2, [], {'c': 5, 'd': 6} )
# Can use list unpack with dict unpack:
assert f(1, *[2, 3, 4], d=6, **{'c': 5}) == (1, 2, [3, 4], {'c': 5, 'd': 6} )
# ERROR: multiple values for `a`:
#f(1, a = 1)
# ERROR: can only pass dictionnaries if there is a kwargs
#def g(a): pass
#g(a = 1)
# OK: we have kwargs:
def g(a, **kwargs): pass
g(a = 1)
# ERROR: cannot change the order of normal args, *args and **kwargs:
#def f(*args, a): pass
#def f(**kwargs, a): pass
#def f(**kwargs, *args): pass
# ERROR: cannot use integer (5) as keyword for kwargs: must use strings
#f(1, 2, *[3, 4], **{5:6})
if '## overload':
"""there is no function overloading in python"""
def f(a):
"""
completely destroys last existing f
"""
return a
def f(a, b):
return a + b
"too many args:"
#f(1, 2, 3)
if 'default values for lots of kwargs':
# If you have default values to a large number of them kwargs
# this is a good way, which saves you from writting lots of ``gets``
def f( **non_default_kwargs ):
kwargs = {
'a':1,
'b':2,
}
kwargs.update( non_default_kwargs )
f2( **kwargs )
if 'variables can contain functions':
def f(x):
return x + 1
g = f
assert g(0) == 1
if '## immutable types ## mutable types':
"""
Literals like `1` and `1.1` are objects.
Immutable type: there is no way (function, member, etc.) to modify the object itself.
It is only possible to point to a different object of the same type.
For all standard types, doing `a = b` always makes a point to a different thing,
and does not change what `a` was pointing to.
For other operators this may vary: `a += 1` may change what `a` points to, or the object pointed to
depending on the type.
Immutable types include:
- numeric types like integers and floats
- strings
- tuples
Mutable types include:
- lists
- dictionnaries
"""
if 'immutable:':
x = 1
assert id(x) == id(1)
y = x
assert id(x) == id(y)
y = 2
assert x == 1
assert id(y) == id(2)
if 'mutable:':
x = [1]
assert id(x) != id([1])
assert x == [1]
x = [1]
y = x
assert id(y) == id(x)
x = [1]
y = x
assert id(y) == id(x)
y[0] = 2
assert x == [2]
assert id(x) == id(y)
# For mutable types, `+=` may change the actuabl object, not just the address to which `y` points to.
y += [3]
assert id(x) == id(y)
assert x == [2, 3]
# Doing `y = ` however does change the address pointed to.
y = [0]
assert id(x) != id(y)
def f(y):
y[0] = 2
x = [1]
f(x)
assert x == [2]
"""
Immutable built-in types all implement `__hash__`. Mutable built-in types are not.
User defined types are all hashable.
"""
s = set()
s.add(1) # OK: hashable.
try:
s.add([1]) # KO: not hashable
except TypeError:
pass
else:
assert False
"""
list constructor does shallow copies.
"""
x = [0, [10]]
y = list(x) # or x[:]
y[0] = 1
y[1][0] = 11
assert x == [0, [11]]
assert y == [1, [11]]
if '## Pass by value ## Pass by reference':
"""
Flamethrower battle: http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference
Only modifications on mutable objects inside a function have effect outside it.
"""
def f(a, b):
a = a + b
# integer: immutable
a = 0
f(a, 1)
assert a == 0
def g(i):
return i + 1
a = 0
a = g(a)
assert a == 1
# string: immutable
a = "a"
f(a, "b")
assert a == "a"
def g(s):
return s + "b"
a = "a"
a = g(a)
assert a == "ab"
# list: mutable
a = [0]
f(a, [1])
assert a == [0]
def g(a):
a.append(1)
a = [0]
g(a)
assert a == [0, 1]
if '## Return value':
if '## Multiple return values':
"""
there is no real multiple return values,
but you can return a single tuple of values and open it
this is one of the major motivations for tuples existing in the language
"""
def f():
"""
returns multiple arguments
"""
return 1, 2
#SAME:
#return (1, 2)
a, b = f()
assert a == 1
assert b == 2
if '## can return nothing':
"""
If a function does not end on a return statement, it returns `None`.
"""
def f(b):
if b:
return 1
assert f(True) == 1
assert f(False) == None
if '## redefine':
# Like any python object, you can redfine functions whenever you want.
def f():
return 0
def f():
return 1
assert f() == 1
class f:
pass
if '## functions can have attributes':
# Function attributes have no relation to local variables.
def f():
c = 1
return c
f.c = 2
assert f() == 1
assert f.c == 2
# View all the function attributes:
print 'dir(f) = ' + str(dir(f))
# The most important attribute is `__call__` which allows us to call the function:
assert f.__call__() == 1
if '## lambda':
"""
Lambda is a function without name
Lambda functions can only contain a single expression.
This means in particular that they cannot contain assigments,
so they are very limited.
"""
f = lambda x: x + 1
assert f(0) == 1
assert f(1) == 2
if '## scope':
"""
If the value of a variable was not defined inside the function,
the value in the currently executing scope is taken.
"""
def f(b):
return a == b
a = 1
assert f(1) == True
a = 2
assert f(1) == False
if '## global':
def global_inc_a_wrong():
a = 2
def global_inc_a():
global a
a = a + 1
a = 1
global_inc_a_wrong()
assert a == 1
global_inc_a()
assert a == 2
# If the variable was not yet defined on global scope,
# it then gets defined once the function is called
# and the assignement occurs:
def global_def():
global defined_in_global_def
#This will define the variable on global scope:
defined_in_global_def = 1
try:
print defined_in_global_def
except NameError:
pass
else:
assert False
global_def()
print defined_in_global_def
# Global means *global*, and *not* inside another function:
def outer():
x = 1
def inner():
#This x is not the same as the first one,
#but one on a global scope
global x
x = 2
#Here we do not see the global x,
#but the one inside outer:
inner()
assert x == 1
#Here we see the global x defined inside inner:
outer()
assert x == 2
# Compare this to what happens with nonlocal in Python 3.
if '## nested functions':
# This is the way to go:
def ex8():
ex8.var = 'foo'
def inner():
ex8.var = 'bar'
print 'inside inner, ex8.var is ', ex8.var
inner()
print 'inside outer function, ex8.var is ', ex8.var
ex8()
if '## call function from its name on a string':
#http://stackoverflow.com/questions/3061/calling-a-function-from-a-string-with-the-functions-name-in-python
pass
if '## class':
"""
Python classes are designed such that some of its syntax is analogous to C++
classes.
However, Python classes are much more dynamic and allow for many things which C++
classes do not.
In most cases, Python classes are used with syntax similar to C++ syntax.
However, there are practical cases where the full flexibility of Python classes are used,
and your C++ knowledge breaks.
The faster you learn about how exacly Python classes work, the faster the magic will go away.
The key points are:
- classes and everythin else in Python are objects
- attributes and the dot `.` operator
- __dict__
- bound methods
"""
if 'Classes are objects':
class C(object):
i = 1
pass
# You can assign it to a variable:
D = C
assert D.i == 1
# You can add attributes to it:
C.j = 2
assert C.j == 2
# You can return it from functions:
def f(i):
class C(object):
if i == 0: