From 836430d032f500a13d3df25093dfaea708d2cba6 Mon Sep 17 00:00:00 2001 From: Brian H Miller <41061953+SmokingPuffin@users.noreply.github.com> Date: Sun, 3 Dec 2023 15:55:15 -0800 Subject: [PATCH] day 2 polish pass --- content/05_other_functions_concepts.ipynb | 1364 +++++++++++++++-- ...06_sequence_iterators_and_generators.ipynb | 864 +++++++++-- content/07_context_managers.ipynb | 639 +++++++- content/08_argparse.ipynb | 319 +++- 4 files changed, 2794 insertions(+), 392 deletions(-) diff --git a/content/05_other_functions_concepts.ipynb b/content/05_other_functions_concepts.ipynb index 2d92193..b5f6d92 100644 --- a/content/05_other_functions_concepts.ipynb +++ b/content/05_other_functions_concepts.ipynb @@ -32,7 +32,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "metadata": {}, "outputs": [], "source": [ @@ -44,16 +44,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "add(1, 2)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": {}, "outputs": [], "source": [ @@ -65,16 +76,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "16" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "square(4)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, "metadata": {}, "outputs": [], "source": [ @@ -86,18 +108,39 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello Brian!'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "greeting(\"Debakar\")" + "greeting(\"Brian\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "type(add) = \n", + "type(square) = \n", + "type(greeting) = \n" + ] + } + ], "source": [ "print(f\"{type(add) = }\\n{type(square) = }\\n{type(greeting) = }\")" ] @@ -118,13 +161,22 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "metadata": { "tags": [ "raises-exception" ] }, - "outputs": [], + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "invalid syntax (3143571765.py, line 4)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m Cell \u001b[1;32mIn[8], line 4\u001b[1;36m\u001b[0m\n\u001b[1;33m add = lambda num1: int, num2: int: num1 + num2\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" + ] + } + ], "source": [ "# def add(num1: int, num2: int) -> int:\n", "# return num1 + num2\n", @@ -141,7 +193,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 9, "metadata": {}, "outputs": [], "source": [ @@ -159,13 +211,22 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "metadata": { "tags": [ "raises-exception" ] }, - "outputs": [], + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "cannot assign to lambda (2862269418.py, line 1)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m Cell \u001b[1;32mIn[10], line 1\u001b[1;36m\u001b[0m\n\u001b[1;33m lambda num: num = 10\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m cannot assign to lambda\n" + ] + } + ], "source": [ "lambda num: num = 10" ] @@ -206,9 +267,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 4, 9, 16, 25]" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "numbers = [1, 2, 3, 4, 5]\n", "\n", @@ -223,9 +295,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 12, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[20, 90, 120, 20, 50]" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "item_quantity = [2, 3, 6, 4, 5]\n", "item_cost = [10, 30, 20, 5, 10]\n", @@ -250,9 +333,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 13, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 4, 6, 8, 10]" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", "\n", @@ -274,11 +368,22 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 18, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 5, 4]" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "items = [1, 2, 0, 5, 4, False, None, None, 0, 0]\n", + "items = [1, 2, 0, 5, 4, False, None, [], '', 0, 0]\n", "\n", "non_falsy = filter(None, items)\n", "list(non_falsy)" @@ -293,9 +398,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "a = [1, 2, 3, 4, 5]\n", "b = [6, 7, 8, 9, 10]\n", @@ -305,9 +421,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[(1, 6, 'a'), (2, 7, 'b'), (3, 8, 'c')]" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# length of the new iterable will be minimum of length of all the iterable\n", "a = [1, 2, 3, 4, 5]\n", @@ -321,26 +448,79 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Generally all this will be used combinely" + "The power of higher-order functions comes from combining them:" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 22, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144]" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "squared_number_below_150 = filter(\n", - " lambda x: x < 150, map(lambda num: num**2, range(20))\n", + "squares_below_150 = filter(lambda x: x < 150, \n", + " map(lambda num: num**2, range(20))\n", ")\n", - "list(squared_number_below_150)" + "list(squares_below_150)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Although list comprehension are more readable" + "When considering whether to use maps and filters, consider whether list comprehension syntax will be more readable." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144]" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "squares_below_150 = [x**2 for x in range(20) if x**2 < 150]\n", + "list(squares_below_150)" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144]" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "squares_below_150 = filter(lambda x: x < 150, [x**2 for x in range(20)])\n", + "list(squares_below_150)" ] }, { @@ -358,7 +538,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 28, "metadata": {}, "outputs": [], "source": [ @@ -375,18 +555,45 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 29, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on function greeting in module __main__:\n", + "\n", + "greeting(name)\n", + " Generate a greeting message for the given 'name'.\n", + " \n", + " :param str name: The name of the person to greet.\n", + " :return: A greeting message.\n", + " :rtype: str\n", + "\n" + ] + } + ], "source": [ "help(greeting)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 30, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "\"\\n Generate a greeting message for the given 'name'.\\n\\n :param str name: The name of the person to greet.\\n :return: A greeting message.\\n :rtype: str\\n \"" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Docstring are stored in __doc__ attribute\n", "greeting.__doc__" @@ -405,7 +612,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 31, "metadata": {}, "outputs": [], "source": [ @@ -421,18 +628,44 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 32, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on function greeting in module __main__:\n", + "\n", + "greeting(name: str) -> str\n", + " Generate a greeting message for the given 'name'.\n", + " \n", + " :param name: The name of the person to greet.\n", + " :return: A greeting message.\n", + "\n" + ] + } + ], "source": [ "help(greeting)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 33, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "{'name': str, 'return': str}" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "greeting.__annotations__" ] @@ -460,9 +693,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 34, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "add\n" + ] + } + ], "source": [ "def add(a, b):\n", " return a + b\n", @@ -480,9 +721,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 35, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "('Hello',)\n" + ] + } + ], "source": [ "def greet(name, greeting=\"Hello\"):\n", " return f\"{greeting}, {name}\"\n", @@ -500,9 +749,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 36, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], "source": [ "def greet(name, greeting=\"Hello\"):\n", " return f\"{greeting}, {name}\"\n", @@ -520,9 +777,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 37, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n" + ] + } + ], "source": [ "def add(a, b):\n", " return a + b\n", @@ -540,9 +805,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 38, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "('a', 'b', 'result')\n" + ] + } + ], "source": [ "def multiply(a, b):\n", " result = a * b\n", @@ -561,9 +834,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 39, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(None, 3.14)\n" + ] + } + ], "source": [ "def multiply(a, b):\n", " pi = 3.14\n", @@ -583,9 +864,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 40, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "('global_var',)\n" + ] + } + ], "source": [ "global_var = 42\n", "\n", @@ -606,9 +895,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 41, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n" + ] + } + ], "source": [ "def calculate(a, b):\n", " result = a + b\n", @@ -634,9 +931,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 42, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(name, greeting='Hello')\n" + ] + } + ], "source": [ "import inspect\n", "\n", @@ -658,9 +963,19 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 43, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "def square(x):\n", + " return x**2\n", + "\n" + ] + } + ], "source": [ "import inspect\n", "\n", @@ -682,9 +997,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 44, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Multiply two numbers and return the result.\n" + ] + } + ], "source": [ "import inspect\n", "\n", @@ -709,9 +1032,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 46, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[('__doc__', 'This module provides access to the mathematical functions\\ndefined by the C standard.'), ('__loader__', ), ('__name__', 'math'), ('__package__', ''), ('__spec__', ModuleSpec(name='math', loader=, origin='built-in')), ('acos', ), ('acosh', ), ('asin', ), ('asinh', ), ('atan', ), ('atan2', ), ('atanh', ), ('cbrt', ), ('ceil', ), ('comb', ), ('copysign', ), ('cos', ), ('cosh', ), ('degrees', ), ('dist', ), ('e', 2.718281828459045), ('erf', ), ('erfc', ), ('exp', ), ('exp2', ), ('expm1', ), ('fabs', ), ('factorial', ), ('floor', ), ('fmod', ), ('frexp', ), ('fsum', ), ('gamma', ), ('gcd', ), ('hypot', ), ('inf', inf), ('isclose', ), ('isfinite', ), ('isinf', ), ('isnan', ), ('isqrt', ), ('lcm', ), ('ldexp', ), ('lgamma', ), ('log', ), ('log10', ), ('log1p', ), ('log2', ), ('modf', ), ('nan', nan), ('nextafter', ), ('perm', ), ('pi', 3.141592653589793), ('pow', ), ('prod', ), ('radians', ), ('remainder', ), ('sin', ), ('sinh', ), ('sqrt', ), ('tan', ), ('tanh', ), ('tau', 6.283185307179586), ('trunc', ), ('ulp', )]\n" + ] + } + ], "source": [ "import math\n", "import inspect\n", @@ -729,9 +1060,488 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 48, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "C:\\Users\\bhmiller\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages\\numpy\\__init__.py\n", + "\"\"\"\n", + "NumPy\n", + "=====\n", + "\n", + "Provides\n", + " 1. An array object of arbitrary homogeneous items\n", + " 2. Fast mathematical operations over arrays\n", + " 3. Linear Algebra, Fourier Transforms, Random Number Generation\n", + "\n", + "How to use the documentation\n", + "----------------------------\n", + "Documentation is available in two forms: docstrings provided\n", + "with the code, and a loose standing reference guide, available from\n", + "`the NumPy homepage `_.\n", + "\n", + "We recommend exploring the docstrings using\n", + "`IPython `_, an advanced Python shell with\n", + "TAB-completion and introspection capabilities. See below for further\n", + "instructions.\n", + "\n", + "The docstring examples assume that `numpy` has been imported as ``np``::\n", + "\n", + " >>> import numpy as np\n", + "\n", + "Code snippets are indicated by three greater-than signs::\n", + "\n", + " >>> x = 42\n", + " >>> x = x + 1\n", + "\n", + "Use the built-in ``help`` function to view a function's docstring::\n", + "\n", + " >>> help(np.sort)\n", + " ... # doctest: +SKIP\n", + "\n", + "For some objects, ``np.info(obj)`` may provide additional help. This is\n", + "particularly true if you see the line \"Help on ufunc object:\" at the top\n", + "of the help() page. Ufuncs are implemented in C, not Python, for speed.\n", + "The native Python help() does not know how to view their help, but our\n", + "np.info() function does.\n", + "\n", + "To search for documents containing a keyword, do::\n", + "\n", + " >>> np.lookfor('keyword')\n", + " ... # doctest: +SKIP\n", + "\n", + "General-purpose documents like a glossary and help on the basic concepts\n", + "of numpy are available under the ``doc`` sub-module::\n", + "\n", + " >>> from numpy import doc\n", + " >>> help(doc)\n", + " ... # doctest: +SKIP\n", + "\n", + "Available subpackages\n", + "---------------------\n", + "lib\n", + " Basic functions used by several sub-packages.\n", + "random\n", + " Core Random Tools\n", + "linalg\n", + " Core Linear Algebra Tools\n", + "fft\n", + " Core FFT routines\n", + "polynomial\n", + " Polynomial tools\n", + "testing\n", + " NumPy testing tools\n", + "distutils\n", + " Enhancements to distutils with support for\n", + " Fortran compilers support and more (for Python <= 3.11).\n", + "\n", + "Utilities\n", + "---------\n", + "test\n", + " Run numpy unittests\n", + "show_config\n", + " Show numpy build configuration\n", + "matlib\n", + " Make everything matrices.\n", + "__version__\n", + " NumPy version string\n", + "\n", + "Viewing documentation using IPython\n", + "-----------------------------------\n", + "\n", + "Start IPython and import `numpy` usually under the alias ``np``: `import\n", + "numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste\n", + "examples into the shell. To see which functions are available in `numpy`,\n", + "type ``np.`` (where ```` refers to the TAB key), or use\n", + "``np.*cos*?`` (where ```` refers to the ENTER key) to narrow\n", + "down the list. To view the docstring for a function, use\n", + "``np.cos?`` (to view the docstring) and ``np.cos??`` (to view\n", + "the source code).\n", + "\n", + "Copies vs. in-place operation\n", + "-----------------------------\n", + "Most of the functions in `numpy` return a copy of the array argument\n", + "(e.g., `np.sort`). In-place versions of these functions are often\n", + "available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.\n", + "Exceptions to this rule are documented.\n", + "\n", + "\"\"\"\n", + "\n", + "\n", + "# start delvewheel patch\n", + "def _delvewheel_patch_1_5_1():\n", + " import os\n", + " libs_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'numpy.libs'))\n", + " if os.path.isdir(libs_dir):\n", + " os.add_dll_directory(libs_dir)\n", + "\n", + "\n", + "_delvewheel_patch_1_5_1()\n", + "del _delvewheel_patch_1_5_1\n", + "# end delvewheel patch\n", + "\n", + "import sys\n", + "import warnings\n", + "\n", + "from ._globals import _NoValue, _CopyMode\n", + "# These exceptions were moved in 1.25 and are hidden from __dir__()\n", + "from .exceptions import (\n", + " ComplexWarning, ModuleDeprecationWarning, VisibleDeprecationWarning,\n", + " TooHardError, AxisError)\n", + "\n", + "\n", + "# If a version with git hash was stored, use that instead\n", + "from . import version\n", + "from .version import __version__\n", + "\n", + "# We first need to detect if we're being called as part of the numpy setup\n", + "# procedure itself in a reliable manner.\n", + "try:\n", + " __NUMPY_SETUP__\n", + "except NameError:\n", + " __NUMPY_SETUP__ = False\n", + "\n", + "if __NUMPY_SETUP__:\n", + " sys.stderr.write('Running from numpy source directory.\\n')\n", + "else:\n", + " # Allow distributors to run custom init code before importing numpy.core\n", + " from . import _distributor_init\n", + "\n", + " try:\n", + " from numpy.__config__ import show as show_config\n", + " except ImportError as e:\n", + " msg = \"\"\"Error importing numpy: you should not try to import numpy from\n", + " its source directory; please exit the numpy source tree, and relaunch\n", + " your python interpreter from there.\"\"\"\n", + " raise ImportError(msg) from e\n", + "\n", + " __all__ = [\n", + " 'exceptions', 'ModuleDeprecationWarning', 'VisibleDeprecationWarning',\n", + " 'ComplexWarning', 'TooHardError', 'AxisError']\n", + "\n", + " # mapping of {name: (value, deprecation_msg)}\n", + " __deprecated_attrs__ = {}\n", + "\n", + " from . import core\n", + " from .core import *\n", + " from . import compat\n", + " from . import exceptions\n", + " from . import dtypes\n", + " from . import lib\n", + " # NOTE: to be revisited following future namespace cleanup.\n", + " # See gh-14454 and gh-15672 for discussion.\n", + " from .lib import *\n", + "\n", + " from . import linalg\n", + " from . import fft\n", + " from . import polynomial\n", + " from . import random\n", + " from . import ctypeslib\n", + " from . import ma\n", + " from . import matrixlib as _mat\n", + " from .matrixlib import *\n", + "\n", + " # Deprecations introduced in NumPy 1.20.0, 2020-06-06\n", + " import builtins as _builtins\n", + "\n", + " _msg = (\n", + " \"module 'numpy' has no attribute '{n}'.\\n\"\n", + " \"`np.{n}` was a deprecated alias for the builtin `{n}`. \"\n", + " \"To avoid this error in existing code, use `{n}` by itself. \"\n", + " \"Doing this will not modify any behavior and is safe. {extended_msg}\\n\"\n", + " \"The aliases was originally deprecated in NumPy 1.20; for more \"\n", + " \"details and guidance see the original release note at:\\n\"\n", + " \" https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\")\n", + "\n", + " _specific_msg = (\n", + " \"If you specifically wanted the numpy scalar type, use `np.{}` here.\")\n", + "\n", + " _int_extended_msg = (\n", + " \"When replacing `np.{}`, you may wish to use e.g. `np.int64` \"\n", + " \"or `np.int32` to specify the precision. If you wish to review \"\n", + " \"your current use, check the release note link for \"\n", + " \"additional information.\")\n", + "\n", + " _type_info = [\n", + " (\"object\", \"\"), # The NumPy scalar only exists by name.\n", + " (\"bool\", _specific_msg.format(\"bool_\")),\n", + " (\"float\", _specific_msg.format(\"float64\")),\n", + " (\"complex\", _specific_msg.format(\"complex128\")),\n", + " (\"str\", _specific_msg.format(\"str_\")),\n", + " (\"int\", _int_extended_msg.format(\"int\"))]\n", + "\n", + " __former_attrs__ = {\n", + " n: _msg.format(n=n, extended_msg=extended_msg)\n", + " for n, extended_msg in _type_info\n", + " }\n", + "\n", + " # Future warning introduced in NumPy 1.24.0, 2022-11-17\n", + " _msg = (\n", + " \"`np.{n}` is a deprecated alias for `{an}`. (Deprecated NumPy 1.24)\")\n", + "\n", + " # Some of these are awkward (since `np.str` may be preferable in the long\n", + " # term), but overall the names ending in 0 seem undesirable\n", + " _type_info = [\n", + " (\"bool8\", bool_, \"np.bool_\"),\n", + " (\"int0\", intp, \"np.intp\"),\n", + " (\"uint0\", uintp, \"np.uintp\"),\n", + " (\"str0\", str_, \"np.str_\"),\n", + " (\"bytes0\", bytes_, \"np.bytes_\"),\n", + " (\"void0\", void, \"np.void\"),\n", + " (\"object0\", object_,\n", + " \"`np.object0` is a deprecated alias for `np.object_`. \"\n", + " \"`object` can be used instead. (Deprecated NumPy 1.24)\")]\n", + "\n", + " # Some of these could be defined right away, but most were aliases to\n", + " # the Python objects and only removed in NumPy 1.24. Defining them should\n", + " # probably wait for NumPy 1.26 or 2.0.\n", + " # When defined, these should possibly not be added to `__all__` to avoid\n", + " # import with `from numpy import *`.\n", + " __future_scalars__ = {\"bool\", \"long\", \"ulong\", \"str\", \"bytes\", \"object\"}\n", + "\n", + " __deprecated_attrs__.update({\n", + " n: (alias, _msg.format(n=n, an=an)) for n, alias, an in _type_info})\n", + "\n", + " import math\n", + "\n", + " __deprecated_attrs__['math'] = (math,\n", + " \"`np.math` is a deprecated alias for the standard library `math` \"\n", + " \"module (Deprecated Numpy 1.25). Replace usages of `np.math` with \"\n", + " \"`math`\")\n", + "\n", + " del math, _msg, _type_info\n", + "\n", + " from .core import abs\n", + " # now that numpy modules are imported, can initialize limits\n", + " core.getlimits._register_known_types()\n", + "\n", + " __all__.extend(['__version__', 'show_config'])\n", + " __all__.extend(core.__all__)\n", + " __all__.extend(_mat.__all__)\n", + " __all__.extend(lib.__all__)\n", + " __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])\n", + "\n", + " # Remove min and max from __all__ to avoid `from numpy import *` override\n", + " # the builtins min/max. Temporary fix for 1.25.x/1.26.x, see gh-24229.\n", + " __all__.remove('min')\n", + " __all__.remove('max')\n", + " __all__.remove('round')\n", + "\n", + " # Remove one of the two occurrences of `issubdtype`, which is exposed as\n", + " # both `numpy.core.issubdtype` and `numpy.lib.issubdtype`.\n", + " __all__.remove('issubdtype')\n", + "\n", + " # These are exported by np.core, but are replaced by the builtins below\n", + " # remove them to ensure that we don't end up with `np.long == np.int_`,\n", + " # which would be a breaking change.\n", + " del long, unicode\n", + " __all__.remove('long')\n", + " __all__.remove('unicode')\n", + "\n", + " # Remove things that are in the numpy.lib but not in the numpy namespace\n", + " # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)\n", + " # that prevents adding more things to the main namespace by accident.\n", + " # The list below will grow until the `from .lib import *` fixme above is\n", + " # taken care of\n", + " __all__.remove('Arrayterator')\n", + " del Arrayterator\n", + "\n", + " # These names were removed in NumPy 1.20. For at least one release,\n", + " # attempts to access these names in the numpy namespace will trigger\n", + " # a warning, and calling the function will raise an exception.\n", + " _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',\n", + " 'ppmt', 'pv', 'rate']\n", + " __expired_functions__ = {\n", + " name: (f'In accordance with NEP 32, the function {name} was removed '\n", + " 'from NumPy version 1.20. A replacement for this function '\n", + " 'is available in the numpy_financial library: '\n", + " 'https://pypi.org/project/numpy-financial')\n", + " for name in _financial_names}\n", + "\n", + " # Filter out Cython harmless warnings\n", + " warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\n", + " warnings.filterwarnings(\"ignore\", message=\"numpy.ufunc size changed\")\n", + " warnings.filterwarnings(\"ignore\", message=\"numpy.ndarray size changed\")\n", + "\n", + " # oldnumeric and numarray were removed in 1.9. In case some packages import\n", + " # but do not use them, we define them here for backward compatibility.\n", + " oldnumeric = 'removed'\n", + " numarray = 'removed'\n", + "\n", + " def __getattr__(attr):\n", + " # Warn for expired attributes, and return a dummy function\n", + " # that always raises an exception.\n", + " import warnings\n", + " import math\n", + " try:\n", + " msg = __expired_functions__[attr]\n", + " except KeyError:\n", + " pass\n", + " else:\n", + " warnings.warn(msg, DeprecationWarning, stacklevel=2)\n", + "\n", + " def _expired(*args, **kwds):\n", + " raise RuntimeError(msg)\n", + "\n", + " return _expired\n", + "\n", + " # Emit warnings for deprecated attributes\n", + " try:\n", + " val, msg = __deprecated_attrs__[attr]\n", + " except KeyError:\n", + " pass\n", + " else:\n", + " warnings.warn(msg, DeprecationWarning, stacklevel=2)\n", + " return val\n", + "\n", + " if attr in __future_scalars__:\n", + " # And future warnings for those that will change, but also give\n", + " # the AttributeError\n", + " warnings.warn(\n", + " f\"In the future `np.{attr}` will be defined as the \"\n", + " \"corresponding NumPy scalar.\", FutureWarning, stacklevel=2)\n", + "\n", + " if attr in __former_attrs__:\n", + " raise AttributeError(__former_attrs__[attr])\n", + "\n", + " if attr == 'testing':\n", + " import numpy.testing as testing\n", + " return testing\n", + " elif attr == 'Tester':\n", + " \"Removed in NumPy 1.25.0\"\n", + " raise RuntimeError(\"Tester was removed in NumPy 1.25.\")\n", + "\n", + " raise AttributeError(\"module {!r} has no attribute \"\n", + " \"{!r}\".format(__name__, attr))\n", + "\n", + " def __dir__():\n", + " public_symbols = globals().keys() | {'testing'}\n", + " public_symbols -= {\n", + " \"core\", \"matrixlib\",\n", + " # These were moved in 1.25 and may be deprecated eventually:\n", + " \"ModuleDeprecationWarning\", \"VisibleDeprecationWarning\",\n", + " \"ComplexWarning\", \"TooHardError\", \"AxisError\"\n", + " }\n", + " return list(public_symbols)\n", + "\n", + " # Pytest testing\n", + " from numpy._pytesttester import PytestTester\n", + " test = PytestTester(__name__)\n", + " del PytestTester\n", + "\n", + " def _sanity_check():\n", + " \"\"\"\n", + " Quick sanity checks for common bugs caused by environment.\n", + " There are some cases e.g. with wrong BLAS ABI that cause wrong\n", + " results under specific runtime conditions that are not necessarily\n", + " achieved during test suite runs, and it is useful to catch those early.\n", + "\n", + " See https://github.com/numpy/numpy/issues/8577 and other\n", + " similar bug reports.\n", + "\n", + " \"\"\"\n", + " try:\n", + " x = ones(2, dtype=float32)\n", + " if not abs(x.dot(x) - float32(2.0)) < 1e-5:\n", + " raise AssertionError()\n", + " except AssertionError:\n", + " msg = (\"The current Numpy installation ({!r}) fails to \"\n", + " \"pass simple sanity checks. This can be caused for example \"\n", + " \"by incorrect BLAS library being linked in, or by mixing \"\n", + " \"package managers (pip, conda, apt, ...). Search closed \"\n", + " \"numpy issues for similar problems.\")\n", + " raise RuntimeError(msg.format(__file__)) from None\n", + "\n", + " _sanity_check()\n", + " del _sanity_check\n", + "\n", + " def _mac_os_check():\n", + " \"\"\"\n", + " Quick Sanity check for Mac OS look for accelerate build bugs.\n", + " Testing numpy polyfit calls init_dgelsd(LAPACK)\n", + " \"\"\"\n", + " try:\n", + " c = array([3., 2., 1.])\n", + " x = linspace(0, 2, 5)\n", + " y = polyval(c, x)\n", + " _ = polyfit(x, y, 2, cov=True)\n", + " except ValueError:\n", + " pass\n", + "\n", + " if sys.platform == \"darwin\":\n", + " with warnings.catch_warnings(record=True) as w:\n", + " _mac_os_check()\n", + " # Throw runtime error, if the test failed Check for warning and error_message\n", + " error_message = \"\"\n", + " if len(w) > 0:\n", + " error_message = \"{}: {}\".format(w[-1].category.__name__, str(w[-1].message))\n", + " msg = (\n", + " \"Polyfit sanity test emitted a warning, most likely due \"\n", + " \"to using a buggy Accelerate backend.\"\n", + " \"\\nIf you compiled yourself, more information is available at:\"\n", + " \"\\nhttps://numpy.org/doc/stable/user/building.html#accelerated-blas-lapack-libraries\"\n", + " \"\\nOtherwise report this to the vendor \"\n", + " \"that provided NumPy.\\n{}\\n\".format(error_message))\n", + " raise RuntimeError(msg)\n", + " del _mac_os_check\n", + "\n", + " # We usually use madvise hugepages support, but on some old kernels it\n", + " # is slow and thus better avoided.\n", + " # Specifically kernel version 4.6 had a bug fix which probably fixed this:\n", + " # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff\n", + " import os\n", + " use_hugepage = os.environ.get(\"NUMPY_MADVISE_HUGEPAGE\", None)\n", + " if sys.platform == \"linux\" and use_hugepage is None:\n", + " # If there is an issue with parsing the kernel version,\n", + " # set use_hugepages to 0. Usage of LooseVersion will handle\n", + " # the kernel version parsing better, but avoided since it\n", + " # will increase the import time. See: #16679 for related discussion.\n", + " try:\n", + " use_hugepage = 1\n", + " kernel_version = os.uname().release.split(\".\")[:2]\n", + " kernel_version = tuple(int(v) for v in kernel_version)\n", + " if kernel_version < (4, 6):\n", + " use_hugepage = 0\n", + " except ValueError:\n", + " use_hugepages = 0\n", + " elif use_hugepage is None:\n", + " # This is not Linux, so it should not matter, just enable anyway\n", + " use_hugepage = 1\n", + " else:\n", + " use_hugepage = int(use_hugepage)\n", + "\n", + " # Note that this will currently only make a difference on Linux\n", + " core.multiarray._set_madvise_hugepage(use_hugepage)\n", + " del use_hugepage\n", + "\n", + " # Give a warning if NumPy is reloaded or imported on a sub-interpreter\n", + " # We do this from python, since the C-module may not be reloaded and\n", + " # it is tidier organized.\n", + " core.multiarray._multiarray_umath._reload_guard()\n", + "\n", + " # default to \"weak\" promotion for \"NumPy 2\".\n", + " core._set_promotion_state(\n", + " os.environ.get(\"NPY_PROMOTION_STATE\",\n", + " \"weak\" if _using_numpy2_behavior() else \"legacy\"))\n", + "\n", + " # Tell PyInstaller where to find hook-numpy.py\n", + " def _pyinstaller_hooks_dir():\n", + " from pathlib import Path\n", + " return [str(Path(__file__).with_name(\"_pyinstaller\").resolve())]\n", + "\n", + " # Remove symbols imported for internal use\n", + " del os\n", + "\n", + "\n", + "# Remove symbols imported for internal use\n", + "del sys, warnings\n", + "\n" + ] + } + ], "source": [ "import numpy as np\n", "import inspect\n", @@ -750,9 +1560,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 49, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], "source": [ "import math\n", "import inspect\n", @@ -786,9 +1604,19 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 50, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "callable(print) = True\n", + "callable(len) = True\n", + "callable(any) = True\n" + ] + } + ], "source": [ "print(f\"{callable(print) = }\")\n", "print(f\"{callable(len) = }\")\n", @@ -804,9 +1632,18 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 51, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "callable(str.upper) = True\n", + "callable(list.append) = True\n" + ] + } + ], "source": [ "print(f\"{callable(str.upper) = }\")\n", "print(f\"{callable(list.append) = }\")" @@ -821,9 +1658,18 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 52, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "callable(add) = True\n", + "callable(mul) = True\n" + ] + } + ], "source": [ "def add(num1, num2):\n", " return num1 + num2\n", @@ -846,9 +1692,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 53, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "callable(Counter) = True\n", + "callable(Counter.current) = True\n", + "callable(counter.current) = True\n", + "callable(counter) = True\n" + ] + } + ], "source": [ "class Counter:\n", " def __init__(self):\n", @@ -879,9 +1736,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 54, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 54, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "def square():\n", " for i in range(10):\n", @@ -904,7 +1772,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 55, "metadata": {}, "outputs": [], "source": [ @@ -922,7 +1790,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 56, "metadata": {}, "outputs": [], "source": [ @@ -937,7 +1805,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 57, "metadata": {}, "outputs": [], "source": [ @@ -954,18 +1822,37 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 58, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "hex(id(add)) = '0x19624a1ea20'\n" + ] + } + ], "source": [ "print(f\"{hex(id(add)) = }\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 59, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "add(2, 3)" ] @@ -979,7 +1866,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 60, "metadata": {}, "outputs": [], "source": [ @@ -988,18 +1875,35 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 61, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "hex(id(add)) = '0x1962477fc40'\n" + ] + } + ], "source": [ "print(f\"{hex(id(add)) = }\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 62, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "add.__code__.co_freevars = ('func',)\n", + "add.__closure__ = (,)\n" + ] + } + ], "source": [ "print(f\"{add.__code__.co_freevars = }\")\n", "print(f\"{add.__closure__ = }\")" @@ -1014,16 +1918,34 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 63, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Caling add with args = (2, 3) and kwargs = {}\n" + ] + }, + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 63, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "add(2, 3)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 64, "metadata": {}, "outputs": [], "source": [ @@ -1034,7 +1956,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 65, "metadata": {}, "outputs": [], "source": [ @@ -1043,9 +1965,18 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 66, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Caling gravitational_force with args = (5.972e+24, 7.3477e+22) and kwargs = {'distance': 384400000.0}\n", + "The gravitational force between the Earth and the Moon is 1.98e+20 Newtons.\n" + ] + } + ], "source": [ "mass1 = 5.972e24 # Mass of the Earth in kilograms\n", "mass2 = 7.3477e22 # Mass of the Moon in kilograms\n", @@ -1057,7 +1988,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 67, "metadata": {}, "outputs": [], "source": [ @@ -1074,9 +2005,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 68, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Caling add with args = (2, 3) and kwargs = {}\n" + ] + }, + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "add(2, 3)" ] @@ -1104,25 +2053,47 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 69, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'call'" + ] + }, + "execution_count": 69, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "add.__name__ # name should have been 'add'" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 70, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on function call in module __main__:\n", + "\n", + "call(*args, **kwargs)\n", + "\n" + ] + } + ], "source": [ "help(add) # docstring as well as original function signature is also lost" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 71, "metadata": {}, "outputs": [], "source": [ @@ -1146,7 +2117,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 72, "metadata": {}, "outputs": [], "source": [ @@ -1165,7 +2136,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 73, "metadata": {}, "outputs": [], "source": [ @@ -1176,18 +2147,40 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 74, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'add'" + ] + }, + "execution_count": 74, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "add.__name__" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 75, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on function add in module __main__:\n", + "\n", + "add(num1, num2)\n", + "\n" + ] + } + ], "source": [ "help(add)" ] @@ -1203,9 +2196,21 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 76, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Running S3 cycle\n", + "Running S3 cycle\n", + "Running S3 cycle\n", + "Running S3 cycle\n", + "Running S3 cycle\n" + ] + } + ], "source": [ "def run_multiple_times(func, num_times):\n", " def wrapper(*args, **kwargs):\n", @@ -1233,13 +2238,25 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 77, "metadata": { "tags": [ "raises-exception" ] }, - "outputs": [], + "outputs": [ + { + "ename": "TypeError", + "evalue": "run_multiple_times() missing 1 required positional argument: 'num_times'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32mc:\\Users\\bhmiller\\OneDrive - Intel Corporation\\Documents\\GitHub\\intermediate-python\\content\\05_other_functions_concepts.ipynb Cell 116\u001b[0m line \u001b[0;36m1\n\u001b[1;32m----> 1\u001b[0m \u001b[39m@run_multiple_times\u001b[39m(\u001b[39m5\u001b[39;49m)\n\u001b[0;32m 2\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mrun_s3_cycle\u001b[39m():\n\u001b[0;32m 3\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39m\"\u001b[39m\u001b[39mRunning S3 cycle\u001b[39m\u001b[39m\"\u001b[39m)\n\u001b[0;32m 6\u001b[0m run_s3_cycle()\n", + "\u001b[1;31mTypeError\u001b[0m: run_multiple_times() missing 1 required positional argument: 'num_times'" + ] + } + ], "source": [ "@run_multiple_times(5)\n", "def run_s3_cycle():\n", @@ -1251,20 +2268,32 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 78, "metadata": {}, - "outputs": [], + "outputs": [ + { + "ename": "TypeError", + "evalue": "run_multiple_times() missing 1 required positional argument: 'num_times'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32mc:\\Users\\bhmiller\\OneDrive - Intel Corporation\\Documents\\GitHub\\intermediate-python\\content\\05_other_functions_concepts.ipynb Cell 117\u001b[0m line \u001b[0;36m1\n\u001b[1;32m----> 1\u001b[0m decorator \u001b[39m=\u001b[39m run_multiple_times(\u001b[39m5\u001b[39;49m) \u001b[39m# This should return the run_multiple_times with parameter num_times parameter set to 5\u001b[39;00m\n\u001b[0;32m 3\u001b[0m \u001b[39m@decorator\u001b[39m\n\u001b[0;32m 4\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mrun_s3_cycle\u001b[39m():\n\u001b[0;32m 5\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39m\"\u001b[39m\u001b[39mRunning S3 cycle\u001b[39m\u001b[39m\"\u001b[39m)\n", + "\u001b[1;31mTypeError\u001b[0m: run_multiple_times() missing 1 required positional argument: 'num_times'" + ] + } + ], "source": [ - "# decorator = run_multiple_times(5) # This should return the run_multiple_times with parameter num_times parameter set to 5\n", + "decorator = run_multiple_times(5) # This should return the run_multiple_times with parameter num_times parameter set to 5\n", "\n", - "# @decorator\n", - "# def run_s3_cycle():\n", - "# print(\"Running S3 cycle\")" + "@decorator\n", + "def run_s3_cycle():\n", + " print(\"Running S3 cycle\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 79, "metadata": {}, "outputs": [], "source": [ @@ -1286,9 +2315,21 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 80, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Running S3 cycle\n", + "Running S3 cycle\n", + "Running S3 cycle\n", + "Running S3 cycle\n", + "Running S3 cycle\n" + ] + } + ], "source": [ "def run_s3_cycle():\n", " print(\"Running S3 cycle\")\n", @@ -1302,17 +2343,28 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "This is often time refer to as [**Currying**](https://en.wikipedia.org/wiki/Currying)" + "This is an instance of [**Currying**](https://en.wikipedia.org/wiki/Currying)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 83, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Running S3 cycle\n", + "Running S3 cycle\n", + "Running S3 cycle\n", + "Running S3 cycle\n", + "Running S3 cycle\n" + ] + } + ], "source": [ "@run_multiple_times(5)\n", - "# @inner_decorator\n", "def run_s3_cycle():\n", " print(\"Running S3 cycle\")\n", "\n", @@ -1324,7 +2376,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "`run_multiple_times` is generally refered to as `decorator factory` since it generates a decorator." + "`run_multiple_times` is generally refered to as a `decorator factory` since it generates a decorator." ] }, { @@ -1336,7 +2388,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 84, "metadata": {}, "outputs": [], "source": [ @@ -1351,9 +2403,22 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 85, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Doing some computation for num1 = 3 and num2 =5\n", + "some_computational_task(3, 5) = 8\n", + "Doing some computation for num1 = 3 and num2 =5\n", + "some_computational_task(3, 5) = 8\n", + "Doing some computation for num1 = 3 and num2 =5\n", + "some_computational_task(3, 5) = 8\n" + ] + } + ], "source": [ "print(f\"{some_computational_task(3, 5) = }\")\n", "print(f\"{some_computational_task(3, 5) = }\")\n", @@ -1362,7 +2427,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 86, "metadata": {}, "outputs": [], "source": [ @@ -1386,7 +2451,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 87, "metadata": {}, "outputs": [], "source": [ @@ -1399,9 +2464,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 88, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Doing some computation for num1 = 3 and num2 =5\n", + "some_computational_task(3, 5) = 8\n", + "some_computational_task(3, 5) = 8\n", + "some_computational_task(3, 5) = 8\n" + ] + } + ], "source": [ "print(f\"{some_computational_task(3, 5) = }\")\n", "print(f\"{some_computational_task(3, 5) = }\")\n", @@ -1441,7 +2517,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.4" + "version": "3.11.6" } }, "nbformat": 4, diff --git a/content/06_sequence_iterators_and_generators.ipynb b/content/06_sequence_iterators_and_generators.ipynb index 6478960..d021498 100644 --- a/content/06_sequence_iterators_and_generators.ipynb +++ b/content/06_sequence_iterators_and_generators.ipynb @@ -30,14 +30,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Sequence support `membership operator` (`in` and `not in`)" + "Sequences support `membership operator` (`in` and `not in`)" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1 in numbers = True\n", + "10 not in numbers = True\n" + ] + } + ], "source": [ "numbers = [1, 2, 3, 4, 5]\n", "\n", @@ -49,14 +58,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Sequence support `concatenation`" + "Sequences support `concatenation`" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n" + ] + } + ], "source": [ "numbers1 = [1, 2, 3, 4, 5]\n", "numbers2 = [6, 7, 8, 9, 10]\n", @@ -68,14 +85,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Sequence support `repetition`" + "Sequences support `repetition`" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]\n" + ] + } + ], "source": [ "numbers1 = [1, 2, 3, 4, 5]\n", "\n", @@ -86,14 +111,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Sequence support built-in functions like `len`, `min`, `max` etc." + "Sequences support built-in functions like `len`, `min`, `max` etc." ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "len(numbers) = 5\n", + "min(numbers) = 1\n", + "max(numbers) = 5\n" + ] + } + ], "source": [ "numbers1 = [1, 2, 3, 4, 5]\n", "\n", @@ -106,14 +141,24 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Sequence are `indexable`" + "Sequences are `index`able" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Index of first 1: numbers.index(1) = 0\n", + "Index of first 1, at or after index 1: numbers.index(1, 1) = 2\n", + "Index of first 3, at or after index 4 and before 12: numbers.index(3, 4, 12) = 8\n" + ] + } + ], "source": [ "numbers = [1, 2, 1, 3, 5, 7, 2, 9, 3, 7, 3, 4, 5]\n", "\n", @@ -128,14 +173,25 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Sequence can be `slice`" + "Sequences can be `slice`d" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "numbers[2] = 1\n", + "numbers[2:10] = [1, 3, 5, 7, 2, 9, 3, 7]\n", + "numbers[2:10:3] = [1, 7, 3]\n", + "numbers[-1] = 5\n" + ] + } + ], "source": [ "numbers = [1, 2, 1, 3, 5, 7, 2, 9, 3, 7, 3, 4, 5]\n", "\n", @@ -163,7 +219,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "metadata": {}, "outputs": [], "source": [ @@ -174,31 +230,68 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], "source": [ "print(type(number_iterator))" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], "source": [ "print(number_iterator)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, "metadata": { "tags": [ "raises-exception" ] }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n" + ] + }, + { + "ename": "StopIteration", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mStopIteration\u001b[0m Traceback (most recent call last)", + "\u001b[1;32mc:\\Users\\bhmiller\\OneDrive - Intel Corporation\\Documents\\GitHub\\intermediate-python\\content\\06_sequence_iterators_and_generators.ipynb Cell 20\u001b[0m line \u001b[0;36m4\n\u001b[0;32m 2\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mnext\u001b[39m(number_iterator))\n\u001b[0;32m 3\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mnext\u001b[39m(number_iterator))\n\u001b[1;32m----> 4\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mnext\u001b[39;49m(number_iterator))\n", + "\u001b[1;31mStopIteration\u001b[0m: " + ] + } + ], "source": [ "print(next(number_iterator))\n", "print(next(number_iterator))\n", @@ -208,9 +301,19 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n" + ] + } + ], "source": [ "numbers = [1, 2, 3]\n", "\n", @@ -229,9 +332,19 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n" + ] + } + ], "source": [ "number_iterator = iter(numbers)\n", "\n", @@ -250,7 +363,9 @@ "source": [ "**Creating custom iterator**\n", "\n", - "Generally custom iterator are created using class and you will define an `__iter__` method and a `__next__` method.\n", + "You may want to support a custom iterator for your class. To do this, you define an `__iter__` method and a `__next__` method.\n", + "\n", + "As Python is duck typed, any class that supplies suitable definitions for `__iter__` and `__next__` can be passed to any operation that expects to iterate over a sequence.\n", "\n", "While defining an iterator you might want to raise `StopIteration` once you reach a certain condition. This is what is used by `for` to stop calling next over the iterator object.\n", "\n", @@ -259,7 +374,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 17, "metadata": {}, "outputs": [], "source": [ @@ -284,9 +399,21 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "2\n", + "4\n", + "6\n", + "8\n" + ] + } + ], "source": [ "for item in MyRangeIterator(0, 10, 2):\n", " print(item)" @@ -296,14 +423,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "You can also have infinite iterator which iterates forever. User have to put bound to make sure they don't end up with infinite loop.\n", + "You can also have infinite iterator which iterates forever. User have to put bound to make sure they don't end up with infinite loop. This can be used to implement [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation).\n", "\n", "Example of creating an infinite iterator which produce square sequence starting from number 1:" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 19, "metadata": {}, "outputs": [], "source": [ @@ -321,9 +448,28 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "4\n", + "9\n", + "16\n", + "25\n", + "36\n", + "49\n", + "64\n", + "81\n", + "100\n", + "121\n", + "144\n" + ] + } + ], "source": [ "square_iterator = SquareIterator()\n", "\n", @@ -358,7 +504,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 21, "metadata": {}, "outputs": [], "source": [ @@ -371,18 +517,37 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], "source": [ "print(type(square_generator()))" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "4\n", + "9\n", + "16\n" + ] + } + ], "source": [ "sq = square_generator()\n", "print(next(sq))\n", @@ -393,9 +558,28 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "4\n", + "9\n", + "16\n", + "25\n", + "36\n", + "49\n", + "64\n", + "81\n", + "100\n", + "121\n", + "144\n" + ] + } + ], "source": [ "for number in square_generator():\n", " if number > 150:\n", @@ -425,9 +609,31 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Dataset 1 - Data point 1\n", + "Dataset 1 - Data point 2\n", + "Dataset 1 - Data point 3\n", + "Dataset 1 - Data point 4\n", + "Dataset 1 - Data point 5\n", + "Dataset 2 - Data point 6\n", + "Dataset 2 - Data point 7\n", + "Dataset 2 - Data point 8\n", + "Dataset 2 - Data point 9\n", + "Dataset 2 - Data point 10\n", + "Dataset 3 - Data point 11\n", + "Dataset 3 - Data point 12\n", + "Dataset 3 - Data point 13\n", + "Dataset 3 - Data point 14\n", + "Dataset 3 - Data point 15\n" + ] + } + ], "source": [ "def dataset1():\n", " for i in range(1, 6):\n", @@ -464,9 +670,18 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Memory usage for infinite square generator: 192 bytes\n", + "Memory usage for infinite square iterator: 56 bytes\n" + ] + } + ], "source": [ "import sys\n", "\n", @@ -489,9 +704,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "67.6 ns ± 1.61 ns per loop (mean ± std. dev. of 5 runs, 100,000 loops each)\n" + ] + } + ], "source": [ "gen = square_generator()\n", "%timeit -n 100000 -r 5 next(gen)" @@ -499,9 +722,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "88.2 ns ± 1.41 ns per loop (mean ± std. dev. of 5 runs, 100,000 loops each)\n" + ] + } + ], "source": [ "it = SquareIterator()\n", "%timeit -n 100000 -r 5 next(it)" @@ -532,9 +763,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Total Sales: 650\n" + ] + } + ], "source": [ "daily_sales = [100, 150, 120, 80, 200]\n", "total_sales = sum(daily_sales)\n", @@ -551,9 +790,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Highest Temperature: 30\n" + ] + } + ], "source": [ "weekly_temperatures = [24, 27, 25, 28, 26, 22, 30]\n", "highest_temperature = max(weekly_temperatures)\n", @@ -570,9 +817,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Lowest Score: 68\n" + ] + } + ], "source": [ "quiz_scores = [85, 72, 90, 68, 78]\n", "lowest_score = min(quiz_scores)\n", @@ -589,9 +844,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Has Overtime: True\n" + ] + } + ], "source": [ "overtime_hours = [0, 0, 0, 3, 1, 0]\n", "has_overtime = any(overtime_hours)\n", @@ -608,9 +871,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "All Passed: False\n" + ] + } + ], "source": [ "exam_results = [True, True, False, True, True]\n", "all_passed = all(exam_results)\n", @@ -627,9 +898,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number of Students: 5\n" + ] + } + ], "source": [ "students = [\"Alice\", \"Bob\", \"Charlie\", \"David\", \"Eva\"]\n", "num_students = len(students)\n", @@ -654,9 +933,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Year: 2023, Month: 07, Day: 15\n" + ] + } + ], "source": [ "date_str = \"2023-07-15\"\n", "year_slice = slice(0, 4)\n", @@ -679,13 +966,25 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 36, "metadata": { "tags": [ "raises-exception" ] }, - "outputs": [], + "outputs": [ + { + "ename": "TypeError", + "evalue": "'slice' object is not iterable", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32mc:\\Users\\bhmiller\\OneDrive - Intel Corporation\\Documents\\GitHub\\intermediate-python\\content\\06_sequence_iterators_and_generators.ipynb Cell 61\u001b[0m line \u001b[0;36m4\n\u001b[0;32m 1\u001b[0m numbers \u001b[39m=\u001b[39m SquareIterator()\n\u001b[0;32m 2\u001b[0m first_5_square \u001b[39m=\u001b[39m \u001b[39mslice\u001b[39m(numbers, \u001b[39m5\u001b[39m)\n\u001b[1;32m----> 4\u001b[0m \u001b[39mfor\u001b[39;49;00m num \u001b[39min\u001b[39;49;00m first_5_square:\n\u001b[0;32m 5\u001b[0m \u001b[39mprint\u001b[39;49m(num)\n", + "\u001b[1;31mTypeError\u001b[0m: 'slice' object is not iterable" + ] + } + ], "source": [ "numbers = SquareIterator()\n", "first_5_square = slice(numbers, 5)\n", @@ -704,9 +1003,27 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "4\n", + "9\n", + "16\n", + "25\n", + "********************\n", + "36\n", + "49\n", + "64\n", + "81\n", + "100\n" + ] + } + ], "source": [ "from itertools import islice\n", "\n", @@ -743,9 +1060,21 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "4\n", + "6\n", + "8\n", + "10\n" + ] + } + ], "source": [ "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", "\n", @@ -768,9 +1097,19 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "banana\n", + "orange\n", + "watermelon\n" + ] + } + ], "source": [ "from itertools import filterfalse\n", "\n", @@ -790,9 +1129,19 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "90\n", + "92\n", + "95\n" + ] + } + ], "source": [ "from functools import partial\n", "\n", @@ -818,9 +1167,19 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n" + ] + } + ], "source": [ "from itertools import takewhile\n", "\n", @@ -844,9 +1203,19 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 44, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n", + "5\n", + "6\n" + ] + } + ], "source": [ "from itertools import dropwhile\n", "\n", @@ -870,9 +1239,19 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 45, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "3\n", + "5\n" + ] + } + ], "source": [ "from itertools import compress\n", "\n", @@ -901,9 +1280,20 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 47, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Item: apple, ID: 1\n", + "Item: banana, ID: 2\n", + "Item: orange, ID: 3\n", + "Item: grape, ID: 4\n" + ] + } + ], "source": [ "import itertools\n", "\n", @@ -931,9 +1321,24 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 48, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Task: Task A, Assigned to: John\n", + "Task: Task B, Assigned to: Alice\n", + "Task: Task C, Assigned to: Bob\n", + "Task: Task D, Assigned to: John\n", + "Task: Task E, Assigned to: Alice\n", + "Task: Task F, Assigned to: Bob\n", + "Task: Task G, Assigned to: John\n", + "Task: Task H, Assigned to: Alice\n" + ] + } + ], "source": [ "import itertools\n", "\n", @@ -962,9 +1367,19 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 49, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, World!\n", + "Hello, World!\n", + "Hello, World!\n" + ] + } + ], "source": [ "import itertools\n", "\n", @@ -992,7 +1407,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 50, "metadata": {}, "outputs": [], "source": [ @@ -1007,9 +1422,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 52, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[('Apple', 370), ('Banana', 240), ('Orange', 600), ('Grapes', 210)]\n" + ] + } + ], "source": [ "# Using map() to calculate the total sales for each product\n", "total_sales_map = map(\n", @@ -1019,10 +1442,25 @@ ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "metadata": {}, - "outputs": [], + "source": [ + "`starmap` is like `map`, but it applies the * to the iterable content before calling the function. It's commonly used with `reduce`:" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[('Apple', 370), ('Banana', 240), ('Orange', 600), ('Grapes', 210)]\n" + ] + } + ], "source": [ "from itertools import starmap\n", "from functools import reduce\n", @@ -1042,9 +1480,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 57, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1420\n" + ] + } + ], "source": [ "from functools import reduce\n", "\n", @@ -1058,9 +1504,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 55, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 3, 6, 10, 15]\n" + ] + } + ], "source": [ "from itertools import accumulate\n", "\n", @@ -1088,9 +1542,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 58, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n" + ] + } + ], "source": [ "from itertools import chain\n", "\n", @@ -1112,9 +1574,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 59, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5, 6, 7, 8, 9]\n" + ] + } + ], "source": [ "from itertools import chain\n", "\n", @@ -1134,9 +1604,26 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 60, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Iterator 1: 1\n", + "Iterator 1: 2\n", + "Iterator 1: 3\n", + "Iterator 1: 4\n", + "Iterator 1: 5\n", + "Iterator 2: 1\n", + "Iterator 2: 2\n", + "Iterator 2: 3\n", + "Iterator 2: 4\n", + "Iterator 2: 5\n" + ] + } + ], "source": [ "from itertools import tee\n", "\n", @@ -1172,9 +1659,20 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 61, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Students with grade A: ['Bob', 'Frank']\n", + "Students with grade B: ['Alice']\n", + "Students with grade C: ['Charlie', 'Eva']\n", + "Students with grade D: ['David']\n" + ] + } + ], "source": [ "from itertools import groupby\n", "\n", @@ -1221,9 +1719,17 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 62, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "defaultdict(, {'Lorem': 2, 'ipsum': 2, 'dolor': 1, 'sit': 1, 'amet': 1, 'consectetur': 1, 'adipiscing': 1, 'elit': 1, 'ipsum.': 1})\n" + ] + } + ], "source": [ "from collections import defaultdict\n", "\n", @@ -1254,9 +1760,22 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 63, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "abc\n", + "acb\n", + "bac\n", + "bca\n", + "cab\n", + "cba\n" + ] + } + ], "source": [ "from itertools import permutations\n", "\n", @@ -1276,9 +1795,19 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 64, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "('red', 'green')\n", + "('red', 'blue')\n", + "('green', 'blue')\n" + ] + } + ], "source": [ "from itertools import combinations\n", "\n", @@ -1298,9 +1827,20 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], + "execution_count": 65, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(1, 'A')\n", + "(1, 'B')\n", + "(2, 'A')\n", + "(2, 'B')\n" + ] + } + ], "source": [ "from itertools import product\n", "\n", @@ -1335,7 +1875,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.4" + "version": "3.11.6" } }, "nbformat": 4, diff --git a/content/07_context_managers.ipynb b/content/07_context_managers.ipynb index f44f855..cff8878 100644 --- a/content/07_context_managers.ipynb +++ b/content/07_context_managers.ipynb @@ -33,7 +33,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "metadata": {}, "outputs": [], "source": [ @@ -46,9 +46,103 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/html": [ + "
Hello there\n",
+       "
\n" + ], + "text/latex": [ + "\\begin{Verbatim}[commandchars=\\\\\\{\\}]\n", + "Hello there\n", + "\\end{Verbatim}\n" + ], + "text/plain": [ + "Hello there" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "from IPython.display import Code\n", "\n", @@ -57,7 +151,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": {}, "outputs": [], "source": [ @@ -68,9 +162,103 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/html": [ + "
Hello there\n",
+       "
\n" + ], + "text/latex": [ + "\\begin{Verbatim}[commandchars=\\\\\\{\\}]\n", + "Hello there\n", + "\\end{Verbatim}\n" + ], + "text/plain": [ + "Hello there" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "Code(filename=\"static/file1.txt\")" ] @@ -88,7 +276,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "metadata": {}, "outputs": [], "source": [ @@ -99,25 +287,213 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 9, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/html": [ + "
Hello from file1\n",
+       "
\n" + ], + "text/latex": [ + "\\begin{Verbatim}[commandchars=\\\\\\{\\}]\n", + "Hello from file1\n", + "\\end{Verbatim}\n" + ], + "text/plain": [ + "Hello from file1" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "Code(filename=\"static/file1.txt\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/html": [ + "
Hello from file2\n",
+       "
\n" + ], + "text/latex": [ + "\\begin{Verbatim}[commandchars=\\\\\\{\\}]\n", + "Hello from file2\n", + "\\end{Verbatim}\n" + ], + "text/plain": [ + "Hello from file2" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "Code(filename=\"static/file2.txt\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "metadata": {}, "outputs": [], "source": [ @@ -136,7 +512,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 12, "metadata": {}, "outputs": [], "source": [ @@ -155,9 +531,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 13, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "inside __init__\n", + "inside __enter__\n", + "x = 1, y = 2, z = 3\n", + "inside __exit__\n" + ] + } + ], "source": [ "with CtxMng() as (x, y, z):\n", " print(f\"{x = }, {y = }, {z = }\")" @@ -179,7 +566,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, "metadata": {}, "outputs": [], "source": [ @@ -197,9 +584,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "

some text

" + ] + } + ], "source": [ "with HTMLTag(\"p\"):\n", " print(\"some text\", end=\"\")" @@ -207,9 +602,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "

some bold text

" + ] + } + ], "source": [ "with HTMLTag(\"p\"):\n", " print(\"some \", end=\"\")\n", @@ -234,7 +637,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 17, "metadata": {}, "outputs": [], "source": [ @@ -260,9 +663,21 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 18, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "inside __init__\n", + "inside __enter__\n", + "x = 1, y = 2, z = 3\n", + "inside __exit__\n", + "Not suppressing exc_value = None\n" + ] + } + ], "source": [ "with CtxMng() as (x, y, z):\n", " print(f\"{x = }, {y = }, {z = }\")" @@ -270,9 +685,21 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 19, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "inside __init__\n", + "inside __enter__\n", + "x = 1, y = 2, z = 3\n", + "inside __exit__\n", + "Supressing exc_value = TypeError()\n" + ] + } + ], "source": [ "with CtxMng() as (x, y, z):\n", " print(f\"{x = }, {y = }, {z = }\")\n", @@ -281,13 +708,36 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 20, "metadata": { "tags": [ "raises-exception" ] }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "inside __init__\n", + "inside __enter__\n", + "x = 1, y = 2, z = 3\n", + "inside __exit__\n", + "Not suppressing exc_value = ValueError()\n" + ] + }, + { + "ename": "ValueError", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32mc:\\Users\\bhmiller\\OneDrive - Intel Corporation\\Documents\\GitHub\\intermediate-python\\content\\07_context_managers.ipynb Cell 25\u001b[0m line \u001b[0;36m3\n\u001b[0;32m 1\u001b[0m \u001b[39mwith\u001b[39;00m CtxMng() \u001b[39mas\u001b[39;00m (x, y, z):\n\u001b[0;32m 2\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m{\u001b[39;00mx\u001b[39m \u001b[39m\u001b[39m= }\u001b[39;00m\u001b[39m, \u001b[39m\u001b[39m{\u001b[39;00my\u001b[39m \u001b[39m\u001b[39m= }\u001b[39;00m\u001b[39m, \u001b[39m\u001b[39m{\u001b[39;00mz\u001b[39m \u001b[39m\u001b[39m= }\u001b[39;00m\u001b[39m\"\u001b[39m)\n\u001b[1;32m----> 3\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m()\n", + "\u001b[1;31mValueError\u001b[0m: " + ] + } + ], "source": [ "with CtxMng() as (x, y, z):\n", " print(f\"{x = }, {y = }, {z = }\")\n", @@ -359,7 +809,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 21, "metadata": {}, "outputs": [], "source": [ @@ -385,7 +835,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 22, "metadata": {}, "outputs": [], "source": [ @@ -411,9 +861,19 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 23, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "before yield\n", + "x = 1, y = 2, z = 3\n", + "cleanup\n" + ] + } + ], "source": [ "with ctx_mng() as (x, y, z):\n", " print(f\"{x = }, {y = }, {z = }\")" @@ -421,9 +881,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 24, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "before yield\n", + "x = 1, y = 2, z = 3\n", + "Supressing exc_value = TypeError()\n", + "cleanup\n" + ] + } + ], "source": [ "with ctx_mng() as (x, y, z):\n", " print(f\"{x = }, {y = }, {z = }\")\n", @@ -432,13 +903,34 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 25, "metadata": { "tags": [ "raises-exception" ] }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "before yield\n", + "x = 1, y = 2, z = 3\n", + "cleanup\n" + ] + }, + { + "ename": "ValueError", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32mc:\\Users\\bhmiller\\OneDrive - Intel Corporation\\Documents\\GitHub\\intermediate-python\\content\\07_context_managers.ipynb Cell 32\u001b[0m line \u001b[0;36m3\n\u001b[0;32m 1\u001b[0m \u001b[39mwith\u001b[39;00m ctx_mng() \u001b[39mas\u001b[39;00m (x, y, z):\n\u001b[0;32m 2\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m{\u001b[39;00mx\u001b[39m \u001b[39m\u001b[39m= }\u001b[39;00m\u001b[39m, \u001b[39m\u001b[39m{\u001b[39;00my\u001b[39m \u001b[39m\u001b[39m= }\u001b[39;00m\u001b[39m, \u001b[39m\u001b[39m{\u001b[39;00mz\u001b[39m \u001b[39m\u001b[39m= }\u001b[39;00m\u001b[39m\"\u001b[39m)\n\u001b[1;32m----> 3\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m()\n", + "\u001b[1;31mValueError\u001b[0m: " + ] + } + ], "source": [ "with ctx_mng() as (x, y, z):\n", " print(f\"{x = }, {y = }, {z = }\")\n", @@ -454,9 +946,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 26, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "inside __init__\n", + "inside __enter__\n", + "inside __exit__\n", + "Supressing exc_value = TypeError(\"'int' object does not support the context manager protocol\")\n" + ] + } + ], "source": [ "with CtxMng() as x, y, z:\n", " print(f\"{x = }, {y = }, {z = }\")" @@ -464,9 +967,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 27, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "inside __init__\n", + "inside __enter__\n", + "inside __exit__\n", + "Supressing exc_value = TypeError(\"'int' object does not support the context manager protocol\")\n" + ] + } + ], "source": [ "with CtxMng() as x:\n", " with y:\n", @@ -478,7 +992,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Some Practicle use case example" + "## A practical example use case" ] }, { @@ -490,11 +1004,22 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 28, "metadata": { "tags": [] }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Before entering example os.getcwd() = 'c:\\\\Users\\\\bhmiller\\\\OneDrive - Intel Corporation\\\\Documents\\\\GitHub\\\\intermediate-python\\\\content'\n", + "After entering example os.getcwd() = 'c:\\\\Users\\\\bhmiller\\\\OneDrive - Intel Corporation\\\\Documents\\\\GitHub\\\\intermediate-python\\\\content\\\\example'\n", + "Do something here\n", + "Outside context manager os.getcwd() = 'c:\\\\Users\\\\bhmiller\\\\OneDrive - Intel Corporation\\\\Documents\\\\GitHub\\\\intermediate-python\\\\content'\n" + ] + } + ], "source": [ "from contextlib import contextmanager\n", "import os\n", @@ -535,7 +1060,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 29, "metadata": {}, "outputs": [], "source": [ @@ -560,7 +1085,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 30, "metadata": {}, "outputs": [], "source": [ @@ -581,9 +1106,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 31, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "C:\\Users\\bhmiller\\AppData\\Local\\Temp\\tmpj_sp_5tn\n" + ] + } + ], "source": [ "import tempfile\n", "\n", @@ -600,9 +1133,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 32, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Execution time: 2.0007057189941406 seconds\n" + ] + } + ], "source": [ "import time\n", "from contextlib import contextmanager\n", @@ -647,7 +1188,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.4" + "version": "3.11.6" } }, "nbformat": 4, diff --git a/content/08_argparse.ipynb b/content/08_argparse.ipynb index bba0c71..6c873af 100644 --- a/content/08_argparse.ipynb +++ b/content/08_argparse.ipynb @@ -116,18 +116,53 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 1, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "usage: vm_cli.py [-h] [-c CPU] [-m MEMORY] [-v] [-f] [-t TAGS] --vm-type\n", + " {linux,windows}\n", + " vm_name\n", + "\n", + "positional arguments:\n", + " vm_name Name of virtual machine to be created\n", + "\n", + "options:\n", + " -h, --help show this help message and exit\n", + " -c CPU, --cpu CPU Number of cpu to use. Default to 4 cores\n", + " -m MEMORY, --memory MEMORY\n", + " Amount of memory to use in GB. Default to 8 GB\n", + " -v, --verbose Amount of verbosity in log.\n", + " -f, --force Force creation without confirmation.\n", + " -t TAGS, --tags TAGS Tags for the VM (can be specified multiple times).\n", + " --vm-type {linux,windows}\n", + " Type of VM (linux or windows).\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py --help" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "usage: vm_cli.py [-h] [-c CPU] [-m MEMORY] [-v] [-f] [-t TAGS] --vm-type\n", + " {linux,windows}\n", + " vm_name\n", + "vm_cli.py: error: the following arguments are required: --vm-type\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1" ] @@ -169,36 +204,93 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "usage: vm_cli.py [-h] [-c CPU] [-m MEMORY] [-v] [-f] [-t TAGS] --vm-type\n", + " {linux,windows}\n", + " vm_name\n", + "\n", + "positional arguments:\n", + " vm_name Name of virtual machine to be created\n", + "\n", + "options:\n", + " -h, --help show this help message and exit\n", + " -c CPU, --cpu CPU Number of cpu to use. Default to 4 cores\n", + " -m MEMORY, --memory MEMORY\n", + " Amount of memory to use in GB. Default to 8 GB\n", + " -v, --verbose Amount of verbosity in log.\n", + " -f, --force Force creation without confirmation.\n", + " -t TAGS, --tags TAGS Tags for the VM (can be specified multiple times).\n", + " --vm-type {linux,windows}\n", + " Type of VM (linux or windows).\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py --help" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "usage: vm_cli.py [-h] [-c CPU] [-m MEMORY] [-v] [-f] [-t TAGS] --vm-type\n", + " {linux,windows}\n", + " vm_name\n", + "vm_cli.py: error: the following arguments are required: --vm-type\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "usage: vm_cli.py [-h] [-c CPU] [-m MEMORY] [-v] [-f] [-t TAGS] --vm-type\n", + " {linux,windows}\n", + " vm_name\n", + "vm_cli.py: error: the following arguments are required: --vm-type\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1 -c 32 -m 256" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "usage: vm_cli.py [-h] [-c CPU] [-m MEMORY] [-v] [-f] [-t TAGS] --vm-type\n", + " {linux,windows}\n", + " vm_name\n", + "vm_cli.py: error: argument -c/--cpu: invalid int value: 'x'\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1 -c x -m 256" ] @@ -252,54 +344,135 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'cpu': 4,\n", + " 'force': False,\n", + " 'memory': 8,\n", + " 'tags': [],\n", + " 'verbose': 0,\n", + " 'vm_name': 'vm1',\n", + " 'vm_type': 'windows'}\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1 --vm-type windows" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "usage: vm_cli.py [-h] [-c CPU] [-m MEMORY] [-v] [-f] [-t TAGS] --vm-type\n", + " {linux,windows}\n", + " vm_name\n", + "vm_cli.py: error: argument --vm-type: invalid choice: 'osx' (choose from 'linux', 'windows')\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1 --vm-type osx" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 9, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'cpu': 4,\n", + " 'force': False,\n", + " 'memory': 8,\n", + " 'tags': [],\n", + " 'verbose': 1,\n", + " 'vm_name': 'vm1',\n", + " 'vm_type': 'windows'}\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1 --vm-type windows -v" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'cpu': 4,\n", + " 'force': False,\n", + " 'memory': 8,\n", + " 'tags': [],\n", + " 'verbose': 3,\n", + " 'vm_name': 'vm1',\n", + " 'vm_type': 'windows'}\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1 --vm-type windows -vvv" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'cpu': 4,\n", + " 'force': True,\n", + " 'memory': 8,\n", + " 'tags': [],\n", + " 'verbose': 0,\n", + " 'vm_name': 'vm1',\n", + " 'vm_type': 'windows'}\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1 --vm-type windows -f" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 12, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'cpu': 4,\n", + " 'force': False,\n", + " 'memory': 8,\n", + " 'tags': ['automation', 'windows', 'gen13'],\n", + " 'verbose': 0,\n", + " 'vm_name': 'vm1',\n", + " 'vm_type': 'windows'}\n" + ] + } + ], "source": [ "!python 08_argparse/vm_cli.py vm1 --vm-type windows -t automation -t windows -t gen13" ] @@ -342,54 +515,126 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 13, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "usage: git_cli.py [-h] {add,commit} ...\n", + "\n", + "positional arguments:\n", + " {add,commit}\n", + " add git-add - Add file contents to the index\n", + " commit git-commit - Record changes to the repository\n", + "\n", + "options:\n", + " -h, --help show this help message and exit\n" + ] + } + ], "source": [ "!python 08_argparse/git_cli.py --help" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "usage: git_cli.py add [-h] path\n", + "\n", + "positional arguments:\n", + " path Files or directory to add to add content from\n", + "\n", + "options:\n", + " -h, --help show this help message and exit\n" + ] + } + ], "source": [ "!python 08_argparse/git_cli.py add --help" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "usage: git_cli.py commit [-h] [-a] [-m MESSAGE]\n", + "\n", + "options:\n", + " -h, --help show this help message and exit\n", + " -a, --all Tell the command to automatically stage files that\n", + " have been modified and deleted, but new files you have\n", + " not told Git about are not affected.\n", + " -m MESSAGE, --message MESSAGE\n", + " Use the given as the commit message. If multiple\n", + " -m options are given, their values are concatenated as\n", + " separate paragraphs.\n" + ] + } + ], "source": [ "!python 08_argparse/git_cli.py commit --help" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'cmd': 'add', 'path': '/path1'}\n" + ] + } + ], "source": [ "!python 08_argparse/git_cli.py add /path1" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 17, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'all': False, 'cmd': 'commit', 'message': 'Some message'}\n" + ] + } + ], "source": [ "!python 08_argparse/git_cli.py commit -m \"Some message\"" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 18, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'all': True, 'cmd': 'commit', 'message': 'Some message'}\n" + ] + } + ], "source": [ "!python 08_argparse/git_cli.py commit -a -m \"Some message\"" ] @@ -418,7 +663,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.4" + "version": "3.11.6" } }, "nbformat": 4,