From ba7d38240198ba854384328843da52a26209f488 Mon Sep 17 00:00:00 2001 From: johannst Date: Sun, 28 Nov 2021 22:26:50 +0000 Subject: deploy: 6660154d7eaae83f3e8765af8b93dcd651e05452 --- development/python.html | 316 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 316 insertions(+) create mode 100644 development/python.html (limited to 'development/python.html') diff --git a/development/python.html b/development/python.html new file mode 100644 index 0000000..27ea896 --- /dev/null +++ b/development/python.html @@ -0,0 +1,316 @@ + + + + + + python - Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + + + +
+
+

python

+

Decorator [run]

+

Some decorator examples with type annotation.

+
from typing import Callable
+
+def log(f: Callable[[int], None]) -> Callable[[int], None]:
+    def inner(x: int):
+        print(f"log::inner f={f.__name__} x={x}")
+        f(x)
+    return inner
+
+@log
+def some_fn(x: int):
+    print(f"some_fn x={x}")
+
+
+def log_tag(tag: str) -> Callable[[Callable[[int], None]], Callable[[int], None]]:
+    def decorator(f: Callable[[int], None]) -> Callable[[int], None]:
+        def inner(x: int):
+            print(f"log_tag::inner f={f.__name__} tag={tag} x={x}")
+            f(x)
+        return inner
+    return decorator
+
+@log_tag("some_tag")
+def some_fn2(x: int):
+    print(f"some_fn2 x={x}")
+
+

Walrus operator [run]

+

Walrus operator := added since python 3.8.

+
from typing import Optional
+
+# Example 1: if let statements
+
+def foo(ret: Optional[int]) -> Optional[int]:
+    return ret
+
+if r := foo(None):
+    print(f"foo(None) -> {r}")
+
+if r := foo(1337):
+    print(f"foo(1337) -> {r}")
+
+# Example 2: while let statements
+
+toks = iter(['a', 'b', 'c'])
+while tok := next(toks, None):
+    print(f"{tok}")
+
+# Example 3: list comprehension
+
+print([tok for t in ["  a", "  ", " b "] if (tok := t.strip())])
+
+

Unittest [run]

+

Run unittests directly from the command line as
+python3 -m unittest -v test

+

Optionally pass -k <patter> to only run subset of tests.

+
# file: test.py
+
+import unittest
+
+class MyTest(unittest.TestCase):
+    def setUp(self):
+        pass
+    def tearDown(self):
+        pass
+    # Tests need to start with the prefix 'test'.
+    def test_foo(self):
+        self.assertEqual(1 + 2, 3)
+    def test_bar(self):
+        with self.assertRaises(IndexError):
+            list()[0]
+
+

Doctest [run]

+

Run doctests directly from the command line as
+python -m doctest -v test.py

+
# file: test.py
+
+def sum(a: int, b: int) -> int:
+    """Sum a and b.
+
+    >>> sum(1, 2)
+    3
+
+    >>> sum(10, 20)
+    30
+    """
+    return a + b
+
+

timeit

+

Micro benchmarking.

+
python -m timeit '[x.strip() for x in ["a ", " b"]]'
+
+ +
+ + +
+
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -- cgit v1.2.3