Python
The Python programming language.
Learn
- Official tutorial
- https://realpython.com
- https://matt.sh/python-project-structure-2024
- #todo Python Cookbook
Notes
- There is no
++
operator, only+= 1
. None
instead of null.and
instead of&&
,or
instead of||
.- Division:
/
is decimal,//
is integer. - Numbers are infinite, so they never overflow.
- Negative indexes are used to get values starting from the end of a list, so
list[-1]
is the last value. - For loops: use
range()
for index only scan, useenumerate()
for index and value scan. - List comprehensions return a list:
list = [x*x for x in y if z]
- Generator expressions return an iterator:
iter = (x*x for x in y if z)
- List values are loaded into memory immediately, while iterator values are computed lazily.
- Rule of thumb: use for loops for modifying lists, use list comprehensions for creating new lists.
Testing
The standard unit testing module is unittest
.
The file naming convention is test_*.py
.
Test template:
import unittest
class TestFoo(unittest.TestCase):
def test_foo(self) -> None:
self.assertEqual(1, 2)
if __name__ == "__main__":
unittest.main()
A popular alternative is pytest.
Virtual environment
A directory that contains an isolated runtime and local pip
dependencies.
Should be created for each project instead of using the global pip
.
- Create:
python3 -m venv .venv
- Activate:
source .venv/bin/activate
- Deactivate:
deactivate
Tooling
- Formatter: https://github.com/psf/black
- Linter: https://github.com/astral-sh/ruff
- Type checker: https://github.com/python/mypy
- Language server: https://github.com/microsoft/pyright