Skip to content

Commit 188a2ae

Browse files
committed
Inline, Class, Shell commands
1 parent 3cff942 commit 188a2ae

3 files changed

Lines changed: 109 additions & 105 deletions

File tree

README.md

Lines changed: 52 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ import itertools as it
215215
```
216216

217217
```python
218-
<iter> = it.count(start=0, step=1) # Returns updated value endlessly. Accepts floats.
218+
<iter> = it.count(start=0, step=1) # Returns updated 'start' endlessly. Accepts floats.
219219
<iter> = it.repeat(<el> [, times]) # Returns passed element endlessly or 'times' times.
220220
<iter> = it.cycle(<collection>) # Repeats the passed sequence of elements endlessly.
221221
```
@@ -744,20 +744,20 @@ Inline
744744
------
745745
### Lambda
746746
```python
747-
<func> = lambda: <return_value> # A single statement function.
748-
<func> = lambda <arg_1>, <arg_2>: <return_value> # Also allows default arguments.
747+
<func> = lambda: <return_value> # A single statement function.
748+
<func> = lambda <arg_1>, <arg_2>: <return_value> # Also allows default arguments.
749749
```
750750

751751
### Comprehensions
752752
```python
753-
<list> = [i+1 for i in range(10)] # Returns `[1, 2, 3, 4, ..., 10]`.
754-
<iter> = (i for i in range(10) if i > 5) # Returns `iter([6, 7, 8, 9])`.
755-
<set> = {i+5 for i in range(10)} # Returns `{5, 6, 7, 8, ..., 14}`.
756-
<dict> = {i: i*2 for i in range(1, 10)} # Returns `{1: 2, 2: 4, ..., 9: 18}`.
753+
<list> = [i+1 for i in range(5)] # Returns `[1, 2, 3, 4, 5]`.
754+
<iter> = (i for i in range(10) if i > 5) # Returns `iter([6, 7, 8, 9])`.
755+
<set> = {i+5 for i in range(5)} # Returns `{5, 6, 7, 8, 9}`.
756+
<dict> = {i: i**2 for i in range(1, 4)} # Returns `{1: 1, 2: 4, 3: 9}`.
757757
```
758758

759759
```python
760-
>>> [l+r for l in 'abc' for r in 'abc'] # Inner loop is on the right side.
760+
>>> [l+r for l in 'abc' for r in 'abc'] # Inner loop is on right side.
761761
['aa', 'ab', 'ac', ..., 'cc']
762762
```
763763

@@ -767,52 +767,52 @@ from functools import reduce
767767
```
768768

769769
```python
770-
<iter> = map(lambda x: x + 1, range(10)) # Returns `iter([1, 2, ..., 10])`.
771-
<iter> = filter(lambda x: x > 5, range(10)) # Returns `iter([6, 7, 8, 9])`.
772-
<obj> = reduce(lambda out, x: out + x, range(10)) # Returns 45. Accepts 'initial'.
770+
<iter> = map(lambda x: x + 1, range(5)) # Returns `iter([1, 2, 3, 4, 5])`.
771+
<iter> = filter(lambda x: x > 5, range(10)) # Returns `iter([6, 7, 8, 9])`.
772+
<obj> = reduce(lambda out, x: out + x, range(5)) # Returns 10. Accepts 'initial'.
773773
```
774774

775775
### Any, All
776776
```python
777-
<bool> = any(<collection>) # Is `bool(<el>)` True for any el?
778-
<bool> = all(<collection>) # True for all? Also True if empty.
777+
<bool> = any(<collection>) # Is bool(<el>) True for any el?
778+
<bool> = all(<collection>) # Is it true for all (or empty)?
779779
```
780780

781781
### Conditional Expression
782782
```python
783-
<obj> = <exp> if <condition> else <exp> # Only one expression is evaluated.
783+
<obj> = <exp> if <condition> else <exp> # Evaluates only one expression.
784784
```
785785

786786
```python
787-
>>> [i if i else 'zero' for i in (0, 1, 2, 3)] # `any([0, '', [], None]) == False`.
787+
>>> [i if i else 'zero' for i in (0, 1, 2, 3)] # `any(['', [], None])` is False.
788788
['zero', 1, 2, 3]
789789
```
790790

