From 3ab66cd3aae5efa7420eeac26cb3cc517f275381 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 13 May 2021 14:56:41 +0200 Subject: [PATCH 001/667] Updated a link to text file --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c80d3b3e8..12c4031ca 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Comprehensive Python Cheatsheet =============================== -[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/master/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions). +[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions). ![Monty Python](web/image_888.jpeg) diff --git a/index.html b/index.html index ea5bfee0d..4b6f8010b 100644 --- a/index.html +++ b/index.html @@ -231,7 +231,7 @@ -

Comprehensive Python Cheatsheet

Comprehensive Python Cheatsheet


#Contents

ToC = {
     '1. Collections': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],
     '2. Types':       [Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime],

From cab456867b4a00e488804d8771a45769b9b75951 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jure=20=C5=A0orn?= 
Date: Sat, 15 May 2021 15:03:59 +0200
Subject: [PATCH 002/667] OS commands, SQLite, Bytes

---
 README.md              | 17 ++++++++++-------
 index.html             | 21 ++++++++++++---------
 parse.js               |  2 +-
 pdf/index_for_pdf.html |  6 +++---
 web/script_2.js        |  4 ++--
 5 files changed, 28 insertions(+), 22 deletions(-)

diff --git a/README.md b/README.md
index 12c4031ca..1953f2927 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@ Contents
 **   ** **3. Syntax:** **         **  **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Closure`](#closure)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Type`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exception`](#exceptions)**__.__  
 **   ** **4. System:** **        **  **[`Exit`](#exit)**__,__ **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#paths)**__,__ **[`OS_Commands`](#os-commands)**__.__  
 **   ** **5. Data:** **             **  **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`CSV`](#csv)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`Memory_View`](#memory-view)**__,__ **[`Deque`](#deque)**__.__  
-**   ** **6. Advanced:** **   **  **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Introspection`](#introspection)**__,__ **[`Metaprograming`](#metaprograming)**__,__ **[`Eval`](#eval)**__,__ **[`Coroutines`](#coroutines)**__.__  
+**   ** **6. Advanced:** **   **  **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Introspection`](#introspection)**__,__ **[`Metaprograming`](#metaprogramming)**__,__ **[`Eval`](#eval)**__,__ **[`Coroutines`](#coroutines)**__.__  
 **   ** **7. Libraries:** **      **  **[`Progress_Bar`](#progress-bar)**__,__ **[`Plot`](#plot)**__,__ **[`Table`](#table)**__,__ **[`Curses`](#curses)**__,__ **[`Logging`](#logging)**__,__ **[`Scraping`](#scraping)**__,__ **[`Web`](#web)**__,__ **[`Profile`](#profiling)**__,__  
 **                                 ** **[`NumPy`](#numpy)**__,__ **[`Image`](#image)**__,__ **[`Audio`](#audio)**__,__ **[`Games`](#pygame)**__,__ **[`Data`](#pandas)**__.__
 
@@ -1670,6 +1670,7 @@ import os, shutil
 ```python
 os.chdir()                    # Changes the current working directory.
 os.mkdir(, mode=0o777)        # Creates a directory. Mode is in octal.
+os.makedirs(, mode=0o777)     # Creates all directories in the path.
 ```
 
 ```python
@@ -1850,13 +1851,14 @@ import sqlite3
 ### Write
 ```python
 .execute('')                       # Can raise a subclass of sqlite3.Error.
-.commit()                                 # Commits all transactions since last commit.
+.commit()                                 # Saves all changes since the last commit.
+.rollback()                               # Discards all changes since the last commit.
 ```
 
 #### Or:
 ```python
-with :
-    .execute('')
+with :                                    # Exits block with commit() or rollback(),
+    .execute('')                   # depending on whether an exception occurred.
 ```
 
 ### Placeholders
@@ -1901,7 +1903,7 @@ Bytes
  = b''                       # Only accepts ASCII characters and \x00-\xff.
    = []               # Returns int in range from 0 to 255.
  = []               # Returns bytes even if it has only one element.
- = .join()  # Joins elements using bytes object as separator.
+ = .join()  # Joins elements using bytes as a separator.
 ```
 
 ### Encode
@@ -1950,6 +1952,7 @@ from struct import pack, unpack, iter_unpack
  = iter_unpack('', )
 ```
 
+### Example
 ```python
 >>> pack('>hhl', 1, 2, 3)
 b'\x00\x01\x00\x02\x00\x00\x00\x03'
@@ -2160,8 +2163,8 @@ from inspect import signature
 ```
 
 
-Metaprograming
---------------
+Metaprogramming
+---------------
 **Code that generates code.**
 
 ### Type
diff --git a/index.html b/index.html
index 4b6f8010b..820e0841e 100644
--- a/index.html
+++ b/index.html
@@ -238,7 +238,7 @@
     '3. Syntax':      [Args, Inline, Closure, Decorator, Class, Duck_Type, Enum, Exception],
     '4. System':      [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],
     '5. Data':        [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],
-    '6. Advanced':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],
+    '6. Advanced':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],
     '7. Libraries':   [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,
                        NumPy, Image, Audio, Games, Data]
 }
@@ -1556,6 +1556,7 @@
 
 
os.chdir(<path>)                    # Changes the current working directory.
 os.mkdir(<path>, mode=0o777)        # Creates a directory. Mode is in octal.
+os.makedirs(<path>, mode=0o777)     # Creates all directories in the path.
 
shutil.copy(from, to)               # Copies the file. 'to' can exist or be a dir.
 shutil.copytree(from, to)           # Copies the directory. 'to' must not exist.
@@ -1686,11 +1687,12 @@
 
 
 

Write

<conn>.execute('<query>')                       # Can raise a subclass of sqlite3.Error.
-<conn>.commit()                                 # Commits all transactions since last commit.
+<conn>.commit()                                 # Saves all changes since the last commit.
+<conn>.rollback()                               # Discards all changes since the last commit.
 
-

Or:

with <conn>:
-    <conn>.execute('<query>')
+

Or:

with <conn>:                                    # Exits block with commit() or rollback(),
+    <conn>.execute('<query>')                   # depending on whether an exception occurred.
 

Placeholders

    @@ -1724,7 +1726,7 @@

    #Bytes

    Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.

    <bytes> = b'<str>'                       # Only accepts ASCII characters and \x00-\xff.
     <int>   = <bytes>[<index>]               # Returns int in range from 0 to 255.
     <bytes> = <bytes>[<slice>]               # Returns bytes even if it has only one element.
    -<bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements using bytes object as separator.
    +<bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements using bytes as a separator.
     
    @@ -1761,11 +1763,12 @@ <tuple> = unpack('<format>', <bytes>) <tuples> = iter_unpack('<format>', <bytes>)
-
>>> pack('>hhl', 1, 2, 3)
+

Example

>>> pack('>hhl', 1, 2, 3)
 b'\x00\x01\x00\x02\x00\x00\x00\x03'
 >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
 (1, 2, 3)
-
+
+

Format

For standard type sizes start format string with:

  • '=' - native byte order (usually little-endian)
  • '<' - little-endian
  • @@ -1921,7 +1924,7 @@ <memb> = <Param>.kind # Member of ParameterKind enum.
-

#Metaprograming

Code that generates code.

Type

Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.

<class> = type('<class_name>', <parents_tuple>, <attributes_dict>)
+

#Metaprogramming

Code that generates code.

Type

Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.

<class> = type('<class_name>', <parents_tuple>, <attributes_dict>)
@@ -2300,7 +2303,7 @@ right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
-

3. If neither non-matching dimension has size 1, raise an error.

Example

For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):

>>> points = np.array([0.1, 0.6, 0.8])
+

3. If neither non-matching dimension has size 1, raise an error.

Example

For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):

