{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[Oregon Curriculum Network](http://www.4dsolutions.net/ocn)
\n", "[Discovering Math with Python](Introduction.ipynb)\n", "\n", "\n", "\n", "# Five Dimensions of Python\n", "\n", "0. Keywords: basic syntax, reserved terms\n", "1. Builtins: available on bootup of Python, no import required\n", "2. Special Names: hooks for tying code to syntax (e.g. obj.attr, obj[index])\n", "3. Standard Library: \"batteries included\"\n", "4. Third Party Packages: vast assortment of libraries, frameworks, distributions\n", "\n", "## Keywords" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield\n" ] } ], "source": [ "from keyword import kwlist\n", "print(\", \".join(kwlist))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Builtins\n", "\n", "When you boot into a Python shell (REPL), you're not entering a blank canvas or blank slate. Lots of names are already defined, and ready for calling or using." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exceptions\n", " ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'NotADirectoryError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError']\n", "------\n", "Callables\n", " ['__build_class__', '__import__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'dreload', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'get_ipython', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']\n", "------\n", "Other\n", " ['Ellipsis', 'False', 'None', 'NotImplemented', 'True', '__IPYTHON__', '__debug__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']\n" ] } ], "source": [ "exceptions, callables, not_callables = [], [], []\n", "for name in dir(__builtins__): # cycle through a bunch of strings\n", " obj = eval(name) # turn strings back into objects\n", " if type(obj) == type and issubclass(obj, BaseException):\n", " exceptions.append(name) # types of exception\n", " elif callable(obj): \n", " callables.append(name) # callable \n", " else:\n", " not_callables.append(name) # whatever is left over\n", " \n", "print(\"Exceptions\\n\", exceptions)\n", "print(\"------\")\n", "print(\"Callables\\n\", callables)\n", "print(\"------\")\n", "print(\"Other\\n\", not_callables)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Special Names\n", "Special names all have a similar look: \\_\\_name\\_\\_\n", "\n", "In other words: two underlines, a name, two underlines. I sometimes think of the special names as the Python's \\_\\_ribs\\_\\_ (snakes have lots of ribs).\n", "\n", "You don't make up or define these special names yourself. They come with the language. Newer versions of Python may have more of them, but within a given version, they're fixed.\n", "\n", "Think of special names as like the strings a puppeteer uses to control marrionettes. Each string goes to a specific aspect of Python's grammar, such as calling an object, getting or setting an object's attribute, getting or setting using index notation (square brackets).\n", "\n", "Many object types come with predefined behaviors for any or all of the above. When you write your own classes, or subclass an existing type, that's when you have the ability to define or override some special name behavior." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A sourpuss is born!\n", "Don't call me at home!\n", "I'm insulted you'd suppose I'd have mood\n", "How dare you touch me with those brackets!\n", "I can't invert, are you kidding?\n", "Don't bother me! Go away.\n" ] } ], "source": [ "\"\"\"\n", "This type of object gets along with nobody!\n", "\n", "or·ner·y\n", "ˈôrn(ə)rē/\n", "adjective North American informal\n", "adjective: ornery\n", "\n", " bad-tempered and combative.\n", " \"some hogs are just mean and ornery\"\n", " synonyms:\tgrouchy, grumpy, cranky, crotchety, cantankerous, bad-tempered, \n", " ill-tempered, dyspeptic, irascible, waspish\n", " \n", "自 = self in Chinese (showing that self is not a keyword, just a placeholder)\n", "\"\"\"\n", "\n", "class Ornery:\n", " \n", " def __init__(自, name=\"Fred\"):\n", " 自.name = name\n", " print(\"A sourpuss is born!\")\n", " \n", " def __getitem__(自, key):\n", " return \"How dare you touch me with those brackets!\"\n", " \n", " def __call__(自, *args, **kwargs):\n", " return \"Don't call me at home!\"\n", " \n", " def __getattr__(自, attr):\n", " return \"I'm insulted you'd suppose I'd have {}\".format(attr)\n", " \n", " def __repr__(自):\n", " return \"Don't bother me! Go away.\"\n", " \n", " def __invert__(自):\n", " return \"I can't invert, are you kidding?\"\n", "\n", "grumpy = Ornery()\n", "print(grumpy(\"Hello?\")) # __call__\n", "print(grumpy.mood) # __getattr__\n", "print(grumpy[3]) # __getitem__\n", "print(~grumpy) # __invert__\n", "print(grumpy) # __repr__\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Standard Library\n", "\n", "Lets take [a tour](https://docs.python.org/3/tutorial/stdlib.html).\n", "\n", "## Third Party\n", "\n", "Lets visit [PiPy](https://pypi.python.org/pypi)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" } }, "nbformat": 4, "nbformat_minor": 2 }