Skip to content

Commit a1438ad

Browse files
Merge pull request #105 from imran1509/main
Python cheatsheet update 4
2 parents 4fef641 + 32ff149 commit a1438ad

File tree

1 file changed

+252
-0
lines changed

1 file changed

+252
-0
lines changed

CheatSheets/Python-cheatsheet.md

Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1139,4 +1139,256 @@ class MyHashable:
11391139
return hash(self.a)
11401140
```
11411141

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+
class MySortable:
1152+
def __init__(self, a):
1153+
self.a = a
1154+
def __eq__(self, other):
1155+
if isinstance(other, type(self)):
1156+
return self.a == other.a
1157+
return NotImplemented
1158+
def __lt__(self, other):
1159+
if isinstance(other, type(self)):
1160+
return self.a < other.a
1161+
return NotImplemented
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+
class Counter:
1170+
def __init__(self):
1171+
self.i = 0
1172+
def __next__(self):
1173+
self.i += 1
1174+
return self.i
1175+
def __iter__(self):
1176+
return self
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+
class Counter:
1196+
def __init__(self):
1197+
self.i = 0
1198+
def __call__(self):
1199+
self.i += 1
1200+
return self.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.**
1214+
```python
1215+
class MyOpen:
1216+
def __init__(self, filename):
1217+
self.filename = filename
1218+
def __enter__(self):
1219+
self.file = open(self.filename)
1220+
return self.file
1221+
def __exit__(self, exc_type, exception, traceback):
1222+
self.file.close()
1223+
```
1224+
1225+
```python
1226+
>>> with open('test.txt', 'w') as file:
1227+
... file.write('Hello World!')
1228+
>>> with MyOpen('test.txt') as file:
1229+
... print(file.read())
1230+
Hello World!
1231+
```
1232+
1233+
1234+
Iterable Duck Types
1235+
-------------------
1236+
### Iterable
1237+
* **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+
class MyIterable:
1241+
def __init__(self, a):
1242+
self.a = a
1243+
def __iter__(self):
1244+
return iter(self.a)
1245+
def __contains__(self, el):
1246+
return el in self.a
1247+
```
1248+
1249+
```python
1250+
>>> obj = MyIterable([1, 2, 3])
1251+
>>> [el for el in obj]
1252+
[1, 2, 3]
1253+
>>> 1 in 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+
class MyCollection:
1263+
def __init__(self, a):
1264+
self.a = a
1265+
def __iter__(self):
1266+
return iter(self.a)
1267+
def __contains__(self, el):
1268+
return el in self.a
1269+
def __len__(self):
1270+
return len(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+
class MySequence:
1280+
def __init__(self, a):
1281+
self.a = a
1282+
def __iter__(self):
1283+
return iter(self.a)
1284+
def __contains__(self, el):
1285+
return el in self.a
1286+
def __len__(self):
1287+
return len(self.a)
1288+
def __getitem__(self, i):
1289+
return self.a[i]
1290+
def __reversed__(self):
1291+
return reversed(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+
class MyAbcSequence(abc.Sequence):
1306+
def __init__(self, a):
1307+
self.a = a
1308+
def __len__(self):
1309+
return len(self.a)
1310+
def __getitem__(self, i):
1311+
return self.a[i]
1312+
```
1313+
1314+
#### Table of required and automatically available special methods:
1315+
```text
1316+
+------------+------------+------------+------------+--------------+
1317+
| | Iterable | Collection | Sequence | abc.Sequence |
1318+
+------------+------------+------------+------------+--------------+
1319+
| iter() | REQ | REQ | Yes | Yes |
1320+
| contains() | Yes | Yes | Yes | Yes |
1321+
| len() | | REQ | REQ | REQ |
1322+
| getitem() | | | REQ | REQ |
1323+
| reversed() | | | Yes | Yes |
1324+
| index() | | | | Yes |
1325+
| count() | | | | Yes |
1326+
+------------+------------+------------+------------+--------------+
1327+
```
1328+
* **Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.**
1329+
* **Names of their required methods are stored in `'<abc>.__abstractmethods__'`.**
1330+
1331+
1332+
Enum
1333+
----
1334+
```python
1335+
from enum import Enum, auto
1336+
```
1337+
1338+
```python
1339+
class <enum_name>(Enum):
1340+
<member_name_1> = <value_1>
1341+
<member_name_2> = <value_2_a>, <value_2_b>
1342+
<member_name_3> = auto()
1343+
```
1344+
* **If there are no numeric values before auto(), it returns 1.**
1345+
* **Otherwise it returns an increment of the last numeric value.**
1346+
1347+
```python
1348+
<member> = <enum>.<member_name> # Returns a member.
1349+
<member> = <enum>['<member_name>'] # Returns a member or raises KeyError.
1350+
<member> = <enum>(<value>) # Returns a member or raises ValueError.
1351+
<str> = <member>.name # Returns member's name.
1352+
<obj> = <member>.value # Returns member's value.
1353+
```
1354+
1355+
```python
1356+
list_of_members = list(<enum>)
1357+
member_names = [a.name for a in <enum>]
1358+
member_values = [a.value for a in <enum>]
1359+
random_member = random.choice(list(<enum>))
1360+
```
1361+
1362+
```python
1363+
def get_next_member(member):
1364+
members = list(member.__class__)
1365+
index = (members.index(member) + 1) % len(members)
1366+
return members[index]
1367+
```
1368+
1369+
### Inline
1370+
```python
1371+
Cutlery = Enum('Cutlery', 'fork knife spoon')
1372+
Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon'])
1373+
Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
1374+
```
1375+
1376+
#### User-defined functions cannot be values, so they must be wrapped:
1377+
```python
1378+
from functools import partial
1379+
LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
1380+
'OR': partial(lambda l, r: l or r)})
1381+
```
1382+
* **Member names are in all caps because trying to access a member that is named after a reserved keyword raises SyntaxError.**
1383+
1384+
1385+
Exceptions
1386+
----------
1387+
```python
1388+
try:
1389+
<code>
1390+
except <exception>:
1391+
<code>
1392+
```
1393+
11421394

0 commit comments

Comments
 (0)