>>> points = np.array([0.1, 0.6, 0.8])
  [ 0.1,  0.6,  0.8]
 >>> wrapped_points = points.reshape(3, 1)
 [[ 0.1],
diff --git a/parse.js b/parse.js
index 2d56bc6d7..c760811a9 100755
--- a/parse.js
+++ b/parse.js
@@ -24,7 +24,7 @@ const TOC =
   '    \'3. Syntax\':      [Args, Inline, Closure, Decorator, Class, Duck_Type, Enum, Exception],\n' +
   '    \'4. System\':      [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],\n' +
   '    \'5. Data\':        [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],\n' +
-  '    \'6. Advanced\':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' +
+  '    \'6. Advanced\':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' +
   '    \'7. Libraries\':   [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,\n' +
   '                       NumPy, Image, Audio, Games, Data]\n' +
   '}\n' +
diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html
index 43ffa77b4..afd9e5c82 100644
--- a/pdf/index_for_pdf.html
+++ b/pdf/index_for_pdf.html
@@ -20,7 +20,7 @@ 

B

C

cache, 13
callable, 17
-class, 4, 14-20, 31-32
+class, 4, 14-20, 31-32
closure, 12-13
collection, 4, 18, 19
collections module, 2, 3, 4, 19, 29
@@ -85,7 +85,7 @@

M

math module, 7
memoryviews, 29
metaclass attribute, 32
-metaprograming, 31-32
+metaprogramming, 31-32
mysql library, 27

N

namedtuples, 3
@@ -139,7 +139,7 @@

T

threading module, 30
time module, 34, 36
tuples, 3, 4, 11
-type, 4, 31-32

+type, 4, 31-32

W

wave module, 40-41
web, 36

diff --git a/web/script_2.js b/web/script_2.js index 97691b47b..efb56e947 100644 --- a/web/script_2.js +++ b/web/script_2.js @@ -5,7 +5,7 @@ const TOC = ' \'3. Syntax\': [Args, Inline, Closure, Decorator, Class, Duck_Type, Enum, Exception],\n' + ' \'4. System\': [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],\n' + ' \'5. Data\': [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],\n' + - ' \'6. Advanced\': [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' + + ' \'6. Advanced\': [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' + ' \'7. Libraries\': [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,\n' + ' NumPy, Image, Audio, Games, Data]\n' + '}\n'; @@ -30,7 +30,7 @@ const TOC_MOBILE = ' Memory_View, Deque],\n' + ' \'6. Advanced\': [Threading, Operator,\n' + ' Introspection,\n' + - ' Metaprograming, Eval,\n' + + ' Metaprograming, Eval,\n' + ' Coroutine],\n' + ' \'7. Libraries\': [Progress_Bar, Plot, Table,\n' + ' Curses, Logging, Scraping,\n' + From 606208ac68a2191d8281f3bfe1903e3233590908 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 16 May 2021 14:36:20 +0200 Subject: [PATCH 003/667] Web, Profiling --- README.md | 15 +++++++-------- index.html | 15 +++++++-------- pdf/index_for_pdf.html | 2 +- pdf/index_for_pdf_print.html | 2 +- 4 files changed, 16 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 1953f2927..b30c92352 100644 --- a/README.md +++ b/README.md @@ -2496,7 +2496,7 @@ def send_page(sport): ### REST Request ```python -@post('/odds/') +@post('//odds') def odds_handler(sport): team = request.forms.get('team') home_odds, away_odds = 2.44, 3.29 @@ -2510,7 +2510,7 @@ def odds_handler(sport): # $ pip3 install requests >>> import threading, requests >>> threading.Thread(target=run, daemon=True).start() ->>> url = 'http://localhost:8080/odds/football' +>>> url = 'http://localhost:8080/football/odds' >>> data = {'team': 'arsenal f.c.'} >>> response = requests.post(url, data=data) >>> response.json() @@ -2577,11 +2577,10 @@ Line # Mem usage Increment Line Contents ### Call Graph #### Generates a PNG image of a call graph with highlighted bottlenecks: ```python -# $ pip3 install pycallgraph -from pycallgraph import output, PyCallGraph +# $ pip3 install pycallgraph2 +from pycallgraph2 import output, PyCallGraph from datetime import datetime -time_str = datetime.now().strftime('%Y%m%d%H%M%S') -filename = f'profile-{time_str}.png' +filename = f'profile-{datetime.now():%Y%m%d%H%M%S}.png' drawer = output.GraphvizOutput(output_file=filename) with PyCallGraph(drawer): @@ -2961,14 +2960,14 @@ while all(event.type != pg.QUIT for event in pg.event.get()): ``` ```python -from pygame.transform import scale, … +from pygame.transform import scale, ... = scale(, (width, height)) # Returns scaled surface. = rotate(, degrees) # Returns rotated and scaled surface. = flip(, x_bool, y_bool) # Returns flipped surface. ``` ```python -from pygame.draw import line, … +from pygame.draw import line, ... line(, color, (x1, y1), (x2, y2), width) # Draws a line to the surface. arc(, color, , from_rad, to_rad) # Also: ellipse(, color, ) rect(, color, ) # Also: polygon(, color, points) diff --git a/index.html b/index.html index 820e0841e..d8f6b6da2 100644 --- a/index.html +++ b/index.html @@ -2184,7 +2184,7 @@ return template('<h1>{{title}}</h1>', title=sport)
-

REST Request

@post('/odds/<sport>')
+

REST Request

@post('/<sport>/odds')
 def odds_handler(sport):
     team = request.forms.get('team')
     home_odds, away_odds = 2.44, 3.29
@@ -2196,7 +2196,7 @@
 

Test:

# $ pip3 install requests
 >>> import threading, requests
 >>> threading.Thread(target=run, daemon=True).start()
->>> url = 'http://localhost:8080/odds/football'
+>>> url = 'http://localhost:8080/football/odds'
 >>> data = {'team': 'arsenal f.c.'}
 >>> response = requests.post(url, data=data)
 >>> response.json()
@@ -2246,11 +2246,10 @@
      3        38.012 MiB      0.344 MiB       a = [*range(10000)]
      4        38.477 MiB      0.465 MiB       b = {*range(10000)}
 
-

Call Graph

Generates a PNG image of a call graph with highlighted bottlenecks:

# $ pip3 install pycallgraph
-from pycallgraph import output, PyCallGraph
+

Call Graph

Generates a PNG image of a call graph with highlighted bottlenecks:

# $ pip3 install pycallgraph2
+from pycallgraph2 import output, PyCallGraph
 from datetime import datetime
-time_str = datetime.now().strftime('%Y%m%d%H%M%S')
-filename = f'profile-{time_str}.png'
+filename = f'profile-{datetime.now():%Y%m%d%H%M%S}.png'
 drawer = output.GraphvizOutput(output_file=filename)
 with PyCallGraph(drawer):
     <code_to_be_profiled>
@@ -2547,12 +2546,12 @@
 <Surf>.set_at((x, y), color)                    # Updates pixel.
 <Surf>.blit(<Surf>, (x, y))                     # Draws passed surface to the surface.
 
-
from pygame.transform import scale, …
+
from pygame.transform import scale, ...
 <Surf> = scale(<Surf>, (width, height))         # Returns scaled surface.
 <Surf> = rotate(<Surf>, degrees)                # Returns rotated and scaled surface.
 <Surf> = flip(<Surf>, x_bool, y_bool)           # Returns flipped surface.
 
-
from pygame.draw import line, …
+
from pygame.draw import line, ...
 line(<Surf>, color, (x1, y1), (x2, y2), width)  # Draws a line to the surface.
 arc(<Surf>, color, <Rect>, from_rad, to_rad)    # Also: ellipse(<Surf>, color, <Rect>)
 rect(<Surf>, color, <Rect>)                     # Also: polygon(<Surf>, color, points)
diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html
index afd9e5c82..192cb16f5 100644
--- a/pdf/index_for_pdf.html
+++ b/pdf/index_for_pdf.html
@@ -51,7 +51,7 @@ 

F

files, 22-29, 34, 46
filter function, 11
floats, 4, 6, 7
-format, 6-7
+format, 6-7, 37
functools module, 11, 12, 13, 16
futures, 30

G

diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index 84a1d47b8..5d9519c36 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -51,7 +51,7 @@

F

files, 22-29, 34, 46
filter function, 11
floats, 4, 6, 7
-format, 6-7
+format, 6-7, 37
functools module, 11, 12, 13, 16
futures, 30

G

From a658334dfe5f5d49c6e8964577676f04972c59a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 19 May 2021 23:39:52 +0200 Subject: [PATCH 004/667] Regex, Format, Struct, Threading --- README.md | 30 ++++++++++++++++-------------- index.html | 38 ++++++++++++++++++++------------------ 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index b30c92352..a88494f3d 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,7 @@ import re ### Special Sequences * **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.** -* **As shown below, it restricts special sequence matches to `'[\x00-\x7f]'` and prevents `'\s'` from accepting `'[\x1c\x1d\x1e\x1f]'`.** +* **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c\x1d\x1e\x1f]'`.** * **Use a capital letter for negation.** ```python '\d' == '[0-9]' # Matches decimal characters. @@ -412,9 +412,10 @@ Format {:.<10} # '......' {:0} # '' ``` +* **Use `'{:{}[...]}'` to set options dynamically.** +* **Adding `'!r'` before the colon converts object to string by calling its [repr()](#class) method.** ### Strings -**`'!r'` calls object's [repr()](#class) method, instead of [str()](#class), to get a string.** ```python {'abcde'!r:10} # "'abcde' " {'abcde':10.3} # 'abc ' @@ -1286,7 +1287,9 @@ Enum ---- ```python from enum import Enum, auto +``` +```python class (Enum): = = , @@ -1857,7 +1860,7 @@ import sqlite3 #### Or: ```python -with : # Exits block with commit() or rollback(), +with : # Exits the block with commit() or rollback(), .execute('') # depending on whether an exception occurred. ``` @@ -1940,7 +1943,7 @@ def write_bytes(filename, bytes_obj): Struct ------ * **Module that performs conversions between a sequence of numbers and a bytes object.** -* **System’s native type sizes and byte order are used by default.** +* **System’s type sizes and byte order are used by default.** ```python from struct import pack, unpack, iter_unpack @@ -1962,7 +1965,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' ### Format #### For standard type sizes start format string with: -* **`'='` - native byte order (usually little-endian)** +* **`'='` - system's byte order (usually little-endian)** * **`'<'` - little-endian** * **`'>'` - big-endian (also `'!'`)** @@ -1998,7 +2001,7 @@ Memory View * **A sequence object that points to the memory of another object.** * **Each element can reference a single or multiple consecutive bytes, depending on format.** * **Order and number of elements can be changed with slicing.** -* **Casting only works between char and other types and always uses native size and b. order.** +* **Casting only works between char and other types and uses system's sizes and byte order.** ```python = memoryview() # Immutable if bytes, else mutable. @@ -2052,10 +2055,10 @@ from concurrent.futures import ThreadPoolExecutor ### Thread ```python - = Thread(target=) # Use `args=` to set arguments. + = Thread(target=) # Use `args=` to set the arguments. .start() # Starts the thread. - = .is_alive() # Checks if thread has finished executing. -.join() # Waits for thread to finish. + = .is_alive() # Checks if the thread has finished executing. +.join() # Waits for the thread to finish. ``` * **Use `'kwargs='` to pass keyword arguments to the function.** * **Use `'daemon=True'`, or the program will not be able to exit while the thread is alive.** @@ -2063,15 +2066,14 @@ from concurrent.futures import ThreadPoolExecutor ### Lock ```python = RLock() # Lock that can only be released by the owner. -.acquire() # Waits for lock to be available. -.release() # Makes lock available again. +.acquire() # Waits for the lock to be available. +.release() # Makes the lock available again. ``` #### Or: ```python -lock = RLock() -with lock: - ... +with : # Enters the block by calling acquire(), + ... # and exits it with release(). ``` ### Semaphore, Event, Barrier diff --git a/index.html b/index.html index d8f6b6da2..4833a5e14 100644 --- a/index.html +++ b/index.html @@ -508,7 +508,7 @@

Special Sequences

  • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
  • -
  • As shown below, it restricts special sequence matches to '[\x00-\x7f]' and prevents '\s' from accepting '[\x1c\x1d\x1e\x1f]'.
  • +
  • As shown below, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c\x1d\x1e\x1f]'.
  • Use a capital letter for negation.