791791
### And, Or
792792
```python
793-
<obj> = <exp> and <exp> [and ...] # Returns first false or last obj.
794-
<obj> = <exp> or <exp> [or ...] # Returns first true or last obj.
793+
<obj> = <exp> and <exp> [and ...] # Returns first false or last obj.
794+
<obj> = <exp> or <exp> [or ...] # Returns first true or last obj.
795795
```
796796

797797
### Walrus Operator
798798
```python
799-
>>> [i for ch in '0123' if (i := int(ch)) > 0] # Assigns to var in mid-sentence.
799+
>>> [i for ch in '0123' if (i := int(ch)) > 0] # Assigns to var in mid-sentence.
800800
[1, 2, 3]
801801
```
802802

803803
### Named Tuple, Enum, Dataclass
804804
```python
805805
from collections import namedtuple
806-
Point = namedtuple('Point', 'x y') # Creates tuple's subclass.
807-
point = Point(0, 0) # Returns its instance.
806+
Point = namedtuple('Point', 'x y') # Creates tuple's subclass.
807+
point = Point(0, 0) # Returns its instance.
808808

809809
from enum import Enum
810-
Direction = Enum('Direction', 'N E S W') # Creates an enumeration.
811-
direction = Direction.N # Returns its member.
810+
Direction = Enum('Direction', 'N E S W') # Creates an enumeration.
811+
direction = Direction.N # Returns its member.
812812

813813
from dataclasses import make_dataclass
814-
Player = make_dataclass('Player', ['loc', 'dir']) # Creates a normal class.
815-
player = Player(point, direction) # Returns its instance.
814+
Player = make_dataclass('Player', ['loc', 'dir']) # Creates a normal class.
815+
player = Player(point, direction) # Returns its instance.
816816
```
817817

818818

@@ -978,18 +978,18 @@ class MyClass:
978978

979979
#### Expressions that call object's str() special method:
980980
```python
981-
print(obj)
982981
f'{obj}'
982+
print(obj)
983983
logging.warning(obj)
984-
csv.writer(<file>).writerow([obj])
984+
<csv_writer>.writerow([obj])
985985
```
986986

987987
#### Expressions that call object's repr() special method:
988988
```python
989+
f'{obj!r}'
989990
print/str/repr([obj])
990991
print/str/repr({obj: obj})
991-
f'{obj!r}'
992-
Z = make_dataclass('Z', ['a']); print/str/repr(Z(obj))
992+
print/str/repr(<dataclass>(obj))
993993
```
994994

995995
### Subclass
@@ -1289,7 +1289,7 @@ class MySequence:
12891289
### ABC Sequence
12901290
* **It's a richer interface than the basic sequence that also requires just getitem() and len().**
12911291
* **Extending it generates iter(), contains(), reversed(), index() and count() special methods.**
1292-
* **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, array, memoryview and deque, since they are registered as Sequence's virtual subclasses.**
1292+
* **Unlike `'abc.Iterable'` and `'abc.Collection'`, it is not a duck type. That is why exp. `'issubclass(MySequence, abc.Sequence)'` would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray, array, memoryview and deque, since they are registered as Sequence's virtual subclasses.**
12931293
```python
12941294
from collections import abc
12951295

@@ -1544,7 +1544,7 @@ p.add_argument('-<short_name>', '--<name>', type=<type>) # Option (defa
15441544
p.add_argument('<name>', type=<type>, nargs=1) # Mandatory first argument.
15451545
p.add_argument('<name>', type=<type>, nargs='+') # Mandatory remaining args.
15461546
p.add_argument('<name>', type=<type>, nargs='?') # Optional argument. Also *.
1547-
args = p.parse_args() # Exits on parsing error.
1547+
args = p.parse_args() # Exits on a parsing error.
15481548
<obj> = args.<name> # Returns `<type>(<arg>)`.
15491549
```
15501550

@@ -1682,7 +1682,7 @@ from pathlib import Path
16821682
<str> = <Path>.name # Returns final component (filename or dirname).
16831683
<str> = <Path>.suffix # Returns the name's last extension, e.g. '.gz'.
16841684
<str> = <Path>.stem # Returns the name without its last extension.
1685-
<tup.> = <Path>.parts # Returns a tuple of all components as strings.
1685+
<tup.> = <Path>.parts # Starts with '/' or 'C:\' if path is absolute.
16861686
```
16871687

16881688
```python
@@ -1699,7 +1699,7 @@ from pathlib import Path
16991699
OS Commands
17001700
-----------
17011701
```python
1702-
import os, shutil, subprocess
1702+
import os, shutil
17031703
```
17041704

