Browse Source

Cleanup

pull/3/head
Jure Šorn 6 years ago
parent
commit
17fb457ab7
1 changed files with 42 additions and 20 deletions
  1. 62
      README.md

62
README.md

@ -3,6 +3,7 @@ Comprehensive Python Cheatsheet
![Monty Python](web/image_888.jpeg) ![Monty Python](web/image_888.jpeg)
Main Main
---- ----
```python ```python
@ -72,6 +73,7 @@ Counter({'blue': 3, 'red': 2, 'yellow': 1})
'blue' 'blue'
``` ```
Set Set
--- ---
```python ```python
@ -96,6 +98,7 @@ Set
<frozenset> = frozenset(<collection>) <frozenset> = frozenset(<collection>)
``` ```
Range Range
----- -----
```python ```python
@ -105,6 +108,7 @@ range(from_inclusive, to_exclusive, step_size)
range(from_inclusive, to_exclusive, -step_size) range(from_inclusive, to_exclusive, -step_size)
``` ```
Enumerate Enumerate
--------- ---------
```python ```python
@ -112,6 +116,7 @@ for i, <el> in enumerate(<collection> [, i_start]):
... ...
``` ```
Named Tuple Named Tuple
----------- -----------
```python ```python
@ -126,6 +131,7 @@ Point(x=1, y=2)
('x', 'y') ('x', 'y')
``` ```
Iterator Iterator
-------- --------
#### Skips first element: #### Skips first element:
@ -285,9 +291,9 @@ import textwrap
textwrap.wrap(text, width) textwrap.wrap(text, width)
``` ```
Numbers Numbers
------- -------
### Basic Functions ### Basic Functions
```python ```python
round(<num> [, ndigits]) round(<num> [, ndigits])
@ -332,6 +338,7 @@ import random
random.shuffle(<list>) random.shuffle(<list>)
``` ```
Datetime Datetime
-------- --------
```python ```python
@ -346,6 +353,7 @@ now.strftime('%Y%m%d%H%M%S') # '20180315002834'
<datetime> = datetime.strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M') <datetime> = datetime.strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M')
``` ```
Arguments Arguments
--------- ---------
**"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call:** **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call:**
@ -384,6 +392,7 @@ def add(*a):
[2, 3] [2, 3]
``` ```
Inline Inline
------ ------
### Lambda ### Lambda
@ -446,6 +455,7 @@ Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
Creature = type('Creature', (), {'position': Point(0, 0), 'direction': Direction.n}) Creature = type('Creature', (), {'position': Point(0, 0), 'direction': Direction.n})
``` ```
Closure Closure
------- -------
```python ```python
@ -463,6 +473,7 @@ from functools import partial
partial(<function>, <arg_1> [, <arg_2>, ...]) partial(<function>, <arg_1> [, <arg_2>, ...])
``` ```
Decorator Decorator
--------- ---------
```python ```python
@ -504,14 +515,23 @@ class <name>:
return cls.__name__ return cls.__name__
``` ```
#### Constructor overloading:
### Constructor Overloading
```python ```python
class <name>: class <name>:
def __init__(self, a=None): def __init__(self, a=None):
self.a = a self.a = a
``` ```
### Enum
### Copy
```python
import copy
<object> = copy.copy(<object>)
<object> = copy.deepcopy(<object>)
```
Enum
----
```python ```python
from enum import Enum, auto from enum import Enum, auto
class <enum_name>(Enum): class <enum_name>(Enum):
@ -543,7 +563,7 @@ list(a.name for a in <enum>) # == ['<member_name_1>', '<member_name_2>', ...]
random.choice(list(<enum>)) # == random <member> random.choice(list(<enum>)) # == random <member>
``` ```
#### Inline:
### Inline
```python ```python
Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon']) Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
Cutlery = Enum('Cutlery', 'knife fork spoon') Cutlery = Enum('Cutlery', 'knife fork spoon')
@ -558,17 +578,9 @@ LogicOp = Enum('LogicOp', {'AND': (auto(), lambda l, r: l and r),
'OR' : (auto(), lambda l, r: l or r)} 'OR' : (auto(), lambda l, r: l or r)}
``` ```
### Copy
```python
import copy
<object> = copy.copy(<object>)
<object> = copy.deepcopy(<object>)
```
System System
------ ------
### Arguments ### Arguments
```python ```python
import sys import sys
@ -615,7 +627,6 @@ b'.\n..\nfile1.txt\nfile2.txt\n'
0 0
``` ```
### Input ### Input
```python ```python
filename = input('Enter a file name: ') filename = input('Enter a file name: ')
@ -630,6 +641,7 @@ while True:
break break
``` ```
JSON JSON
---- ----
```python ```python
@ -662,6 +674,7 @@ def write_to_json_file(filename, an_object):
json.dump(an_object, file, ensure_ascii=False, indent=2) json.dump(an_object, file, ensure_ascii=False, indent=2)
``` ```
SQLite SQLite
------ ------
```python ```python
@ -683,6 +696,7 @@ db.execute(<query>)
db.commit() db.commit()
``` ```
Exceptions Exceptions
---------- ----------
```python ```python
@ -701,6 +715,7 @@ while True:
raise IOError("input/output error") raise IOError("input/output error")
``` ```
Bytes Bytes
----- -----
**Bytes objects are immutable sequences of single bytes.** **Bytes objects are immutable sequences of single bytes.**
@ -738,6 +753,7 @@ def write_bytes(filename, bytes):
<Bytes> = b''.join(<list_of_Bytes>) <Bytes> = b''.join(<list_of_Bytes>)
``` ```
Struct Struct
------ ------
**This module performs conversions between Python values and C structs represented as Python Bytes objects:** **This module performs conversions between Python values and C structs represented as Python Bytes objects:**
@ -768,6 +784,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03'
* `f` - float * `f` - float
* `d` - double * `d` - double
Hashlib Hashlib
------- -------
```python ```python
@ -775,6 +792,7 @@ Hashlib
'33d0eba106da4d3ebca17fcd3f4c3d77' '33d0eba106da4d3ebca17fcd3f4c3d77'
``` ```
Threading Threading
--------- ---------
```python ```python
@ -797,6 +815,7 @@ lock.acquire()
lock.release() lock.release()
``` ```
Itertools Itertools
--------- ---------
**Every function returns a generator and can accept any collection. If you want to print an output of generator, as in examples, you need to pass it to the list() function.** **Every function returns a generator and can accept any collection. If you want to print an output of generator, as in examples, you need to pass it to the list() function.**
@ -806,7 +825,6 @@ from itertools import *
``` ```
### Combinatoric iterators ### Combinatoric iterators
```python ```python
>>> combinations('abc', 2) >>> combinations('abc', 2)
[('a', 'b'), ('a', 'c'), ('b', 'c')] [('a', 'b'), ('a', 'c'), ('b', 'c')]
@ -822,7 +840,6 @@ from itertools import *
``` ```
### Infinite iterators ### Infinite iterators
```python ```python
>>> i = count(5, 2) >>> i = count(5, 2)
>>> next(i), next(i), next(i) >>> next(i), next(i), next(i)
@ -837,7 +854,6 @@ from itertools import *
``` ```
### Iterators ### Iterators
```python ```python
>>> chain([1, 2], range(3, 5)) >>> chain([1, 2], range(3, 5))
[1, 2, 3, 4] [1, 2, 3, 4]
@ -912,7 +928,6 @@ type(<class_name>, <parents_tuple>, <attributes_dict>)
>>> z = Z() >>> z = Z()
``` ```
### MetaClass ### MetaClass
#### Class that creates class: #### Class that creates class:
```python ```python
@ -980,6 +995,7 @@ def eval_(node):
-5.0 -5.0
``` ```
Coroutine Coroutine
--------- ---------
* **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().** * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
@ -1037,6 +1053,7 @@ pyplot.show()
pyplot.savefig(<filename>, transparent=True) pyplot.savefig(<filename>, transparent=True)
``` ```
Table Table
----- -----
#### Prints CSV file as ASCII table: #### Prints CSV file as ASCII table:
@ -1050,6 +1067,7 @@ with open(<filename>, newline='') as csv_file:
print(tabulate(reader, headers)) print(tabulate(reader, headers))
``` ```
Curses Curses
------ ------
```python ```python
@ -1072,6 +1090,7 @@ def get_border(screen):
return P(width - 1, height - 1) return P(width - 1, height - 1)
``` ```
Image Image
----- -----
#### Creates PNG image of greyscale gradient: #### Creates PNG image of greyscale gradient:
@ -1091,6 +1110,7 @@ img.save('out.png')
* `RGBA` - 4x8-bit pixels, true color with transparency mask * `RGBA` - 4x8-bit pixels, true color with transparency mask
* `HSV` - 3x8-bit pixels, Hue, Saturation, Value color space * `HSV` - 3x8-bit pixels, Hue, Saturation, Value color space
Audio Audio
----- -----
#### Saves list of floats with values between 0 and 1 to a WAV file: #### Saves list of floats with values between 0 and 1 to a WAV file:
@ -1105,6 +1125,7 @@ wf.writeframes(b''.join(frames))
wf.close() wf.close()
``` ```
UrlLib UrlLib
------ ------
### Translate special characters ### Translate special characters
@ -1113,6 +1134,7 @@ import urllib.parse
<str> = urllib.parse.quote_plus(<str>) <str> = urllib.parse.quote_plus(<str>)
``` ```
Web Web
--- ---
```python ```python
@ -1159,6 +1181,7 @@ def p_handler(sport):
return json.dumps([home_odds, away_odds]) return json.dumps([home_odds, away_odds])
``` ```
Profile Profile
------- -------
#### Basic: #### Basic:
@ -1199,6 +1222,7 @@ def get_datetime_string(a_datetime):
return a_datetime.strftime('%Y%m%d%H%M%S') return a_datetime.strftime('%Y%m%d%H%M%S')
``` ```
Progress Bar Progress Bar
------------ ------------
### Basic: ### Basic:
@ -1260,6 +1284,7 @@ for i in range(STEPS):
bar.finish() bar.finish()
``` ```
Basic Script Template Basic Script Template
--------------------- ---------------------
```python ```python
@ -1293,6 +1318,3 @@ def read_file(filename):
if __name__ == '__main__': if __name__ == '__main__':
main() main()
``` ```
Loading…
Cancel
Save