'\d' == '[0-9]'                                # Matches decimal characters.
 '\w' == '[a-zA-Z0-9_]'                         # Matches alphanumerics and underscore.
@@ -536,12 +536,15 @@
 {<el>:0}                                       # '<el>'
 
-

Strings

'!r' calls object's repr() method, instead of str(), to get a string.

{'abcde'!r:10}                                 # "'abcde'   "
+
    +
  • Use '{<el>:{<str/int/float>}[...]}' to set options dynamically.
  • +
  • Adding '!r' before the colon converts object to string by calling its repr() method.
  • +
+

Strings

{'abcde'!r:10}                                 # "'abcde'   "
 {'abcde':10.3}                                 # 'abc       '
 {'abcde':.3}                                   # 'abc'
 
-

Numbers

{ 123456:10,}                                  # '   123,456'
 { 123456:10_}                                  # '   123_456'
 { 123456:+10}                                  # '   +123456'
@@ -1252,13 +1255,13 @@
 
  • Names of their required methods are stored in '<abc>.__abstractmethods__'.
  • #Enum

    from enum import Enum, auto
    +
    -class <enum_name>(Enum): +
    class <enum_name>(Enum):
         <member_name_1> = <value_1>
         <member_name_2> = <value_2_a>, <value_2_b>
         <member_name_3> = auto()
    -
    - +
    • If there are no numeric values before auto(), it returns 1.
    • Otherwise it returns an increment of the last numeric value.
    • @@ -1691,7 +1694,7 @@ <conn>.rollback() # Discards all changes since the last commit.
    -

    Or:

    with <conn>:                                    # Exits block with commit() or rollback(),
    +

    Or:

    with <conn>:                                    # Exits the block with commit() or rollback(),
         <conn>.execute('<query>')                   # depending on whether an exception occurred.
     
    @@ -1754,7 +1757,7 @@

    #Struct

    • Module that performs conversions between a sequence of numbers and a bytes object.
    • -
    • System’s native type sizes and byte order are used by default.
    • +
    • System’s type sizes and byte order are used by default.
    from struct import pack, unpack, iter_unpack
     
    @@ -1770,7 +1773,7 @@

    Format

    For standard type sizes start format string with:

      -
    • '=' - native byte order (usually little-endian)
    • +
    • '=' - system's byte order (usually little-endian)
    • '<' - little-endian
    • '>' - big-endian (also '!')

    Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:

      @@ -1803,7 +1806,7 @@
    • A sequence object that points to the memory of another object.
    • Each element can reference a single or multiple consecutive bytes, depending on format.
    • Order and number of elements can be changed with slicing.
    • -
    • Casting only works between char and other types and always uses native size and b. order.
    • +
    • Casting only works between char and other types and uses system's sizes and byte order.
    <mview> = memoryview(<bytes/bytearray/array>)  # Immutable if bytes, else mutable.
     <real>  = <mview>[<index>]                     # Returns an int or a float.
     <mview> = <mview>[<slice>]                     # Mview with rearranged elements.
    @@ -1841,10 +1844,10 @@
     
    -

    Thread

    <Thread> = Thread(target=<function>)           # Use `args=<collection>` to set arguments.
    +

    Thread

    <Thread> = Thread(target=<function>)           # Use `args=<collection>` to set the arguments.
     <Thread>.start()                               # Starts the thread.
    -<bool> = <Thread>.is_alive()                   # Checks if thread has finished executing.
    -<Thread>.join()                                # Waits for thread to finish.
    +<bool> = <Thread>.is_alive()                   # Checks if the thread has finished executing.
    +<Thread>.join()                                # Waits for the thread to finish.
     
      @@ -1852,13 +1855,12 @@
    • Use 'daemon=True', or the program will not be able to exit while the thread is alive.

    Lock

    <lock> = RLock()                               # Lock that can only be released by the owner.
    -<lock>.acquire()                               # Waits for lock to be available.
    -<lock>.release()                               # Makes lock available again.
    +<lock>.acquire()                               # Waits for the lock to be available.
    +<lock>.release()                               # Makes the lock available again.
     
    -

    Or:

    lock = RLock()
    -with lock:
    -    ...
    +

    Or:

    with <lock>:                                   # Enters the block by calling acquire(),
    +    ...                                        # and exits it with release().
     

    Semaphore, Event, Barrier

    <Semaphore> = Semaphore(value=1)               # Lock that can be acquired by 'value' threads.
    
    From 52abd7b82b865922bcad1272be7fbd12f307b015 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 20 May 2021 11:58:00 +0200
    Subject: [PATCH 005/667] Changed date
    
    ---
     index.html        | 4 ++--
     web/template.html | 4 ++--
     2 files changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/index.html b/index.html
    index 4833a5e14..bc15fc509 100644
    --- a/index.html
    +++ b/index.html
    @@ -226,7 +226,7 @@
     
     
       
    - +
    @@ -3005,7 +3005,7 @@ diff --git a/web/template.html b/web/template.html index ab2864476..d508fa55b 100644 --- a/web/template.html +++ b/web/template.html @@ -226,7 +226,7 @@
    - +
    @@ -234,7 +234,7 @@
    From f3ea09fe8be31556402ab26f549145e6d445934a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 20 May 2021 12:54:51 +0200 Subject: [PATCH 006/667] Regex --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a88494f3d..19637c4ad 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,7 @@ import re ### Special Sequences * **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.** -* **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c\x1d\x1e\x1f]'`.** +* **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c-\x1f]'`.** * **Use a capital letter for negation.** ```python '\d' == '[0-9]' # Matches decimal characters. diff --git a/index.html b/index.html index bc15fc509..bc964be98 100644 --- a/index.html +++ b/index.html @@ -508,7 +508,7 @@

    Special Sequences

    • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
    • -
    • As shown below, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c\x1d\x1e\x1f]'.
    • +
    • As shown below, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]'.
    • Use a capital letter for negation.
    '\d' == '[0-9]'                                # Matches decimal characters.
     '\w' == '[a-zA-Z0-9_]'                         # Matches alphanumerics and underscore.
    
    From f4d5399d2d58b2afb176c53bfb500d8fdf873133 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 20 May 2021 14:50:43 +0200
    Subject: [PATCH 007/667] Updated remove_links.py script
    
    ---
     pdf/remove_links.py | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/pdf/remove_links.py b/pdf/remove_links.py
    index 2f97aef27..1dc54a4ed 100755
    --- a/pdf/remove_links.py
    +++ b/pdf/remove_links.py
    @@ -8,9 +8,9 @@
     
     MATCHES = {
         'Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.': 'Module \'operator\' (p. 31) provides functions itemgetter() and mul() that offer the same functionality as lambda expressions (p. 11) above.',
    -    '\'!r\' calls object\'s repr() method, instead of str(), to get a string.': '\'!r\' calls object\'s repr() method, instead of str(), to get a string (p. 14).',
    +    'Adding \'!r\' before the colon converts object to string by calling its repr() method.': 'Adding \'!r\' before the colon converts object to string by calling its repr() method (p. 14).',
         'Default_factory can be any callable.': 'Default_factory can be any callable (p. 17).',
    -    'Iterators returned by the iter() function, such as list_iterator and set_iterator.': 'Iterators returned by the iter() function, such as list_iterator and set_iterator (p. 3).',
    +    'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator.': 'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator (p. 3).',
         'Objects returned by the itertools module, such as count, repeat and cycle.': 'Objects returned by the itertools module, such as count, repeat and cycle (p. 3).',
         'Generators returned by the generator functions and generator expressions.': 'Generators returned by the generator functions (p. 4) and generator expressions (p. 11).',
         'File objects returned by the open() function, etc.': 'File objects returned by the open() function (p. 22), etc.',
    
    From de1f11380cdaa01f68bbe8f68261b3176c9024ee Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 28 Jul 2021 20:03:59 +0200
    Subject: [PATCH 008/667] Updated parse.js documentation
    
    ---
     .gitignore |  3 +++
     parse.js   | 12 +++++++++---
     2 files changed, 12 insertions(+), 3 deletions(-)
     create mode 100644 .gitignore
    
    diff --git a/.gitignore b/.gitignore
    new file mode 100644
    index 000000000..b8ffe08f2
    --- /dev/null
    +++ b/.gitignore
    @@ -0,0 +1,3 @@
    +node_modules/
    +package-lock.json
    +
    diff --git a/parse.js b/parse.js
    index c760811a9..69f53d0ea 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -1,12 +1,18 @@
     #!/usr/bin/env node
     // Usage: node parse.js
    +//
     // Script that creates index.html out of web/template.html and README.md.
     // It is written in JS because this code used to be executed on the client side.
    -// To install dependencies run:
    -// $ npm install -g jsdom jquery showdown highlightjs
    -// If running on Mac and modules can't be found after installation add:
    +// To install the Node.js and npm run:
    +// $ sudo apt install nodejs npm  # On macOS use `brew install ...` instead.
    +// To install dependencies globally, run:
    +// $ npm install -g jsdom jquery showdown highlightjs@9.12.0
    +// If running on macOS and modules can't be found after installation add:
     // export NODE_PATH=/usr/local/lib/node_modules
     // to the ~/.bash_profile or ~/.bashrc file and run '$ bash'.
    +// To avoid problems with permissions and path variables, install modules
    +// into project's directory using:
    +// $ npm install jsdom jquery showdown highlightjs@9.12.0
     
     
     const fs = require('fs');
    
    From 6b23015f735d6080670dd358bb6f61cc9a828580 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 28 Jul 2021 20:15:25 +0200
    Subject: [PATCH 009/667] Updated parse.js documentation
    
    ---
     parse.js | 3 +++
     1 file changed, 3 insertions(+)
    
    diff --git a/parse.js b/parse.js
    index 69f53d0ea..aaba64012 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -13,6 +13,9 @@
     // To avoid problems with permissions and path variables, install modules
     // into project's directory using:
     // $ npm install jsdom jquery showdown highlightjs@9.12.0
    +// It is also advisable to add a script into .git/hooks directory, that will run 
    +// this script before every commit. It should be named 'pre-commit' and it should
    +// contain the following line: `./parse.js`.
     
     
     const fs = require('fs');
    
    From 332bf7e913a7849943c77824425e4b30afe1876a Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 29 Jul 2021 00:58:34 +0200
    Subject: [PATCH 010/667] Removed .gitignore
    
    ---
     .gitignore | 3 ---
     1 file changed, 3 deletions(-)
     delete mode 100644 .gitignore
    
    diff --git a/.gitignore b/.gitignore
    deleted file mode 100644
    index b8ffe08f2..000000000
    --- a/.gitignore
    +++ /dev/null
    @@ -1,3 +0,0 @@
    -node_modules/
    -package-lock.json
    -
    
    From 1fa9a9939b3ebb086a041d1a021d89f372f308d5 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 11 Aug 2021 21:18:55 +0200
    Subject: [PATCH 011/667] Parse.js now automatically updates the date of
     index.html
    
    ---
     index.html        |  6 +++---
     parse.js          | 26 ++++++++++++++++++++++----
     web/template.html |  2 +-
     3 files changed, 26 insertions(+), 8 deletions(-)
    
    diff --git a/index.html b/index.html
    index bc964be98..e62fe063f 100644
    --- a/index.html
    +++ b/index.html
    @@ -226,7 +226,7 @@
     
     
       
    - +
    @@ -3005,8 +3005,8 @@ diff --git a/parse.js b/parse.js index aaba64012..ab5bdbe32 100755 --- a/parse.js +++ b/parse.js @@ -2,20 +2,25 @@ // Usage: node parse.js // // Script that creates index.html out of web/template.html and README.md. +// // It is written in JS because this code used to be executed on the client side. // To install the Node.js and npm run: // $ sudo apt install nodejs npm # On macOS use `brew install ...` instead. +// // To install dependencies globally, run: // $ npm install -g jsdom jquery showdown highlightjs@9.12.0 +// // If running on macOS and modules can't be found after installation add: // export NODE_PATH=/usr/local/lib/node_modules // to the ~/.bash_profile or ~/.bashrc file and run '$ bash'. +// // To avoid problems with permissions and path variables, install modules // into project's directory using: // $ npm install jsdom jquery showdown highlightjs@9.12.0 -// It is also advisable to add a script into .git/hooks directory, that will run -// this script before every commit. It should be named 'pre-commit' and it should -// contain the following line: `./parse.js`. +// +// It is also advisable to add a Bash script into .git/hooks directory, that will +// run this script before every commit. It should be named 'pre-commit' and it +// should contain the following line: `./parse.js`. const fs = require('fs'); @@ -408,7 +413,8 @@ function main() { const html = getMd(); initDom(html); modifyPage(); - const template = readFile('web/template.html'); + var template = readFile('web/template.html'); + template = updateDate(template); const tokens = template.split('
    '); const text = `${tokens[0]} ${document.body.innerHTML} ${tokens[1]}`; writeToFile('index.html', text); @@ -580,6 +586,18 @@ function removePlotImages() { $('img[alt="Covid Cases"]').remove(); } + +function updateDate(template) { + const date = new Date(); + const date_str = date.toLocaleString('en-us', {month: 'long', day: 'numeric', year: 'numeric'}); + template = template.replace('May 20, 2021', date_str); + template = template.replace('May 20, 2021', date_str); + return template; +} + + +// UTIL + function readFile(filename) { try { return fs.readFileSync(filename, 'utf8'); diff --git a/web/template.html b/web/template.html index d508fa55b..8db5fe75e 100644 --- a/web/template.html +++ b/web/template.html @@ -235,7 +235,7 @@ From dd37505f3fc1c80bef73d9c5ec798a7dc49c550d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 1 Oct 2021 01:22:39 +0200 Subject: [PATCH 012/667] Inline --- README.md | 22 +++++++++++----------- index.html | 26 +++++++++++++------------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 19637c4ad..26e451a55 100644 --- a/README.md +++ b/README.md @@ -732,10 +732,10 @@ def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3 ### Other Uses ```python - = [* [, ...]] - = {* [, ...]} - = (*, [...]) - = {** [, ...]} + = [* [, ...]] + = {* [, ...]} + = (*, [...]) + = {** [, ...]} ``` ```python @@ -774,8 +774,8 @@ Inline ### Any, All ```python - = any() # False if empty. - = all(el[1] for el in ) # True if empty. + = any() # Is `bool(el)` True for any element. + = all() # Is True for all elements or empty. ``` ### Conditional Expression @@ -788,11 +788,11 @@ Inline ['zero', 1, 2, 3] ``` -### Namedtuple, Enum, Dataclass +### Named Tuple, Enum, Dataclass ```python from collections import namedtuple -Point = namedtuple('Point', 'x y') -point = Point(0, 0) +Point = namedtuple('Point', 'x y') +point = Point(0, 0) ``` ```python @@ -803,8 +803,8 @@ direction = Direction.n ```python from dataclasses import make_dataclass -Creature = make_dataclass('Creature', ['loc', 'dir']) -creature = Creature(Point(0, 0), Direction.n) +Creature = make_dataclass('Creature', ['loc', 'dir']) +creature = Creature(point, direction) ``` diff --git a/index.html b/index.html index e62fe063f..6a3e2e703 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
    - +
    @@ -786,10 +786,10 @@ def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
    -

    Other Uses

    <list> = [*<collection> [, ...]]
    -<set>  = {*<collection> [, ...]}
    -<tup.> = (*<collection>, [...])
    -<dict> = {**<dict> [, ...]}
    +

    Other Uses

    <list>  = [*<collection> [, ...]]
    +<set>   = {*<collection> [, ...]}
    +<tuple> = (*<collection>, [...])
    +<dict>  = {**<dict> [, ...]}
     
    head, *body, tail = <collection>
    @@ -816,8 +816,8 @@
     
    • Reduce must be imported from functools module.
    -

    Any, All

    <bool> = any(<collection>)                                # False if empty.
    -<bool> = all(el[1] for el in <collection>)                # True if empty.
    +

    Any, All

    <bool> = any(<collection>)                                # Is `bool(el)` True for any element.
    +<bool> = all(<collection>)                                # Is True for all elements or empty.
     

    Conditional Expression

    <obj> = <exp_if_true> if <condition> else <exp_if_false>
    @@ -826,9 +826,9 @@
     
    >>> [a if a else 'zero' for a in (0, 1, 2, 3)]
     ['zero', 1, 2, 3]
     
    -

    Namedtuple, Enum, Dataclass

    from collections import namedtuple
    -Point     = namedtuple('Point', 'x y')
    -point     = Point(0, 0)
    +

    Named Tuple, Enum, Dataclass

    from collections import namedtuple
    +Point = namedtuple('Point', 'x y')
    +point = Point(0, 0)
     
    from enum import Enum
    @@ -836,8 +836,8 @@
     direction = Direction.n
     
    from dataclasses import make_dataclass
    -Creature  = make_dataclass('Creature', ['loc', 'dir'])
    -creature  = Creature(Point(0, 0), Direction.n)
    +Creature = make_dataclass('Creature', ['loc', 'dir'])
    +creature = Creature(point, direction)
     

    #Closure

    We have a closure in Python when:

    • A nested function references a value of its enclosing function and then
    • @@ -3005,7 +3005,7 @@ From 19eb97ccf52601e83651a5e918d2d96df9e078c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 1 Oct 2021 04:12:05 +0200 Subject: [PATCH 013/667] String --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 26e451a55..79a3f9d10 100644 --- a/README.md +++ b/README.md @@ -308,7 +308,7 @@ String ```python = .split() # Splits on one or more whitespace characters. = .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times. - = .splitlines(keepends=False) # Splits on [\n\r\f\v\x1c\x1d\x1e\x85] and '\r\n'. + = .splitlines(keepends=False) # Splits on [\n\r\f\v\x1c\x1d\x1e\x85…] and \r\n. = .join() # Joins elements using string as a separator. ``` diff --git a/index.html b/index.html index 6a3e2e703..7afc768d0 100644 --- a/index.html +++ b/index.html @@ -449,7 +449,7 @@
      <list> = <str>.split()                       # Splits on one or more whitespace characters.
       <list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
      -<list> = <str>.splitlines(keepends=False)    # Splits on [\n\r\f\v\x1c\x1d\x1e\x85] and '\r\n'.
      +<list> = <str>.splitlines(keepends=False)    # Splits on [\n\r\f\v\x1c\x1d\x1e\x85…] and \r\n.
       <str>  = <str>.join(<coll_of_strings>)       # Joins elements using string as a separator.
       
      <bool> = <sub_str> in <str>                  # Checks if string contains a substring.
      
      From 7af8bec7c34403de4d7c80a316de2f2ee815eb7e Mon Sep 17 00:00:00 2001
      From: =?UTF-8?q?Jure=20=C5=A0orn?= 
      Date: Sat, 2 Oct 2021 03:05:05 +0200
      Subject: [PATCH 014/667] Curses
      
      ---
       README.md  | 4 ++--
       index.html | 8 ++++----
       2 files changed, 6 insertions(+), 6 deletions(-)
      
      diff --git a/README.md b/README.md
      index 79a3f9d10..57bbf577a 100644
      --- a/README.md
      +++ b/README.md
      @@ -2383,8 +2383,8 @@ def main(screen):
           while ch != ascii.ESC:
               height, _ = screen.getmaxyx()
               screen.clear()
      -        for y, a_path in enumerate(paths[first : first+height]):
      -            screen.addstr(y, 0, a_path, A_REVERSE * (selected == first + y))
      +        for y, filename in enumerate(paths[first : first+height]):
      +            screen.addstr(y, 0, filename, A_REVERSE * (selected == first + y))
               ch = screen.getch()
               selected += (ch == KEY_DOWN) - (ch == KEY_UP)
               selected = max(0, min(len(paths)-1, selected))
      diff --git a/index.html b/index.html
      index 7afc768d0..009e5f7b9 100644
      --- a/index.html
      +++ b/index.html
      @@ -226,7 +226,7 @@
       
       
         
      - +
      @@ -2093,8 +2093,8 @@ while ch != ascii.ESC: height, _ = screen.getmaxyx() screen.clear() - for y, a_path in enumerate(paths[first : first+height]): - screen.addstr(y, 0, a_path, A_REVERSE * (selected == first + y)) + for y, filename in enumerate(paths[first : first+height]): + screen.addstr(y, 0, filename, A_REVERSE * (selected == first + y)) ch = screen.getch() selected += (ch == KEY_DOWN) - (ch == KEY_UP) selected = max(0, min(len(paths)-1, selected)) @@ -3005,7 +3005,7 @@ From 6344398401ca3b9c6466a53e95d966ed398e57ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Oct 2021 03:15:42 +0200 Subject: [PATCH 015/667] Fixed links at the top --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 57bbf577a..31722a497 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Comprehensive Python Cheatsheet =============================== -[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions). +Download text file, Buy PDF, Fork me on GitHub or Check out FAQ. ![Monty Python](web/image_888.jpeg) From fd773050e35876500b810ad4a84d23870320dcb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Oct 2021 03:20:15 +0200 Subject: [PATCH 016/667] Reverted link changes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 31722a497..57bbf577a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Comprehensive Python Cheatsheet =============================== -Download text file, Buy PDF, Fork me on GitHub or Check out FAQ. +[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions). ![Monty Python](web/image_888.jpeg) From bbde7a70b58ff97b8706e3734794fee4bf346737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 4 Oct 2021 04:31:29 +0200 Subject: [PATCH 017/667] Format, Pygame --- README.md | 8 +++++--- index.html | 14 ++++++++------ 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 57bbf577a..7c213e3aa 100644 --- a/README.md +++ b/README.md @@ -412,18 +412,20 @@ Format {:.<10} # '......' {:0} # '' ``` -* **Use `'{:{}[...]}'` to set options dynamically.** +* **Options can be generated dynamically: `f'{:{}[…]}'`.** * **Adding `'!r'` before the colon converts object to string by calling its [repr()](#class) method.** ### Strings ```python -{'abcde'!r:10} # "'abcde' " +{'abcde':10} # 'abcde ' {'abcde':10.3} # 'abc ' {'abcde':.3} # 'abc' +{'abcde'!r:10} # "'abcde' " ``` ### Numbers ```python +{ 123456:10} # ' 123456' { 123456:10,} # ' 123,456' { 123456:10_} # ' 123_456' { 123456:+10} # ' +123456' @@ -2950,7 +2952,7 @@ while all(event.type != pg.QUIT for event in pg.event.get()): **Object for representing images.** ```python = pg.display.set_mode((width, height)) # Returns display surface. - = pg.Surface((width, height), …) # New RGB surface. Add `pg.SRCALPHA` for RGBA. + = pg.Surface((width, height) [, flags]) # New RGB surface. RGBA if `flags=pg.SRCALPHA`. = pg.image.load('') # Loads the image. Format depends on source. = .subsurface() # Returns a subsurface. ``` diff --git a/index.html b/index.html index 009e5f7b9..1d802bbef 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
      - +
      @@ -537,15 +537,17 @@
      -
    • Use '{<el>:{<str/int/float>}[...]}' to set options dynamically.
    • +
    • Options can be generated dynamically: f'{<el>:{<str/int>}[…]}'.
    • Adding '!r' before the colon converts object to string by calling its repr() method.
    -

    Strings

    {'abcde'!r:10}                                 # "'abcde'   "
    +

    Strings

    {'abcde':10}                                   # 'abcde     '
     {'abcde':10.3}                                 # 'abc       '
     {'abcde':.3}                                   # 'abc'
    +{'abcde'!r:10}                                 # "'abcde'   "
     
    -

    Numbers

    { 123456:10,}                                  # '   123,456'
    +

    Numbers

    { 123456:10}                                   # '    123456'
    +{ 123456:10,}                                  # '   123,456'
     { 123456:10_}                                  # '   123_456'
     { 123456:+10}                                  # '   +123456'
     {-123456:=10}                                  # '-   123456'
    @@ -2538,7 +2540,7 @@
     <list> = <Rect>.collidelistall(<list_of_Rect>)  # Returns indexes of all colliding Rects.
     

    Surface

    Object for representing images.

    <Surf> = pg.display.set_mode((width, height))   # Returns display surface.
    -<Surf> = pg.Surface((width, height), …)         # New RGB surface. Add `pg.SRCALPHA` for RGBA.
    +<Surf> = pg.Surface((width, height) [, flags])  # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
     <Surf> = pg.image.load('<path>')                # Loads the image. Format depends on source.
     <Surf> = <Surf>.subsurface(<Rect>)              # Returns a subsurface.
     
    @@ -3005,7 +3007,7 @@ From a9454ebabd0fab409d71eec41eea1a6eade84593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=AD=E4=B9=9D=E9=BC=8E?= <109224573@qq.com> Date: Wed, 6 Oct 2021 10:21:42 +0800 Subject: [PATCH 018/667] subprocess.run: encoding -> text=True --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7c213e3aa..94f8ada68 100644 --- a/README.md +++ b/README.md @@ -1703,7 +1703,7 @@ import os #### Sends '1 + 1' to the basic calculator and captures its output: ```python >>> from subprocess import run ->>> run('bc', input='1 + 1\n', capture_output=True, encoding='utf-8') +>>> run('bc', input='1 + 1\n', capture_output=True, text=True) CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='') ``` From 2be9c2df86dfd98a8ece1bfed24a2d255785f3ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 7 Oct 2021 10:03:17 +0200 Subject: [PATCH 019/667] Format, Class, Enum, Exception --- README.md | 20 ++++++++++---------- index.html | 24 ++++++++++++------------ web/faq.html | 2 +- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 7c213e3aa..fde4a5d09 100644 --- a/README.md +++ b/README.md @@ -425,12 +425,12 @@ Format ### Numbers ```python -{ 123456:10} # ' 123456' -{ 123456:10,} # ' 123,456' -{ 123456:10_} # ' 123_456' -{ 123456:+10} # ' +123456' -{-123456:=10} # '- 123456' -{ 123456: } # ' 123456' +{123456:10} # ' 123456' +{123456:10,} # ' 123,456' +{123456:10_} # ' 123_456' +{123456:+10} # ' +123456' +{123456:=+10} # '+ 123456' +{123456: } # ' 123456' {-123456: } # '-123456' ``` @@ -1031,6 +1031,7 @@ class : : = : list/dict/set = field(default_factory=list/dict/set) ``` +* **For arbitrary type use `'typing.Any'`.** * **Objects can be made sortable with `'order=True'` and immutable with `'frozen=True'`.** * **For object to be hashable, all attributes must be hashable and frozen must be True.** * **Function field() is needed because `': list = []'` would make a list that is shared among all instances.** @@ -1333,9 +1334,9 @@ Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3}) ```python from functools import partial LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), - 'OR' : partial(lambda l, r: l or r)}) + 'OR': partial(lambda l, r: l or r)}) ``` -* **Another solution in this particular case is to use functions and\_() and or\_() from the module [operator](#operator).** +* **Member names are in all caps because trying to access a member that is named after a reserved keyword raises SyntaxError.** Exceptions @@ -1362,7 +1363,7 @@ finally: ``` * **Code inside the `'else'` block will only be executed if `'try'` block had no exceptions.** -* **Code inside the `'finally'` block will always be executed.** +* **Code inside the `'finally'` block will always be executed (unless a signal is received).** ### Catching Exceptions ```python @@ -2131,7 +2132,6 @@ sorted_by_second = sorted(, key=op.itemgetter(1)) sorted_by_both = sorted(, key=op.itemgetter(1, 0)) product_of_elems = functools.reduce(op.mul, ) union_of_sets = functools.reduce(op.or_, ) -LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR': op.or_}) last_el = op.methodcaller('pop')() ``` diff --git a/index.html b/index.html index 1d802bbef..3326aeade 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
    - +
    @@ -546,12 +546,12 @@ {'abcde'!r:10} # "'abcde' "
    -

    Numbers

    { 123456:10}                                   # '    123456'
    -{ 123456:10,}                                  # '   123,456'
    -{ 123456:10_}                                  # '   123_456'
    -{ 123456:+10}                                  # '   +123456'
    -{-123456:=10}                                  # '-   123456'
    -{ 123456: }                                    # ' 123456'
    +

    Numbers

    {123456:10}                                    # '    123456'
    +{123456:10,}                                   # '   123,456'
    +{123456:10_}                                   # '   123_456'
    +{123456:+10}                                   # '   +123456'
    +{123456:=+10}                                  # '+   123456'
    +{123456: }                                     # ' 123456'
     {-123456: }                                    # '-123456'
     
    @@ -1025,6 +1025,7 @@
      +
    • For arbitrary type use 'typing.Any'.
    • Objects can be made sortable with 'order=True' and immutable with 'frozen=True'.
    • For object to be hashable, all attributes must be hashable and frozen must be True.
    • Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances.
    • @@ -1291,11 +1292,11 @@

      User-defined functions cannot be values, so they must be wrapped:

      from functools import partial
       LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
      -                           'OR' : partial(lambda l, r: l or r)})
      +                           'OR':  partial(lambda l, r: l or r)})
       
        -
      • Another solution in this particular case is to use functions and_() and or_() from the module operator.
      • +
      • Member names are in all caps because trying to access a member that is named after a reserved keyword raises SyntaxError.

      #Exceptions

      Basic Example

      try:
           <code>
      @@ -1318,7 +1319,7 @@
       
       
      • Code inside the 'else' block will only be executed if 'try' block had no exceptions.
      • -
      • Code inside the 'finally' block will always be executed.
      • +
      • Code inside the 'finally' block will always be executed (unless a signal is received).

      Catching Exceptions

      except <exception>:
       except <exception> as <name>:
      @@ -1903,7 +1904,6 @@
       sorted_by_both   = sorted(<collection>, key=op.itemgetter(1, 0))
       product_of_elems = functools.reduce(op.mul, <collection>)
       union_of_sets    = functools.reduce(op.or_, <coll_of_sets>)
      -LogicOp          = enum.Enum('LogicOp', {'AND': op.and_, 'OR': op.or_})
       last_el          = op.methodcaller('pop')(<list>)
       

      #Introspection

      Inspecting code at runtime.

      Variables

      <list> = dir()                             # Names of local variables (incl. functions).
      @@ -3007,7 +3007,7 @@
        
       
         
       
      diff --git a/web/faq.html b/web/faq.html
      index 088ed6110..1c659c3c1 100644
      --- a/web/faq.html
      +++ b/web/faq.html
      @@ -1,5 +1,5 @@
       
      Python 2 or Python 3?
      -    Python 3.6 (Except for dataclasses and asyncio that require version 3.7). +    Python 3.7

      What is the best way to use it?
      From 85bbdb43d937a821556eb0a9dd0b1c6bba26c8ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 8 Oct 2021 17:24:07 +0200 Subject: [PATCH 020/667] Path, SQLite, Synthesizer --- README.md | 12 ++++++------ index.html | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index fde4a5d09..87e97d3e9 100644 --- a/README.md +++ b/README.md @@ -1645,7 +1645,7 @@ from pathlib import Path ``` ```python - = .parent # Returns Path without final component. + = .parent # Returns Path without the final component. = .name # Returns final component as a string. = .stem # Returns final component without extension. = .suffix # Returns final component's extension. @@ -1864,11 +1864,11 @@ import sqlite3 #### Or: ```python with : # Exits the block with commit() or rollback(), - .execute('') # depending on whether an exception occurred. + .execute('') # depending on whether any exception occurred. ``` ### Placeholders -* **Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.** +* **Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.** * **Bools will be stored and returned as ints and dates as [ISO formatted strings](#encode).** ```python .execute('', ) # Replaces '?'s in query with values. @@ -2900,15 +2900,15 @@ Synthesizer import math, struct, simpleaudio from itertools import repeat, chain F = 44100 -P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,' -P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,' +P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,' +P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,' get_pause = lambda seconds: repeat(0, int(seconds * F)) sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F) get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F))) get_hz = lambda key: 8.176 * 2 ** (int(key) / 12) parse_note = lambda note: (get_hz(note[:2]), 1/4 if '♩' in note else 1/8) get_samples = lambda note: get_wave(*parse_note(note)) if note else get_pause(1/8) -samples_f = chain.from_iterable(get_samples(n) for n in f'{P1}{P1}{P2}'.split(',')) +samples_f = chain.from_iterable(get_samples(n) for n in f'{P1},{P1},{P2}'.split(',')) samples_b = b''.join(struct.pack('
      - +
      @@ -1540,7 +1540,7 @@ <Path> = Path.home() # Returns user's home directory. <Path> = Path(__file__).resolve() # Returns script's path if cwd wasn't changed.
      -
      <Path> = <Path>.parent              # Returns Path without final component.
      +
      <Path> = <Path>.parent              # Returns Path without the final component.
       <str>  = <Path>.name                # Returns final component as a string.
       <str>  = <Path>.stem                # Returns final component without extension.
       <str>  = <Path>.suffix              # Returns final component's extension.
      @@ -1698,11 +1698,11 @@
       

      Or:

      with <conn>:                                    # Exits the block with commit() or rollback(),
      -    <conn>.execute('<query>')                   # depending on whether an exception occurred.
      +    <conn>.execute('<query>')                   # depending on whether any exception occurred.
       

      Placeholders

        -
      • Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.
      • +
      • Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.
      • Bools will be stored and returned as ints and dates as ISO formatted strings.
      <conn>.execute('<query>', <list/tuple>)         # Replaces '?'s in query with values.
       <conn>.execute('<query>', <dict/namedtuple>)    # Replaces ':<key>'s with values.
      @@ -2498,15 +2498,15 @@
       import math, struct, simpleaudio
       from itertools import repeat, chain
       F  = 44100
      -P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,'
      -P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,'
      +P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,'
      +P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,'
       get_pause   = lambda seconds: repeat(0, int(seconds * F))
       sin_f       = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
       get_wave    = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
       get_hz      = lambda key: 8.176 * 2 ** (int(key) / 12)
       parse_note  = lambda note: (get_hz(note[:2]), 1/4 if '♩' in note else 1/8)
       get_samples = lambda note: get_wave(*parse_note(note)) if note else get_pause(1/8)
      -samples_f   = chain.from_iterable(get_samples(n) for n in f'{P1}{P1}{P2}'.split(','))
      +samples_f   = chain.from_iterable(get_samples(n) for n in f'{P1},{P1},{P2}'.split(','))
       samples_b   = b''.join(struct.pack('<h', int(f * 30000)) for f in samples_f)
       simpleaudio.play_buffer(samples_b, 1, 2, F)
       
      @@ -3007,7 +3007,7 @@ From 4c53f911818aa09712bb2784b2a8a9ac6de40d11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 8 Oct 2021 17:29:36 +0200 Subject: [PATCH 021/667] Parsed changes to OS Commands --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 94671a3b8..c9fca8bde 100644 --- a/index.html +++ b/index.html @@ -1579,7 +1579,7 @@

      Sends '1 + 1' to the basic calculator and captures its output:

      >>> from subprocess import run
      ->>> run('bc', input='1 + 1\n', capture_output=True, encoding='utf-8')
      +>>> run('bc', input='1 + 1\n', capture_output=True, text=True)
       CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='')
       
      From ac54ab1e1ff2ce8e02970f255ffb654ce7d31fb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 13 Oct 2021 10:42:30 +0200 Subject: [PATCH 022/667] Input, Pygame --- README.md | 4 ++-- index.html | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c08762812..bbed66a37 100644 --- a/README.md +++ b/README.md @@ -1489,7 +1489,7 @@ Input ``` * **Trailing newline gets stripped.** * **Prompt string is printed to the standard output before reading input.** -* **Raises EOFError when user hits EOF (ctrl-d/z) or input stream gets exhausted.** +* **Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.** Command Line Arguments @@ -2952,7 +2952,7 @@ while all(event.type != pg.QUIT for event in pg.event.get()): **Object for representing images.** ```python = pg.display.set_mode((width, height)) # Returns display surface. - = pg.Surface((width, height) [, flags]) # New RGB surface. RGBA if `flags=pg.SRCALPHA`. + = pg.Surface((width, height), flags=0) # New RGB surface. RGBA if `flags=pg.SRCALPHA`. = pg.image.load('') # Loads the image. Format depends on source. = .subsurface() # Returns a subsurface. ``` diff --git a/index.html b/index.html index c9fca8bde..14acf5f4b 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
      - +
      @@ -1422,7 +1422,7 @@
      • Trailing newline gets stripped.
      • Prompt string is printed to the standard output before reading input.
      • -
      • Raises EOFError when user hits EOF (ctrl-d/z) or input stream gets exhausted.
      • +
      • Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.

      #Command Line Arguments

      import sys
       scripts_path = sys.argv[0]
      @@ -2540,7 +2540,7 @@
       <list> = <Rect>.collidelistall(<list_of_Rect>)  # Returns indexes of all colliding Rects.
       

      Surface

      Object for representing images.

      <Surf> = pg.display.set_mode((width, height))   # Returns display surface.
      -<Surf> = pg.Surface((width, height) [, flags])  # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
      +<Surf> = pg.Surface((width, height), flags=0)   # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
       <Surf> = pg.image.load('<path>')                # Loads the image. Format depends on source.
       <Surf> = <Surf>.subsurface(<Rect>)              # Returns a subsurface.
       
      @@ -3007,7 +3007,7 @@ From dd2f928c29b7cc9c6c47831b317a93dbc4d63943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 14 Oct 2021 14:56:22 +0200 Subject: [PATCH 023/667] Added Imports --- README.md | 11 +++++++++++ index.html | 13 +++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bbed66a37..82b99f930 100644 --- a/README.md +++ b/README.md @@ -810,6 +810,17 @@ creature = Creature(point, direction) ``` +Imports +------- +```python +import # Imports a built-in or '.py'. +import # Imports a built-in or '/__init__.py'. +import . # Imports a built-in or '/.py'. +``` +* **Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called `'__init__.py'` as a package.** +* **Running `'import '` does not automatically provide access to package's modules unless they are imported in its init script.** + + Closure ------- **We have a closure in Python when:** diff --git a/index.html b/index.html index 14acf5f4b..a652a550e 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
      - +
      @@ -841,6 +841,15 @@ Creature = make_dataclass('Creature', ['loc', 'dir']) creature = Creature(point, direction)
    +

    #Imports

    import <module>            # Imports a built-in or '<module>.py'.
    +import <package>           # Imports a built-in or '<package>/__init__.py'.
    +import <package>.<module>  # Imports a built-in or '<package>/<module>.py'.
    +
    + +
      +
    • Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called '__init__.py' as a package.
    • +
    • Running 'import <package>' does not automatically provide access to package's modules unless they are imported in its init script.
    • +

    #Closure

    We have a closure in Python when:

    • A nested function references a value of its enclosing function and then
    • the enclosing function returns the nested function.
    • @@ -3007,7 +3016,7 @@
      - +
      From f340968b233f60114eee58bed6f58e0993cf46aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Oct 2021 12:33:14 +0200 Subject: [PATCH 024/667] Updated index --- index.html | 4 ++-- pdf/index_for_pdf.html | 1 + pdf/index_for_pdf_print.html | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index a652a550e..1372d41dc 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
      - +
      @@ -3016,7 +3016,7 @@
      - +
      diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html index 192cb16f5..3593efe73 100644 --- a/pdf/index_for_pdf.html +++ b/pdf/index_for_pdf.html @@ -63,6 +63,7 @@

      H

      hexadecimal representation, 7, 8, 28

      I

      image, 35, 39-40, 42-43
      +imports, 12
      inline, 11-12, 15, 20
      input function, 22
      introspection, 31
      diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index 5d9519c36..1720a9692 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -63,6 +63,7 @@

      H

      hexadecimal representation, 7, 8, 28

      I

      image, 35, 39-40, 42-43
      +imports, 12
      inline, 11-12, 15, 20
      input function, 22
      introspection, 31
      From cae27c1fb3d6058749110dac65b166d9aeba33a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Oct 2021 17:18:42 +0200 Subject: [PATCH 025/667] Imports --- README.md | 5 +++-- index.html | 9 +++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 82b99f930..da01ea7b4 100644 --- a/README.md +++ b/README.md @@ -817,8 +817,9 @@ import # Imports a built-in or '.py'. import # Imports a built-in or '/__init__.py'. import . # Imports a built-in or '/.py'. ``` -* **Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called `'__init__.py'` as a package.** -* **Running `'import '` does not automatically provide access to package's modules unless they are imported in its init script.** +* **Package is a collection of modules, but it can also define its own objects.** +* **On a filesystem this corresponds to a directory of Python files with an optional init script.** +* **Running `'import '` does not automatically provide access to the package's modules unless they are explicitly imported in its init script.** Closure diff --git a/index.html b/index.html index 1372d41dc..2e416ed7e 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@

      - +
      @@ -847,8 +847,9 @@
      -
    • Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called '__init__.py' as a package.
    • -
    • Running 'import <package>' does not automatically provide access to package's modules unless they are imported in its init script.
    • +
    • Package is a collection of modules, but it can also define its own objects.
    • +
    • On a filesystem this corresponds to a directory of Python files with an optional init script.
    • +
    • Running 'import <package>' does not automatically provide access to the package's modules unless they are explicitly imported in its init script.

    #Closure

    We have a closure in Python when: