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
Copy file name to clipboardExpand all lines: CheatSheets/Python-cheatsheet.md
+252Lines changed: 252 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -1139,4 +1139,256 @@ class MyHashable:
1139
1139
returnhash(self.a)
1140
1140
```
1141
1141
1142
+
### Sortable
1143
+
***With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated.**
1144
+
***Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn't arise in other contexts.**
1145
+
***When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.**
1146
+
1147
+
```python
1148
+
from functools import total_ordering
1149
+
1150
+
@total_ordering
1151
+
classMySortable:
1152
+
def__init__(self, a):
1153
+
self.a = a
1154
+
def__eq__(self, other):
1155
+
ifisinstance(other, type(self)):
1156
+
returnself.a == other.a
1157
+
returnNotImplemented
1158
+
def__lt__(self, other):
1159
+
ifisinstance(other, type(self)):
1160
+
returnself.a < other.a
1161
+
returnNotImplemented
1162
+
```
1163
+
1164
+
### Iterator
1165
+
***Any object that has methods next() and iter() is an iterator.**
1166
+
***Next() should return next item or raise StopIteration.**
1167
+
***Iter() should return 'self'.**
1168
+
```python
1169
+
classCounter:
1170
+
def__init__(self):
1171
+
self.i =0
1172
+
def__next__(self):
1173
+
self.i +=1
1174
+
returnself.i
1175
+
def__iter__(self):
1176
+
returnself
1177
+
```
1178
+
1179
+
```python
1180
+
>>> counter = Counter()
1181
+
>>>next(counter), next(counter), next(counter)
1182
+
(1, 2, 3)
1183
+
```
1184
+
1185
+
#### Python has many different iterator objects:
1186
+
***Sequence iterators returned by the [iter()](#iterator) function, such as list\_iterator and set\_iterator.**
1187
+
***Objects returned by the [itertools](#itertools) module, such as count, repeat and cycle.**
1188
+
***Generators returned by the [generator functions](#generator) and [generator expressions](#comprehensions).**
1189
+
***File objects returned by the [open()](#open) function, etc.**
1190
+
1191
+
### Callable
1192
+
***All functions and classes have a call() method, hence are callable.**
1193
+
***When this cheatsheet uses `'<function>'` as an argument, it actually means `'<callable>'`.**
1194
+
```python
1195
+
classCounter:
1196
+
def__init__(self):
1197
+
self.i =0
1198
+
def__call__(self):
1199
+
self.i +=1
1200
+
returnself.i
1201
+
```
1202
+
1203
+
```python
1204
+
>>> counter = Counter()
1205
+
>>> counter(), counter(), counter()
1206
+
(1, 2, 3)
1207
+
```
1208
+
1209
+
### Context Manager
1210
+
***Enter() should lock the resources and optionally return an object.**
1211
+
***Exit() should release the resources.**
1212
+
***Any exception that happens inside the with block is passed to the exit() method.**
1213
+
***If it wishes to suppress the exception it must return a true value.**
***Only required method is iter(). It should return an iterator of object's items.**
1238
+
***Contains() automatically works on any object that has iter() defined.**
1239
+
```python
1240
+
classMyIterable:
1241
+
def__init__(self, a):
1242
+
self.a = a
1243
+
def__iter__(self):
1244
+
returniter(self.a)
1245
+
def__contains__(self, el):
1246
+
return el inself.a
1247
+
```
1248
+
1249
+
```python
1250
+
>>> obj = MyIterable([1, 2, 3])
1251
+
>>> [el for el in obj]
1252
+
[1, 2, 3]
1253
+
>>>1in obj
1254
+
True
1255
+
```
1256
+
1257
+
### Collection
1258
+
***Only required methods are iter() and len(). Len() should return the number of items.**
1259
+
***This cheatsheet actually means `'<iterable>'` when it uses `'<collection>'`.**
1260
+
***I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.**
1261
+
```python
1262
+
classMyCollection:
1263
+
def__init__(self, a):
1264
+
self.a = a
1265
+
def__iter__(self):
1266
+
returniter(self.a)
1267
+
def__contains__(self, el):
1268
+
return el inself.a
1269
+
def__len__(self):
1270
+
returnlen(self.a)
1271
+
```
1272
+
1273
+
### Sequence
1274
+
***Only required methods are len() and getitem().**
1275
+
***Getitem() should return an item at the passed index or raise IndexError.**
1276
+
***Iter() and contains() automatically work on any object that has getitem() defined.**
1277
+
***Reversed() automatically works on any object that has len() and getitem() defined.**
1278
+
```python
1279
+
classMySequence:
1280
+
def__init__(self, a):
1281
+
self.a = a
1282
+
def__iter__(self):
1283
+
returniter(self.a)
1284
+
def__contains__(self, el):
1285
+
return el inself.a
1286
+
def__len__(self):
1287
+
returnlen(self.a)
1288
+
def__getitem__(self, i):
1289
+
returnself.a[i]
1290
+
def__reversed__(self):
1291
+
returnreversed(self.a)
1292
+
```
1293
+
1294
+
#### Discrepancies between glossary definitions and abstract base classes:
1295
+
***Glossary defines iterable as any object with iter() or getitem() and sequence as any object with getitem() and len(). It does not define collection.**
1296
+
***Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has method iter(), while ABC Collection checks for iter(), contains() and len().**
1297
+
1298
+
### ABC Sequence
1299
+
***It's a richer interface than the basic sequence.**
1300
+
***Extending it generates iter(), contains(), reversed(), index() and count().**
1301
+
***Unlike `'abc.Iterable'` and `'abc.Collection'`, it is not a duck type. That is why `'issubclass(MySequence, abc.Sequence)'` would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray, memoryview and deque, because they are registered as Sequence's virtual subclasses.**
1302
+
```python
1303
+
from collections import abc
1304
+
1305
+
classMyAbcSequence(abc.Sequence):
1306
+
def__init__(self, a):
1307
+
self.a = a
1308
+
def__len__(self):
1309
+
returnlen(self.a)
1310
+
def__getitem__(self, i):
1311
+
returnself.a[i]
1312
+
```
1313
+
1314
+
#### Table of required and automatically available special methods:
0 commit comments