from datetime import date, time, datetime, timedelta, timezone
from datetime import date, time, datetime, timedelta, timezone
from dateutil.tz import tzlocal, gettz
import zoneinfo, dateutil.tz
```
```
```python
```python
@ -601,7 +601,7 @@ from dateutil.tz import tzlocal, gettz
```
```
* **Aware `<a>` time and datetime objects have defined timezone, while naive `<n>` don't. If object is naive, it is presumed to be in the system's timezone!**
* **Aware `<a>` time and datetime objects have defined timezone, while naive `<n>` don't. If object is naive, it is presumed to be in the system's timezone!**
* **`'fold=1'` means the second pass in case of time jumping back for one hour.**
* **`'fold=1'` means the second pass in case of time jumping back for one hour.**
* **Timedelta normalizes arguments to ±days, seconds (<86400)andmicroseconds(<1M).**
* **Timedelta normalizes arguments to ±days, seconds (<86400)andmicroseconds(<1M).Itsstr()methodreturns`'[±D, ]H:MM:SS[.…]'`andtotal_seconds()afloatofallseconds.**
* **Use `'<D/DT>.weekday()'` to get the day of the week as an int, with Monday being 0.**
* **Use `'<D/DT>.weekday()'` to get the day of the week as an int, with Monday being 0.**
### Now
### Now
@ -615,13 +615,13 @@ from dateutil.tz import tzlocal, gettz
```python
```python
<tzinfo> = timezone.utc # London without daylight saving time (DST).
<tzinfo> = timezone.utc # London without daylight saving time (DST).
<tzinfo> = timezone(<timedelta>) # Timezone with fixed offset from UTC.
<tzinfo> = timezone(<timedelta>) # Timezone with fixed offset from UTC.
<tzinfo> = tzlocal() # Local tz with dynamic offset. Also gettz().
<tzinfo> = gettz('<Continent>/<City>') # 'Continent/City_Name' timezone or None.
<tzinfo> = dateutil.tz.tzlocal() # Local timezone with dynamic offset from UTC.
<tzinfo> = zoneinfo.ZoneInfo('<iana_key>') # 'Continent/City_Name' zone with dynamic offset.
<DTa> = <DT>.astimezone([<tzinfo>]) # Converts DT to the passed or local fixed zone.
<DTa> = <DT>.astimezone([<tzinfo>]) # Converts DT to the passed or local fixed zone.
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) # Changes object's timezone without conversion.
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) # Changes object's timezone without conversion.
```
```
* **Timezones returned by tzlocal(), gettz(), and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the zone's base offset.**
* **Standard library's zoneinfo.ZoneInfo() can be used instead of gettz() on Python 3.9 and later. It requires 'tzdata' package on Windows. It doesn't return local tz if arg. is omitted.**
* **Timezones returned by tzlocal(), ZoneInfo() and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the base offset.**
* **To get zoneinfo module to work on Windows run `'> pip3 install tzdata'`.**
### Encode
### Encode
```python
```python
@ -660,7 +660,7 @@ from dateutil.tz import tzlocal, gettz
<TD> = <DTa> - <DTa> # Ignores jumps if they share tzinfo object.
<TD> = <DTa> - <DTa> # Ignores jumps if they share tzinfo object.
<D/DT> = <D/DT> ± <TD> # Returned datetime can fall into missing hour.
<D/DT> = <D/DT> ± <TD> # Returned datetime can fall into missing hour.
* **Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out).**
* **Without it, `'add.__name__'` would return `'out'`.**
* **Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out). Without it, `'add.__name__'` would return `'out'`.**
### LRU Cache
### Cache
**Decorator that caches function's return values. All function's arguments must be hashable.**
**Decorator that caches function's return values. All function's arguments must be hashable.**
```python
```python
from functools import lru_cache
from functools import cache
@lru_cache(maxsize=None)
@cache
def fib(n):
def fib(n):
return n if n <2elsefib(n-2)+fib(n-1)
return n if n <2elsefib(n-2)+fib(n-1)
```
```
* **Default size of the cache is 128 values. Passing `'maxsize=None'` makes it unbounded.**
* **CPython interpreter limits recursion depth to 3000 by default. To increase it use`'sys.setrecursionlimit(<int>)'`.**
* **Potential problem with cache is that it can grow indefinitely. To clear the cache run `'fib.cache_clear()'` or use `'@functools.lru_cache(maxsize=<int>)'` instead.**
* **CPython interpreter limits recursion depth to 3000 by default. To increase it run`'sys.setrecursionlimit(<int>)'`.**
### Parametrized Decorator
### Parametrized Decorator
**A decorator that accepts arguments and returns a normal decorator that accepts a function.**
**A decorator that accepts arguments and returns a normal decorator that accepts a function.**
@ -1253,7 +1252,7 @@ True
### Collection
### Collection
* **Only required methods are iter() and len(). Len() should return the number of items.**
* **Only required methods are iter() and len(). Len() should return the number of items.**
* **This cheatsheet actually means `'<iterable>'` when it uses `'<collection>'`.**
* **This cheatsheet actually means `'<iterable>'` when it uses `'<collection>'`.**
* **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that the reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.**
* **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The main drawback of this decision is that the reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.**
```python
```python
class MyCollection:
class MyCollection:
def __init__(self, a):
def __init__(self, a):
@ -2201,8 +2200,8 @@ match <object/expression>:
### Patterns
### Patterns
```python
```python
<value_pattern> = 1/'abc'/True/None/math.pi # Matches the literal or a dotted name.
<value_pattern> = 1/'abc'/True/None/math.pi # Matches the literal or a dotted name.
<class_pattern> = <type>() # Matches any object of that type.
<wildcard_patt> = _ # Matches any object.
<class_pattern> = <type>() # Matches any object of that type (or ABC).
<wildcard_patt> = _ # Matches any object. Useful in last case.
<capture_patt> = <name> # Matches any object and binds it to name.
<capture_patt> = <name> # Matches any object and binds it to name.
<as_pattern> = <pattern> as <name> # Binds match to name. Also <type>(<name>).
<as_pattern> = <pattern> as <name> # Binds match to name. Also <type>(<name>).
<or_pattern> = <pattern> | <pattern> [| ...] # Matches any of the patterns.
<or_pattern> = <pattern> | <pattern> [| ...] # Matches any of the patterns.
@ -2212,7 +2211,7 @@ match <object/expression>:
```
```
* **Sequence pattern can also be written as a tuple.**
* **Sequence pattern can also be written as a tuple.**
* **Use `'*<name>'` and `'**<name>'` in sequence/mapping patterns to bind remaining items.**
* **Use `'*<name>'` and `'**<name>'` in sequence/mapping patterns to bind remaining items.**
* **Sequence pattern must match all items, while mapping pattern does not.**
* **Sequence pattern must match all items of the collection, while mapping pattern does not.**
* **Patterns can be surrounded with brackets to override precedence (`'|'` > `'as'` > `','`).**
* **Patterns can be surrounded with brackets to override precedence (`'|'` > `'as'` > `','`).**
* **Built-in types allow a single positional pattern that is matched against the entire object.**
* **Built-in types allow a single positional pattern that is matched against the entire object.**
* **All names that are bound in the matching case, as well as variables initialized in its block, are visible after the match statement.**
* **All names that are bound in the matching case, as well as variables initialized in its block, are visible after the match statement.**
<div><h2id="datetime"><ahref="#datetime"name="datetime">#</a>Datetime</h2><p><strong>Provides 'date', 'time', 'datetime' and 'timedelta' classes. All are immutable and hashable.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-comment"># $ pip3 install python-dateutil</span>
<div><h2id="datetime"><ahref="#datetime"name="datetime">#</a>Datetime</h2><p><strong>Provides 'date', 'time', 'datetime' and 'timedelta' classes. All are immutable and hashable.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-comment"># $ pip3 install python-dateutil</span>
<spanclass="hljs-keyword">from</span> datetime <spanclass="hljs-keyword">import</span> date, time, datetime, timedelta, timezone
<spanclass="hljs-keyword">from</span> datetime <spanclass="hljs-keyword">import</span> date, time, datetime, timedelta, timezone
<li><strong>Aware <codeclass="apache hljs"><spanclass="hljs-section"><a></span></code> time and datetime objects have defined timezone, while naive <codeclass="apache hljs"><spanclass="hljs-section"><n></span></code> don't. If object is naive, it is presumed to be in the system's timezone!</strong></li>
<li><strong>Aware <codeclass="apache hljs"><spanclass="hljs-section"><a></span></code> time and datetime objects have defined timezone, while naive <codeclass="apache hljs"><spanclass="hljs-section"><n></span></code> don't. If object is naive, it is presumed to be in the system's timezone!</strong></li>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'fold=1'</span></code> means the second pass in case of time jumping back for one hour.</strong></li>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'fold=1'</span></code> means the second pass in case of time jumping back for one hour.</strong></li>
<li><strong>Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).</strong></li>
<li><strong>Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M). Its str() method returns <codeclass="python hljs"><spanclass="hljs-string">'[±D, ]H:MM:SS[.…]'</span></code> and total_seconds() a float of all seconds.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'<D/DT>.weekday()'</span></code> to get the day of the week as an int, with Monday being 0.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'<D/DT>.weekday()'</span></code> to get the day of the week as an int, with Monday being 0.</strong></li>
</ul>
</ul>
<div><h3id="now">Now</h3><pre><codeclass="python language-python hljs"><D/DTn> = D/DT.today() <spanclass="hljs-comment"># Current local date or naive DT. Also DT.now().</span>
<div><h3id="now">Now</h3><pre><codeclass="python language-python hljs"><D/DTn> = D/DT.today() <spanclass="hljs-comment"># Current local date or naive DT. Also DT.now().</span>
<div><h3id="timezone">Timezone</h3><pre><codeclass="python language-python apache hljs"><tzinfo> = timezone.utc <spanclass="hljs-comment"># London without daylight saving time (DST).</span>
<div><h3id="timezone">Timezone</h3><pre><codeclass="python language-python apache hljs"><tzinfo> = timezone.utc <spanclass="hljs-comment"># London without daylight saving time (DST).</span>
<tzinfo> = timezone(<timedelta>) <spanclass="hljs-comment"># Timezone with fixed offset from UTC.</span>
<tzinfo> = timezone(<timedelta>) <spanclass="hljs-comment"># Timezone with fixed offset from UTC.</span>
<tzinfo> = tzlocal()<spanclass="hljs-comment"># Local tz with dynamic offset. Also gettz().</span>
<tzinfo> = gettz(<spanclass="hljs-string">'<Continent>/<City>'</span>)<spanclass="hljs-comment"># 'Continent/City_Name' timezone or None.</span>
<tzinfo> = dateutil.tz.tzlocal() <spanclass="hljs-comment"># Local timezone with dynamic offset from UTC.</span>
<tzinfo> = zoneinfo.ZoneInfo(<spanclass="hljs-string">'<iana_key>'</span>) <spanclass="hljs-comment"># 'Continent/City_Name' zone with dynamic offset.</span>
<DTa> = <DT>.astimezone([<tzinfo>]) <spanclass="hljs-comment"># Converts DT to the passed or local fixed zone.</span>
<DTa> = <DT>.astimezone([<tzinfo>]) <spanclass="hljs-comment"># Converts DT to the passed or local fixed zone.</span>
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) <spanclass="hljs-comment"># Changes object's timezone without conversion.</span>
<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) <spanclass="hljs-comment"># Changes object's timezone without conversion.</span>
</code></pre></div>
</code></pre></div>
<ul>
<ul>
<li><strong>Timezones returned by tzlocal(), gettz(), and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the zone's base offset.</strong></li>
<li><strong>Standard library's zoneinfo.ZoneInfo() can be used instead of gettz() on Python 3.9 and later. It requires 'tzdata' package on Windows. It doesn't return local tz if arg. is omitted.</strong></li>
<li><strong>Timezones returned by tzlocal(), ZoneInfo() and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the base offset.</strong></li>
<li><strong>To get zoneinfo module to work on Windows run <codeclass="python hljs"><spanclass="hljs-string">'> pip3 install tzdata'</span></code>.</strong></li>
</ul>
</ul>
<div><h3id="encode">Encode</h3><pre><codeclass="python language-python apache hljs"><D/T/DT> = D/T/DT.fromisoformat(<str>) <spanclass="hljs-comment"># Object from ISO string. Raises ValueError.</span>
<div><h3id="encode">Encode</h3><pre><codeclass="python language-python apache hljs"><D/T/DT> = D/T/DT.fromisoformat(<str>) <spanclass="hljs-comment"># Object from ISO string. Raises ValueError.</span>
<DT> = DT.strptime(<str>, <spanclass="hljs-string">'<format>'</span>) <spanclass="hljs-comment"># Datetime from str, according to format.</span>
<DT> = DT.strptime(<str>, <spanclass="hljs-string">'<format>'</span>) <spanclass="hljs-comment"># Datetime from str, according to format.</span>
<pre><codeclass="python language-python hljs">head, *body, tail = <coll.><spanclass="hljs-comment"># Head or tail can be omitted.</span>
<pre><codeclass="python language-python hljs">head, *body, tail = <coll.><spanclass="hljs-comment"># Head or tail can be omitted.</span>
@ -766,20 +766,18 @@ player = Player(point, direction) <span class="hljs-comment">#
<ul>
<ul>
<li><strong>Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out).</strong></li>
<li><strong>Without it, <codeclass="python hljs"><spanclass="hljs-string">'add.__name__'</span></code> would return <codeclass="python hljs"><spanclass="hljs-string">'out'</span></code>.</strong></li>
<li><strong>Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out). Without it, <codeclass="python hljs"><spanclass="hljs-string">'add.__name__'</span></code> would return <codeclass="python hljs"><spanclass="hljs-string">'out'</span></code>.</strong></li>
</ul>
</ul>
<div><h3id="lrucache">LRU Cache</h3><p><strong>Decorator that caches function's return values. All function's arguments must be hashable.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> functools <spanclass="hljs-keyword">import</span>lru_cache
<div><h3id="cache">Cache</h3><p><strong>Decorator that caches function's return values. All function's arguments must be hashable.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> functools <spanclass="hljs-keyword">import</span> cache
<spanclass="hljs-keyword">return</span> n <spanclass="hljs-keyword">if</span> n <<spanclass="hljs-number">2</span><spanclass="hljs-keyword">else</span> fib(n-<spanclass="hljs-number">2</span>) + fib(n-<spanclass="hljs-number">1</span>)
</code></pre></div>
<spanclass="hljs-keyword">return</span> n <spanclass="hljs-keyword">if</span> n <<spanclass="hljs-number">2</span><spanclass="hljs-keyword">else</span> fib(n-<spanclass="hljs-number">2</span>) + fib(n-<spanclass="hljs-number">1</span>)</code></pre></div>
<ul>
<ul>
<li><strong>Default size of the cache is 128 values. Passing<codeclass="python hljs"><spanclass="hljs-string">'maxsize=None'</span></code>makes it unbounded.</strong></li>
<li><strong>CPython interpreter limits recursion depth to 3000 by default. To increase it use<codeclass="python hljs"><spanclass="hljs-string">'sys.setrecursionlimit(<int>)'</span></code>.</strong></li>
<li><strong>Potential problem with cache is that it can grow indefinitely. To clear the cache run <codeclass="python hljs"><spanclass="hljs-string">'fib.cache_clear()'</span></code> or use<codeclass="python hljs"><spanclass="hljs-string">'@functools.lru_cache(maxsize=<int>)'</span></code>instead.</strong></li>
<li><strong>CPython interpreter limits recursion depth to 3000 by default. To increase it run<codeclass="python hljs"><spanclass="hljs-string">'sys.setrecursionlimit(<int>)'</span></code>.</strong></li>
</ul>
</ul>
<div><h3id="parametrizeddecorator">Parametrized Decorator</h3><p><strong>A decorator that accepts arguments and returns a normal decorator that accepts a function.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> functools <spanclass="hljs-keyword">import</span> wraps
<div><h3id="parametrizeddecorator">Parametrized Decorator</h3><p><strong>A decorator that accepts arguments and returns a normal decorator that accepts a function.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> functools <spanclass="hljs-keyword">import</span> wraps
@ -1063,7 +1061,7 @@ Hello World!
<div><h3id="collection">Collection</h3><ul>
<div><h3id="collection">Collection</h3><ul>
<li><strong>Only required methods are iter() and len(). Len() should return the number of items.</strong></li>
<li><strong>Only required methods are iter() and len(). Len() should return the number of items.</strong></li>
<li><strong>This cheatsheet actually means <codeclass="python hljs"><spanclass="hljs-string">'<iterable>'</span></code> when it uses <codeclass="python hljs"><spanclass="hljs-string">'<collection>'</span></code>.</strong></li>
<li><strong>This cheatsheet actually means <codeclass="python hljs"><spanclass="hljs-string">'<iterable>'</span></code> when it uses <codeclass="python hljs"><spanclass="hljs-string">'<collection>'</span></code>.</strong></li>
<li><strong>I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that the reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.</strong></li>
<li><strong>I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The main drawback of this decision is that the reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.</strong></li>
<div><h3id="patterns">Patterns</h3><pre><codeclass="python language-python hljs"><value_pattern> = <spanclass="hljs-number">1</span>/<spanclass="hljs-string">'abc'</span>/<spanclass="hljs-keyword">True</span>/<spanclass="hljs-keyword">None</span>/math.pi <spanclass="hljs-comment"># Matches the literal or a dotted name.</span>
<div><h3id="patterns">Patterns</h3><pre><codeclass="python language-python hljs"><value_pattern> = <spanclass="hljs-number">1</span>/<spanclass="hljs-string">'abc'</span>/<spanclass="hljs-keyword">True</span>/<spanclass="hljs-keyword">None</span>/math.pi <spanclass="hljs-comment"># Matches the literal or a dotted name.</span>
<class_pattern> = <type>() <spanclass="hljs-comment"># Matches any object of that type.</span>
<wildcard_patt> = _ <spanclass="hljs-comment"># Matches any object.</span>
<class_pattern> = <type>() <spanclass="hljs-comment"># Matches any object of that type (or ABC).</span>
<wildcard_patt> = _ <spanclass="hljs-comment"># Matches any object. Useful in last case.</span>
<capture_patt> = <name><spanclass="hljs-comment"># Matches any object and binds it to name.</span>
<capture_patt> = <name><spanclass="hljs-comment"># Matches any object and binds it to name.</span>
<as_pattern> = <pattern><spanclass="hljs-keyword">as</span><name><spanclass="hljs-comment"># Binds match to name. Also <type>(<name>).</span>
<as_pattern> = <pattern><spanclass="hljs-keyword">as</span><name><spanclass="hljs-comment"># Binds match to name. Also <type>(<name>).</span>
<or_pattern> = <pattern> | <pattern> [| ...] <spanclass="hljs-comment"># Matches any of the patterns.</span>
<or_pattern> = <pattern> | <pattern> [| ...] <spanclass="hljs-comment"># Matches any of the patterns.</span>
<li><strong>Sequence pattern can also be written as a tuple.</strong></li>
<li><strong>Sequence pattern can also be written as a tuple.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'*<name>'</span></code> and <codeclass="python hljs"><spanclass="hljs-string">'**<name>'</span></code> in sequence/mapping patterns to bind remaining items.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'*<name>'</span></code> and <codeclass="python hljs"><spanclass="hljs-string">'**<name>'</span></code> in sequence/mapping patterns to bind remaining items.</strong></li>
<li><strong>Sequence pattern must match all items, while mapping pattern does not.</strong></li>
<li><strong>Sequence pattern must match all items of the collection, while mapping pattern does not.</strong></li>
<li><strong>Patterns can be surrounded with brackets to override precedence (<codeclass="python hljs"><spanclass="hljs-string">'|'</span></code>><codeclass="python hljs"><spanclass="hljs-string">'as'</span></code>><codeclass="python hljs"><spanclass="hljs-string">','</span></code>).</strong></li>
<li><strong>Patterns can be surrounded with brackets to override precedence (<codeclass="python hljs"><spanclass="hljs-string">'|'</span></code>><codeclass="python hljs"><spanclass="hljs-string">'as'</span></code>><codeclass="python hljs"><spanclass="hljs-string">','</span></code>).</strong></li>
<li><strong>Built-in types allow a single positional pattern that is matched against the entire object.</strong></li>
<li><strong>Built-in types allow a single positional pattern that is matched against the entire object.</strong></li>
<li><strong>All names that are bound in the matching case, as well as variables initialized in its block, are visible after the match statement.</strong></li>
<li><strong>All names that are bound in the matching case, as well as variables initialized in its block, are visible after the match statement.</strong></li>
@ -2931,7 +2929,7 @@ $ deactivate <span class="hljs-comment"># Deactivates the active
<detailsopen><summary><strong>Which Python version is this for?</strong></summary><br>
<detailsopen><summary><strong>Which Python version is this for?</strong></summary><br>
Everything should work in the latest Python version, which is 3.12. Every feature that requires version higher than 3.8 has that mentioned in comments or brackets. There are only six such features, four requiring 3.9, and two requiring 3.10.<br><br>
As of 12th March 2024, the only libraries whose latest version requires Python version higher than 3.8 are: numpy, pandas and matplotlib. They all require Python 3.9. This cheatsheet covers pandas library version 2.0 or higher which was released on 3rd April 2023.
Everything should work in the latest Python version, which is 3.12. Every feature that requires version higher than 3.9 has that mentioned in comments or brackets. There are only two such features, both requiring 3.10.<br><br>
As of 12th March 2024, the only libraries whose latest version requires Python version higher than 3.8 are: numpy, pandas and matplotlib. They all require Python 3.9. This cheatsheet covers numpy version numpy 2.0 (or higher) that was released on 16th June, 2024 pandas version 2.0 (or higher) that was released on 3rd April 2023.
</details><br>
</details><br>
<detailsopen><summary><strong>How to use it?</strong></summary><br>
<detailsopen><summary><strong>How to use it?</strong></summary><br>