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
@@ -1235,6 +1168,86 @@ con = sqlite3.connect('<path>'); with con: con.execute('<insert_query>')
1235
1168
```
1236
1169
1237
1170
1171
+
Iterable Duck Types
1172
+
-------------------
1173
+
1174
+
### Iterable
1175
+
***Only required method for iterable is iter(), that should return an iterator of its contents.**
1176
+
***Contains() is automatically generated whenever iter() is present.**
1177
+
```python
1178
+
classMyIterable:
1179
+
def__init__(self, a):
1180
+
self.a = a
1181
+
def__iter__(self):
1182
+
for el inself.a:
1183
+
yield el
1184
+
```
1185
+
1186
+
```python
1187
+
>>> a = MyIterable([1, 2, 3])
1188
+
>>>iter(a)
1189
+
<generator object MyIterable.__iter__ at 0x1026c18b8>
1190
+
>>>1in a
1191
+
True
1192
+
```
1193
+
1194
+
### Collection
1195
+
***Every collection is also an iterable.**
1196
+
***This cheatsheet actually means `'<iterable>'` when it uses `'<collection>'`.**
1197
+
***I chose not to use the name iterable because it sounds scarier and more vague than collection.**
1198
+
```python
1199
+
classMyCollection:
1200
+
def__init__(self, a):
1201
+
self.a = a
1202
+
def__contains__(self, el):
1203
+
return el inself.a
1204
+
def__len__(self):
1205
+
returnlen(self.a)
1206
+
def__iter__(self):
1207
+
for el inself.a:
1208
+
yield el
1209
+
```
1210
+
1211
+
### Sequence
1212
+
***Every sequence is also a collection.**
1213
+
***Iter() and reversed() are automatically generated whenever getitem() is present.**
1214
+
```python
1215
+
classMySequence:
1216
+
def__init__(self, a):
1217
+
self.a = a
1218
+
def__getitem__(self, i):
1219
+
returnself.a[i]
1220
+
def__len__(self):
1221
+
returnlen(self.a)
1222
+
```
1223
+
1224
+
### Collections.abc.Sequence
1225
+
***It's a richer interface than the basic sequence.**
1226
+
***Extending it generates contains(), iter(), reversed(), index(), and count().**
1227
+
***Unlike `'abc.Iterable'` and `'abc.Collection'`, it is not a duck type. That's why `'issubclass(MySequence, collections.abc.Sequence)'` would return 'False' even if it had all the methods defined.**
1228
+
```python
1229
+
classMyAbcSequence(collections.abc.Sequence):
1230
+
def__init__(self, a):
1231
+
self.a = a
1232
+
def__getitem__(self, i):
1233
+
returnself.a[i]
1234
+
def__len__(self):
1235
+
returnlen(self.a)
1236
+
```
1237
+
1238
+
#### Table of the methods that each (duck) type provides:
0 commit comments