Removed PythonCheatsheat Files
This commit is contained in:
parent
d394efe13d
commit
fcbaa04a0a
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
@ -9,8 +9,5 @@
|
|||||||
".vs": true,
|
".vs": true,
|
||||||
".lh": true,
|
".lh": true,
|
||||||
"__pycache__": true,
|
"__pycache__": true,
|
||||||
"Deprecated-POC": true,
|
|
||||||
"BlenderDocumentation": true,
|
|
||||||
"PythonCheatsheats": true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,73 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Args and Kwargs - Python Cheatsheet
|
|
||||||
description: args and kwargs may seem scary, but the truth is that they are not that difficult to grasp and have the power to grant your functions with flexibility and readability
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Args and Kwargs
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
<a href="https://docs.python.org/3/tutorial/index.html">Python args and kwargs Made Easy</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
<code>*args</code> and <code>**kwargs</code> may seem scary, but the truth is that they are not that difficult to grasp and have the power to grant your functions with lots of flexibility.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
Read the article <router-link to="/blog/python-easy-args-kwargs">Python \*args and \*\*kwargs Made Easy</router-link> for a more in deep introduction.
|
|
||||||
|
|
||||||
## Args and Kwargs
|
|
||||||
|
|
||||||
`*args` and `**kwargs` allow you to pass an undefined number of arguments and keywords when calling a function.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def some_function(*args, **kwargs):
|
|
||||||
... pass
|
|
||||||
...
|
|
||||||
>>> # call some_function with any number of arguments
|
|
||||||
>>> some_function(arg1, arg2, arg3)
|
|
||||||
|
|
||||||
>>> # call some_function with any number of keywords
|
|
||||||
>>> some_function(key1=arg1, key2=arg2, key3=arg3)
|
|
||||||
|
|
||||||
>>> # call both, arguments and keywords
|
|
||||||
>>> some_function(arg, key1=arg1)
|
|
||||||
|
|
||||||
>>> # or none
|
|
||||||
>>> some_function()
|
|
||||||
```
|
|
||||||
|
|
||||||
<base-warning>
|
|
||||||
<base-warning-title>
|
|
||||||
Python conventions
|
|
||||||
</base-warning-title>
|
|
||||||
<base-warning-content>
|
|
||||||
The words <code>*args</code> and <code>**kwargs</code> are conventions. They are not imposed by the interpreter, but considered good practice by the Python community.
|
|
||||||
</base-warning-content>
|
|
||||||
</base-warning>
|
|
||||||
|
|
||||||
## args
|
|
||||||
|
|
||||||
You can access the _arguments_ through the `args` variable:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def some_function(*args):
|
|
||||||
... print(f'Arguments passed: {args} as {type(args)}')
|
|
||||||
...
|
|
||||||
>>> some_function('arg1', 'arg2', 'arg3')
|
|
||||||
# Arguments passed: ('arg1', 'arg2', 'arg3') as <class 'tuple'>
|
|
||||||
```
|
|
||||||
|
|
||||||
## kwargs
|
|
||||||
|
|
||||||
Keywords are accessed through the `kwargs` variable:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def some_function(**kwargs):
|
|
||||||
... print(f'keywords: {kwargs} as {type(kwargs)}')
|
|
||||||
...
|
|
||||||
>>> some_function(key1='arg1', key2='arg2')
|
|
||||||
# keywords: {'key1': 'arg1', 'key2': 'arg2'} as <class 'dict'>
|
|
||||||
```
|
|
||||||
@ -1,340 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Basics - Python Cheatsheet
|
|
||||||
description: The basics of python. We all need to start somewhere, so how about doing it here.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Basics
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
We all need to start somewhere, so how about doing it here.
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
From the <a href="https://docs.python.org/3/tutorial/index.html">Python 3 tutorial</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
Python is an easy to learn, powerful programming language [...] Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
## Math Operators
|
|
||||||
|
|
||||||
From **highest** to **lowest** precedence:
|
|
||||||
|
|
||||||
| Operators | Operation | Example |
|
|
||||||
| --------- | ----------------- | --------------- |
|
|
||||||
| \*\* | Exponent | `2 ** 3 = 8` |
|
|
||||||
| % | Modulus/Remainder | `22 % 8 = 6` |
|
|
||||||
| // | Integer division | `22 // 8 = 2` |
|
|
||||||
| / | Division | `22 / 8 = 2.75` |
|
|
||||||
| \* | Multiplication | `3 * 3 = 9` |
|
|
||||||
| - | Subtraction | `5 - 2 = 3` |
|
|
||||||
| + | Addition | `2 + 2 = 4` |
|
|
||||||
|
|
||||||
Examples of expressions:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 2 + 3 * 6
|
|
||||||
# 20
|
|
||||||
|
|
||||||
>>> (2 + 3) * 6
|
|
||||||
# 30
|
|
||||||
|
|
||||||
>>> 2 ** 8
|
|
||||||
#256
|
|
||||||
|
|
||||||
>>> 23 // 7
|
|
||||||
# 3
|
|
||||||
|
|
||||||
>>> 23 % 7
|
|
||||||
# 2
|
|
||||||
|
|
||||||
>>> (5 - 1) * ((7 + 1) / (3 - 1))
|
|
||||||
# 16.0
|
|
||||||
```
|
|
||||||
|
|
||||||
## Augmented Assignment Operators
|
|
||||||
|
|
||||||
| Operator | Equivalent |
|
|
||||||
| ----------- | ---------------- |
|
|
||||||
| `var += 1` | `var = var + 1` |
|
|
||||||
| `var -= 1` | `var = var - 1` |
|
|
||||||
| `var *= 1` | `var = var * 1` |
|
|
||||||
| `var /= 1` | `var = var / 1` |
|
|
||||||
| `var //= 1` | `var = var // 1` |
|
|
||||||
| `var %= 1` | `var = var % 1` |
|
|
||||||
| `var **= 1` | `var = var ** 1` |
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> greeting = 'Hello'
|
|
||||||
>>> greeting += ' world!'
|
|
||||||
>>> greeting
|
|
||||||
# 'Hello world!'
|
|
||||||
|
|
||||||
>>> number = 1
|
|
||||||
>>> number += 1
|
|
||||||
>>> number
|
|
||||||
# 2
|
|
||||||
|
|
||||||
>>> my_list = ['item']
|
|
||||||
>>> my_list *= 3
|
|
||||||
>>> my_list
|
|
||||||
# ['item', 'item', 'item']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Walrus Operator
|
|
||||||
|
|
||||||
The Walrus Operator allows assignment of variables within an expression while returning the value of the variable
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> print(my_var:="Hello World!")
|
|
||||||
# 'Hello world!'
|
|
||||||
|
|
||||||
>>> my_var="Yes"
|
|
||||||
>>> print(my_var)
|
|
||||||
# 'Yes'
|
|
||||||
|
|
||||||
>>> print(my_var:="Hello")
|
|
||||||
# 'Hello'
|
|
||||||
```
|
|
||||||
|
|
||||||
The _Walrus Operator_, or **Assignment Expression Operator** was firstly introduced in 2018 via [PEP 572](https://peps.python.org/pep-0572/), and then officially released with **Python 3.8** in October 2019.
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
Syntax Semantics & Examples
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
The <a href="https://peps.python.org/pep-0572/" target="_blank">PEP 572</a> provides the syntax, semantics and examples for the Walrus Operator.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
## Data Types
|
|
||||||
|
|
||||||
| Data Type | Examples |
|
|
||||||
| ---------------------- | ----------------------------------------- |
|
|
||||||
| Integers | `-2, -1, 0, 1, 2, 3, 4, 5` |
|
|
||||||
| Floating-point numbers | `-1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25` |
|
|
||||||
| Strings | `'a', 'aa', 'aaa', 'Hello!', '11 cats'` |
|
|
||||||
|
|
||||||
## Concatenation and Replication
|
|
||||||
|
|
||||||
String concatenation:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 'Alice' 'Bob'
|
|
||||||
# 'AliceBob'
|
|
||||||
```
|
|
||||||
|
|
||||||
String replication:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 'Alice' * 5
|
|
||||||
# 'AliceAliceAliceAliceAlice'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Variables
|
|
||||||
|
|
||||||
You can name a variable anything as long as it obeys the following rules:
|
|
||||||
|
|
||||||
1. It can be only one word.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> # bad
|
|
||||||
>>> my variable = 'Hello'
|
|
||||||
|
|
||||||
>>> # good
|
|
||||||
>>> var = 'Hello'
|
|
||||||
```
|
|
||||||
|
|
||||||
2. It can use only letters, numbers, and the underscore (`_`) character.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> # bad
|
|
||||||
>>> %$@variable = 'Hello'
|
|
||||||
|
|
||||||
>>> # good
|
|
||||||
>>> my_var = 'Hello'
|
|
||||||
|
|
||||||
>>> # good
|
|
||||||
>>> my_var_2 = 'Hello'
|
|
||||||
```
|
|
||||||
|
|
||||||
3. It can’t begin with a number.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> # this wont work
|
|
||||||
>>> 23_var = 'hello'
|
|
||||||
```
|
|
||||||
|
|
||||||
4. Variable name starting with an underscore (`_`) are considered as "unuseful".
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> # _spam should not be used again in the code
|
|
||||||
>>> _spam = 'Hello'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Comments
|
|
||||||
|
|
||||||
Inline comment:
|
|
||||||
|
|
||||||
```python
|
|
||||||
# This is a comment
|
|
||||||
```
|
|
||||||
|
|
||||||
Multiline comment:
|
|
||||||
|
|
||||||
```python
|
|
||||||
# This is a
|
|
||||||
# multiline comment
|
|
||||||
```
|
|
||||||
|
|
||||||
Code with a comment:
|
|
||||||
|
|
||||||
```python
|
|
||||||
a = 1 # initialization
|
|
||||||
```
|
|
||||||
|
|
||||||
Please note the two spaces in front of the comment.
|
|
||||||
|
|
||||||
Function docstring:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def foo():
|
|
||||||
"""
|
|
||||||
This is a function docstring
|
|
||||||
You can also use:
|
|
||||||
''' Function Docstring '''
|
|
||||||
"""
|
|
||||||
```
|
|
||||||
|
|
||||||
## The print() Function
|
|
||||||
|
|
||||||
The `print()` function writes the value of the argument(s) it is given. [...] it handles multiple arguments, floating point-quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> print('Hello world!')
|
|
||||||
# Hello world!
|
|
||||||
|
|
||||||
>>> a = 1
|
|
||||||
>>> print('Hello world!', a)
|
|
||||||
# Hello world! 1
|
|
||||||
```
|
|
||||||
|
|
||||||
### The end keyword
|
|
||||||
|
|
||||||
The keyword argument `end` can be used to avoid the newline after the output, or end the output with a different string:
|
|
||||||
|
|
||||||
```python
|
|
||||||
phrase = ['printed', 'with', 'a', 'dash', 'in', 'between']
|
|
||||||
>>> for word in phrase:
|
|
||||||
... print(word, end='-')
|
|
||||||
...
|
|
||||||
# printed-with-a-dash-in-between-
|
|
||||||
```
|
|
||||||
|
|
||||||
### The sep keyword
|
|
||||||
|
|
||||||
The keyword `sep` specify how to separate the objects, if there is more than one:
|
|
||||||
|
|
||||||
```python
|
|
||||||
print('cats', 'dogs', 'mice', sep=',')
|
|
||||||
# cats,dogs,mice
|
|
||||||
```
|
|
||||||
|
|
||||||
## The input() Function
|
|
||||||
|
|
||||||
This function takes the input from the user and converts it into a string:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> print('What is your name?') # ask for their name
|
|
||||||
>>> my_name = input()
|
|
||||||
>>> print('Hi, {}'.format(my_name))
|
|
||||||
# What is your name?
|
|
||||||
# Martha
|
|
||||||
# Hi, Martha
|
|
||||||
```
|
|
||||||
|
|
||||||
`input()` can also set a default message without using `print()`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> my_name = input('What is your name? ') # default message
|
|
||||||
>>> print('Hi, {}'.format(my_name))
|
|
||||||
# What is your name? Martha
|
|
||||||
# Hi, Martha
|
|
||||||
```
|
|
||||||
|
|
||||||
It is also possible to use formatted strings to avoid using .format:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> my_name = input('What is your name? ') # default message
|
|
||||||
>>> print(f'Hi, {my_name}')
|
|
||||||
# What is your name? Martha
|
|
||||||
# Hi, Martha
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## The len() Function
|
|
||||||
|
|
||||||
Evaluates to the integer value of the number of characters in a string, list, dictionary, etc.:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> len('hello')
|
|
||||||
# 5
|
|
||||||
|
|
||||||
>>> len(['cat', 3, 'dog'])
|
|
||||||
# 3
|
|
||||||
```
|
|
||||||
|
|
||||||
<base-warning>
|
|
||||||
<base-warning-title>Test of emptiness</base-warning-title>
|
|
||||||
<base-warning-content>
|
|
||||||
Test of emptiness of strings, lists, dictionaries, etc., should not use
|
|
||||||
<code>len</code>, but prefer direct boolean evaluation.
|
|
||||||
</base-warning-content>
|
|
||||||
</base-warning>
|
|
||||||
|
|
||||||
Test of emptiness example:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> a = [1, 2, 3]
|
|
||||||
|
|
||||||
# bad
|
|
||||||
>>> if len(a) > 0: # evaluates to True
|
|
||||||
... print("the list is not empty!")
|
|
||||||
...
|
|
||||||
# the list is not empty!
|
|
||||||
|
|
||||||
# good
|
|
||||||
>>> if a: # evaluates to True
|
|
||||||
... print("the list is not empty!")
|
|
||||||
...
|
|
||||||
# the list is not empty!
|
|
||||||
```
|
|
||||||
|
|
||||||
## The str(), int(), and float() Functions
|
|
||||||
|
|
||||||
These functions allow you to change the type of variable. For example, you can transform from an `integer` or `float` to a `string`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> str(29)
|
|
||||||
# '29'
|
|
||||||
|
|
||||||
>>> str(-3.14)
|
|
||||||
# '-3.14'
|
|
||||||
```
|
|
||||||
|
|
||||||
Or from a `string` to an `integer` or `float`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> int('11')
|
|
||||||
# 11
|
|
||||||
|
|
||||||
>>> float('3.14')
|
|
||||||
# 3.14
|
|
||||||
```
|
|
||||||
@ -1,83 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python built-in functions - Python Cheatsheet
|
|
||||||
description: The Python interpreter has a number of functions and types built into it that are always available.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Built-in Functions
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
The Python interpreter has a number of functions and types built into it that are always available.
|
|
||||||
|
|
||||||
## Python built-in Functions
|
|
||||||
|
|
||||||
| Function | Description |
|
|
||||||
| -------------------------------------------------------------------- | ------------------------------------------------------------------------- |
|
|
||||||
| <router-link to='/builtin/abs'>abs()</router-link> | Return the absolute value of a number. |
|
|
||||||
| <router-link to='/builtin/aiter'>aiter()</router-link> | Return an asynchronous iterator for an asynchronous iterable. |
|
|
||||||
| <router-link to='/builtin/all'>all()</router-link> | Return True if all elements of the iterable are true. |
|
|
||||||
| <router-link to='/builtin/any'>any()</router-link> | Return True if any element of the iterable is true. |
|
|
||||||
| <router-link to='/builtin/ascii'>ascii()</router-link> | Return a string with a printable representation of an object. |
|
|
||||||
| <router-link to='/builtin/bin'>bin()</router-link> | Convert an integer number to a binary string. |
|
|
||||||
| <router-link to='/builtin/bool'>bool()</router-link> | Return a Boolean value. |
|
|
||||||
| <router-link to='/builtin/breakpoint'>breakpoint()</router-link> | Drops you into the debugger at the call site. |
|
|
||||||
| <router-link to='/builtin/bytearray'>bytearray()</router-link> | Return a new array of bytes. |
|
|
||||||
| <router-link to='/builtin/bytes'>bytes()</router-link> | Return a new “bytes” object. |
|
|
||||||
| <router-link to='/builtin/callable'>callable()</router-link> | Return True if the object argument is callable, False if not. |
|
|
||||||
| <router-link to='/builtin/chr'>chr()</router-link> | Return the string representing a character. |
|
|
||||||
| <router-link to='/builtin/classmethod'>classmethod()</router-link> | Transform a method into a class method. |
|
|
||||||
| <router-link to='/builtin/compile'>compile()</router-link> | Compile the source into a code or AST object. |
|
|
||||||
| <router-link to='/builtin/complex'>complex()</router-link> | Return a complex number with the value real + imag\*1j. |
|
|
||||||
| <router-link to='/builtin/delattr'>delattr()</router-link> | Deletes the named attribute, provided the object allows it. |
|
|
||||||
| <router-link to='/builtin/dict'>dict()</router-link> | Create a new dictionary. |
|
|
||||||
| <router-link to='/builtin/dir'>dir()</router-link> | Return the list of names in the current local scope. |
|
|
||||||
| <router-link to='/builtin/divmod'>divmod()</router-link> | Return a pair of numbers consisting of their quotient and remainder. |
|
|
||||||
| <router-link to='/builtin/enumerate'>enumerate()</router-link> | Return an enumerate object. |
|
|
||||||
| <router-link to='/builtin/eval'>eval()</router-link> | Evaluates and executes an expression. |
|
|
||||||
| <router-link to='/builtin/exec'>exec()</router-link> | This function supports dynamic execution of Python code. |
|
|
||||||
| <router-link to='/builtin/filter'>filter()</router-link> | Construct an iterator from an iterable and returns true. |
|
|
||||||
| <router-link to='/builtin/float'>float()</router-link> | Return a floating point number from a number or string. |
|
|
||||||
| <router-link to='/builtin/format'>format()</router-link> | Convert a value to a “formatted” representation. |
|
|
||||||
| <router-link to='/builtin/frozenset'>frozenset()</router-link> | Return a new frozenset object. |
|
|
||||||
| <router-link to='/builtin/getattr'>getattr()</router-link> | Return the value of the named attribute of object. |
|
|
||||||
| <router-link to='/builtin/globals'>globals()</router-link> | Return the dictionary implementing the current module namespace. |
|
|
||||||
| <router-link to='/builtin/hasattr'>hasattr()</router-link> | True if the string is the name of one of the object’s attributes. |
|
|
||||||
| <router-link to='/builtin/hash'>hash()</router-link> | Return the hash value of the object. |
|
|
||||||
| <router-link to='/builtin/help'>help()</router-link> | Invoke the built-in help system. |
|
|
||||||
| <router-link to='/builtin/hex'>hex()</router-link> | Convert an integer number to a lowercase hexadecimal string. |
|
|
||||||
| <router-link to='/builtin/id'>id()</router-link> | Return the “identity” of an object. |
|
|
||||||
| <router-link to='/builtin/input'>input()</router-link> | This function takes an input and converts it into a string. |
|
|
||||||
| <router-link to='/builtin/int'>int()</router-link> | Return an integer object constructed from a number or string. |
|
|
||||||
| <router-link to='/builtin/isinstance'>isinstance()</router-link> | Return True if the object argument is an instance of an object. |
|
|
||||||
| <router-link to='/builtin/issubclass'>issubclass()</router-link> | Return True if class is a subclass of classinfo. |
|
|
||||||
| <router-link to='/builtin/iter'>iter()</router-link> | Return an iterator object. |
|
|
||||||
| <router-link to='/builtin/len'>len()</router-link> | Return the length (the number of items) of an object. |
|
|
||||||
| <router-link to='/builtin/list'>list()</router-link> | Rather than being a function, list is a mutable sequence type. |
|
|
||||||
| <router-link to='/builtin/locals'>locals()</router-link> | Update and return a dictionary with the current local symbol table. |
|
|
||||||
| <router-link to='/builtin/map'>map()</router-link> | Return an iterator that applies function to every item of iterable. |
|
|
||||||
| <router-link to='/builtin/max'>max()</router-link> | Return the largest item in an iterable. |
|
|
||||||
| <router-link to='/builtin/min'>min()</router-link> | Return the smallest item in an iterable. |
|
|
||||||
| <router-link to='/builtin/next'>next()</router-link> | Retrieve the next item from the iterator. |
|
|
||||||
| <router-link to='/builtin/object'>object()</router-link> | Return a new featureless object. |
|
|
||||||
| <router-link to='/builtin/oct'>oct()</router-link> | Convert an integer number to an octal string. |
|
|
||||||
| <router-link to='/builtin/open'>open()</router-link> | Open file and return a corresponding file object. |
|
|
||||||
| <router-link to='/builtin/ord'>ord()</router-link> | Return an integer representing the Unicode code point of a character. |
|
|
||||||
| <router-link to='/builtin/pow'>pow()</router-link> | Return base to the power exp. |
|
|
||||||
| <router-link to='/builtin/print'>print()</router-link> | Print objects to the text stream file. |
|
|
||||||
| <router-link to='/builtin/property'>property()</router-link> | Return a property attribute. |
|
|
||||||
| <router-link to='/builtin/repr'>repr()</router-link> | Return a string containing a printable representation of an object. |
|
|
||||||
| <router-link to='/builtin/reversed'>reversed()</router-link> | Return a reverse iterator. |
|
|
||||||
| <router-link to='/builtin/round'>round()</router-link> | Return number rounded to ndigits precision after the decimal point. |
|
|
||||||
| <router-link to='/builtin/set'>set()</router-link> | Return a new set object. |
|
|
||||||
| <router-link to='/builtin/setattr'>setattr()</router-link> | This is the counterpart of getattr(). |
|
|
||||||
| <router-link to='/builtin/slice'>slice()</router-link> | Return a sliced object representing a set of indices. |
|
|
||||||
| <router-link to='/builtin/sorted'>sorted()</router-link> | Return a new sorted list from the items in iterable. |
|
|
||||||
| <router-link to='/builtin/staticmethod'>staticmethod()</router-link> | Transform a method into a static method. |
|
|
||||||
| <router-link to='/builtin/str'>str()</router-link> | Return a str version of object. |
|
|
||||||
| <router-link to='/builtin/sum'>sum()</router-link> | Sums start and the items of an iterable. |
|
|
||||||
| <router-link to='/builtin/super'>super()</router-link> | Return a proxy object that delegates method calls to a parent or sibling. |
|
|
||||||
| <router-link to='/builtin/tuple'>tuple()</router-link> | Rather than being a function, is actually an immutable sequence type. |
|
|
||||||
| <router-link to='/builtin/type'>type()</router-link> | Return the type of an object. |
|
|
||||||
| <router-link to='/builtin/vars'>vars()</router-link> | Return the dict attribute for any other object with a dict attribute. |
|
|
||||||
| <router-link to='/builtin/zip'>zip()</router-link> | Iterate over several iterables in parallel. |
|
|
||||||
| <router-link to='/builtin/import'>**import**()</router-link> | This function is invoked by the import statement. |
|
|
||||||
@ -1,120 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Comprehensions - Python Cheatsheet
|
|
||||||
description: List comprehensions provide a concise way to create lists
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Comprehensions
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
List Comprehensions are a special kind of syntax that let us create lists out of other lists, and are incredibly useful when dealing with numbers and with one or two levels of nested for loops.
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
From the Python 3 <a target="_blank" href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions">tutorial</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
List comprehensions provide a concise way to create lists. [...] or to create a subsequence of those elements that satisfy a certain condition.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
Read <router-link to="/blog/python-comprehensions-step-by-step">Python Comprehensions: A step by step Introduction</router-link> for a more in-depth introduction.
|
|
||||||
|
|
||||||
## List comprehension
|
|
||||||
|
|
||||||
This is how we create a new list from an existing collection with a For Loop:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> names = ['Charles', 'Susan', 'Patrick', 'George']
|
|
||||||
|
|
||||||
>>> new_list = []
|
|
||||||
>>> for n in names:
|
|
||||||
... new_list.append(n)
|
|
||||||
...
|
|
||||||
>>> new_list
|
|
||||||
# ['Charles', 'Susan', 'Patrick', 'George']
|
|
||||||
```
|
|
||||||
|
|
||||||
And this is how we do the same with a List Comprehension:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> names = ['Charles', 'Susan', 'Patrick', 'George']
|
|
||||||
|
|
||||||
>>> new_list = [n for n in names]
|
|
||||||
>>> new_list
|
|
||||||
# ['Charles', 'Susan', 'Patrick', 'George']
|
|
||||||
```
|
|
||||||
|
|
||||||
We can do the same with numbers:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> n = [(a, b) for a in range(1, 3) for b in range(1, 3)]
|
|
||||||
>>> n
|
|
||||||
# [(1, 1), (1, 2), (2, 1), (2, 2)]
|
|
||||||
```
|
|
||||||
|
|
||||||
## Adding conditionals
|
|
||||||
|
|
||||||
If we want `new_list` to have only the names that start with C, with a for loop, we would do it like this:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> names = ['Charles', 'Susan', 'Patrick', 'George', 'Carol']
|
|
||||||
|
|
||||||
>>> new_list = []
|
|
||||||
>>> for n in names:
|
|
||||||
... if n.startswith('C'):
|
|
||||||
... new_list.append(n)
|
|
||||||
...
|
|
||||||
>>> print(new_list)
|
|
||||||
# ['Charles', 'Carol']
|
|
||||||
```
|
|
||||||
|
|
||||||
In a List Comprehension, we add the `if` statement at the end:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> new_list = [n for n in names if n.startswith('C')]
|
|
||||||
>>> print(new_list)
|
|
||||||
# ['Charles', 'Carol']
|
|
||||||
```
|
|
||||||
|
|
||||||
To use an `if-else` statement in a List Comprehension:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> nums = [1, 2, 3, 4, 5, 6]
|
|
||||||
>>> new_list = [num*2 if num % 2 == 0 else num for num in nums]
|
|
||||||
>>> print(new_list)
|
|
||||||
# [1, 4, 3, 8, 5, 12]
|
|
||||||
```
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
Set and Dict comprehensions
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
The basics of `list` comprehensions also apply to <b>sets</b> and <b>dictionaries</b>.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
## Set comprehension
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> b = {"abc", "def"}
|
|
||||||
>>> {s.upper() for s in b}
|
|
||||||
{"ABC", "DEF"}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Dict comprehension
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> c = {'name': 'Pooka', 'age': 5}
|
|
||||||
>>> {v: k for k, v in c.items()}
|
|
||||||
{'Pooka': 'name', 5: 'age'}
|
|
||||||
```
|
|
||||||
|
|
||||||
A List comprehension can be generated from a dictionary:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> c = {'name': 'Pooka', 'age': 5}
|
|
||||||
>>> ["{}:{}".format(k.upper(), v) for k, v in c.items()]
|
|
||||||
['NAME:Pooka', 'AGE:5']
|
|
||||||
```
|
|
||||||
@ -1,68 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Context Manager - Python Cheatsheet
|
|
||||||
description: While Python's context managers are widely used, few understand the purpose behind their use. These statements, commonly used with reading and writing files, assist the application in conserving system memory and improve resource management by ensuring specific resources are only in use for certain processes.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Context Manager
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
While Python's context managers are widely used, few understand the purpose behind their use. These statements, commonly used with reading and writing files, assist the application in conserving system memory and improve resource management by ensuring specific resources are only in use for certain processes.
|
|
||||||
|
|
||||||
## The with statement
|
|
||||||
|
|
||||||
A context manager is an object that is notified when a context (a block of code) starts and ends. You commonly use one with the `with` statement. It takes care of the notifying.
|
|
||||||
|
|
||||||
For example, file objects are context managers. When a context ends, the file object is closed automatically:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> with open(filename) as f:
|
|
||||||
... file_contents = f.read()
|
|
||||||
...
|
|
||||||
>>> # the open_file object has automatically been closed.
|
|
||||||
```
|
|
||||||
|
|
||||||
Anything that ends execution of the block causes the context manager's exit method to be called. This includes exceptions, and can be useful when an error causes you to prematurely exit an open file or connection. Exiting a script without properly closing files/connections is a bad idea, that may cause data loss or other problems. By using a context manager, you can ensure that precautions are always taken to prevent damage or loss in this way.
|
|
||||||
|
|
||||||
## Writing your own context manager
|
|
||||||
|
|
||||||
It is also possible to write a context manager using generator syntax thanks to the `contextlib.contextmanager` decorator:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import contextlib
|
|
||||||
>>> @contextlib.contextmanager
|
|
||||||
... def context_manager(num):
|
|
||||||
... print('Enter')
|
|
||||||
... yield num + 1
|
|
||||||
... print('Exit')
|
|
||||||
...
|
|
||||||
>>> with context_manager(2) as cm:
|
|
||||||
... # the following instructions are run when
|
|
||||||
... # the 'yield' point of the context manager is
|
|
||||||
... # reached. 'cm' will have the value that was yielded
|
|
||||||
... print('Right in the middle with cm = {}'.format(cm))
|
|
||||||
...
|
|
||||||
# Enter
|
|
||||||
# Right in the middle with cm = 3
|
|
||||||
# Exit
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Class based context manager
|
|
||||||
|
|
||||||
You can define class based context manager. The key methods are `__enter__` and `__exit__`
|
|
||||||
```python
|
|
||||||
class ContextManager:
|
|
||||||
def __enter__(self, *args, **kwargs):
|
|
||||||
print("--enter--")
|
|
||||||
|
|
||||||
def __exit__(self, *args):
|
|
||||||
print("--exit--")
|
|
||||||
|
|
||||||
|
|
||||||
with ContextManager():
|
|
||||||
print("test")
|
|
||||||
#--enter--
|
|
||||||
#test
|
|
||||||
#--exit--
|
|
||||||
```
|
|
||||||
@ -1,490 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Control Flow - Python Cheatsheet
|
|
||||||
description: Control flow is the order in which individual statements, instructions or function calls are executed or evaluated. The control flow of a Python program is regulated by conditional statements, loops, and function calls.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Control Flow
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
Python control flow
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
Control flow is the order in which individual statements, instructions, or function calls are executed or evaluated. The control flow of a Python program is regulated by conditional statements, loops, and function calls.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
## Comparison Operators
|
|
||||||
|
|
||||||
| Operator | Meaning |
|
|
||||||
| -------- | ------------------------ |
|
|
||||||
| `==` | Equal to |
|
|
||||||
| `!=` | Not equal to |
|
|
||||||
| `<` | Less than |
|
|
||||||
| `>` | Greater Than |
|
|
||||||
| `<=` | Less than or Equal to |
|
|
||||||
| `>=` | Greater than or Equal to |
|
|
||||||
|
|
||||||
These operators evaluate to True or False depending on the values you give them.
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 42 == 42
|
|
||||||
True
|
|
||||||
|
|
||||||
>>> 40 == 42
|
|
||||||
False
|
|
||||||
|
|
||||||
>>> 'hello' == 'hello'
|
|
||||||
True
|
|
||||||
|
|
||||||
>>> 'hello' == 'Hello'
|
|
||||||
False
|
|
||||||
|
|
||||||
>>> 'dog' != 'cat'
|
|
||||||
True
|
|
||||||
|
|
||||||
>>> 42 == 42.0
|
|
||||||
True
|
|
||||||
|
|
||||||
>>> 42 == '42'
|
|
||||||
False
|
|
||||||
```
|
|
||||||
|
|
||||||
## Boolean Operators
|
|
||||||
|
|
||||||
There are three Boolean operators: `and`, `or`, and `not`.
|
|
||||||
In the order of precedence, highest to lowest they are `not`, `and` and `or`.
|
|
||||||
|
|
||||||
The `and` Operator’s _Truth_ Table:
|
|
||||||
|
|
||||||
| Expression | Evaluates to |
|
|
||||||
| ----------------- | ------------ |
|
|
||||||
| `True and True` | `True` |
|
|
||||||
| `True and False` | `False` |
|
|
||||||
| `False and True` | `False` |
|
|
||||||
| `False and False` | `False` |
|
|
||||||
|
|
||||||
The `or` Operator’s _Truth_ Table:
|
|
||||||
|
|
||||||
| Expression | Evaluates to |
|
|
||||||
| ---------------- | ------------ |
|
|
||||||
| `True or True` | `True` |
|
|
||||||
| `True or False` | `True` |
|
|
||||||
| `False or True` | `True` |
|
|
||||||
| `False or False` | `False` |
|
|
||||||
|
|
||||||
The `not` Operator’s _Truth_ Table:
|
|
||||||
|
|
||||||
| Expression | Evaluates to |
|
|
||||||
| ----------- | ------------ |
|
|
||||||
| `not True` | `False` |
|
|
||||||
| `not False` | `True` |
|
|
||||||
|
|
||||||
## Mixing Operators
|
|
||||||
|
|
||||||
You can mix boolean and comparison operators:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> (4 < 5) and (5 < 6)
|
|
||||||
True
|
|
||||||
|
|
||||||
>>> (4 < 5) and (9 < 6)
|
|
||||||
False
|
|
||||||
|
|
||||||
>>> (1 == 2) or (2 == 2)
|
|
||||||
True
|
|
||||||
```
|
|
||||||
|
|
||||||
Also, you can mix use multiple Boolean operators in an expression, along with the comparison operators:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
|
|
||||||
True
|
|
||||||
>>> # In the statement below 3 < 4 and 5 > 5 gets executed first evaluating to False
|
|
||||||
>>> # Then 5 > 4 returns True so the results after True or False is True
|
|
||||||
>>> 5 > 4 or 3 < 4 and 5 > 5
|
|
||||||
True
|
|
||||||
>>> # Now the statement within parentheses gets executed first so True and False returns False.
|
|
||||||
>>> (5 > 4 or 3 < 4) and 5 > 5
|
|
||||||
False
|
|
||||||
```
|
|
||||||
|
|
||||||
## if Statements
|
|
||||||
|
|
||||||
The `if` statement evaluates an expression, and if that expression is `True`, it then executes the following indented code:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> name = 'Debora'
|
|
||||||
|
|
||||||
>>> if name == 'Debora':
|
|
||||||
... print('Hi, Debora')
|
|
||||||
...
|
|
||||||
# Hi, Debora
|
|
||||||
|
|
||||||
>>> if name != 'George':
|
|
||||||
... print('You are not George')
|
|
||||||
...
|
|
||||||
# You are not George
|
|
||||||
```
|
|
||||||
|
|
||||||
The `else` statement executes only if the evaluation of the `if` and all the `elif` expressions are `False`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> name = 'Debora'
|
|
||||||
|
|
||||||
>>> if name == 'George':
|
|
||||||
... print('Hi, George.')
|
|
||||||
... else:
|
|
||||||
... print('You are not George')
|
|
||||||
...
|
|
||||||
# You are not George
|
|
||||||
```
|
|
||||||
|
|
||||||
Only after the `if` statement expression is `False`, the `elif` statement is evaluated and executed:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> name = 'George'
|
|
||||||
|
|
||||||
>>> if name == 'Debora':
|
|
||||||
... print('Hi Debora!')
|
|
||||||
... elif name == 'George':
|
|
||||||
... print('Hi George!')
|
|
||||||
...
|
|
||||||
# Hi George!
|
|
||||||
```
|
|
||||||
|
|
||||||
the `elif` and `else` parts are optional.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> name = 'Antony'
|
|
||||||
|
|
||||||
>>> if name == 'Debora':
|
|
||||||
... print('Hi Debora!')
|
|
||||||
... elif name == 'George':
|
|
||||||
... print('Hi George!')
|
|
||||||
... else:
|
|
||||||
... print('Who are you?')
|
|
||||||
...
|
|
||||||
# Who are you?
|
|
||||||
```
|
|
||||||
|
|
||||||
## Ternary Conditional Operator
|
|
||||||
|
|
||||||
Many programming languages have a ternary operator, which define a conditional expression. The most common usage is to make a terse, simple conditional assignment statement. In other words, it offers one-line code to evaluate the first expression if the condition is true, and otherwise it evaluates the second expression.
|
|
||||||
|
|
||||||
```
|
|
||||||
<expression1> if <condition> else <expression2>
|
|
||||||
```
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> age = 15
|
|
||||||
|
|
||||||
>>> # this if statement:
|
|
||||||
>>> if age < 18:
|
|
||||||
... print('kid')
|
|
||||||
... else:
|
|
||||||
... print('adult')
|
|
||||||
...
|
|
||||||
# output: kid
|
|
||||||
|
|
||||||
>>> # is equivalent to this ternary operator:
|
|
||||||
>>> print('kid' if age < 18 else 'adult')
|
|
||||||
# output: kid
|
|
||||||
```
|
|
||||||
|
|
||||||
Ternary operators can be chained:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> age = 15
|
|
||||||
|
|
||||||
>>> # this ternary operator:
|
|
||||||
>>> print('kid' if age < 13 else 'teen' if age < 18 else 'adult')
|
|
||||||
|
|
||||||
>>> # is equivalent to this if statement:
|
|
||||||
>>> if age < 18:
|
|
||||||
... if age < 13:
|
|
||||||
... print('kid')
|
|
||||||
... else:
|
|
||||||
... print('teen')
|
|
||||||
... else:
|
|
||||||
... print('adult')
|
|
||||||
...
|
|
||||||
# output: teen
|
|
||||||
```
|
|
||||||
|
|
||||||
## Switch-Case Statement
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
Switch-Case statements
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
The _Switch-Case statements_, or **Structural Pattern Matching**, was firstly introduced in 2020 via [PEP 622](https://peps.python.org/pep-0622/), and then officially released with **Python 3.10** in September 2022.
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
Official Tutorial
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
The <a href="https://peps.python.org/pep-0636/" target="_blank">PEP 636</a> provides an official tutorial for the Python Pattern matching or Switch-Case statements.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
### Matching single values
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> response_code = 201
|
|
||||||
>>> match response_code:
|
|
||||||
... case 200:
|
|
||||||
... print("OK")
|
|
||||||
... case 201:
|
|
||||||
... print("Created")
|
|
||||||
... case 300:
|
|
||||||
... print("Multiple Choices")
|
|
||||||
... case 307:
|
|
||||||
... print("Temporary Redirect")
|
|
||||||
... case 404:
|
|
||||||
... print("404 Not Found")
|
|
||||||
... case 500:
|
|
||||||
... print("Internal Server Error")
|
|
||||||
... case 502:
|
|
||||||
... print("502 Bad Gateway")
|
|
||||||
...
|
|
||||||
# Created
|
|
||||||
```
|
|
||||||
|
|
||||||
### Matching with the or Pattern
|
|
||||||
|
|
||||||
In this example, the pipe character (`|` or `or`) allows python to return the same response for two or more cases.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> response_code = 502
|
|
||||||
>>> match response_code:
|
|
||||||
... case 200 | 201:
|
|
||||||
... print("OK")
|
|
||||||
... case 300 | 307:
|
|
||||||
... print("Redirect")
|
|
||||||
... case 400 | 401:
|
|
||||||
... print("Bad Request")
|
|
||||||
... case 500 | 502:
|
|
||||||
... print("Internal Server Error")
|
|
||||||
...
|
|
||||||
# Internal Server Error
|
|
||||||
```
|
|
||||||
|
|
||||||
### Matching by the length of an Iterable
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> today_responses = [200, 300, 404, 500]
|
|
||||||
>>> match today_responses:
|
|
||||||
... case [a]:
|
|
||||||
... print(f"One response today: {a}")
|
|
||||||
... case [a, b]:
|
|
||||||
... print(f"Two responses today: {a} and {b}")
|
|
||||||
... case [a, b, *rest]:
|
|
||||||
... print(f"All responses: {a}, {b}, {rest}")
|
|
||||||
...
|
|
||||||
# All responses: 200, 300, [404, 500]
|
|
||||||
```
|
|
||||||
|
|
||||||
### Default value
|
|
||||||
|
|
||||||
The underscore symbol (`_`) is used to define a default case:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> response_code = 800
|
|
||||||
>>> match response_code:
|
|
||||||
... case 200 | 201:
|
|
||||||
... print("OK")
|
|
||||||
... case 300 | 307:
|
|
||||||
... print("Redirect")
|
|
||||||
... case 400 | 401:
|
|
||||||
... print("Bad Request")
|
|
||||||
... case 500 | 502:
|
|
||||||
... print("Internal Server Error")
|
|
||||||
... case _:
|
|
||||||
... print("Invalid Code")
|
|
||||||
...
|
|
||||||
# Invalid Code
|
|
||||||
```
|
|
||||||
|
|
||||||
### Matching Builtin Classes
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> response_code = "300"
|
|
||||||
>>> match response_code:
|
|
||||||
... case int():
|
|
||||||
... print('Code is a number')
|
|
||||||
... case str():
|
|
||||||
... print('Code is a string')
|
|
||||||
... case _:
|
|
||||||
... print('Code is neither a string nor a number')
|
|
||||||
...
|
|
||||||
# Code is a string
|
|
||||||
```
|
|
||||||
|
|
||||||
### Guarding Match-Case Statements
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> response_code = 300
|
|
||||||
>>> match response_code:
|
|
||||||
... case int():
|
|
||||||
... if response_code > 99 and response_code < 500:
|
|
||||||
... print('Code is a valid number')
|
|
||||||
... case _:
|
|
||||||
... print('Code is an invalid number')
|
|
||||||
...
|
|
||||||
# Code is a valid number
|
|
||||||
```
|
|
||||||
|
|
||||||
## while Loop Statements
|
|
||||||
|
|
||||||
The while statement is used for repeated execution as long as an expression is `True`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> spam = 0
|
|
||||||
>>> while spam < 5:
|
|
||||||
... print('Hello, world.')
|
|
||||||
... spam = spam + 1
|
|
||||||
...
|
|
||||||
# Hello, world.
|
|
||||||
# Hello, world.
|
|
||||||
# Hello, world.
|
|
||||||
# Hello, world.
|
|
||||||
# Hello, world.
|
|
||||||
```
|
|
||||||
|
|
||||||
## break Statements
|
|
||||||
|
|
||||||
If the execution reaches a `break` statement, it immediately exits the `while` loop’s clause:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> while True:
|
|
||||||
... name = input('Please type your name: ')
|
|
||||||
... if name == 'your name':
|
|
||||||
... break
|
|
||||||
...
|
|
||||||
>>> print('Thank you!')
|
|
||||||
# Please type your name: your name
|
|
||||||
# Thank you!
|
|
||||||
```
|
|
||||||
|
|
||||||
## continue Statements
|
|
||||||
|
|
||||||
When the program execution reaches a `continue` statement, the program execution immediately jumps back to the start of the loop.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> while True:
|
|
||||||
... name = input('Who are you? ')
|
|
||||||
... if name != 'Joe':
|
|
||||||
... continue
|
|
||||||
... password = input('Password? (It is a fish.): ')
|
|
||||||
... if password == 'swordfish':
|
|
||||||
... break
|
|
||||||
...
|
|
||||||
>>> print('Access granted.')
|
|
||||||
# Who are you? Charles
|
|
||||||
# Who are you? Debora
|
|
||||||
# Who are you? Joe
|
|
||||||
# Password? (It is a fish.): swordfish
|
|
||||||
# Access granted.
|
|
||||||
```
|
|
||||||
|
|
||||||
## For loop
|
|
||||||
|
|
||||||
The `for` loop iterates over a `list`, `tuple`, `dictionary`, `set` or `string`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> pets = ['Bella', 'Milo', 'Loki']
|
|
||||||
>>> for pet in pets:
|
|
||||||
... print(pet)
|
|
||||||
...
|
|
||||||
# Bella
|
|
||||||
# Milo
|
|
||||||
# Loki
|
|
||||||
```
|
|
||||||
|
|
||||||
## The range() function
|
|
||||||
|
|
||||||
The `range()` function returns a sequence of numbers. It starts from 0, increments by 1, and stops before a specified number:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> for i in range(5):
|
|
||||||
... print(f'Will stop at 5! or 4? ({i})')
|
|
||||||
...
|
|
||||||
# Will stop at 5! or 4? (0)
|
|
||||||
# Will stop at 5! or 4? (1)
|
|
||||||
# Will stop at 5! or 4? (2)
|
|
||||||
# Will stop at 5! or 4? (3)
|
|
||||||
# Will stop at 5! or 4? (4)
|
|
||||||
```
|
|
||||||
|
|
||||||
The `range()` function can also modify its 3 defaults arguments. The first two will be the `start` and `stop` values, and the third will be the `step` argument. The step is the amount that the variable is increased by after each iteration.
|
|
||||||
|
|
||||||
```python
|
|
||||||
# range(start, stop, step)
|
|
||||||
>>> for i in range(0, 10, 2):
|
|
||||||
... print(i)
|
|
||||||
...
|
|
||||||
# 0
|
|
||||||
# 2
|
|
||||||
# 4
|
|
||||||
# 6
|
|
||||||
# 8
|
|
||||||
```
|
|
||||||
|
|
||||||
You can even use a negative number for the step argument to make the for loop count down instead of up.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> for i in range(5, -1, -1):
|
|
||||||
... print(i)
|
|
||||||
...
|
|
||||||
# 5
|
|
||||||
# 4
|
|
||||||
# 3
|
|
||||||
# 2
|
|
||||||
# 1
|
|
||||||
# 0
|
|
||||||
```
|
|
||||||
|
|
||||||
## For else statement
|
|
||||||
|
|
||||||
This allows to specify a statement to execute in case of the full loop has been executed. Only
|
|
||||||
useful when a `break` condition can occur in the loop:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> for i in [1, 2, 3, 4, 5]:
|
|
||||||
... if i == 3:
|
|
||||||
... break
|
|
||||||
... else:
|
|
||||||
... print("only executed when no item is equal to 3")
|
|
||||||
```
|
|
||||||
|
|
||||||
## Ending a Program with sys.exit()
|
|
||||||
|
|
||||||
`exit()` function allows exiting Python.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import sys
|
|
||||||
|
|
||||||
>>> while True:
|
|
||||||
... feedback = input('Type exit to exit: ')
|
|
||||||
... if feedback == 'exit':
|
|
||||||
... print(f'You typed {feedback}.')
|
|
||||||
... sys.exit()
|
|
||||||
...
|
|
||||||
# Type exit to exit: open
|
|
||||||
# Type exit to exit: close
|
|
||||||
# Type exit to exit: exit
|
|
||||||
# You typed exit
|
|
||||||
```
|
|
||||||
@ -1,77 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Dataclasses - Python Cheatsheet
|
|
||||||
description: Dataclasses are python classes, but are suited for storing data objects. This module provides a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Dataclasses
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
`Dataclasses` are python classes, but are suited for storing data objects.
|
|
||||||
This module provides a decorator and functions for automatically adding generated special methods such as `__init__()` and `__repr__()` to user-defined classes.
|
|
||||||
|
|
||||||
## Features
|
|
||||||
|
|
||||||
1. They store data and represent a certain data type. Ex: A number. For people familiar with ORMs, a model instance is a data object. It represents a specific kind of entity. It holds attributes that define or represent the entity.
|
|
||||||
|
|
||||||
2. They can be compared to other objects of the same type. Ex: A number can be greater than, less than, or equal to another number.
|
|
||||||
|
|
||||||
Python 3.7 provides a decorator dataclass that is used to convert a class into a dataclass.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> class Number:
|
|
||||||
... def __init__(self, val):
|
|
||||||
... self.val = val
|
|
||||||
...
|
|
||||||
>>> obj = Number(2)
|
|
||||||
>>> obj.val
|
|
||||||
# 2
|
|
||||||
```
|
|
||||||
|
|
||||||
with dataclass
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> @dataclass
|
|
||||||
... class Number:
|
|
||||||
... val: int
|
|
||||||
...
|
|
||||||
>>> obj = Number(2)
|
|
||||||
>>> obj.val
|
|
||||||
# 2
|
|
||||||
```
|
|
||||||
|
|
||||||
## Default values
|
|
||||||
|
|
||||||
It is easy to add default values to the fields of your data class.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> @dataclass
|
|
||||||
... class Product:
|
|
||||||
... name: str
|
|
||||||
... count: int = 0
|
|
||||||
... price: float = 0.0
|
|
||||||
...
|
|
||||||
>>> obj = Product("Python")
|
|
||||||
>>> obj.name
|
|
||||||
# Python
|
|
||||||
|
|
||||||
>>> obj.count
|
|
||||||
# 0
|
|
||||||
|
|
||||||
>>> obj.price
|
|
||||||
# 0.0
|
|
||||||
```
|
|
||||||
|
|
||||||
## Type hints
|
|
||||||
|
|
||||||
It is mandatory to define the data type in dataclass. However, If you would rather not specify the datatype then, use `typing.Any`.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from dataclasses import dataclass
|
|
||||||
>>> from typing import Any
|
|
||||||
|
|
||||||
>>> @dataclass
|
|
||||||
... class WithoutExplicitTypes:
|
|
||||||
... name: Any
|
|
||||||
... value: Any = 42
|
|
||||||
```
|
|
||||||
@ -1,197 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Debugging - Python Cheatsheet
|
|
||||||
description: In computer programming and software development, debugging is the process of finding and resolving bugs (defects or problems that prevent correct operation) within computer programs, software, or systems.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Debugging
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
<a target="_blank" href="https://en.wikipedia.org/wiki/Debugging">Finding and resolving bugs</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
In computer programming and software development, debugging is the process of finding and resolving bugs (defects or problems that prevent correct operation) within computer programs, software, or systems.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
## Raising Exceptions
|
|
||||||
|
|
||||||
Exceptions are raised with a raise statement. In code, a raise statement consists of the following:
|
|
||||||
|
|
||||||
- The `raise` keyword
|
|
||||||
- A call to the `Exception()` function
|
|
||||||
- A string with a helpful error message passed to the `Exception()` function
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> raise Exception('This is the error message.')
|
|
||||||
# Traceback (most recent call last):
|
|
||||||
# File "<pyshell#191>", line 1, in <module>
|
|
||||||
# raise Exception('This is the error message.')
|
|
||||||
# Exception: This is the error message.
|
|
||||||
```
|
|
||||||
|
|
||||||
Typically, it’s the code that calls the function, not the function itself, that knows how to handle an exception. So, you will commonly see a raise statement inside a function and the `try` and `except` statements in the code calling the function.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def box_print(symbol, width, height):
|
|
||||||
... if len(symbol) != 1:
|
|
||||||
... raise Exception('Symbol must be a single character string.')
|
|
||||||
... if width <= 2:
|
|
||||||
... raise Exception('Width must be greater than 2.')
|
|
||||||
... if height <= 2:
|
|
||||||
... raise Exception('Height must be greater than 2.')
|
|
||||||
... print(symbol * width)
|
|
||||||
... for i in range(height - 2):
|
|
||||||
... print(symbol + (' ' * (width - 2)) + symbol)
|
|
||||||
... print(symbol * width)
|
|
||||||
...
|
|
||||||
>>> for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
|
|
||||||
... try:
|
|
||||||
... box_print(sym, w, h)
|
|
||||||
... except Exception as err:
|
|
||||||
... print('An exception happened: ' + str(err))
|
|
||||||
...
|
|
||||||
# ****
|
|
||||||
# * *
|
|
||||||
# * *
|
|
||||||
# ****
|
|
||||||
# OOOOOOOOOOOOOOOOOOOO
|
|
||||||
# O O
|
|
||||||
# O O
|
|
||||||
# O O
|
|
||||||
# OOOOOOOOOOOOOOOOOOOO
|
|
||||||
# An exception happened: Width must be greater than 2.
|
|
||||||
# An exception happened: Symbol must be a single character string.
|
|
||||||
```
|
|
||||||
|
|
||||||
Read more about [Exception Handling](/cheatsheet/exception-handling).
|
|
||||||
|
|
||||||
## Getting the Traceback as a string
|
|
||||||
|
|
||||||
The `traceback` is displayed by Python whenever a raised exception goes unhandled. But can also obtain it as a string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s traceback but also want an except statement to gracefully handle the exception. You will need to import Python’s traceback module before calling this function.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import traceback
|
|
||||||
|
|
||||||
>>> try:
|
|
||||||
... raise Exception('This is the error message.')
|
|
||||||
>>> except:
|
|
||||||
... with open('errorInfo.txt', 'w') as error_file:
|
|
||||||
... error_file.write(traceback.format_exc())
|
|
||||||
... print('The traceback info was written to errorInfo.txt.')
|
|
||||||
...
|
|
||||||
# 116
|
|
||||||
# The traceback info was written to errorInfo.txt.
|
|
||||||
```
|
|
||||||
|
|
||||||
The 116 is the return value from the `write()` method, since 116 characters were written to the file. The `traceback` text was written to errorInfo.txt.
|
|
||||||
|
|
||||||
Traceback (most recent call last):
|
|
||||||
File "<pyshell#28>", line 2, in <module>
|
|
||||||
Exception: This is the error message.
|
|
||||||
|
|
||||||
## Assertions
|
|
||||||
|
|
||||||
An assertion is a sanity check to make sure your code isn’t doing something obviously wrong. These sanity checks are performed by `assert` statements. If the sanity check fails, then an `AssertionError` exception is raised. In code, an `assert` statement consists of the following:
|
|
||||||
|
|
||||||
- The `assert` keyword
|
|
||||||
- A condition (that is, an expression that evaluates to `True` or `False`)
|
|
||||||
- A comma
|
|
||||||
- A `string` to display when the condition is `False`
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> pod_bay_door_status = 'open'
|
|
||||||
>>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be "open".'
|
|
||||||
|
|
||||||
>>> pod_bay_door_status = 'I\'m sorry, Dave. I\'m afraid I can\'t do that.'
|
|
||||||
>>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be "open".'
|
|
||||||
# Traceback (most recent call last):
|
|
||||||
# File "<pyshell#10>", line 1, in <module>
|
|
||||||
# assert pod_bay_door_status == 'open', 'The pod bay doors need to be "open".'
|
|
||||||
# AssertionError: The pod bay doors need to be "open".
|
|
||||||
```
|
|
||||||
|
|
||||||
In plain English, an assert statement says, “I assert that this condition holds true, and if not, there is a bug somewhere in the program.” Unlike exceptions, your code should not handle assert statements with try and except; if an assert fails, your program should crash. By failing fast like this, you shorten the time between the original cause of the bug and when you first notice the bug. This will reduce the amount of code you will have to check before finding the code that’s causing the bug.
|
|
||||||
|
|
||||||
### Disabling Assertions
|
|
||||||
|
|
||||||
Assertions can be disabled by passing the `-O` option when running Python.
|
|
||||||
|
|
||||||
## Logging
|
|
||||||
|
|
||||||
To enable the `logging` module to display log messages on your screen as your program runs, copy the following to the top of your program:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import logging
|
|
||||||
>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')
|
|
||||||
```
|
|
||||||
|
|
||||||
Say you wrote a function to calculate the factorial of a number. In mathematics, factorial 4 is 1 × 2 × 3 × 4, or 24. Factorial 7 is 1 × 2 × 3 × 4 × 5 × 6 × 7, or 5,040. Open a new file editor window and enter the following code. It has a bug in it, but you will also enter several log messages to help yourself figure out what is going wrong. Save the program as factorialLog.py.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import logging
|
|
||||||
>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')
|
|
||||||
>>> logging.debug('Start of program')
|
|
||||||
|
|
||||||
>>> def factorial(n):
|
|
||||||
... logging.debug('Start of factorial(%s)' % (n))
|
|
||||||
... total = 1
|
|
||||||
... for i in range(1, n + 1):
|
|
||||||
... total *= i
|
|
||||||
... logging.debug('i is ' + str(i) + ', total is ' + str(total))
|
|
||||||
... logging.debug('End of factorial(%s)' % (n))
|
|
||||||
... return total
|
|
||||||
...
|
|
||||||
>>> print(factorial(5))
|
|
||||||
>>> logging.debug('End of program')
|
|
||||||
# 2015-05-23 16:20:12,664 - DEBUG - Start of program
|
|
||||||
# 2015-05-23 16:20:12,664 - DEBUG - Start of factorial(5)
|
|
||||||
# 2015-05-23 16:20:12,665 - DEBUG - i is 0, total is 0
|
|
||||||
# 2015-05-23 16:20:12,668 - DEBUG - i is 1, total is 0
|
|
||||||
# 2015-05-23 16:20:12,670 - DEBUG - i is 2, total is 0
|
|
||||||
# 2015-05-23 16:20:12,673 - DEBUG - i is 3, total is 0
|
|
||||||
# 2015-05-23 16:20:12,675 - DEBUG - i is 4, total is 0
|
|
||||||
# 2015-05-23 16:20:12,678 - DEBUG - i is 5, total is 0
|
|
||||||
# 2015-05-23 16:20:12,680 - DEBUG - End of factorial(5)
|
|
||||||
# 0
|
|
||||||
# 2015-05-23 16:20:12,684 - DEBUG - End of program
|
|
||||||
```
|
|
||||||
|
|
||||||
## Logging Levels
|
|
||||||
|
|
||||||
Logging levels provide a way to categorize your log messages by importance. There are five logging levels, described in Table 10-1 from least to most important. Messages can be logged at each level using a different logging function.
|
|
||||||
|
|
||||||
| Level | Logging Function | Description |
|
|
||||||
| ---------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
||||||
| `DEBUG` | `logging.debug()` | The lowest level. Used for small details. Usually you care about these messages only when diagnosing problems. |
|
|
||||||
| `INFO` | `logging.info()` | Used to record information on general events in your program or confirm that things are working at their point in the program. |
|
|
||||||
| `WARNING` | `logging.warning()` | Used to indicate a potential problem that doesn’t prevent the program from working but might do so in the future. |
|
|
||||||
| `ERROR` | `logging.error()` | Used to record an error that caused the program to fail to do something. |
|
|
||||||
| `CRITICAL` | `logging.critical()` | The highest level. Used to indicate a fatal error that has caused or is about to cause the program to stop running entirely. |
|
|
||||||
|
|
||||||
## Disabling Logging
|
|
||||||
|
|
||||||
After you’ve debugged your program, you probably don’t want all these log messages cluttering the screen. The logging.disable() function disables these so that you don’t have to go into your program and remove all the logging calls by hand.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import logging
|
|
||||||
|
|
||||||
>>> logging.basicConfig(level=logging.INFO, format=' %(asctime)s -%(levelname)s - %(message)s')
|
|
||||||
>>> logging.critical('Critical error! Critical error!')
|
|
||||||
# 2015-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!
|
|
||||||
|
|
||||||
>>> logging.disable(logging.CRITICAL)
|
|
||||||
>>> logging.critical('Critical error! Critical error!')
|
|
||||||
>>> logging.error('Error! Error!')
|
|
||||||
```
|
|
||||||
|
|
||||||
## Logging to a File
|
|
||||||
|
|
||||||
Instead of displaying the log messages to the screen, you can write them to a text file. The `logging.basicConfig()` function takes a filename keyword argument, like so:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import logging
|
|
||||||
>>> logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
||||||
```
|
|
||||||
@ -1,188 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Decorators - Python Cheatsheet
|
|
||||||
description: A Python Decorator is a syntax that provide a concise and reusable way for extending a function or a class.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Decorators
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
A Python Decorator provides a concise and reusable way for extending
|
|
||||||
a function or a class.
|
|
||||||
|
|
||||||
## Bare bone decorator
|
|
||||||
|
|
||||||
A decorator in its simplest form is a function that takes another
|
|
||||||
function as an argument and returns a wrapper. The following example
|
|
||||||
shows the creation of a decorator and its usage.
|
|
||||||
|
|
||||||
```python
|
|
||||||
def your_decorator(func):
|
|
||||||
def wrapper():
|
|
||||||
# Do stuff before func...
|
|
||||||
print("Before func!")
|
|
||||||
func()
|
|
||||||
# Do stuff after func...
|
|
||||||
print("After func!")
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
@your_decorator
|
|
||||||
def foo():
|
|
||||||
print("Hello World!")
|
|
||||||
|
|
||||||
foo()
|
|
||||||
# Before func!
|
|
||||||
# Hello World!
|
|
||||||
# After func!
|
|
||||||
```
|
|
||||||
|
|
||||||
## Decorator for a function with parameters
|
|
||||||
|
|
||||||
```python
|
|
||||||
def your_decorator(func):
|
|
||||||
def wrapper(*args,**kwargs):
|
|
||||||
# Do stuff before func...
|
|
||||||
print("Before func!")
|
|
||||||
func(*args,**kwargs)
|
|
||||||
# Do stuff after func...
|
|
||||||
print("After func!")
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
@your_decorator
|
|
||||||
def foo(bar):
|
|
||||||
print("My name is " + bar)
|
|
||||||
|
|
||||||
foo("Jack")
|
|
||||||
|
|
||||||
# Before func!
|
|
||||||
# My name is Jack
|
|
||||||
# After func!
|
|
||||||
```
|
|
||||||
|
|
||||||
## Template for a basic decorator
|
|
||||||
|
|
||||||
This template is useful for most decorator use-cases. It is valid for functions
|
|
||||||
with or without parameters, and with or without a return value.
|
|
||||||
|
|
||||||
```python
|
|
||||||
import functools
|
|
||||||
|
|
||||||
def your_decorator(func):
|
|
||||||
@functools.wraps(func) # For preserving the metadata of func.
|
|
||||||
def wrapper(*args,**kwargs):
|
|
||||||
# Do stuff before func...
|
|
||||||
result = func(*args,**kwargs)
|
|
||||||
# Do stuff after func..
|
|
||||||
return result
|
|
||||||
return wrapper
|
|
||||||
```
|
|
||||||
|
|
||||||
## Decorator with parameters
|
|
||||||
|
|
||||||
You can also define parameters for the decorator to use.
|
|
||||||
|
|
||||||
```python
|
|
||||||
import functools
|
|
||||||
|
|
||||||
def your_decorator(arg):
|
|
||||||
def decorator(func):
|
|
||||||
@functools.wraps(func) # For preserving the metadata of func.
|
|
||||||
def wrapper(*args,**kwargs):
|
|
||||||
# Do stuff before func possibly using arg...
|
|
||||||
result = func(*args,**kwargs)
|
|
||||||
# Do stuff after func possibly using arg...
|
|
||||||
return result
|
|
||||||
return wrapper
|
|
||||||
return decorator
|
|
||||||
```
|
|
||||||
|
|
||||||
To use this decorator:
|
|
||||||
|
|
||||||
```python
|
|
||||||
@your_decorator(arg = 'x')
|
|
||||||
def foo(bar):
|
|
||||||
return bar
|
|
||||||
```
|
|
||||||
|
|
||||||
## Class based decorators
|
|
||||||
|
|
||||||
To decorate a class method, you must define the decorator within the class. When
|
|
||||||
only the implicit argument `self` is passed to the method, without any explicit
|
|
||||||
additional arguments, you must make a separate decorator for only those methods
|
|
||||||
without any additional arguments. An example of this, shown below, is when you
|
|
||||||
want to catch and print exceptions in a certain way.
|
|
||||||
|
|
||||||
```python
|
|
||||||
class DecorateMyMethod:
|
|
||||||
|
|
||||||
def decorator_for_class_method_with_no_args(method):
|
|
||||||
def wrapper_for_class_method(self)
|
|
||||||
try:
|
|
||||||
return method(self)
|
|
||||||
except Exception as e:
|
|
||||||
print("\nWARNING: Please make note of the following:\n")
|
|
||||||
print(e)
|
|
||||||
return wrapper_for_class_method
|
|
||||||
|
|
||||||
def __init__(self,succeed:bool):
|
|
||||||
self.succeed = succeed
|
|
||||||
|
|
||||||
@decorator_for_class_method_with_no_args
|
|
||||||
def class_action(self):
|
|
||||||
if self.succeed:
|
|
||||||
print("You succeeded by choice.")
|
|
||||||
else:
|
|
||||||
raise Exception("Epic fail of your own creation.")
|
|
||||||
|
|
||||||
test_succeed = DecorateMyMethods(True)
|
|
||||||
test_succeed.class_action()
|
|
||||||
# You succeeded by choice.
|
|
||||||
|
|
||||||
test_fail = DecorateMyMethod(False)
|
|
||||||
test_fail.class_action()
|
|
||||||
# Exception: Epic fail of your own creation.
|
|
||||||
```
|
|
||||||
|
|
||||||
A decorator can also be defined as a class instead of a method. This is useful
|
|
||||||
for maintaining and updating a state, such as in the following example, where we
|
|
||||||
count the number of calls made to a method:
|
|
||||||
|
|
||||||
```python
|
|
||||||
class CountCallNumber:
|
|
||||||
|
|
||||||
def __init__(self, func):
|
|
||||||
self.func = func
|
|
||||||
self.call_number = 0
|
|
||||||
|
|
||||||
def __call__(self, *args, **kwargs):
|
|
||||||
self.call_number += 1
|
|
||||||
print("This is execution number " + str(self.call_number))
|
|
||||||
return self.func(*args, **kwargs)
|
|
||||||
|
|
||||||
@CountCallNumber
|
|
||||||
def say_hi(name):
|
|
||||||
print("Hi! My name is " + name)
|
|
||||||
|
|
||||||
say_hi("Jack")
|
|
||||||
# This is execution number 1
|
|
||||||
# Hi! My name is Jack
|
|
||||||
|
|
||||||
say_hi("James")
|
|
||||||
# This is execution number 2
|
|
||||||
# Hi! My name is James
|
|
||||||
```
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
Count Example
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
This count example is inspired by Patrick Loeber's <a href="https://youtu.be/HGOBQPFzWKo?si=IUvFzeQbzTmeEgKV" target="_blank">YouTube tutorial</a>.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -1,269 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Dictionaries - Python Cheatsheet
|
|
||||||
description: In Python, a dictionary is an insertion-ordered (from Python > 3.7) collection of key, value pairs.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Dictionaries
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
In Python, a dictionary is an _ordered_ (from Python > 3.7) collection of `key`: `value` pairs.
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
From the Python 3 <a target="_blank" href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries">documentation</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with <code>del</code>.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
Example Dictionary:
|
|
||||||
|
|
||||||
```python
|
|
||||||
my_cat = {
|
|
||||||
'size': 'fat',
|
|
||||||
'color': 'gray',
|
|
||||||
'disposition': 'loud'
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Set key, value using subscript operator `[]`
|
|
||||||
```python
|
|
||||||
>>> my_cat = {
|
|
||||||
... 'size': 'fat',
|
|
||||||
... 'color': 'gray',
|
|
||||||
... 'disposition': 'loud',
|
|
||||||
... }
|
|
||||||
>>> my_cat['age_years'] = 2
|
|
||||||
>>> print(my_cat)
|
|
||||||
...
|
|
||||||
# {'size': 'fat', 'color': 'gray', 'disposition': 'loud', 'age_years': 2}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Get value using subscript operator `[]`
|
|
||||||
|
|
||||||
In case the key is not present in dictionary <a target="_blank" href="https://docs.python.org/3/library/exceptions.html#KeyError">`KeyError`</a> is raised.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> my_cat = {
|
|
||||||
... 'size': 'fat',
|
|
||||||
... 'color': 'gray',
|
|
||||||
... 'disposition': 'loud',
|
|
||||||
... }
|
|
||||||
>>> print(my_cat['size'])
|
|
||||||
...
|
|
||||||
# fat
|
|
||||||
>>> print(my_cat['eye_color'])
|
|
||||||
# Traceback (most recent call last):
|
|
||||||
# File "<stdin>", line 1, in <module>
|
|
||||||
# KeyError: 'eye_color'
|
|
||||||
```
|
|
||||||
|
|
||||||
## values()
|
|
||||||
|
|
||||||
The `values()` method gets the **values** of the dictionary:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> pet = {'color': 'red', 'age': 42}
|
|
||||||
>>> for value in pet.values():
|
|
||||||
... print(value)
|
|
||||||
...
|
|
||||||
# red
|
|
||||||
# 42
|
|
||||||
```
|
|
||||||
|
|
||||||
## keys()
|
|
||||||
|
|
||||||
The `keys()` method gets the **keys** of the dictionary:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> pet = {'color': 'red', 'age': 42}
|
|
||||||
>>> for key in pet.keys():
|
|
||||||
... print(key)
|
|
||||||
...
|
|
||||||
# color
|
|
||||||
# age
|
|
||||||
```
|
|
||||||
|
|
||||||
There is no need to use **.keys()** since by default you will loop through keys:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> pet = {'color': 'red', 'age': 42}
|
|
||||||
>>> for key in pet:
|
|
||||||
... print(key)
|
|
||||||
...
|
|
||||||
# color
|
|
||||||
# age
|
|
||||||
```
|
|
||||||
|
|
||||||
## items()
|
|
||||||
|
|
||||||
The `items()` method gets the **items** of a dictionary and returns them as a <router-link to=/cheatsheet/lists-and-tuples#the-tuple-data-type>Tuple</router-link>:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> pet = {'color': 'red', 'age': 42}
|
|
||||||
>>> for item in pet.items():
|
|
||||||
... print(item)
|
|
||||||
...
|
|
||||||
# ('color', 'red')
|
|
||||||
# ('age', 42)
|
|
||||||
```
|
|
||||||
|
|
||||||
Using the `keys()`, `values()`, and `items()` methods, a for loop can iterate over the keys, values, or key-value pairs in a dictionary, respectively.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> pet = {'color': 'red', 'age': 42}
|
|
||||||
>>> for key, value in pet.items():
|
|
||||||
... print(f'Key: {key} Value: {value}')
|
|
||||||
...
|
|
||||||
# Key: color Value: red
|
|
||||||
# Key: age Value: 42
|
|
||||||
```
|
|
||||||
|
|
||||||
## get()
|
|
||||||
|
|
||||||
The `get()` method returns the value of an item with the given key. If the key doesn't exist, it returns `None`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> wife = {'name': 'Rose', 'age': 33}
|
|
||||||
|
|
||||||
>>> f'My wife name is {wife.get("name")}'
|
|
||||||
# 'My wife name is Rose'
|
|
||||||
|
|
||||||
>>> f'She is {wife.get("age")} years old.'
|
|
||||||
# 'She is 33 years old.'
|
|
||||||
|
|
||||||
>>> f'She is deeply in love with {wife.get("husband")}'
|
|
||||||
# 'She is deeply in love with None'
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also change the default `None` value to one of your choice:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> wife = {'name': 'Rose', 'age': 33}
|
|
||||||
|
|
||||||
>>> f'She is deeply in love with {wife.get("husband", "lover")}'
|
|
||||||
# 'She is deeply in love with lover'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Adding items with setdefault()
|
|
||||||
|
|
||||||
It's possible to add an item to a dictionary in this way:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> wife = {'name': 'Rose', 'age': 33}
|
|
||||||
>>> if 'has_hair' not in wife:
|
|
||||||
... wife['has_hair'] = True
|
|
||||||
```
|
|
||||||
|
|
||||||
Using the `setdefault` method, we can make the same code more short:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> wife = {'name': 'Rose', 'age': 33}
|
|
||||||
>>> wife.setdefault('has_hair', True)
|
|
||||||
>>> wife
|
|
||||||
# {'name': 'Rose', 'age': 33, 'has_hair': True}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Removing Items
|
|
||||||
|
|
||||||
### pop()
|
|
||||||
|
|
||||||
The `pop()` method removes and returns an item based on a given key.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
|
|
||||||
>>> wife.pop('age')
|
|
||||||
# 33
|
|
||||||
>>> wife
|
|
||||||
# {'name': 'Rose', 'hair': 'brown'}
|
|
||||||
```
|
|
||||||
|
|
||||||
### popitem()
|
|
||||||
|
|
||||||
The `popitem()` method removes the last item in a dictionary and returns it.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
|
|
||||||
>>> wife.popitem()
|
|
||||||
# ('hair', 'brown')
|
|
||||||
>>> wife
|
|
||||||
# {'name': 'Rose', 'age': 33}
|
|
||||||
```
|
|
||||||
|
|
||||||
### del()
|
|
||||||
|
|
||||||
The `del()` method removes an item based on a given key.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
|
|
||||||
>>> del wife['age']
|
|
||||||
>>> wife
|
|
||||||
# {'name': 'Rose', 'hair': 'brown'}
|
|
||||||
```
|
|
||||||
|
|
||||||
### clear()
|
|
||||||
|
|
||||||
The`clear()` method removes all the items in a dictionary.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
|
|
||||||
>>> wife.clear()
|
|
||||||
>>> wife
|
|
||||||
# {}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Checking keys in a Dictionary
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> person = {'name': 'Rose', 'age': 33}
|
|
||||||
|
|
||||||
>>> 'name' in person.keys()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'height' in person.keys()
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> 'skin' in person # You can omit keys()
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
## Checking values in a Dictionary
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> person = {'name': 'Rose', 'age': 33}
|
|
||||||
|
|
||||||
>>> 'Rose' in person.values()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 33 in person.values()
|
|
||||||
# True
|
|
||||||
```
|
|
||||||
|
|
||||||
## Pretty Printing
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import pprint
|
|
||||||
|
|
||||||
>>> wife = {'name': 'Rose', 'age': 33, 'has_hair': True, 'hair_color': 'brown', 'height': 1.6, 'eye_color': 'brown'}
|
|
||||||
>>> pprint.pprint(wife)
|
|
||||||
# {'age': 33,
|
|
||||||
# 'eye_color': 'brown',
|
|
||||||
# 'hair_color': 'brown',
|
|
||||||
# 'has_hair': True,
|
|
||||||
# 'height': 1.6,
|
|
||||||
# 'name': 'Rose'}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Merge two dictionaries
|
|
||||||
|
|
||||||
For Python 3.5+:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> dict_a = {'a': 1, 'b': 2}
|
|
||||||
>>> dict_b = {'b': 3, 'c': 4}
|
|
||||||
>>> dict_c = {**dict_a, **dict_b}
|
|
||||||
>>> dict_c
|
|
||||||
# {'a': 1, 'b': 3, 'c': 4}
|
|
||||||
```
|
|
||||||
@ -1,136 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Exception Handling - Python Cheatsheet
|
|
||||||
description: In Python, exception handling is the process of responding to the occurrence of exceptions.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Exception Handling
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
<a target="_blank" href="https://en.wikipedia.org/wiki/Exception_handling">Exception handling</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
In computing and computer programming, exception handling is the process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
Python has many [built-in exceptions](https://docs.python.org/3/library/exceptions.html) that are raised when a program encounters an error, and most external libraries, like the popular [Requests](https://requests.readthedocs.io/en/latest), include his own [custom exceptions](https://requests.readthedocs.io/en/latest/user/quickstart/#errors-and-exceptions) that we will need to deal to.
|
|
||||||
|
|
||||||
## Basic exception handling
|
|
||||||
|
|
||||||
You can't divide by zero, that is a mathematical true, and if you try to do it in Python, the interpreter will raise the built-in exception [ZeroDivisionError](https://docs.python.org/3/library/exceptions.html#ZeroDivisionError):
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def divide(dividend , divisor):
|
|
||||||
... print(dividend / divisor)
|
|
||||||
...
|
|
||||||
>>> divide(dividend=10, divisor=5)
|
|
||||||
# 2
|
|
||||||
|
|
||||||
>>> divide(dividend=10, divisor=0)
|
|
||||||
# Traceback (most recent call last):
|
|
||||||
# File "<stdin>", line 1, in <module>
|
|
||||||
# ZeroDivisionError: division by zero
|
|
||||||
```
|
|
||||||
|
|
||||||
Let's say we don't want our program to stop its execution or show the user an output he will not understand. Say we want to print a useful and clear message, then we need to **_handle_** the exception with the `try` and `except` keywords:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def divide(dividend , divisor):
|
|
||||||
... try:
|
|
||||||
... print(dividend / divisor)
|
|
||||||
... except ZeroDivisionError:
|
|
||||||
... print('You can not divide by 0')
|
|
||||||
...
|
|
||||||
>>> divide(dividend=10, divisor=5)
|
|
||||||
# 2
|
|
||||||
|
|
||||||
>>> divide(dividend=10, divisor=0)
|
|
||||||
# You can not divide by 0
|
|
||||||
```
|
|
||||||
|
|
||||||
## Handling Multiple exceptions using one exception block
|
|
||||||
|
|
||||||
You can also handle multiple exceptions in one line like the following without the need to create multiple exception blocks.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def divide(dividend , divisor):
|
|
||||||
... try:
|
|
||||||
... if (dividend == 10):
|
|
||||||
... var = 'str' + 1
|
|
||||||
... else:
|
|
||||||
... print(dividend / divisor)
|
|
||||||
... except (ZeroDivisionError, TypeError) as error:
|
|
||||||
... print(error)
|
|
||||||
...
|
|
||||||
|
|
||||||
>>> divide(dividend=20, divisor=5)
|
|
||||||
# 4
|
|
||||||
|
|
||||||
>>> divide(dividend=10, divisor=5)
|
|
||||||
# `can only concatenate str (not "int") to str` Error message
|
|
||||||
|
|
||||||
>>> divide(dividend=10, divisor=0)
|
|
||||||
# `division by zero` Error message
|
|
||||||
```
|
|
||||||
|
|
||||||
## Finally code in exception handling
|
|
||||||
|
|
||||||
The code inside the `finally` section is always executed, no matter if an exception has been raised or not:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def divide(dividend , divisor):
|
|
||||||
... try:
|
|
||||||
... print(dividend / divisor)
|
|
||||||
... except ZeroDivisionError:
|
|
||||||
... print('You can not divide by 0')
|
|
||||||
... finally:
|
|
||||||
... print('Execution finished')
|
|
||||||
...
|
|
||||||
>>> divide(dividend=10, divisor=5)
|
|
||||||
# 5
|
|
||||||
# Execution finished
|
|
||||||
|
|
||||||
>>> divide(dividend=10, divisor=0)
|
|
||||||
# You can not divide by 0
|
|
||||||
# Execution finished
|
|
||||||
```
|
|
||||||
|
|
||||||
## Custom Exceptions
|
|
||||||
|
|
||||||
Custom exceptions initialize by creating a `class` that inherits from the base `Exception` class of Python, and are raised using the `raise` keyword:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> class MyCustomException(Exception):
|
|
||||||
... pass
|
|
||||||
...
|
|
||||||
>>> raise MyCustomException
|
|
||||||
# Traceback (most recent call last):
|
|
||||||
# File "<stdin>", line 1, in <module>
|
|
||||||
# __main__.MyCustomException
|
|
||||||
```
|
|
||||||
|
|
||||||
To declare a custom exception message, you can pass it as a parameter:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> class MyCustomException(Exception):
|
|
||||||
... pass
|
|
||||||
...
|
|
||||||
>>> raise MyCustomException('A custom message for my custom exception')
|
|
||||||
# Traceback (most recent call last):
|
|
||||||
# File "<stdin>", line 1, in <module>
|
|
||||||
# __main__.MyCustomException: A custom message for my custom exception
|
|
||||||
```
|
|
||||||
|
|
||||||
Handling a custom exception is the same as any other:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> try:
|
|
||||||
... raise MyCustomException('A custom message for my custom exception')
|
|
||||||
>>> except MyCustomException:
|
|
||||||
... print('My custom exception was raised')
|
|
||||||
...
|
|
||||||
# My custom exception was raised
|
|
||||||
```
|
|
||||||
@ -1,529 +0,0 @@
|
|||||||
---
|
|
||||||
title: File and directory Paths - Python Cheatsheet
|
|
||||||
description: There are two main modules in Python that deals with path manipulation. One is the os.path module and the other is the pathlib module.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Handling file and directory Paths
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
There are two main modules in Python that deal with path manipulation.
|
|
||||||
One is the `os.path` module and the other is the `pathlib` module.
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
os.path VS pathlib
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
The `pathlib` module was added in Python 3.4, offering an object-oriented way to handle file system paths.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
## Linux and Windows Paths
|
|
||||||
|
|
||||||
On Windows, paths are written using backslashes (`\`) as the separator between
|
|
||||||
folder names. On Unix based operating system such as macOS, Linux, and BSDs,
|
|
||||||
the forward slash (`/`) is used as the path separator. Joining paths can be
|
|
||||||
a headache if your code needs to work on different platforms.
|
|
||||||
|
|
||||||
Fortunately, Python provides easy ways to handle this. We will showcase
|
|
||||||
how to deal with both, `os.path.join` and `pathlib.Path.joinpath`
|
|
||||||
|
|
||||||
Using `os.path.join` on Windows:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
|
|
||||||
>>> os.path.join('usr', 'bin', 'spam')
|
|
||||||
# 'usr\\bin\\spam'
|
|
||||||
```
|
|
||||||
|
|
||||||
And using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
|
|
||||||
>>> print(Path('usr').joinpath('bin').joinpath('spam'))
|
|
||||||
# usr/bin/spam
|
|
||||||
```
|
|
||||||
|
|
||||||
`pathlib` also provides a shortcut to joinpath using the `/` operator:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
|
|
||||||
>>> print(Path('usr') / 'bin' / 'spam')
|
|
||||||
# usr/bin/spam
|
|
||||||
```
|
|
||||||
|
|
||||||
Notice the path separator is different between Windows and Unix based operating
|
|
||||||
system, that's why you want to use one of the above methods instead of
|
|
||||||
adding strings together to join paths together.
|
|
||||||
|
|
||||||
Joining paths is helpful if you need to create different file paths under
|
|
||||||
the same directory.
|
|
||||||
|
|
||||||
Using `os.path.join` on Windows:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']
|
|
||||||
|
|
||||||
>>> for filename in my_files:
|
|
||||||
... print(os.path.join('C:\\Users\\asweigart', filename))
|
|
||||||
...
|
|
||||||
# C:\Users\asweigart\accounts.txt
|
|
||||||
# C:\Users\asweigart\details.csv
|
|
||||||
# C:\Users\asweigart\invite.docx
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']
|
|
||||||
>>> home = Path.home()
|
|
||||||
>>> for filename in my_files:
|
|
||||||
... print(home / filename)
|
|
||||||
...
|
|
||||||
# /home/asweigart/accounts.txt
|
|
||||||
# /home/asweigart/details.csv
|
|
||||||
# /home/asweigart/invite.docx
|
|
||||||
```
|
|
||||||
|
|
||||||
## The current working directory
|
|
||||||
|
|
||||||
Using `os` on Windows:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
|
|
||||||
>>> os.getcwd()
|
|
||||||
# 'C:\\Python34'
|
|
||||||
>>> os.chdir('C:\\Windows\\System32')
|
|
||||||
|
|
||||||
>>> os.getcwd()
|
|
||||||
# 'C:\\Windows\\System32'
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
>>> from os import chdir
|
|
||||||
|
|
||||||
>>> print(Path.cwd())
|
|
||||||
# /home/asweigart
|
|
||||||
|
|
||||||
>>> chdir('/usr/lib/python3.6')
|
|
||||||
>>> print(Path.cwd())
|
|
||||||
# /usr/lib/python3.6
|
|
||||||
```
|
|
||||||
|
|
||||||
## Creating new folders
|
|
||||||
|
|
||||||
Using `os` on Windows:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
>>> cwd = Path.cwd()
|
|
||||||
>>> (cwd / 'delicious' / 'walnut' / 'waffles').mkdir()
|
|
||||||
# Traceback (most recent call last):
|
|
||||||
# File "<stdin>", line 1, in <module>
|
|
||||||
# File "/usr/lib/python3.6/pathlib.py", line 1226, in mkdir
|
|
||||||
# self._accessor.mkdir(self, mode)
|
|
||||||
# File "/usr/lib/python3.6/pathlib.py", line 387, in wrapped
|
|
||||||
# return strfunc(str(pathobj), *args)
|
|
||||||
# FileNotFoundError: [Errno 2] No such file or directory: '/home/asweigart/delicious/walnut/waffles'
|
|
||||||
```
|
|
||||||
|
|
||||||
Oh no, we got a nasty error! The reason is that the 'delicious' directory does
|
|
||||||
not exist, so we cannot make the 'walnut' and the 'waffles' directories under
|
|
||||||
it. To fix this, do:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
>>> cwd = Path.cwd()
|
|
||||||
>>> (cwd / 'delicious' / 'walnut' / 'waffles').mkdir(parents=True)
|
|
||||||
```
|
|
||||||
|
|
||||||
And all is good :)
|
|
||||||
|
|
||||||
## Absolute vs. Relative paths
|
|
||||||
|
|
||||||
There are two ways to specify a file path.
|
|
||||||
|
|
||||||
- An **absolute path**, which always begins with the root folder
|
|
||||||
- A **relative path**, which is relative to the program’s current working directory
|
|
||||||
|
|
||||||
There are also the dot (`.`) and dot-dot (`..`) folders. These are not real folders, but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot-dot”) means “the parent folder.”
|
|
||||||
|
|
||||||
### Handling Absolute paths
|
|
||||||
|
|
||||||
To see if a path is an absolute path:
|
|
||||||
|
|
||||||
Using `os.path` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
>>> os.path.isabs('/')
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> os.path.isabs('..')
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
>>> Path('/').is_absolute()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> Path('..').is_absolute()
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
You can extract an absolute path with both `os.path` and `pathlib`
|
|
||||||
|
|
||||||
Using `os.path` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
>>> os.getcwd()
|
|
||||||
'/home/asweigart'
|
|
||||||
|
|
||||||
>>> os.path.abspath('..')
|
|
||||||
'/home'
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
from pathlib import Path
|
|
||||||
print(Path.cwd())
|
|
||||||
# /home/asweigart
|
|
||||||
|
|
||||||
print(Path('..').resolve())
|
|
||||||
# /home
|
|
||||||
```
|
|
||||||
|
|
||||||
### Handling Relative paths
|
|
||||||
|
|
||||||
You can get a relative path from a starting path to another path.
|
|
||||||
|
|
||||||
Using `os.path` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
>>> os.path.relpath('/etc/passwd', '/')
|
|
||||||
# 'etc/passwd'
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
>>> print(Path('/etc/passwd').relative_to('/'))
|
|
||||||
# etc/passwd
|
|
||||||
```
|
|
||||||
|
|
||||||
## Path and File validity
|
|
||||||
|
|
||||||
### Checking if a file/directory exists
|
|
||||||
|
|
||||||
Using `os.path` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
|
|
||||||
>>> os.path.exists('.')
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> os.path.exists('setup.py')
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> os.path.exists('/etc')
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> os.path.exists('nonexistentfile')
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
>>> Path('.').exists()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> Path('setup.py').exists()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> Path('/etc').exists()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> Path('nonexistentfile').exists()
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
### Checking if a path is a file
|
|
||||||
|
|
||||||
Using `os.path` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
|
|
||||||
>>> os.path.isfile('setup.py')
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> os.path.isfile('/home')
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> os.path.isfile('nonexistentfile')
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
|
|
||||||
>>> Path('setup.py').is_file()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> Path('/home').is_file()
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> Path('nonexistentfile').is_file()
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
### Checking if a path is a directory
|
|
||||||
|
|
||||||
Using `os.path` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
|
|
||||||
>>> os.path.isdir('/')
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> os.path.isdir('setup.py')
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> os.path.isdir('/spam')
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
|
|
||||||
>>> Path('/').is_dir()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> Path('setup.py').is_dir()
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> Path('/spam').is_dir()
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
## Getting a file's size in bytes
|
|
||||||
|
|
||||||
Using `os.path` on Windows:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
|
|
||||||
>>> os.path.getsize('C:\\Windows\\System32\\calc.exe')
|
|
||||||
# 776192
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
|
|
||||||
>>> stat = Path('/bin/python3.6').stat()
|
|
||||||
>>> print(stat) # stat contains some other information about the file as well
|
|
||||||
# os.stat_result(st_mode=33261, st_ino=141087, st_dev=2051, st_nlink=2, st_uid=0,
|
|
||||||
# --snip--
|
|
||||||
# st_gid=0, st_size=10024, st_atime=1517725562, st_mtime=1515119809, st_ctime=1517261276)
|
|
||||||
|
|
||||||
>>> print(stat.st_size) # size in bytes
|
|
||||||
# 10024
|
|
||||||
```
|
|
||||||
|
|
||||||
## Listing directories
|
|
||||||
|
|
||||||
Listing directory contents using `os.listdir` on Windows:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
|
|
||||||
>>> os.listdir('C:\\Windows\\System32')
|
|
||||||
# ['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',
|
|
||||||
# --snip--
|
|
||||||
# 'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']
|
|
||||||
```
|
|
||||||
|
|
||||||
Listing directory contents using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
|
|
||||||
>>> for f in Path('/usr/bin').iterdir():
|
|
||||||
... print(f)
|
|
||||||
...
|
|
||||||
# ...
|
|
||||||
# /usr/bin/tiff2rgba
|
|
||||||
# /usr/bin/iconv
|
|
||||||
# /usr/bin/ldd
|
|
||||||
# /usr/bin/cache_restore
|
|
||||||
# /usr/bin/udiskie
|
|
||||||
# /usr/bin/unix2dos
|
|
||||||
# /usr/bin/t1reencode
|
|
||||||
# /usr/bin/epstopdf
|
|
||||||
# /usr/bin/idle3
|
|
||||||
# ...
|
|
||||||
```
|
|
||||||
|
|
||||||
## Directory file sizes
|
|
||||||
|
|
||||||
<base-warning>
|
|
||||||
<base-warning-title>
|
|
||||||
WARNING
|
|
||||||
</base-warning-title>
|
|
||||||
<base-warning-content>
|
|
||||||
Directories themselves also have a size! So, you might want to check for whether a path is a file or directory using the methods in the methods discussed in the above section.
|
|
||||||
</base-warning-content>
|
|
||||||
</base-warning>
|
|
||||||
|
|
||||||
Using `os.path.getsize()` and `os.listdir()` together on Windows:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
>>> total_size = 0
|
|
||||||
|
|
||||||
>>> for filename in os.listdir('C:\\Windows\\System32'):
|
|
||||||
... total_size = total_size + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
|
|
||||||
...
|
|
||||||
>>> print(total_size)
|
|
||||||
# 1117846456
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `pathlib` on \*nix:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from pathlib import Path
|
|
||||||
|
|
||||||
>>> total_size = 0
|
|
||||||
>>> for sub_path in Path('/usr/bin').iterdir():
|
|
||||||
... total_size += sub_path.stat().st_size
|
|
||||||
...
|
|
||||||
>>> print(total_size)
|
|
||||||
# 1903178911
|
|
||||||
```
|
|
||||||
|
|
||||||
## Copying files and folders
|
|
||||||
|
|
||||||
The `shutil` module provides functions for copying files, as well as entire folders.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import shutil, os
|
|
||||||
|
|
||||||
>>> os.chdir('C:\\')
|
|
||||||
>>> shutil.copy('C:\\spam.txt', 'C:\\delicious')
|
|
||||||
# C:\\delicious\\spam.txt'
|
|
||||||
|
|
||||||
>>> shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')
|
|
||||||
# 'C:\\delicious\\eggs2.txt'
|
|
||||||
```
|
|
||||||
|
|
||||||
While `shutil.copy()` will copy a single file, `shutil.copytree()` will copy an entire folder and every folder and file contained in it:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import shutil, os
|
|
||||||
|
|
||||||
>>> os.chdir('C:\\')
|
|
||||||
>>> shutil.copytree('C:\\bacon', 'C:\\bacon_backup')
|
|
||||||
# 'C:\\bacon_backup'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Moving and Renaming
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import shutil
|
|
||||||
|
|
||||||
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
|
|
||||||
# 'C:\\eggs\\bacon.txt'
|
|
||||||
```
|
|
||||||
|
|
||||||
The destination path can also specify a filename. In the following example, the source file is moved and renamed:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs\\new_bacon.txt')
|
|
||||||
# 'C:\\eggs\\new_bacon.txt'
|
|
||||||
```
|
|
||||||
|
|
||||||
If there is no eggs folder, then `move()` will rename bacon.txt to a file named eggs:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
|
|
||||||
# 'C:\\eggs'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Deleting files and folders
|
|
||||||
|
|
||||||
- Calling `os.unlink(path)` or `Path.unlink()` will delete the file at path.
|
|
||||||
|
|
||||||
- Calling `os.rmdir(path)` or `Path.rmdir()` will delete the folder at path. This folder must be empty of any files or folders.
|
|
||||||
|
|
||||||
- Calling `shutil.rmtree(path)` will remove the folder at path, and all files and folders it contains will also be deleted.
|
|
||||||
|
|
||||||
## Walking a Directory Tree
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import os
|
|
||||||
>>>
|
|
||||||
>>> for folder_name, subfolders, filenames in os.walk('C:\\delicious'):
|
|
||||||
... print(f'The current folder is {folder_name}')
|
|
||||||
... for subfolder in subfolders:
|
|
||||||
... print(f'SUBFOLDER OF {folder_name}: {subfolder}')
|
|
||||||
... for filename in filenames:
|
|
||||||
... print(f'FILE INSIDE {folder_name}: {filename}')
|
|
||||||
... print('')
|
|
||||||
...
|
|
||||||
# The current folder is C:\delicious
|
|
||||||
# SUBFOLDER OF C:\delicious: cats
|
|
||||||
# SUBFOLDER OF C:\delicious: walnut
|
|
||||||
# FILE INSIDE C:\delicious: spam.txt
|
|
||||||
|
|
||||||
# The current folder is C:\delicious\cats
|
|
||||||
# FILE INSIDE C:\delicious\cats: catnames.txt
|
|
||||||
# FILE INSIDE C:\delicious\cats: zophie.jpg
|
|
||||||
|
|
||||||
# The current folder is C:\delicious\walnut
|
|
||||||
# SUBFOLDER OF C:\delicious\walnut: waffles
|
|
||||||
|
|
||||||
# The current folder is C:\delicious\walnut\waffles
|
|
||||||
# FILE INSIDE C:\delicious\walnut\waffles: butter.txt
|
|
||||||
```
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
Pathlib vs Os Module
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
`pathlib` provides a lot more functionality than the ones listed above, like getting file name, getting file extension, reading/writing a file without manually opening it, etc. See the <a target="_blank" href="https://docs.python.org/3/library/pathlib.html">official documentation</a> if you intend to know more.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
@ -1,176 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Functions - Python Cheatsheet
|
|
||||||
description: In Python, A function is a block of organized code that is used to perform a single task.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Functions
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
<a target="_blank" href="https://en.wikiversity.org/wiki/Programming_Fundamentals/Functions">Programming Functions</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
A function is a block of organized code that is used to perform a single task. They provide better modularity for your application and reuse-ability.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
## Function Arguments
|
|
||||||
|
|
||||||
A function can take `arguments` and `return values`:
|
|
||||||
|
|
||||||
In the following example, the function **say_hello** receives the argument "name" and prints a greeting:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def say_hello(name):
|
|
||||||
... print(f'Hello {name}')
|
|
||||||
...
|
|
||||||
>>> say_hello('Carlos')
|
|
||||||
# Hello Carlos
|
|
||||||
|
|
||||||
>>> say_hello('Wanda')
|
|
||||||
# Hello Wanda
|
|
||||||
|
|
||||||
>>> say_hello('Rose')
|
|
||||||
# Hello Rose
|
|
||||||
```
|
|
||||||
|
|
||||||
## Keyword Arguments
|
|
||||||
|
|
||||||
To improve code readability, we should be as explicit as possible. We can achieve this in our functions by using `Keyword Arguments`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def say_hi(name, greeting):
|
|
||||||
... print(f"{greeting} {name}")
|
|
||||||
...
|
|
||||||
>>> # without keyword arguments
|
|
||||||
>>> say_hi('John', 'Hello')
|
|
||||||
# Hello John
|
|
||||||
|
|
||||||
>>> # with keyword arguments
|
|
||||||
>>> say_hi(name='Anna', greeting='Hi')
|
|
||||||
# Hi Anna
|
|
||||||
```
|
|
||||||
|
|
||||||
## Return Values
|
|
||||||
|
|
||||||
When creating a function using the `def` statement, you can specify what the return value should be with a `return` statement. A return statement consists of the following:
|
|
||||||
|
|
||||||
- The `return` keyword.
|
|
||||||
|
|
||||||
- The value or expression that the function should return.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def sum_two_numbers(number_1, number_2):
|
|
||||||
... return number_1 + number_2
|
|
||||||
...
|
|
||||||
>>> result = sum_two_numbers(7, 8)
|
|
||||||
>>> print(result)
|
|
||||||
# 15
|
|
||||||
```
|
|
||||||
|
|
||||||
## Local and Global Scope
|
|
||||||
|
|
||||||
- Code in the global scope cannot use any local variables.
|
|
||||||
|
|
||||||
- However, a local scope can access global variables.
|
|
||||||
|
|
||||||
- Code in a function’s local scope cannot use variables in any other local scope.
|
|
||||||
|
|
||||||
- You can use the same name for different variables if they are in different scopes. That is, there can be a local variable named spam and a global variable also named spam.
|
|
||||||
|
|
||||||
```python
|
|
||||||
global_variable = 'I am available everywhere'
|
|
||||||
|
|
||||||
>>> def some_function():
|
|
||||||
... print(global_variable) # because is global
|
|
||||||
... local_variable = "only available within this function"
|
|
||||||
... print(local_variable)
|
|
||||||
...
|
|
||||||
>>> # the following code will throw error because
|
|
||||||
>>> # 'local_variable' only exists inside 'some_function'
|
|
||||||
>>> print(local_variable)
|
|
||||||
Traceback (most recent call last):
|
|
||||||
File "<stdin>", line 10, in <module>
|
|
||||||
NameError: name 'local_variable' is not defined
|
|
||||||
```
|
|
||||||
|
|
||||||
## The global Statement
|
|
||||||
|
|
||||||
If you need to modify a global variable from within a function, use the global statement:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def spam():
|
|
||||||
... global eggs
|
|
||||||
... eggs = 'spam'
|
|
||||||
...
|
|
||||||
>>> eggs = 'global'
|
|
||||||
>>> spam()
|
|
||||||
>>> print(eggs)
|
|
||||||
```
|
|
||||||
|
|
||||||
There are four rules to tell whether a variable is in a local scope or global scope:
|
|
||||||
|
|
||||||
1. If a variable is being used in the global scope (that is, outside all functions), then it is always a global variable.
|
|
||||||
|
|
||||||
1. If there is a global statement for that variable in a function, it is a global variable.
|
|
||||||
|
|
||||||
1. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
|
|
||||||
|
|
||||||
1. But if the variable is not used in an assignment statement, it is a global variable.
|
|
||||||
|
|
||||||
## Lambda Functions
|
|
||||||
|
|
||||||
In Python, a lambda function is a single-line, anonymous function, which can have any number of arguments, but it can only have one expression.
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
From the <a target="_blank" href="https://docs.python.org/3/library/ast.html?highlight=lambda#function-and-class-definitions">Python 3 Tutorial</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
lambda is a minimal function definition that can be used inside an expression. Unlike FunctionDef, body holds a single node.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
<base-warning>
|
|
||||||
<base-warning-title>
|
|
||||||
Single line expression
|
|
||||||
</base-warning-title>
|
|
||||||
<base-warning-content>
|
|
||||||
Lambda functions can only evaluate an expression, like a single line of code.
|
|
||||||
</base-warning-content>
|
|
||||||
</base-warning>
|
|
||||||
|
|
||||||
This function:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def add(x, y):
|
|
||||||
... return x + y
|
|
||||||
...
|
|
||||||
>>> add(5, 3)
|
|
||||||
# 8
|
|
||||||
```
|
|
||||||
|
|
||||||
Is equivalent to the _lambda_ function:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> add = lambda x, y: x + y
|
|
||||||
>>> add(5, 3)
|
|
||||||
# 8
|
|
||||||
```
|
|
||||||
|
|
||||||
Like regular nested functions, lambdas also work as lexical closures:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def make_adder(n):
|
|
||||||
... return lambda x: x + n
|
|
||||||
...
|
|
||||||
>>> plus_3 = make_adder(3)
|
|
||||||
>>> plus_5 = make_adder(5)
|
|
||||||
|
|
||||||
>>> plus_3(4)
|
|
||||||
# 7
|
|
||||||
>>> plus_5(4)
|
|
||||||
# 9
|
|
||||||
```
|
|
||||||
@ -1,69 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Json and YAML - Python Cheatsheet
|
|
||||||
description: JSON stands for JavaScript Object Notation and is a lightweight format for storing and transporting data. Json is often used when data is sent from a server to a web page.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
JSON and YAML
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
## JSON
|
|
||||||
|
|
||||||
JSON stands for JavaScript Object Notation and is a lightweight format for storing and transporting data. Json is often used when data is sent from a server to a web page.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import json
|
|
||||||
>>> with open("filename.json", "r") as f:
|
|
||||||
... content = json.load(f)
|
|
||||||
```
|
|
||||||
|
|
||||||
Write a JSON file with:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import json
|
|
||||||
|
|
||||||
>>> content = {"name": "Joe", "age": 20}
|
|
||||||
>>> with open("filename.json", "w") as f:
|
|
||||||
... json.dump(content, f, indent=2)
|
|
||||||
```
|
|
||||||
|
|
||||||
## YAML
|
|
||||||
|
|
||||||
Compared to JSON, YAML allows a much better human maintainability and gives ability to add comments. It is a convenient choice for configuration files where a human will have to edit.
|
|
||||||
|
|
||||||
There are two main libraries allowing access to YAML files:
|
|
||||||
|
|
||||||
- [PyYaml](https://pypi.python.org/pypi/PyYAML)
|
|
||||||
- [Ruamel.yaml](https://pypi.python.org/pypi/ruamel.yaml)
|
|
||||||
|
|
||||||
Install them using `pip install` in your virtual environment.
|
|
||||||
|
|
||||||
The first one is easier to use but the second one, Ruamel, implements much better the YAML
|
|
||||||
specification, and allow for example to modify a YAML content without altering comments.
|
|
||||||
|
|
||||||
Open a YAML file with:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from ruamel.yaml import YAML
|
|
||||||
|
|
||||||
>>> with open("filename.yaml") as f:
|
|
||||||
... yaml=YAML()
|
|
||||||
... yaml.load(f)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Anyconfig
|
|
||||||
|
|
||||||
[Anyconfig](https://pypi.python.org/pypi/anyconfig) is a very handy package, allowing to abstract completely the underlying configuration file format. It allows to load a Python dictionary from JSON, YAML, TOML, and so on.
|
|
||||||
|
|
||||||
Install it with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pip install anyconfig
|
|
||||||
```
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import anyconfig
|
|
||||||
>>> conf1 = anyconfig.load("/path/to/foo/conf.d/a.yml")
|
|
||||||
```
|
|
||||||
@ -1,394 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Lists and Tuples - Python Cheatsheet
|
|
||||||
description: In python, Lists are are one of the 4 data types in Python used to store collections of data.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Lists
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
Lists are one of the 4 data types in Python used to store collections of data.
|
|
||||||
|
|
||||||
```python
|
|
||||||
['John', 'Peter', 'Debora', 'Charles']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Getting values with indexes
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
|
|
||||||
>>> furniture[0]
|
|
||||||
# 'table'
|
|
||||||
|
|
||||||
>>> furniture[1]
|
|
||||||
# 'chair'
|
|
||||||
|
|
||||||
>>> furniture[2]
|
|
||||||
# 'rack'
|
|
||||||
|
|
||||||
>>> furniture[3]
|
|
||||||
# 'shelf'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Negative indexes
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
|
|
||||||
>>> furniture[-1]
|
|
||||||
# 'shelf'
|
|
||||||
|
|
||||||
>>> furniture[-3]
|
|
||||||
# 'chair'
|
|
||||||
|
|
||||||
>>> f'The {furniture[-1]} is bigger than the {furniture[-3]}'
|
|
||||||
# 'The shelf is bigger than the chair'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Getting sublists with Slices
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
|
|
||||||
>>> furniture[0:4]
|
|
||||||
# ['table', 'chair', 'rack', 'shelf']
|
|
||||||
|
|
||||||
>>> furniture[1:3]
|
|
||||||
# ['chair', 'rack']
|
|
||||||
|
|
||||||
>>> furniture[0:-1]
|
|
||||||
# ['table', 'chair', 'rack']
|
|
||||||
|
|
||||||
>>> furniture[:2]
|
|
||||||
# ['table', 'chair']
|
|
||||||
|
|
||||||
>>> furniture[1:]
|
|
||||||
# ['chair', 'rack', 'shelf']
|
|
||||||
|
|
||||||
>>> furniture[:]
|
|
||||||
# ['table', 'chair', 'rack', 'shelf']
|
|
||||||
```
|
|
||||||
|
|
||||||
Slicing the complete list will perform a copy:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> spam2 = spam[:]
|
|
||||||
# ['cat', 'bat', 'rat', 'elephant']
|
|
||||||
|
|
||||||
>>> spam.append('dog')
|
|
||||||
>>> spam
|
|
||||||
# ['cat', 'bat', 'rat', 'elephant', 'dog']
|
|
||||||
|
|
||||||
>>> spam2
|
|
||||||
# ['cat', 'bat', 'rat', 'elephant']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Getting a list length with len()
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> len(furniture)
|
|
||||||
# 4
|
|
||||||
```
|
|
||||||
|
|
||||||
## Changing values with indexes
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
|
|
||||||
>>> furniture[0] = 'desk'
|
|
||||||
>>> furniture
|
|
||||||
# ['desk', 'chair', 'rack', 'shelf']
|
|
||||||
|
|
||||||
>>> furniture[2] = furniture[1]
|
|
||||||
>>> furniture
|
|
||||||
# ['desk', 'chair', 'chair', 'shelf']
|
|
||||||
|
|
||||||
>>> furniture[-1] = 'bed'
|
|
||||||
>>> furniture
|
|
||||||
# ['desk', 'chair', 'chair', 'bed']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Concatenation and Replication
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> [1, 2, 3] + ['A', 'B', 'C']
|
|
||||||
# [1, 2, 3, 'A', 'B', 'C']
|
|
||||||
|
|
||||||
>>> ['X', 'Y', 'Z'] * 3
|
|
||||||
# ['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
|
|
||||||
|
|
||||||
>>> my_list = [1, 2, 3]
|
|
||||||
>>> my_list = my_list + ['A', 'B', 'C']
|
|
||||||
>>> my_list
|
|
||||||
# [1, 2, 3, 'A', 'B', 'C']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Using for loops with Lists
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
|
|
||||||
>>> for item in furniture:
|
|
||||||
... print(item)
|
|
||||||
# table
|
|
||||||
# chair
|
|
||||||
# rack
|
|
||||||
# shelf
|
|
||||||
```
|
|
||||||
|
|
||||||
## Getting the index in a loop with enumerate()
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
|
|
||||||
>>> for index, item in enumerate(furniture):
|
|
||||||
... print(f'index: {index} - item: {item}')
|
|
||||||
# index: 0 - item: table
|
|
||||||
# index: 1 - item: chair
|
|
||||||
# index: 2 - item: rack
|
|
||||||
# index: 3 - item: shelf
|
|
||||||
```
|
|
||||||
|
|
||||||
## Loop in Multiple Lists with zip()
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> price = [100, 50, 80, 40]
|
|
||||||
|
|
||||||
>>> for item, amount in zip(furniture, price):
|
|
||||||
... print(f'The {item} costs ${amount}')
|
|
||||||
# The table costs $100
|
|
||||||
# The chair costs $50
|
|
||||||
# The rack costs $80
|
|
||||||
# The shelf costs $40
|
|
||||||
```
|
|
||||||
|
|
||||||
## The in and not in operators
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 'rack' in ['table', 'chair', 'rack', 'shelf']
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'bed' in ['table', 'chair', 'rack', 'shelf']
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> 'bed' not in furniture
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'rack' not in furniture
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
## The Multiple Assignment Trick
|
|
||||||
|
|
||||||
The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> table = furniture[0]
|
|
||||||
>>> chair = furniture[1]
|
|
||||||
>>> rack = furniture[2]
|
|
||||||
>>> shelf = furniture[3]
|
|
||||||
```
|
|
||||||
|
|
||||||
You could type this line of code:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> table, chair, rack, shelf = furniture
|
|
||||||
|
|
||||||
>>> table
|
|
||||||
# 'table'
|
|
||||||
|
|
||||||
>>> chair
|
|
||||||
# 'chair'
|
|
||||||
|
|
||||||
>>> rack
|
|
||||||
# 'rack'
|
|
||||||
|
|
||||||
>>> shelf
|
|
||||||
# 'shelf'
|
|
||||||
```
|
|
||||||
|
|
||||||
The multiple assignment trick can also be used to swap the values in two variables:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> a, b = 'table', 'chair'
|
|
||||||
>>> a, b = b, a
|
|
||||||
>>> print(a)
|
|
||||||
# chair
|
|
||||||
|
|
||||||
>>> print(b)
|
|
||||||
# table
|
|
||||||
```
|
|
||||||
|
|
||||||
## The index Method
|
|
||||||
|
|
||||||
The `index` method allows you to find the index of a value by passing its name:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> furniture.index('chair')
|
|
||||||
# 1
|
|
||||||
```
|
|
||||||
|
|
||||||
## Adding Values
|
|
||||||
|
|
||||||
### append()
|
|
||||||
|
|
||||||
`append` adds an element to the end of a `list`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> furniture.append('bed')
|
|
||||||
>>> furniture
|
|
||||||
# ['table', 'chair', 'rack', 'shelf', 'bed']
|
|
||||||
```
|
|
||||||
|
|
||||||
### insert()
|
|
||||||
|
|
||||||
`insert` adds an element to a `list` at a given position:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> furniture.insert(1, 'bed')
|
|
||||||
>>> furniture
|
|
||||||
# ['table', 'bed', 'chair', 'rack', 'shelf']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Removing Values
|
|
||||||
|
|
||||||
### del()
|
|
||||||
|
|
||||||
`del` removes an item using the index:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> del furniture[2]
|
|
||||||
>>> furniture
|
|
||||||
# ['table', 'chair', 'shelf']
|
|
||||||
|
|
||||||
>>> del furniture[2]
|
|
||||||
>>> furniture
|
|
||||||
# ['table', 'chair']
|
|
||||||
```
|
|
||||||
|
|
||||||
### remove()
|
|
||||||
|
|
||||||
`remove` removes an item with using actual value of it:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> furniture.remove('chair')
|
|
||||||
>>> furniture
|
|
||||||
# ['table', 'rack', 'shelf']
|
|
||||||
```
|
|
||||||
|
|
||||||
<base-warning>
|
|
||||||
<base-warning-title>
|
|
||||||
Removing repeated items
|
|
||||||
</base-warning-title>
|
|
||||||
<base-warning-content>
|
|
||||||
If the value appears multiple times in the list, only the first instance of the value will be removed.
|
|
||||||
</base-warning-content>
|
|
||||||
</base-warning>
|
|
||||||
|
|
||||||
### pop()
|
|
||||||
|
|
||||||
By default, `pop` will remove and return the last item of the list. You can also pass the index of the element as an optional parameter:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> animals = ['cat', 'bat', 'rat', 'elephant']
|
|
||||||
|
|
||||||
>>> animals.pop()
|
|
||||||
'elephant'
|
|
||||||
|
|
||||||
>>> animals
|
|
||||||
['cat', 'bat', 'rat']
|
|
||||||
|
|
||||||
>>> animals.pop(0)
|
|
||||||
'cat'
|
|
||||||
|
|
||||||
>>> animals
|
|
||||||
['bat', 'rat']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Sorting values with sort()
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> numbers = [2, 5, 3.14, 1, -7]
|
|
||||||
>>> numbers.sort()
|
|
||||||
>>> numbers
|
|
||||||
# [-7, 1, 2, 3.14, 5]
|
|
||||||
|
|
||||||
furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
furniture.sort()
|
|
||||||
furniture
|
|
||||||
# ['chair', 'rack', 'shelf', 'table']
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also pass `True` for the `reverse` keyword argument to have `sort()` sort the values in reverse order:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture.sort(reverse=True)
|
|
||||||
>>> furniture
|
|
||||||
# ['table', 'shelf', 'rack', 'chair']
|
|
||||||
```
|
|
||||||
|
|
||||||
If you need to sort the values in regular alphabetical order, pass `str.lower` for the key keyword argument in the sort() method call:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> letters = ['a', 'z', 'A', 'Z']
|
|
||||||
>>> letters.sort(key=str.lower)
|
|
||||||
>>> letters
|
|
||||||
# ['a', 'A', 'z', 'Z']
|
|
||||||
```
|
|
||||||
|
|
||||||
You can use the built-in function `sorted` to return a new list:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ['table', 'chair', 'rack', 'shelf']
|
|
||||||
>>> sorted(furniture)
|
|
||||||
# ['chair', 'rack', 'shelf', 'table']
|
|
||||||
```
|
|
||||||
|
|
||||||
## The Tuple data type
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
<a target="_blank" href="https://stackoverflow.com/questions/1708510/list-vs-tuple-when-to-use-each">Tuples vs Lists</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
The key difference between tuples and lists is that, while <code>tuples</code> are <i>immutable</i> objects, <code>lists</code> are <i>mutable</i>. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> furniture = ('table', 'chair', 'rack', 'shelf')
|
|
||||||
|
|
||||||
>>> furniture[0]
|
|
||||||
# 'table'
|
|
||||||
|
|
||||||
>>> furniture[1:3]
|
|
||||||
# ('chair', 'rack')
|
|
||||||
|
|
||||||
>>> len(furniture)
|
|
||||||
# 4
|
|
||||||
```
|
|
||||||
|
|
||||||
The main way that tuples are different from lists is that tuples, like strings, are immutable.
|
|
||||||
|
|
||||||
## Converting between list() and tuple()
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> tuple(['cat', 'dog', 5])
|
|
||||||
# ('cat', 'dog', 5)
|
|
||||||
|
|
||||||
>>> list(('cat', 'dog', 5))
|
|
||||||
# ['cat', 'dog', 5]
|
|
||||||
|
|
||||||
>>> list('hello')
|
|
||||||
# ['h', 'e', 'l', 'l', 'o']
|
|
||||||
```
|
|
||||||
@ -1,40 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Main function - Python Cheatsheet
|
|
||||||
description: is the name of the scope in which top-level code executes. A module’s name is set equal to main when read from standard input, a script, or from an interactive prompt.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Main top-level script environment
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
## What is it
|
|
||||||
|
|
||||||
`__main__` is the name of the scope in which top-level code executes.
|
|
||||||
A module’s **name** is set equal to `__main__` when read from standard input, a script, or from an interactive prompt.
|
|
||||||
|
|
||||||
A module can discover whether it is running in the main scope by checking its own `__name__`, which allows a common idiom for conditionally executing code in a module. When it is run as a script or with `python -m` but not when it is imported:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> if __name__ == "__main__":
|
|
||||||
... # execute only if run as a script
|
|
||||||
... main()
|
|
||||||
```
|
|
||||||
|
|
||||||
For a package, the same effect can be achieved by including a **main**.py module, the contents of which will be executed when the module is run with -m.
|
|
||||||
|
|
||||||
For example, we are developing a script designed to be used as a module, we should do:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> def add(a, b):
|
|
||||||
... return a+b
|
|
||||||
...
|
|
||||||
>>> if __name__ == "__main__":
|
|
||||||
... add(3, 5)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Advantages
|
|
||||||
|
|
||||||
1. Every Python module has it’s `__name__` defined and if this is `__main__`, it implies that the module is run standalone by the user, and we can do corresponding appropriate actions.
|
|
||||||
2. If you import this script as a module in another script, the **name** is set to the name of the script/module.
|
|
||||||
3. Python files can act as either reusable modules, or as standalone programs.
|
|
||||||
4. `if __name__ == "__main__":` is used to execute some code only if the file is run directly, and is not being imported.
|
|
||||||
@ -1,332 +0,0 @@
|
|||||||
---
|
|
||||||
title: Manipulating strings - Python Cheatsheet
|
|
||||||
description: An escape character is created by typing a backslash \ followed by the character you want to insert.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Manipulating Strings
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
## Escape characters
|
|
||||||
|
|
||||||
An escape character is created by typing a backslash `\` followed by the character you want to insert.
|
|
||||||
|
|
||||||
| Escape character | Prints as |
|
|
||||||
| ---------------- | -------------------- |
|
|
||||||
| `\'` | Single quote |
|
|
||||||
| `\"` | Double quote |
|
|
||||||
| `\t` | Tab |
|
|
||||||
| `\n` | Newline (line break) |
|
|
||||||
| `\\` | Backslash |
|
|
||||||
| `\b` | Backspace |
|
|
||||||
| `\ooo` | Octal value |
|
|
||||||
| `\r` | Carriage Return |
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> print("Hello there!\nHow are you?\nI\'m doing fine.")
|
|
||||||
# Hello there!
|
|
||||||
# How are you?
|
|
||||||
# I'm doing fine.
|
|
||||||
```
|
|
||||||
|
|
||||||
## Raw strings
|
|
||||||
|
|
||||||
A raw string entirely ignores all escape characters and prints any backslash that appears in the string.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> print(r"Hello there!\nHow are you?\nI\'m doing fine.")
|
|
||||||
# Hello there!\nHow are you?\nI\'m doing fine.
|
|
||||||
```
|
|
||||||
|
|
||||||
Raw strings are mostly used for <router-link to="/cheatsheet/regular-expressions">regular expression</router-link> definition.
|
|
||||||
|
|
||||||
## Multiline Strings
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> print(
|
|
||||||
... """Dear Alice,
|
|
||||||
...
|
|
||||||
... Eve's cat has been arrested for catnapping,
|
|
||||||
... cat burglary, and extortion.
|
|
||||||
...
|
|
||||||
... Sincerely,
|
|
||||||
... Bob"""
|
|
||||||
... )
|
|
||||||
|
|
||||||
# Dear Alice,
|
|
||||||
|
|
||||||
# Eve's cat has been arrested for catnapping,
|
|
||||||
# cat burglary, and extortion.
|
|
||||||
|
|
||||||
# Sincerely,
|
|
||||||
# Bob
|
|
||||||
```
|
|
||||||
|
|
||||||
## Indexing and Slicing strings
|
|
||||||
|
|
||||||
H e l l o w o r l d !
|
|
||||||
0 1 2 3 4 5 6 7 8 9 10 11
|
|
||||||
|
|
||||||
### Indexing
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> spam = 'Hello world!'
|
|
||||||
|
|
||||||
>>> spam[0]
|
|
||||||
# 'H'
|
|
||||||
|
|
||||||
>>> spam[4]
|
|
||||||
# 'o'
|
|
||||||
|
|
||||||
>>> spam[-1]
|
|
||||||
# '!'
|
|
||||||
```
|
|
||||||
|
|
||||||
### Slicing
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> spam = 'Hello world!'
|
|
||||||
|
|
||||||
>>> spam[0:5]
|
|
||||||
# 'Hello'
|
|
||||||
|
|
||||||
>>> spam[:5]
|
|
||||||
# 'Hello'
|
|
||||||
|
|
||||||
>>> spam[6:]
|
|
||||||
# 'world!'
|
|
||||||
|
|
||||||
>>> spam[6:-1]
|
|
||||||
# 'world'
|
|
||||||
|
|
||||||
>>> spam[:-1]
|
|
||||||
# 'Hello world'
|
|
||||||
|
|
||||||
>>> spam[::-1]
|
|
||||||
# '!dlrow olleH'
|
|
||||||
|
|
||||||
>>> fizz = spam[0:5]
|
|
||||||
>>> fizz
|
|
||||||
# 'Hello'
|
|
||||||
```
|
|
||||||
|
|
||||||
## The in and not in operators
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 'Hello' in 'Hello World'
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'Hello' in 'Hello'
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'HELLO' in 'Hello World'
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> '' in 'spam'
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'cats' not in 'cats and dogs'
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
## upper(), lower() and title()
|
|
||||||
|
|
||||||
Transforms a string to upper, lower and title case:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> greet = 'Hello world!'
|
|
||||||
>>> greet.upper()
|
|
||||||
# 'HELLO WORLD!'
|
|
||||||
|
|
||||||
>>> greet.lower()
|
|
||||||
# 'hello world!'
|
|
||||||
|
|
||||||
>>> greet.title()
|
|
||||||
# 'Hello World!'
|
|
||||||
```
|
|
||||||
|
|
||||||
## isupper() and islower() methods
|
|
||||||
|
|
||||||
Returns `True` or `False` after evaluating if a string is in upper or lower case:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> spam = 'Hello world!'
|
|
||||||
>>> spam.islower()
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> spam.isupper()
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> 'HELLO'.isupper()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'abc12345'.islower()
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> '12345'.islower()
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> '12345'.isupper()
|
|
||||||
# False
|
|
||||||
```
|
|
||||||
|
|
||||||
## The isX string methods
|
|
||||||
|
|
||||||
| Method | Description |
|
|
||||||
| ----------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
||||||
| isalpha() | returns `True` if the string consists only of letters. |
|
|
||||||
| isalnum() | returns `True` if the string consists only of letters and numbers. |
|
|
||||||
| isdecimal() | returns `True` if the string consists only of numbers. |
|
|
||||||
| isspace() | returns `True` if the string consists only of spaces, tabs, and new-lines. |
|
|
||||||
| istitle() | returns `True` if the string consists only of words that begin with an uppercase letter followed by only lowercase characters. |
|
|
||||||
|
|
||||||
## startswith() and endswith()
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 'Hello world!'.startswith('Hello')
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'Hello world!'.endswith('world!')
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'abc123'.startswith('abcdef')
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> 'abc123'.endswith('12')
|
|
||||||
# False
|
|
||||||
|
|
||||||
>>> 'Hello world!'.startswith('Hello world!')
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> 'Hello world!'.endswith('Hello world!')
|
|
||||||
# True
|
|
||||||
```
|
|
||||||
|
|
||||||
## join() and split()
|
|
||||||
|
|
||||||
### join()
|
|
||||||
|
|
||||||
The `join()` method takes all the items in an iterable, like a <router-link to="/cheatsheet/lists-and-tuples">list</router-link>, <router-link to="/cheatsheet/dictionaries">dictionary</router-link>, <router-link to="/cheatsheet/lists-and-tuples#the-tuple-data-type">tuple</router-link> or <router-link to="/cheatsheet/sets">set</router-link>, and joins them into a string. You can also specify a separator.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> ''.join(['My', 'name', 'is', 'Simon'])
|
|
||||||
'MynameisSimon'
|
|
||||||
|
|
||||||
>>> ', '.join(['cats', 'rats', 'bats'])
|
|
||||||
# 'cats, rats, bats'
|
|
||||||
|
|
||||||
>>> ' '.join(['My', 'name', 'is', 'Simon'])
|
|
||||||
# 'My name is Simon'
|
|
||||||
|
|
||||||
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
|
|
||||||
# 'MyABCnameABCisABCSimon'
|
|
||||||
```
|
|
||||||
|
|
||||||
### split()
|
|
||||||
|
|
||||||
The `split()` method splits a `string` into a `list`. By default, it will use whitespace to separate the items, but you can also set another character of choice:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 'My name is Simon'.split()
|
|
||||||
# ['My', 'name', 'is', 'Simon']
|
|
||||||
|
|
||||||
>>> 'MyABCnameABCisABCSimon'.split('ABC')
|
|
||||||
# ['My', 'name', 'is', 'Simon']
|
|
||||||
|
|
||||||
>>> 'My name is Simon'.split('m')
|
|
||||||
# ['My na', 'e is Si', 'on']
|
|
||||||
|
|
||||||
>>> ' My name is Simon'.split()
|
|
||||||
# ['My', 'name', 'is', 'Simon']
|
|
||||||
|
|
||||||
>>> ' My name is Simon'.split(' ')
|
|
||||||
# ['', 'My', '', 'name', 'is', '', 'Simon']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Justifying text with rjust(), ljust() and center()
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 'Hello'.rjust(10)
|
|
||||||
# ' Hello'
|
|
||||||
|
|
||||||
>>> 'Hello'.rjust(20)
|
|
||||||
# ' Hello'
|
|
||||||
|
|
||||||
>>> 'Hello World'.rjust(20)
|
|
||||||
# ' Hello World'
|
|
||||||
|
|
||||||
>>> 'Hello'.ljust(10)
|
|
||||||
# 'Hello '
|
|
||||||
|
|
||||||
>>> 'Hello'.center(20)
|
|
||||||
# ' Hello '
|
|
||||||
```
|
|
||||||
|
|
||||||
An optional second argument to `rjust()` and `ljust()` will specify a fill character apart from a space character:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> 'Hello'.rjust(20, '*')
|
|
||||||
# '***************Hello'
|
|
||||||
|
|
||||||
>>> 'Hello'.ljust(20, '-')
|
|
||||||
# 'Hello---------------'
|
|
||||||
|
|
||||||
>>> 'Hello'.center(20, '=')
|
|
||||||
# '=======Hello========'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Removing whitespace with strip(), rstrip(), and lstrip()
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> spam = ' Hello World '
|
|
||||||
>>> spam.strip()
|
|
||||||
# 'Hello World'
|
|
||||||
|
|
||||||
>>> spam.lstrip()
|
|
||||||
# 'Hello World '
|
|
||||||
|
|
||||||
>>> spam.rstrip()
|
|
||||||
# ' Hello World'
|
|
||||||
|
|
||||||
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
|
|
||||||
>>> spam.strip('ampS')
|
|
||||||
# 'BaconSpamEggs'
|
|
||||||
```
|
|
||||||
|
|
||||||
## The Count Method
|
|
||||||
|
|
||||||
Counts the number of occurrences of a given character or substring in the string it is applied to. Can be optionally provided start and end index.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> sentence = 'one sheep two sheep three sheep four'
|
|
||||||
>>> sentence.count('sheep')
|
|
||||||
# 3
|
|
||||||
|
|
||||||
>>> sentence.count('e')
|
|
||||||
# 9
|
|
||||||
|
|
||||||
>>> sentence.count('e', 6)
|
|
||||||
# 8
|
|
||||||
# returns count of e after 'one sh' i.e 6 chars since beginning of string
|
|
||||||
|
|
||||||
>>> sentence.count('e', 7)
|
|
||||||
# 7
|
|
||||||
```
|
|
||||||
|
|
||||||
## Replace Method
|
|
||||||
|
|
||||||
Replaces all occurences of a given substring with another substring. Can be optionally provided a third argument to limit the number of replacements. Returns a new string.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> text = "Hello, world!"
|
|
||||||
>>> text.replace("world", "planet")
|
|
||||||
# 'Hello, planet!'
|
|
||||||
|
|
||||||
>>> fruits = "apple, banana, cherry, apple"
|
|
||||||
>>> fruits.replace("apple", "orange", 1)
|
|
||||||
# 'orange, banana, cherry, apple'
|
|
||||||
|
|
||||||
>>> sentence = "I like apples, Apples are my favorite fruit"
|
|
||||||
>>> sentence.replace("apples", "oranges")
|
|
||||||
# 'I like oranges, Apples are my favorite fruit'
|
|
||||||
```
|
|
||||||
@ -1,216 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python OOP Basics - Python Cheatsheet
|
|
||||||
|
|
||||||
description: Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of objects, which are instances of classes. OOP principles are fundamental concepts that guide the design and development of software in an object-oriented way. In Python, OOP is supported by the use of classes and objects. Here are some of the basic OOP principles in Python
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python OOP Basics
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
<a href="https://en.wikipedia.org/wiki/Object-oriented_programming">Object-Oriented Programming</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or properties), and the code is in the form of procedures (often known as methods).
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
## Encapsulation
|
|
||||||
|
|
||||||
Encapsulation is one of the fundamental concepts of object-oriented programming, which helps to protect the data and methods of an object from unauthorized access and modification. It is a way to achieve data abstraction, which means that the implementation details of an object are hidden from the outside world, and only the essential information is exposed.
|
|
||||||
|
|
||||||
In Python, encapsulation can be achieved by using access modifiers. Access modifiers are keywords that define the accessibility of attributes and methods in a class. The three access modifiers available in Python are public, private, and protected. However, Python does not have an explicit way of defining access modifiers like some other programming languages such as Java and C++. Instead, it uses a convention of using underscore prefixes to indicate the access level.
|
|
||||||
|
|
||||||
In the given code example, the class MyClass has two attributes, _protected_var and __private_var. The _protected_var is marked as protected by using a single underscore prefix. This means that the attribute can be accessed within the class and its subclasses but not outside the class. The __private_var is marked as private by using two underscore prefixes. This means that the attribute can only be accessed within the class and not outside the class, not even in its subclasses.
|
|
||||||
|
|
||||||
When we create an object of the MyClass class, we can access the _protected_var attribute using the object name with a single underscore prefix. However, we cannot access the __private_var attribute using the object name, as it is hidden from the outside world. If we try to access the __private_var attribute, we will get an AttributeError as shown in the code.
|
|
||||||
|
|
||||||
In summary, encapsulation is an important concept in object-oriented programming that helps to protect the implementation details of an object. In Python, we can achieve encapsulation by using access modifiers and using underscore prefixes to indicate the access level.
|
|
||||||
|
|
||||||
```python
|
|
||||||
# Define a class named MyClass
|
|
||||||
class MyClass:
|
|
||||||
|
|
||||||
# Constructor method that initializes the class object
|
|
||||||
def __init__(self):
|
|
||||||
|
|
||||||
# Define a protected variable with an initial value of 10
|
|
||||||
# The variable name starts with a single underscore, which indicates protected access
|
|
||||||
self._protected_var = 10
|
|
||||||
|
|
||||||
# Define a private variable with an initial value of 20
|
|
||||||
# The variable name starts with two underscores, which indicates private access
|
|
||||||
self.__private_var = 20
|
|
||||||
|
|
||||||
# Create an object of MyClass class
|
|
||||||
obj = MyClass()
|
|
||||||
|
|
||||||
# Access the protected variable using the object name and print its value
|
|
||||||
# The protected variable can be accessed outside the class but
|
|
||||||
# it is intended to be used within the class or its subclasses
|
|
||||||
print(obj._protected_var) # output: 10
|
|
||||||
|
|
||||||
# Try to access the private variable using the object name and print its value
|
|
||||||
# The private variable cannot be accessed outside the class, even by its subclasses
|
|
||||||
# This will raise an AttributeError because the variable is not accessible outside the class
|
|
||||||
print(obj.__private_var) # AttributeError: 'MyClass' object has no attribute '__private_var'
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
## Inheritance
|
|
||||||
|
|
||||||
Inheritance promotes code reuse and allows you to create a hierarchy of classes that share common attributes and methods. It helps in creating clean and organized code by keeping related functionality in one place and promoting the concept of modularity. The base class from which a new class is derived is also known as a parent class, and the new class is known as the child class or subclass.
|
|
||||||
|
|
||||||
In the code, we define a class named Animal which has a constructor method that initializes the class object with a name attribute and a method named speak. The speak method is defined in the Animal class but does not have a body.
|
|
||||||
|
|
||||||
We then define two subclasses named Dog and Cat which inherit from the Animal class. These subclasses override the speak method of the Animal class.
|
|
||||||
|
|
||||||
We create a Dog object with a name attribute "Rover" and a Cat object with a name attribute "Whiskers". We call the speak method of the Dog object using dog.speak(), and it prints "Woof!" because the speak method of the Dog class overrides the speak method of the Animal class. Similarly, we call the speak method of the Cat object using cat.speak(), and it prints "Meow!" because the speak method of the Cat class overrides the speak method of the Animal class.
|
|
||||||
|
|
||||||
``` python
|
|
||||||
# Define a class named Animal
|
|
||||||
class Animal:
|
|
||||||
|
|
||||||
# Constructor method that initializes the class object with a name attribute
|
|
||||||
def __init__(self, name):
|
|
||||||
self.name = name
|
|
||||||
|
|
||||||
# Method that is defined in the Animal class but does not have a body
|
|
||||||
# This method will be overridden in the subclasses of Animal
|
|
||||||
def speak(self):
|
|
||||||
print("")
|
|
||||||
|
|
||||||
# Define a subclass named Dog that inherits from the Animal class
|
|
||||||
class Dog(Animal):
|
|
||||||
|
|
||||||
# Override the speak method of the Animal class
|
|
||||||
def speak(self):
|
|
||||||
print("Woof!")
|
|
||||||
|
|
||||||
# Define a subclass named Cat that inherits from the Animal class
|
|
||||||
class Cat(Animal):
|
|
||||||
|
|
||||||
# Override the speak method of the Animal class
|
|
||||||
def speak(self):
|
|
||||||
print("Meow!")
|
|
||||||
|
|
||||||
# Create a Dog object with a name attribute "Rover"
|
|
||||||
dog = Dog("Rover")
|
|
||||||
|
|
||||||
# Create a Cat object with a name attribute "Whiskers"
|
|
||||||
cat = Cat("Whiskers")
|
|
||||||
|
|
||||||
# Call the speak method of the Dog class and print the output
|
|
||||||
# The speak method of the Dog class overrides the speak method of the Animal class
|
|
||||||
# Therefore, when we call the speak method of the Dog object, it will print "Woof!"
|
|
||||||
dog.speak() # output: Woof!
|
|
||||||
|
|
||||||
# Call the speak method of the Cat class and print the output
|
|
||||||
# The speak method of the Cat class overrides the speak method of the Animal class
|
|
||||||
# Therefore, when we call the speak method of the Cat object, it will print "Meow!"
|
|
||||||
cat.speak() # output: Meow!
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
## Polymorphism
|
|
||||||
|
|
||||||
Polymorphism is an important concept in object-oriented programming that allows you to write code that can work with objects of different classes in a uniform way. In Python, polymorphism is achieved by using method overriding or method overloading.
|
|
||||||
|
|
||||||
Method overriding is when a subclass provides its own implementation of a method that is already defined in its parent class. This allows the subclass to modify the behavior of the method without changing its name or signature.
|
|
||||||
|
|
||||||
Method overloading is when multiple methods have the same name but different parameters. Python does not support method overloading directly, but it can be achieved using default arguments or variable-length arguments.
|
|
||||||
|
|
||||||
Polymorphism makes it easier to write flexible and reusable code. It allows you to write code that can work with different objects without needing to know their specific types.
|
|
||||||
|
|
||||||
```python
|
|
||||||
#The Shape class is defined with an abstract area method, which is intended to be overridden by subclasses.
|
|
||||||
class Shape:
|
|
||||||
def area(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
class Rectangle(Shape):
|
|
||||||
# The Rectangle class is defined with an __init__ method that initializes
|
|
||||||
# width and height instance variables.
|
|
||||||
# It also defines an area method that calculates and returns
|
|
||||||
# the area of a rectangle using the width and height instance variables.
|
|
||||||
def __init__(self, width, height):
|
|
||||||
self.width = width # Initialize width instance variable
|
|
||||||
self.height = height # Initialize height instance variable
|
|
||||||
|
|
||||||
def area(self):
|
|
||||||
return self.width * self.height # Return area of rectangle
|
|
||||||
|
|
||||||
|
|
||||||
# The Circle class is defined with an __init__ method
|
|
||||||
# that initializes a radius instance variable.
|
|
||||||
# It also defines an area method that calculates and
|
|
||||||
# returns the area of a circle using the radius instance variable.
|
|
||||||
class Circle(Shape):
|
|
||||||
def __init__(self, radius):
|
|
||||||
self.radius = radius # Initialize radius instance variable
|
|
||||||
|
|
||||||
def area(self):
|
|
||||||
return 3.14 * self.radius ** 2 # Return area of circle using pi * r^2
|
|
||||||
|
|
||||||
# The shapes list is created with one Rectangle object and one Circle object. The for
|
|
||||||
# loop iterates over each object in the list and calls the area method of each object
|
|
||||||
# The output will be the area of the rectangle (20) and the area of the circle (153.86).
|
|
||||||
shapes = [Rectangle(4, 5), Circle(7)] # Create a list of Shape objects
|
|
||||||
for shape in shapes:
|
|
||||||
print(shape.area()) # Output the area of each Shape object
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
## Abstraction
|
|
||||||
Abstraction is an important concept in object-oriented programming (OOP) because it allows you to focus on the essential features of an object or system while ignoring the details that aren't relevant to the current context. By reducing complexity and hiding unnecessary details, abstraction can make code more modular, easier to read, and easier to maintain.
|
|
||||||
|
|
||||||
In Python, abstraction can be achieved by using abstract classes or interfaces. An abstract class is a class that cannot be instantiated directly, but is meant to be subclassed by other classes. It often includes abstract methods that have no implementation, but provide a template for how the subclass should be implemented. This allows the programmer to define a common interface for a group of related classes, while still allowing each class to have its own specific behavior.
|
|
||||||
|
|
||||||
An interface, on the other hand, is a collection of method signatures that a class must implement in order to be considered "compatible" with the interface. Interfaces are often used to define a common set of methods that multiple classes can implement, allowing them to be used interchangeably in certain contexts.
|
|
||||||
|
|
||||||
Python does not have built-in support for abstract classes or interfaces, but they can be implemented using the abc (abstract base class) module. This module provides the ABC class and the abstractmethod decorator, which can be used to define abstract classes and methods.
|
|
||||||
|
|
||||||
Overall, abstraction is a powerful tool for managing complexity and improving code quality in object-oriented programming, and Python provides a range of options for achieving abstraction in your code.
|
|
||||||
|
|
||||||
```python
|
|
||||||
# Import the abc module to define abstract classes and methods
|
|
||||||
from abc import ABC, abstractmethod
|
|
||||||
|
|
||||||
# Define an abstract class called Shape that has an abstract method called area
|
|
||||||
class Shape(ABC):
|
|
||||||
@abstractmethod
|
|
||||||
def area(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Define a Rectangle class that inherits from Shape
|
|
||||||
class Rectangle(Shape):
|
|
||||||
def __init__(self, width, height):
|
|
||||||
self.width = width
|
|
||||||
self.height = height
|
|
||||||
|
|
||||||
# Implement the area method for Rectangles
|
|
||||||
def area(self):
|
|
||||||
return self.width * self.height
|
|
||||||
|
|
||||||
# Define a Circle class that also inherits from Shape
|
|
||||||
class Circle(Shape):
|
|
||||||
def __init__(self, radius):
|
|
||||||
self.radius = radius
|
|
||||||
|
|
||||||
# Implement the area method for Circles
|
|
||||||
def area(self):
|
|
||||||
return 3.14 * self.radius ** 2
|
|
||||||
|
|
||||||
# Create a list of shapes that includes both Rectangles and Circles
|
|
||||||
shapes = [Rectangle(4, 5), Circle(7)]
|
|
||||||
|
|
||||||
# Loop through each shape in the list and print its area
|
|
||||||
for shape in shapes:
|
|
||||||
print(shape.area())
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
These are some of the basic OOP principles in Python. This page is currently in progress and more
|
|
||||||
detailed examples and explanations will be coming soon.
|
|
||||||
@ -1,71 +0,0 @@
|
|||||||
---
|
|
||||||
title: Reading and writing files - Python Cheatsheet
|
|
||||||
description: To read/write to a file in Python, you will want to use the with statement, which will close the file for you after you are done, managing the available resources for you.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Reading and Writing Files
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
## The file Reading/Writing process
|
|
||||||
|
|
||||||
To read/write to a file in Python, you will want to use the `with`
|
|
||||||
statement, which will close the file for you after you are done, managing the available resources for you.
|
|
||||||
|
|
||||||
## Opening and reading files
|
|
||||||
|
|
||||||
The `open` function opens a file and return a corresponding file object.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> with open('C:\\Users\\your_home_folder\\hi.txt') as hello_file:
|
|
||||||
... hello_content = hello_file.read()
|
|
||||||
...
|
|
||||||
>>> hello_content
|
|
||||||
'Hello World!'
|
|
||||||
```
|
|
||||||
|
|
||||||
Alternatively, you can use the _readlines()_ method to get a list of string values from the file, one string for each line of text:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> with open('sonnet29.txt') as sonnet_file:
|
|
||||||
... sonnet_file.readlines()
|
|
||||||
...
|
|
||||||
# [When, in disgrace with fortune and men's eyes,\n',
|
|
||||||
# ' I all alone beweep my outcast state,\n',
|
|
||||||
# And trouble deaf heaven with my bootless cries,\n', And
|
|
||||||
# look upon myself and curse my fate,']
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also iterate through the file line by line:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> with open('sonnet29.txt') as sonnet_file:
|
|
||||||
... for line in sonnet_file:
|
|
||||||
... print(line, end='')
|
|
||||||
...
|
|
||||||
# When, in disgrace with fortune and men's eyes,
|
|
||||||
# I all alone beweep my outcast state,
|
|
||||||
# And trouble deaf heaven with my bootless cries,
|
|
||||||
# And look upon myself and curse my fate,
|
|
||||||
```
|
|
||||||
|
|
||||||
## Writing to files
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> with open('bacon.txt', 'w') as bacon_file:
|
|
||||||
... bacon_file.write('Hello world!\n')
|
|
||||||
...
|
|
||||||
# 13
|
|
||||||
|
|
||||||
>>> with open('bacon.txt', 'a') as bacon_file:
|
|
||||||
... bacon_file.write('Bacon is not a vegetable.')
|
|
||||||
...
|
|
||||||
# 25
|
|
||||||
|
|
||||||
>>> with open('bacon.txt') as bacon_file:
|
|
||||||
... content = bacon_file.read()
|
|
||||||
...
|
|
||||||
>>> print(content)
|
|
||||||
# Hello world!
|
|
||||||
# Bacon is not a vegetable.
|
|
||||||
```
|
|
||||||
@ -1,393 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Regular Expressions - Python Cheatsheet
|
|
||||||
description: A regular expression (shortened as regex) is a sequence of characters that specifies a search pattern in text and used by string-searching algorithms.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Regular Expressions
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
<a target="_blank" href="https://en.wikipedia.org/wiki/Regular_expression">Regular expressions</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
A regular expression (shortened as regex [...]) is a sequence of characters that specifies a search pattern in text. [...] used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
1. Import the regex module with `import re`.
|
|
||||||
2. Create a Regex object with the `re.compile()` function. (Remember to use a raw string.)
|
|
||||||
3. Pass the string you want to search into the Regex object’s `search()` method. This returns a `Match` object.
|
|
||||||
4. Call the Match object’s `group()` method to return a string of the actual matched text.
|
|
||||||
|
|
||||||
All the regex functions in Python are in the re module:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> import re
|
|
||||||
```
|
|
||||||
|
|
||||||
## Regex symbols
|
|
||||||
|
|
||||||
| Symbol | Matches |
|
|
||||||
| ------------------------ | ------------------------------------------------------ |
|
|
||||||
| `?` | zero or one of the preceding group. |
|
|
||||||
| `*` | zero or more of the preceding group. |
|
|
||||||
| `+` | one or more of the preceding group. |
|
|
||||||
| `{n}` | exactly n of the preceding group. |
|
|
||||||
| `{n,}` | n or more of the preceding group. |
|
|
||||||
| `{,m}` | 0 to m of the preceding group. |
|
|
||||||
| `{n,m}` | at least n and at most m of the preceding p. |
|
|
||||||
| `{n,m}?` or `*?` or `+?` | performs a non-greedy match of the preceding p. |
|
|
||||||
| `^spam` | means the string must begin with spam. |
|
|
||||||
| `spam$` | means the string must end with spam. |
|
|
||||||
| `.` | any character, except newline characters. |
|
|
||||||
| `\d`, `\w`, and `\s` | a digit, word, or space character, respectively. |
|
|
||||||
| `\D`, `\W`, and `\S` | anything except a digit, word, or space, respectively. |
|
|
||||||
| `[abc]` | any character between the brackets (such as a, b, ). |
|
|
||||||
| `[^abc]` | any character that isn’t between the brackets. |
|
|
||||||
|
|
||||||
## Matching regex objects
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
|
|
||||||
|
|
||||||
>>> mo = phone_num_regex.search('My number is 415-555-4242.')
|
|
||||||
|
|
||||||
>>> print(f'Phone number found: {mo.group()}')
|
|
||||||
# Phone number found: 415-555-4242
|
|
||||||
```
|
|
||||||
|
|
||||||
## Grouping with parentheses
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> phone_num_regex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
|
|
||||||
>>> mo = phone_num_regex.search('My number is 415-555-4242.')
|
|
||||||
|
|
||||||
>>> mo.group(1)
|
|
||||||
# '415'
|
|
||||||
|
|
||||||
>>> mo.group(2)
|
|
||||||
# '555-4242'
|
|
||||||
|
|
||||||
>>> mo.group(0)
|
|
||||||
# '415-555-4242'
|
|
||||||
|
|
||||||
>>> mo.group()
|
|
||||||
# '415-555-4242'
|
|
||||||
```
|
|
||||||
|
|
||||||
To retrieve all the groups at once use the `groups()` method:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> mo.groups()
|
|
||||||
('415', '555-4242')
|
|
||||||
|
|
||||||
>>> area_code, main_number = mo.groups()
|
|
||||||
|
|
||||||
>>> print(area_code)
|
|
||||||
415
|
|
||||||
|
|
||||||
>>> print(main_number)
|
|
||||||
555-4242
|
|
||||||
```
|
|
||||||
|
|
||||||
## Multiple groups with Pipe
|
|
||||||
|
|
||||||
You can use the `|` character anywhere you want to match one of many expressions.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> hero_regex = re.compile (r'Batman|Tina Fey')
|
|
||||||
|
|
||||||
>>> mo1 = hero_regex.search('Batman and Tina Fey.')
|
|
||||||
>>> mo1.group()
|
|
||||||
# 'Batman'
|
|
||||||
|
|
||||||
>>> mo2 = hero_regex.search('Tina Fey and Batman.')
|
|
||||||
>>> mo2.group()
|
|
||||||
# 'Tina Fey'
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also use the pipe to match one of several patterns as part of your regex:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> bat_regex = re.compile(r'Bat(man|mobile|copter|bat)')
|
|
||||||
>>> mo = bat_regex.search('Batmobile lost a wheel')
|
|
||||||
|
|
||||||
>>> mo.group()
|
|
||||||
# 'Batmobile'
|
|
||||||
|
|
||||||
>>> mo.group(1)
|
|
||||||
# 'mobile'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Optional matching with the Question Mark
|
|
||||||
|
|
||||||
The `?` character flags the group that precedes it as an optional part of the pattern.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> bat_regex = re.compile(r'Bat(wo)?man')
|
|
||||||
|
|
||||||
>>> mo1 = bat_regex.search('The Adventures of Batman')
|
|
||||||
>>> mo1.group()
|
|
||||||
# 'Batman'
|
|
||||||
|
|
||||||
>>> mo2 = bat_regex.search('The Adventures of Batwoman')
|
|
||||||
>>> mo2.group()
|
|
||||||
# 'Batwoman'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Matching zero or more with the Star
|
|
||||||
|
|
||||||
The `*` (star or asterisk) means “match zero or more”. The group that precedes the star can occur any number of times in the text.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> bat_regex = re.compile(r'Bat(wo)*man')
|
|
||||||
>>> mo1 = bat_regex.search('The Adventures of Batman')
|
|
||||||
>>> mo1.group()
|
|
||||||
'Batman'
|
|
||||||
|
|
||||||
>>> mo2 = bat_regex.search('The Adventures of Batwoman')
|
|
||||||
>>> mo2.group()
|
|
||||||
'Batwoman'
|
|
||||||
|
|
||||||
>>> mo3 = bat_regex.search('The Adventures of Batwowowowoman')
|
|
||||||
>>> mo3.group()
|
|
||||||
'Batwowowowoman'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Matching one or more with the Plus
|
|
||||||
|
|
||||||
The `+` (or plus) _means match one or more_. The group preceding a plus must appear at least once:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> bat_regex = re.compile(r'Bat(wo)+man')
|
|
||||||
|
|
||||||
>>> mo1 = bat_regex.search('The Adventures of Batwoman')
|
|
||||||
>>> mo1.group()
|
|
||||||
# 'Batwoman'
|
|
||||||
|
|
||||||
>>> mo2 = bat_regex.search('The Adventures of Batwowowowoman')
|
|
||||||
>>> mo2.group()
|
|
||||||
# 'Batwowowowoman'
|
|
||||||
|
|
||||||
>>> mo3 = bat_regex.search('The Adventures of Batman')
|
|
||||||
>>> mo3 is None
|
|
||||||
# True
|
|
||||||
```
|
|
||||||
|
|
||||||
## Matching specific repetitions with Curly Brackets
|
|
||||||
|
|
||||||
If you have a group that you want to repeat a specific number of times, follow the group in your regex with a number in curly brackets:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> ha_regex = re.compile(r'(Ha){3}')
|
|
||||||
|
|
||||||
>>> mo1 = ha_regex.search('HaHaHa')
|
|
||||||
>>> mo1.group()
|
|
||||||
# 'HaHaHa'
|
|
||||||
|
|
||||||
>>> mo2 = ha_regex.search('Ha')
|
|
||||||
>>> mo2 is None
|
|
||||||
# True
|
|
||||||
```
|
|
||||||
|
|
||||||
Instead of one number, you can specify a range with minimum and a maximum in between the curly brackets. For example, the regex (Ha){3,5} will match 'HaHaHa', 'HaHaHaHa', and 'HaHaHaHaHa'.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> ha_regex = re.compile(r'(Ha){2,3}')
|
|
||||||
>>> mo1 = ha_regex.search('HaHaHaHa')
|
|
||||||
>>> mo1.group()
|
|
||||||
# 'HaHaHa'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Greedy and non-greedy matching
|
|
||||||
|
|
||||||
Python’s regular expressions are greedy by default: in ambiguous situations they will match the longest string possible. The non-greedy version of the curly brackets, which matches the shortest string possible, has the closing curly bracket followed by a question mark.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> greedy_ha_regex = re.compile(r'(Ha){3,5}')
|
|
||||||
|
|
||||||
>>> mo1 = greedy_ha_regex.search('HaHaHaHaHa')
|
|
||||||
>>> mo1.group()
|
|
||||||
# 'HaHaHaHaHa'
|
|
||||||
|
|
||||||
>>> non_greedy_ha_regex = re.compile(r'(Ha){3,5}?')
|
|
||||||
>>> mo2 = non_greedy_ha_regex.search('HaHaHaHaHa')
|
|
||||||
>>> mo2.group()
|
|
||||||
# 'HaHaHa'
|
|
||||||
```
|
|
||||||
|
|
||||||
## The findall() method
|
|
||||||
|
|
||||||
The `findall()` method will return the strings of every match in the searched string.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # has no groups
|
|
||||||
|
|
||||||
>>> phone_num_regex.findall('Cell: 415-555-9999 Work: 212-555-0000')
|
|
||||||
# ['415-555-9999', '212-555-0000']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Making your own character classes
|
|
||||||
|
|
||||||
You can define your own character class using square brackets. For example, the character class _[aeiouAEIOU]_ will match any vowel, both lowercase and uppercase.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> vowel_regex = re.compile(r'[aeiouAEIOU]')
|
|
||||||
>>> vowel_regex.findall('Robocop eats baby food. BABY FOOD.')
|
|
||||||
# ['o', 'o', 'o', 'e', 'a', 'a', 'o', 'o', 'A', 'O', 'O']
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also include ranges of letters or numbers by using a hyphen. For example, the character class _[a-zA-Z0-9]_ will match all lowercase letters, uppercase letters, and numbers.
|
|
||||||
|
|
||||||
By placing a caret character (`^`) just after the character class’s opening bracket, you can make a negative character class that will match all the characters that are not in the character class:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> consonant_regex = re.compile(r'[^aeiouAEIOU]')
|
|
||||||
>>> consonant_regex.findall('Robocop eats baby food. BABY FOOD.')
|
|
||||||
# ['R', 'b', 'c', 'p', ' ', 't', 's', ' ', 'b', 'b', 'y', ' ', 'f', 'd', '.', '
|
|
||||||
# ', 'B', 'B', 'Y', ' ', 'F', 'D', '.']
|
|
||||||
```
|
|
||||||
|
|
||||||
## The Caret and Dollar sign characters
|
|
||||||
|
|
||||||
- You can also use the caret symbol `^` at the start of a regex to indicate that a match must occur at the beginning of the searched text.
|
|
||||||
|
|
||||||
- Likewise, you can put a dollar sign `$` at the end of the regex to indicate the string must end with this regex pattern.
|
|
||||||
|
|
||||||
- And you can use the `^` and `$` together to indicate that the entire string must match the regex.
|
|
||||||
|
|
||||||
The `r'^Hello`' regular expression string matches strings that begin with 'Hello':
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> begins_with_hello = re.compile(r'^Hello')
|
|
||||||
>>> begins_with_hello.search('Hello world!')
|
|
||||||
# <_sre.SRE_Match object; span=(0, 5), match='Hello'>
|
|
||||||
|
|
||||||
>>> begins_with_hello.search('He said hello.') is None
|
|
||||||
# True
|
|
||||||
```
|
|
||||||
|
|
||||||
The `r'\d\$'` regular expression string matches strings that end with a numeric character from 0 to 9:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> whole_string_is_num = re.compile(r'^\d+$')
|
|
||||||
|
|
||||||
>>> whole_string_is_num.search('1234567890')
|
|
||||||
# <_sre.SRE_Match object; span=(0, 10), match='1234567890'>
|
|
||||||
|
|
||||||
>>> whole_string_is_num.search('12345xyz67890') is None
|
|
||||||
# True
|
|
||||||
|
|
||||||
>>> whole_string_is_num.search('12 34567890') is None
|
|
||||||
# True
|
|
||||||
```
|
|
||||||
|
|
||||||
## The Wildcard character
|
|
||||||
|
|
||||||
The `.` (or dot) character in a regular expression will match any character except for a newline:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> at_regex = re.compile(r'.at')
|
|
||||||
|
|
||||||
>>> at_regex.findall('The cat in the hat sat on the flat mat.')
|
|
||||||
['cat', 'hat', 'sat', 'lat', 'mat']
|
|
||||||
```
|
|
||||||
|
|
||||||
## Matching everything with Dot-Star
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> name_regex = re.compile(r'First Name: (.*) Last Name: (.*)')
|
|
||||||
|
|
||||||
>>> mo = name_regex.search('First Name: Al Last Name: Sweigart')
|
|
||||||
>>> mo.group(1)
|
|
||||||
# 'Al'
|
|
||||||
|
|
||||||
>>> mo.group(2)
|
|
||||||
'Sweigart'
|
|
||||||
```
|
|
||||||
|
|
||||||
The `.*` uses greedy mode: It will always try to match as much text as possible. To match any and all text in a non-greedy fashion, use the dot, star, and question mark (`.*?`). The question mark tells Python to match in a non-greedy way:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> non_greedy_regex = re.compile(r'<.*?>')
|
|
||||||
>>> mo = non_greedy_regex.search('<To serve man> for dinner.>')
|
|
||||||
>>> mo.group()
|
|
||||||
# '<To serve man>'
|
|
||||||
|
|
||||||
>>> greedy_regex = re.compile(r'<.*>')
|
|
||||||
>>> mo = greedy_regex.search('<To serve man> for dinner.>')
|
|
||||||
>>> mo.group()
|
|
||||||
# '<To serve man> for dinner.>'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Matching newlines with the Dot character
|
|
||||||
|
|
||||||
The dot-star will match everything except a newline. By passing `re.DOTALL` as the second argument to `re.compile()`, you can make the dot character match all characters, including the newline character:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> no_newline_regex = re.compile('.*')
|
|
||||||
>>> no_newline_regex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()
|
|
||||||
# 'Serve the public trust.'
|
|
||||||
|
|
||||||
>>> newline_regex = re.compile('.*', re.DOTALL)
|
|
||||||
>>> newline_regex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()
|
|
||||||
# 'Serve the public trust.\nProtect the innocent.\nUphold the law.'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Case-Insensitive matching
|
|
||||||
|
|
||||||
To make your regex case-insensitive, you can pass `re.IGNORECASE` or `re.I` as a second argument to `re.compile()`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> robocop = re.compile(r'robocop', re.I)
|
|
||||||
|
|
||||||
>>> robocop.search('Robocop is part man, part machine, all cop.').group()
|
|
||||||
# 'Robocop'
|
|
||||||
|
|
||||||
>>> robocop.search('ROBOCOP protects the innocent.').group()
|
|
||||||
# 'ROBOCOP'
|
|
||||||
|
|
||||||
>>> robocop.search('Al, why does your programming book talk about robocop so much?').group()
|
|
||||||
# 'robocop'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Substituting strings with the sub() method
|
|
||||||
|
|
||||||
The `sub()` method for Regex objects is passed two arguments:
|
|
||||||
|
|
||||||
1. The first argument is a string to replace any matches.
|
|
||||||
1. The second is the string for the regular expression.
|
|
||||||
|
|
||||||
The `sub()` method returns a string with the substitutions applied:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> names_regex = re.compile(r'Agent \w+')
|
|
||||||
|
|
||||||
>>> names_regex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')
|
|
||||||
# 'CENSORED gave the secret documents to CENSORED.'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Managing complex Regexes
|
|
||||||
|
|
||||||
To tell the `re.compile()` function to ignore whitespace and comments inside the regular expression string, “verbose mode” can be enabled by passing the variable `re.VERBOSE` as the second argument to `re.compile()`.
|
|
||||||
|
|
||||||
Now instead of a hard-to-read regular expression like this:
|
|
||||||
|
|
||||||
```python
|
|
||||||
phone_regex = re.compile(r'((\d{3}|\(\d{3}\))?(\s|-|\.)?\d{3}(\s|-|\.)\d{4}(\s*(ext|x|ext.)\s*\d{2,5})?)')
|
|
||||||
```
|
|
||||||
|
|
||||||
you can spread the regular expression over multiple lines with comments like this:
|
|
||||||
|
|
||||||
```python
|
|
||||||
phone_regex = re.compile(r'''(
|
|
||||||
(\d{3}|\(\d{3}\))? # area code
|
|
||||||
(\s|-|\.)? # separator
|
|
||||||
\d{3} # first 3 digits
|
|
||||||
(\s|-|\.) # separator
|
|
||||||
\d{4} # last 4 digits
|
|
||||||
(\s*(ext|x|ext.)\s*\d{2,5})? # extension
|
|
||||||
)''', re.VERBOSE)
|
|
||||||
```
|
|
||||||
@ -1,158 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Sets - Python Cheatsheet
|
|
||||||
description: Python comes equipped with several built-in data types to help us organize our data. These structures include lists, dictionaries, tuples and sets.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python Sets
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
Python comes equipped with several built-in data types to help us organize our data. These structures include lists, dictionaries, tuples and **sets**.
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
From the Python 3 <a target="_blank" href="https://docs.python.org/3/tutorial/datastructures.html#sets">documentation</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
Read <router-link to="/blog/python-sets-what-why-how">Python Sets: What, Why and How</router-link> for a more in-deep reference.
|
|
||||||
|
|
||||||
## Initializing a set
|
|
||||||
|
|
||||||
There are two ways to create sets: using curly braces `{}` and the built-in function `set()`
|
|
||||||
|
|
||||||
<base-warning>
|
|
||||||
<base-warning-title>
|
|
||||||
Empty Sets
|
|
||||||
</base-warning-title>
|
|
||||||
<base-warning-content>
|
|
||||||
When creating set, be sure to not use empty curly braces <code>{}</code> or you will get an empty dictionary instead.
|
|
||||||
</base-warning-content>
|
|
||||||
</base-warning>
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s = {1, 2, 3}
|
|
||||||
>>> s = set([1, 2, 3])
|
|
||||||
|
|
||||||
>>> s = {} # this will create a dictionary instead of a set
|
|
||||||
>>> type(s)
|
|
||||||
# <class 'dict'>
|
|
||||||
```
|
|
||||||
|
|
||||||
## Unordered collections of unique elements
|
|
||||||
|
|
||||||
A set automatically removes all the duplicate values.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s = {1, 2, 3, 2, 3, 4}
|
|
||||||
>>> s
|
|
||||||
# {1, 2, 3, 4}
|
|
||||||
```
|
|
||||||
|
|
||||||
And as an unordered data type, they can't be indexed.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s = {1, 2, 3}
|
|
||||||
>>> s[0]
|
|
||||||
# Traceback (most recent call last):
|
|
||||||
# File "<stdin>", line 1, in <module>
|
|
||||||
# TypeError: 'set' object does not support indexing
|
|
||||||
```
|
|
||||||
|
|
||||||
## set add and update
|
|
||||||
|
|
||||||
Using the `add()` method we can add a single element to the set.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s = {1, 2, 3}
|
|
||||||
>>> s.add(4)
|
|
||||||
>>> s
|
|
||||||
# {1, 2, 3, 4}
|
|
||||||
```
|
|
||||||
|
|
||||||
And with `update()`, multiple ones:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s = {1, 2, 3}
|
|
||||||
>>> s.update([2, 3, 4, 5, 6])
|
|
||||||
>>> s
|
|
||||||
# {1, 2, 3, 4, 5, 6}
|
|
||||||
```
|
|
||||||
|
|
||||||
## set remove and discard
|
|
||||||
|
|
||||||
Both methods will remove an element from the set, but `remove()` will raise a `key error` if the value doesn't exist.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s = {1, 2, 3}
|
|
||||||
>>> s.remove(3)
|
|
||||||
>>> s
|
|
||||||
# {1, 2}
|
|
||||||
|
|
||||||
>>> s.remove(3)
|
|
||||||
# Traceback (most recent call last):
|
|
||||||
# File "<stdin>", line 1, in <module>
|
|
||||||
# KeyError: 3
|
|
||||||
```
|
|
||||||
|
|
||||||
`discard()` won't raise any errors.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s = {1, 2, 3}
|
|
||||||
>>> s.discard(3)
|
|
||||||
>>> s
|
|
||||||
# {1, 2}
|
|
||||||
>>> s.discard(3)
|
|
||||||
```
|
|
||||||
|
|
||||||
## set union
|
|
||||||
|
|
||||||
`union()` or `|` will create a new set with all the elements from the sets provided.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s1 = {1, 2, 3}
|
|
||||||
>>> s2 = {3, 4, 5}
|
|
||||||
>>> s1.union(s2) # or 's1 | s2'
|
|
||||||
# {1, 2, 3, 4, 5}
|
|
||||||
```
|
|
||||||
|
|
||||||
## set intersection
|
|
||||||
|
|
||||||
`intersection()` or `&` will return a set with only the elements that are common to all of them.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s1 = {1, 2, 3}
|
|
||||||
>>> s2 = {2, 3, 4}
|
|
||||||
>>> s3 = {3, 4, 5}
|
|
||||||
>>> s1.intersection(s2, s3) # or 's1 & s2 & s3'
|
|
||||||
# {3}
|
|
||||||
```
|
|
||||||
|
|
||||||
## set difference
|
|
||||||
|
|
||||||
`difference()` or `-` will return only the elements that are unique to the first set (invoked set).
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s1 = {1, 2, 3}
|
|
||||||
>>> s2 = {2, 3, 4}
|
|
||||||
|
|
||||||
>>> s1.difference(s2) # or 's1 - s2'
|
|
||||||
# {1}
|
|
||||||
|
|
||||||
>>> s2.difference(s1) # or 's2 - s1'
|
|
||||||
# {4}
|
|
||||||
```
|
|
||||||
|
|
||||||
## set symmetric_difference
|
|
||||||
|
|
||||||
`symmetric_difference()` or `^` will return all the elements that are not common between them.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> s1 = {1, 2, 3}
|
|
||||||
>>> s2 = {2, 3, 4}
|
|
||||||
>>> s1.symmetric_difference(s2) # or 's1 ^ s2'
|
|
||||||
# {1, 4}
|
|
||||||
```
|
|
||||||
@ -1,54 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Setup.py - Python Cheatsheet
|
|
||||||
description: The setup script is the centre of all activity in building, distributing, and installing modules using the Distutils. The main purpose of the setup script is to describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python setup.py
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
<base-warning>
|
|
||||||
<base-warning-title>
|
|
||||||
A 'controversial' opinion
|
|
||||||
</base-warning-title>
|
|
||||||
<base-warning-content>
|
|
||||||
Using `setup.py` to pack and distribute your python packages can be quite challenging every so often. Tools like <a target="_blank" href="https://python-poetry.org/">Poetry</a> make not only the packaging a <b>lot easier</b>, but also help you to manage your dependencies in a very convenient way.
|
|
||||||
</base-warning-content>
|
|
||||||
</base-warning>
|
|
||||||
|
|
||||||
If you want more information about Poetry you can read the following articles:
|
|
||||||
|
|
||||||
- <router-link to="/blog/python-projects-with-poetry-and-vscode-part-1">Python projects with Poetry and VSCode. Part 1</router-link>
|
|
||||||
- <router-link to="/blog/python-projects-with-poetry-and-vscode-part-2">Python projects with Poetry and VSCode. Part 2</router-link>
|
|
||||||
- <router-link to="/blog/python-projects-with-poetry-and-vscode-part-3">Python projects with Poetry and VSCode. Part 3</router-link>
|
|
||||||
|
|
||||||
## Introduction
|
|
||||||
|
|
||||||
The setup script is the center of all activity in building, distributing, and installing modules using the Distutils. The main purpose of the setup script is to describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing.
|
|
||||||
|
|
||||||
The `setup.py` file is at the heart of a Python project. It describes all the metadata about your project. There are quite a few fields you can add to a project to give it a rich set of metadata describing the project. However, there are only three required fields: name, version, and packages. The name field must be unique if you wish to publish your package on the Python Package Index (PyPI). The version field keeps track of different releases of the project. The package's field describes where you’ve put the Python source code within your project.
|
|
||||||
|
|
||||||
This allows you to easily install Python packages. Often it's enough to write:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python setup.py install
|
|
||||||
```
|
|
||||||
|
|
||||||
and module will install itself.
|
|
||||||
|
|
||||||
## Example
|
|
||||||
|
|
||||||
Our initial setup.py will also include information about the license and will re-use the README.txt file for the long_description field. This will look like:
|
|
||||||
|
|
||||||
```python
|
|
||||||
from distutils.core import setup
|
|
||||||
setup(
|
|
||||||
name='pythonCheatsheet',
|
|
||||||
version='0.1',
|
|
||||||
packages=['pipenv',],
|
|
||||||
license='MIT',
|
|
||||||
long_description=open('README.txt').read(),
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
Find more information visit the [official documentation](http://docs.python.org/3.11/install/index.html).
|
|
||||||
@ -1,177 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python String Formatting - Python Cheatsheet
|
|
||||||
description: If your are using Python 3.6+, string f-strings are the recommended way to format strings.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Python String Formatting
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
From the <a href="https://docs.python.org/3/library/stdtypes.html?highlight=sprintf#printf-style-string-formatting">Python 3 documentation</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
The formatting operations described here (<b>% operator</b>) exhibit a variety of quirks that lead to a number of common errors [...]. Using the newer <a href="#formatted-string-literals-or-f-strings">formatted string literals</a> [...] helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
## % operator
|
|
||||||
|
|
||||||
<base-warning>
|
|
||||||
<base-warning-title>
|
|
||||||
Prefer String Literals
|
|
||||||
</base-warning-title>
|
|
||||||
<base-warning-content>
|
|
||||||
For new code, using <a href="#strformat">str.format</a>, or <a href="#formatted-string-literals-or-f-strings">formatted string literals</a> (Python 3.6+) over the <code>%</code> operator is strongly recommended.
|
|
||||||
</base-warning-content>
|
|
||||||
</base-warning>
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> name = 'Pete'
|
|
||||||
>>> 'Hello %s' % name
|
|
||||||
# "Hello Pete"
|
|
||||||
```
|
|
||||||
|
|
||||||
We can use the `%d` format specifier to convert an int value to a string:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> num = 5
|
|
||||||
>>> 'I have %d apples' % num
|
|
||||||
# "I have 5 apples"
|
|
||||||
```
|
|
||||||
|
|
||||||
## str.format
|
|
||||||
|
|
||||||
Python 3 introduced a new way to do string formatting that was later back-ported to Python 2.7. This makes the syntax for string formatting more regular.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> name = 'John'
|
|
||||||
>>> age = 20
|
|
||||||
|
|
||||||
>>> "Hello I'm {}, my age is {}".format(name, age)
|
|
||||||
# "Hello I'm John, my age is 20"
|
|
||||||
|
|
||||||
>>> "Hello I'm {0}, my age is {1}".format(name, age)
|
|
||||||
# "Hello I'm John, my age is 20"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Formatted String Literals or f-Strings
|
|
||||||
|
|
||||||
If your are using Python 3.6+, string `f-Strings` are the recommended way to format strings.
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
From the <a href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings">Python 3 documentation</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
A formatted string literal or f-string is a string literal that is prefixed with `f` or `F`. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> name = 'Elizabeth'
|
|
||||||
>>> f'Hello {name}!'
|
|
||||||
# 'Hello Elizabeth!'
|
|
||||||
```
|
|
||||||
|
|
||||||
It is even possible to do inline arithmetic with it:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> a = 5
|
|
||||||
>>> b = 10
|
|
||||||
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
|
|
||||||
# 'Five plus ten is 15 and not 30.'
|
|
||||||
```
|
|
||||||
|
|
||||||
### Multiline f-Strings
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> name = 'Robert'
|
|
||||||
>>> messages = 12
|
|
||||||
>>> (
|
|
||||||
... f'Hi, {name}. '
|
|
||||||
... f'You have {messages} unread messages'
|
|
||||||
... )
|
|
||||||
# 'Hi, Robert. You have 12 unread messages'
|
|
||||||
```
|
|
||||||
|
|
||||||
### The `=` specifier
|
|
||||||
|
|
||||||
This will print the expression and its value:
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from datetime import datetime
|
|
||||||
>>> now = datetime.now().strftime("%b/%d/%Y - %H:%M:%S")
|
|
||||||
>>> f'date and time: {now=}'
|
|
||||||
# "date and time: now='Nov/14/2022 - 20:50:01'"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Adding spaces or characters
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> f"{name.upper() = :-^20}"
|
|
||||||
# 'name.upper() = -------ROBERT-------'
|
|
||||||
>>>
|
|
||||||
>>> f"{name.upper() = :^20}"
|
|
||||||
# 'name.upper() = ROBERT '
|
|
||||||
>>>
|
|
||||||
>>> f"{name.upper() = :20}"
|
|
||||||
# 'name.upper() = ROBERT '
|
|
||||||
```
|
|
||||||
|
|
||||||
## Formatting Digits
|
|
||||||
|
|
||||||
Adding thousands separator
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> a = 10000000
|
|
||||||
>>> f"{a:,}"
|
|
||||||
# '10,000,000'
|
|
||||||
```
|
|
||||||
|
|
||||||
Rounding
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> a = 3.1415926
|
|
||||||
>>> f"{a:.2f}"
|
|
||||||
# '3.14'
|
|
||||||
```
|
|
||||||
|
|
||||||
Showing as Percentage
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> a = 0.816562
|
|
||||||
>>> f"{a:.2%}"
|
|
||||||
# '81.66%'
|
|
||||||
```
|
|
||||||
|
|
||||||
### Number formatting table
|
|
||||||
|
|
||||||
| Number | Format | Output | description |
|
|
||||||
| ---------- | ------- | --------- | --------------------------------------------- |
|
|
||||||
| 3.1415926 | {:.2f} | 3.14 | Format float 2 decimal places |
|
|
||||||
| 3.1415926 | {:+.2f} | +3.14 | Format float 2 decimal places with sign |
|
|
||||||
| -1 | {:+.2f} | -1.00 | Format float 2 decimal places with sign |
|
|
||||||
| 2.71828 | {:.0f} | 3 | Format float with no decimal places |
|
|
||||||
| 4 | {:0>2d} | 04 | Pad number with zeros (left padding, width 2) |
|
|
||||||
| 4 | {:x<4d} | 4xxx | Pad number with x’s (right padding, width 4) |
|
|
||||||
| 10 | {:x<4d} | 10xx | Pad number with x’s (right padding, width 4) |
|
|
||||||
| 1000000 | {:,} | 1,000,000 | Number format with comma separator |
|
|
||||||
| 0.35 | {:.2%} | 35.00% | Format percentage |
|
|
||||||
| 1000000000 | {:.2e} | 1.00e+09 | Exponent notation |
|
|
||||||
| 11 | {:11d} | 11 | Right-aligned (default, width 10) |
|
|
||||||
| 11 | {:<11d} | 11 | Left-aligned (width 10) |
|
|
||||||
| 11 | {:^11d} | 11 | Center aligned (width 10) |
|
|
||||||
|
|
||||||
## Template Strings
|
|
||||||
|
|
||||||
A simpler and less powerful mechanism, but it is recommended when handling strings generated by users. Due to their reduced complexity, template strings are a safer choice.
|
|
||||||
|
|
||||||
```python
|
|
||||||
>>> from string import Template
|
|
||||||
>>> name = 'Elizabeth'
|
|
||||||
>>> t = Template('Hey $name!')
|
|
||||||
>>> t.substitute(name=name)
|
|
||||||
# 'Hey Elizabeth!'
|
|
||||||
```
|
|
||||||
@ -1,180 +0,0 @@
|
|||||||
---
|
|
||||||
title: Python Virtual environments - Python Cheatsheet
|
|
||||||
description: The use of a Virtual Environment is to test python code in encapsulated environments and to also avoid filling the base Python installation with libraries we might use for only one project.
|
|
||||||
---
|
|
||||||
|
|
||||||
<base-title :title="frontmatter.title" :description="frontmatter.description">
|
|
||||||
Virtual Environment
|
|
||||||
</base-title>
|
|
||||||
|
|
||||||
The use of a Virtual Environment is to test python code in encapsulated environments, and to also avoid filling the base Python installation with libraries we might use for only one project.
|
|
||||||
|
|
||||||
## virtualenv
|
|
||||||
|
|
||||||
1. Install virtualenv
|
|
||||||
|
|
||||||
pip install virtualenv
|
|
||||||
|
|
||||||
1. Install virtualenvwrapper-win (Windows)
|
|
||||||
|
|
||||||
pip install virtualenvwrapper-win
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
|
|
||||||
1. Make a Virtual Environment named `HelloWorld`
|
|
||||||
|
|
||||||
mkvirtualenv HelloWorld
|
|
||||||
|
|
||||||
Anything we install now will be specific to this project. And available to the projects we connect to this environment.
|
|
||||||
|
|
||||||
1. Set Project Directory
|
|
||||||
|
|
||||||
To bind our virtualenv with our current working directory we simply enter:
|
|
||||||
|
|
||||||
setprojectdir .
|
|
||||||
|
|
||||||
1. Deactivate
|
|
||||||
|
|
||||||
To move onto something else in the command line type `deactivate` to deactivate your environment.
|
|
||||||
|
|
||||||
deactivate
|
|
||||||
|
|
||||||
Notice how the parenthesis disappear.
|
|
||||||
|
|
||||||
1. Workon
|
|
||||||
|
|
||||||
Open up the command prompt and type `workon HelloWorld` to activate the environment and move into your root project folder
|
|
||||||
|
|
||||||
workon HelloWorld
|
|
||||||
|
|
||||||
## Poetry
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
From <a href="https://python-poetry.org/">Poetry website</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
Poetry is a tool for dependency management and packaging in Python. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
1. Install Poetry
|
|
||||||
|
|
||||||
pip install --user poetry
|
|
||||||
|
|
||||||
2. Create a new project
|
|
||||||
|
|
||||||
poetry new my-project
|
|
||||||
|
|
||||||
This will create a my-project directory:
|
|
||||||
|
|
||||||
my-project
|
|
||||||
├── pyproject.toml
|
|
||||||
├── README.rst
|
|
||||||
├── poetry_demo
|
|
||||||
│ └── __init__.py
|
|
||||||
└── tests
|
|
||||||
├── __init__.py
|
|
||||||
└── test_poetry_demo.py
|
|
||||||
|
|
||||||
The pyproject.toml file will orchestrate your project and its dependencies:
|
|
||||||
|
|
||||||
[tool.poetry]
|
|
||||||
name = "my-project"
|
|
||||||
version = "0.1.0"
|
|
||||||
description = ""
|
|
||||||
authors = ["your name <your@mail.com>"]
|
|
||||||
|
|
||||||
[tool.poetry.dependencies]
|
|
||||||
python = "*"
|
|
||||||
|
|
||||||
[tool.poetry.dev-dependencies]
|
|
||||||
pytest = "^3.4"
|
|
||||||
|
|
||||||
3. Packages
|
|
||||||
|
|
||||||
To add dependencies to your project, you can specify them in the tool.poetry.dependencies section:
|
|
||||||
|
|
||||||
[tool.poetry.dependencies]
|
|
||||||
pendulum = "^1.4"
|
|
||||||
|
|
||||||
Also, instead of modifying the pyproject.toml file by hand, you can use the add command and it will automatically find a suitable version constraint.
|
|
||||||
|
|
||||||
$ poetry add pendulum
|
|
||||||
|
|
||||||
To install the dependencies listed in the pyproject.toml:
|
|
||||||
|
|
||||||
poetry install
|
|
||||||
|
|
||||||
To remove dependencies:
|
|
||||||
|
|
||||||
poetry remove pendulum
|
|
||||||
|
|
||||||
For more information, check the [documentation](https://poetry.eustace.io/docs/) or read here:
|
|
||||||
|
|
||||||
- <router-link to="/blog/python-projects-with-poetry-and-vscode-part-1">Python projects with Poetry and VSCode. Part 1</router-link>
|
|
||||||
- <router-link to="/blog/python-projects-with-poetry-and-vscode-part-2">Python projects with Poetry and VSCode. Part 2</router-link>
|
|
||||||
- <router-link to="/blog/python-projects-with-poetry-and-vscode-part-3">Python projects with Poetry and VSCode. Part 3</router-link>
|
|
||||||
|
|
||||||
## Pipenv
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
From <a target="_blank" href="https://pipenv.pypa.io/en/latest/">Pipenv website</a>
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
Pipenv is a tool that aims to bring the best of all packaging worlds (bundler, composer, npm, cargo, yarn, etc.) to the Python world. Windows is a first-class citizen, in our world.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
1. Install pipenv
|
|
||||||
|
|
||||||
pip install pipenv
|
|
||||||
|
|
||||||
2. Enter your Project directory and install the Packages for your project
|
|
||||||
|
|
||||||
cd my_project
|
|
||||||
pipenv install <package>
|
|
||||||
|
|
||||||
Pipenv will install your package and create a Pipfile for you in your project’s directory. The Pipfile is used to track which dependencies your project needs in case you need to re-install them.
|
|
||||||
|
|
||||||
3. Uninstall Packages
|
|
||||||
|
|
||||||
pipenv uninstall <package>
|
|
||||||
|
|
||||||
4. Activate the Virtual Environment associated with your Python project
|
|
||||||
|
|
||||||
pipenv shell
|
|
||||||
|
|
||||||
5. Exit the Virtual Environment
|
|
||||||
|
|
||||||
exit
|
|
||||||
|
|
||||||
Find more information and a video in [docs.pipenv.org](https://docs.pipenv.org/).
|
|
||||||
|
|
||||||
## Anaconda
|
|
||||||
|
|
||||||
<base-disclaimer>
|
|
||||||
<base-disclaimer-title>
|
|
||||||
<a target="k" href="https://anaconda.com/">Anaconda</a> is another popular tool to manage python packages.
|
|
||||||
</base-disclaimer-title>
|
|
||||||
<base-disclaimer-content>
|
|
||||||
Where packages, notebooks, projects and environments are shared. Your place for free public conda package hosting.
|
|
||||||
</base-disclaimer-content>
|
|
||||||
</base-disclaimer>
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
|
|
||||||
1. Make a Virtual Environment
|
|
||||||
|
|
||||||
conda create -n HelloWorld
|
|
||||||
|
|
||||||
2. To use the Virtual Environment, activate it by:
|
|
||||||
|
|
||||||
conda activate HelloWorld
|
|
||||||
|
|
||||||
Anything installed now will be specific to the project HelloWorld
|
|
||||||
|
|
||||||
3. Exit the Virtual Environment
|
|
||||||
|
|
||||||
conda deactivate
|
|
||||||
Loading…
x
Reference in New Issue
Block a user