17051705
```python
@@ -1711,28 +1711,36 @@ os.makedirs(<path>, mode=0o777) # Creates all path's dirs. Also `exist_ok=False
17111711
```python
17121712
shutil.copy(from, to) # Copies the file ('to' can exist or be a dir).
17131713
shutil.copy2(from, to) # Also copies creation and modification time.
1714-
shutil.copytree(from, to) # Copies the directory ('to' must not exist).
1714+
shutil.copytree(from, to) # Copies the directory ('to' should not exist).
17151715
```
17161716

17171717
```python
17181718
os.rename(from, to) # Renames or moves the file or directory 'from'.
17191719
os.replace(from, to) # Same, but overwrites file 'to' even on Windows.
1720-
shutil.move(from, to) # Rename() that moves into 'to' if it's a dir.
1720+
shutil.move(from, to) # Rename() that moves into 'to' if it is a dir.
17211721
```
17221722

17231723
```python
17241724
os.remove(<path>) # Deletes file. Also `$ pip3 install send2trash`.
17251725
os.rmdir(<path>) # Deletes the empty directory or raises OSError.
17261726
shutil.rmtree(<path>) # Deletes the directory and all of its contents.
17271727
```
1728-
* **Paths can be either strings, Path objects, or DirEntry objects.**
1728+
* **Provided paths can be either strings, Path objects, or DirEntry objects.**
17291729
* **Functions report OS related errors by raising OSError or one of its [subclasses](#exceptions-1).**
17301730

1731-
### Shell Commands
1731+
1732+
Shell Commands
1733+
--------------
17321734
```python
1733-
<pipe> = os.popen('<commands>') # Executes commands in sh/cmd. Also os.system().
1734-
<str> = <pipe>.read(size=-1) # Returns a combined stdout. Also readline/s().
1735-
<int> = <pipe>.close() # Returns None if last command exited with 0.
1735+
import os, subprocess, shlex
1736+
```
1737+
1738+
```python
1739+
<int> = os.system('<commands>') # Runs commands in sh/cmd shell. Prints results.
1740+
<proc> = subprocess.run('<command>') # For arguments see examples. Prints by default.
1741+
<pipe> = os.popen('<commands>') # Prints only stderr. Soft deprecated since 3.14.
1742+
<str> = <pipe>.read(size=-1) # Returns combined stdout. Provides readline/s().
1743+
<int> = <pipe>.close() # Returns None if last command had returncode 0.
17361744
```
17371745

17381746
#### Sends "1 + 1" to the basic calculator and captures its output:
@@ -1743,19 +1751,16 @@ CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='')
17431751

17441752
#### Sends test.in to the basic calculator running in standard mode and saves its output to test.out:
17451753
```python
1746-
>>> from shlex import split
1747-
>>> os.popen('echo 1 + 1 > test.in')
1748-
>>> subprocess.run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w'))
1749-
CompletedProcess(args=['bc', '-s'], returncode=0)
1750-
>>> open('test.out').read()
1751-
'2\n'
1754+
>>> if os.system('echo 1 + 1 > test.in') == 0:
1755+
... with open('test.in') as file_in, open('test.out', 'w') as file_out:
1756+
... subprocess.run(shlex.split('bc -s'), stdin=file_in, stdout=file_out)
1757+
... print(open('test.out').read())
1758+
2
17521759
```
17531760

17541761

17551762
JSON
17561763
----
1757-
**Text file format for storing collections of strings and numbers.**
1758-
17591764
```python
17601765
import json
17611766
<str> = json.dumps(<list/dict>) # Converts collection to JSON string.
@@ -1779,8 +1784,6 @@ def write_to_json_file(filename, collection):
17791784

17801785
Pickle
17811786
------
1782-
**Binary file format for storing Python objects.**
1783-
17841787
```python
17851788
import pickle
17861789
<bytes> = pickle.dumps(<object>) # Converts object to bytes object.

0 commit comments

Comments
 (0)