-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·2817 lines (1955 loc) · 70.3 KB
/
main.py
File metadata and controls
executable file
·2817 lines (1955 loc) · 70.3 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 '## 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:
j = 0
else:
j = 1
return C
assert f(0).j == 0
assert f(1).j == 1
if 'Everything is an object':
# All built-in types like `int`, `string` and `list`:
assert (1).__class__ == int
assert "ab".__class__ == str
assert [1, 2].__class__ == list
# Functions:
def f(): pass
print f.__class__
# Classes:
class C(object): pass
assert C.__class__ == type
assert C().__class__ == C
# Modules:
import os
print os.__class__
if '## __metaclass__ ## __new__':
"""
TODO
"""
if '## Bound method ## Unbound method':
"""
<http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static>
"""
class C(object):
def __init__(self, i):
self.i = i
def m(self):
return self.i
c = C(1)
# When we call a bound method:
assert c.m() == 1
# Python executes exactly the following call to an unbound method:
assert C.m(c) == 1
# This is why methods without a `self` always fail.
if '## Object':
"""
Base type of all Python built-in types.
In Python 2, it is possible for a user defined object not to
inherit from `object` (old style class).
In Python 3, user defined classes automatically inherit from it,
so every type derives from `object`.
"""
assert isinstance(1, object)
assert isinstance("ab", object)
def f(): pass
assert isinstance(f, object)
class C(object): pass
assert isinstance(C, object)
assert isinstance(C(), object)
import os
assert isinstance(os, object)
# This is everything objects give to classes:
print 'dir(object) = ' + str(dir(object))
print 'dir(object()) = ' + str(dir(object()))
if '## type':
"""
Built-in function type does two things:
- determine the type of an object
- dynamically create classes from strings
Important rules:
- the type of any type (built-in or user defined) is `type`.
- the type of any object is its type,
also known as class for user defined types.
"""
if 'determine type of value':
"""
The `type` object is at the base of all the hierarchy.
"""
assert type(type) == type
assert type(object) == type
assert type(1) == int
assert type(1.0) == float
assert type('abc') == str
assert type(u's') == unicode
assert type([]) == list
assert type({}) == dict
print type(lambda:1)
#<type 'function'>
class C(object): pass
assert type(C) == type
assert type(C()) == C
import os
print type(os)
#<type 'module'>
if 'Make classes dynamically':
class B(object): pass
class C(B):
a = 1
# Same as above.
C = type('C', (B,), {'a': 1})
assert C.a == 1
if '## __class__':
"""
Corresponding class object of a object.
The only difference from `type()` seems to be for old style classes:
<http://stackoverflow.com/questions/1060499/difference-between-typeobj-and-obj-class>
Therefore, there is no difference in Python 3.
"""
assert object.__class__ == type
assert (1).__class__ == int
"""
`__class__` can be set to something else however.
This has no special effect.
"""
class D(object): pass
class C(object):
__class__ = D
assert type(C()) == C
assert C().__class__ == D
if '## isinstance':
"""
TODO: like type but also considers base types?
"""
assert isinstance(object, type)
assert isinstance(1, int)
class C0(object): pass
class C1(C0): pass
assert isinstance(C1(), C1)
assert isinstance(C1(), C0)
if '## attributes':
"""
Anything you can get from an object via a dot `.`, including methods and memebers.
Good tutorial: <http://www.cafepy.com/article/python_attributes_and_methods/contents.html>
How the dot searches for attributes on `obj.attr`:
1) `obj.__dict__` itself
2) `obj.__class__.__dict__`
3) then searches all base classes via MRO.
"""
class C:
pass
# Create a new attribute for class object C:
C.i = 1
c = C()
c2 = C()
# Attribute not found on object. Look at class:
assert c.i == 1
# Add attribute to object.
c.i = 2
# Attribute found on object. Ignore class attributes:
assert c.i == 2
# Can use __class__ to reach the class attribute:
assert c.__class__.i == 1
# Create a new function attribute for the class:
def m(self):
return 1
C.m = m
assert C().m() == 1
if '## haSattr':
class A:
a = 1
def f():
pass
assert hasattr(A, 'a')
assert hasattr(A, 'f')
assert not hasattr(A, 'b')
assert hasattr(A(), 'a')
assert hasattr(A(), 'f')
assert not hasattr(A(), 'b')
if '## geAttr':
class C:
def __init__(self, i):
self.attribute = i
c = C(1)
c.attribute2 = 2
assert getattr(c, "attribute") == 1
assert getattr(c, "attribute2") == 2
assert getattr(c, "notanattribute", "default") == "default"
if '## seTattr':
class A: pass
setattr(A, 'name', 'value')
assert A.name == 'value'
###any expression goes
hasa = True
class A:
if hasa:
a = 1
else:
a = 0
assert A.a == 1
if '## __dict__':
"""
Contains all attributes of an object.
Represents a base data structure for objects, and is used on the magic dot `.` attribute lookup.
"""
if 'Does not contain attributes inherited through `__class__` and MRO.':
class B(object):
a = 1
def __init__(self):
self.b = 1
class C(B):
c = 2
def __init__(self):
self.d = 2
super(C, self).__init__()
print 'C.__dict__ = ' + str(C.__dict__)
C.__dict__
assert C().__dict__ == {'b':1, 'd':2}
if 'It is possible to write directly to it from both sides.':
class C(object): pass
c = C()
c.__dict__['a'] = 1
assert c.a == 1
c.a = 2
assert c.__dict__['a'] == 2
class C(object): pass
c = C()
c.__dict__ = {'a':1, 'b':2}
assert c.a == 1
assert c.b == 2
c.__dict__.update({'a':2, 'c':3})
assert c.a == 2
assert c.c == 3
# TODO why not here:
class C(object): pass
try:
C.__dict__['a'] = 1
except TypeError:
#'dictproxy' object does not support item assignment
pass
else:
assert False
# Built-in functions and types don't have a dict.
# It is not possible to set their attributes.
try:
(1).__dict__
except AttributeError:
#'int' object has no attribute '__dict__'
pass
else:
assert False
try:
(1).a = 2
except AttributeError:
#'int' object has no attribute 'a'
pass
else:
assert False
try:
(len).a = 2
except AttributeError:
#'builtin_function_or_method' object has no attribute 'a'
pass
else:
assert False
# Functions:
def f():
"""doc"""
a = 1
assert f.__dict__ == {}
f.a = 1
assert f.__dict__['a'] == 1
f.__dict__['b'] = 2
assert f.b == 2
print 'f.__dict__ = ' + str(f.__dict__)
# Sample output:
#{'a': 1, '__module__': '__main__', '__doc__': 'doc', 'f': <function f at 0x9cb82cc>}
if '## dir':
"""
Returns a list of all attributes of an object.
Includes attributes available through `__class__` and base classes.
Does a search in the `__dict__` attributes in the same order as the dot `.` operator.
"""
print 'dir(1) = ' + str(dir(1))
class C(object): pass
print 'dir(C) = ' + str(dir(C))
print 'dir(C()) = ' + str(dir(C()))
import os
print 'dir(os) = ' + str(dir(os))
if '## inspect':
"""
Module that can do many introspective things on Python objects.
"""
if '## reflection':
# Get meta info objects.
class C:
"""doc"""
def __init__(self, name):
"""initdoc"""
self.name = name
def print_attrs(self):
"""print_attrs_doc"""
for name in dir(self):
attr = getattr(self, name)
if not callable(attr):
print name, ':', attr
def print_method_docs(self):
"""print_method_docs.doc"""
for name in dir(self):
attr = getattr(self, name)
if callable(attr):
print name, ':', attr.__doc__
c = C('the my object')
c.print_attrs()
# TODO: sane way to get only user defined attributes: http://stackoverflow.com/questions/4241171/inspect-python-class-attributes
if '## vars':
#list all available names in current scope and their string values:
vars()
if '## old style ## new style ## classic':
"""
In Python 2 there are 2 types of classes:
- classic classes. The only type that existed up to `2.1`.
They are deprecated and existed only for backwards compatibility.
- new-style classes. Appeared in 2.2. To create a new-style class
it must derive from `object`.
Always use new style classes for new code.
In Python 3 classic classes disappear, and it is not necessary
to derive from `object` anymore.
<http://stackoverflow.com/questions/2399307/python-invoke-super-constructor>
Behaviours that have changed between old and new style classes:
- super added
- MRO changed
- descriptors added
- `__slots__` added
"""
class Old: