{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# import and from\n", "Both **import** and **from** are statements, not compile-time declarations. \n", "Thus, they can be nested in **if** like other statements.\n", "\n", "## import \n", "Assigning an entire module object to a single name\n", "\n", "## from\n", "- Copy specific names from one file to another. \n", "- Assigning one or more names to objects of the same names in another module.\n", " - No link from a name copied with **from** back to the original file.\n", " - To really change a global name in another file, you must use **import**.(Not Recommaned design)\n", " \n", "### from gotchas\n", "- **from** only copies names from one module to another, it does not assign the module name itself\n", "- **from** always load the whole file into memory. \n", " There is no way to load part of a module file. \n", " \n", "### from ... import *\n", "Get copies of all names assigned at the top level of referenced module. \n", "Note that only \\* works. Other pattern matching rule won't work. \n", "\n", "In Python3, `from ... import *` can only be used at the top level of a module file, not within functions. \n", "In Python2, it's allowed, but will issue a warning\n", "\n", "*Using `from ... import *` statement might hide variables that have the same names without notice* \n", "Thus, the following design is recommanded.\n", "```python\n", "from moduel import x, y, z\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## import and from Equivalence\n", "\n", "\n", "### from\n", "```python\n", "from module import name1, name2\n", "```\n", "\n", "### import\n", "```python\n", "import module\n", "name1 = module.name1\n", "name2 = module.name2\n", "```" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## import or from?\n", "- Prefer **import** to **from** for simple modules\n", "- Explicityly list the variables you want in **from** statements\n", " - Limit `from module import *` to at most once per file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## When import is required?\n", "When you must use the same name defined in two different modules \n", "\n", "e.g.\n", "```python\n", "# a.py and b.py exist in the same folder to be used as a sample\n", "\n", "# a.py\n", "def func():\n", " print(\"This is a\")\n", "\n", "# b.py\n", "def func():\n", " print(\"This is b\")\n", "```" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is b\n" ] } ], "source": [ "# main.py\n", "from a import func\n", "from b import func\n", "\n", "func()" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is a\n", "This is b\n" ] } ], "source": [ "# main2.py\n", "import a, b\n", "\n", "a.func()\n", "b.func()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another way to solve this dilemma is using **as** statement" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is a\n", "This is b\n" ] } ], "source": [ "from a import func as afunc\n", "from b import func as bfunc\n", "\n", "afunc()\n", "bfunc()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Module Namespace\n", "Module namespaces can be accessed via the attribute `__dict__` or `dir(M)` " ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SEEK_END\n", "\t 2\n", "pardir\n", "\t ..\n", "execl\n", "\t \n", "execve\n", "\t \n", "curdir\n", "\t .\n", "link\n", "\t \n", "_execvpe\n", "\t \n", "sys\n", "\t \n", "access\n", "\t \n", "O_TEXT\n", "\t 16384\n", "chdir\n", "\t \n", "urandom\n", "\t \n", "_wrap_close\n", "\t \n", "devnull\n", "\t nul\n", "W_OK\n", "\t 2\n", "spawnl\n", "\t \n", "P_NOWAITO\n", "\t 3\n", "supports_fd\n", "\t {}\n", "O_SHORT_LIVED\n", "\t 4096\n", "O_BINARY\n", "\t 32768\n", "pathsep\n", "\t ;\n", "O_RDWR\n", "\t 2\n", "SEEK_CUR\n", "\t 1\n", "execlp\n", "\t \n", "lstat\n", "\t \n", "dup2\n", "\t \n", "popen\n", "\t \n", "read\n", "\t \n", "set_inheritable\n", "\t \n", "defpath\n", "\t .;C:\\bin\n", "__builtins__\n", "\t {'bool': , 'EOFError': , 'sum': , 'enumerate': , 'dict': , 'Exception': , 'ascii': , 'map': , 'DeprecationWarning': , 'ord': , 'IsADirectoryError': , 'BytesWarning': , 'list': , 'exec': , 'OverflowError': , 'float': , 'id': , 'locals': , 'BlockingIOError': , 'FileExistsError': , 'SystemExit': , 'tuple': , 'BaseException': , 'hasattr': , 'AttributeError': , '__IPYTHON__active': 'Deprecated, check for __IPYTHON__', 'all': , 'max': , 'InterruptedError': , 'oct': , 'GeneratorExit': , 'NotImplementedError': , 'NotADirectoryError': , 'set': , 'eval': , 'NameError': , 'ConnectionResetError': , 'EnvironmentError': , 'Ellipsis': Ellipsis, 'repr': , 'IOError': , 'help': Type help() for interactive help, or help(object) for help about object., 'staticmethod': , 'FloatingPointError': , 'FutureWarning': , 'BrokenPipeError': , 'IndexError': , 'SystemError': , 'ConnectionRefusedError': , 'Warning': , 'RuntimeWarning': , 'BufferError': , 'slice': , 'license': See https://www.python.org/psf/license/, 'object': , 'UnboundLocalError': , 'len': , 'any': , 'UnicodeEncodeError': , 'ResourceWarning': , 'UserWarning': , 'None': None, '__package__': '', 'reversed': , 'frozenset': , 'FileNotFoundError': , 'dir': , 'callable': , 'hex': , '__doc__': \"Built-in functions, exceptions, and other objects.\\n\\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.\", 'type': , 'setattr': , 'abs': , 'zip': , 'SyntaxWarning': , '__name__': 'builtins', 'str': , 'memoryview': , '__import__': , 'compile': , 'vars': , 'SyntaxError': , 'open': , 'property': , 'NotImplemented': NotImplemented, 'AssertionError': , 'min': , 'ZeroDivisionError': , 'int': , 'isinstance': , 'ConnectionAbortedError': , 'format': , 'globals': , 'hash': , 'copyright': Copyright (c) 2001-2015 Python Software Foundation.\n", "All Rights Reserved.\n", "\n", "Copyright (c) 2000 BeOpen.com.\n", "All Rights Reserved.\n", "\n", "Copyright (c) 1995-2001 Corporation for National Research Initiatives.\n", "All Rights Reserved.\n", "\n", "Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\n", "All Rights Reserved., 'super': , 'UnicodeDecodeError': , 'PermissionError': , 'TimeoutError': , 'ConnectionError': , 'sorted': , 'print': , 'round': , 'MemoryError': , 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\n", " for supporting Python development. See www.python.org for more information., 'ChildProcessError': , 'ProcessLookupError': , 'False': False, 'getattr': , 'TabError': , 'ArithmeticError': , 'dreload': , 'bin': , 'chr': , 'iter': , '__IPYTHON__': True, 'True': True, 'IndentationError': , 'LookupError': , 'ImportWarning': , 'OSError': , 'WindowsError': , 'ImportError': , 'delattr': , 'get_ipython': >, '__build_class__': , 'bytes': , 'KeyError': , 'ValueError': , 'ReferenceError': , 'bytearray': , 'UnicodeWarning': , 'PendingDeprecationWarning': , '__spec__': ModuleSpec(name='builtins', loader=), 'divmod': , 'StopIteration': , 'range': , 'next': , 'RuntimeError': , 'filter': , '__debug__': True, 'UnicodeTranslateError': , 'TypeError': , 'complex': , 'pow': , 'UnicodeError': , '__loader__': , 'classmethod': , 'issubclass': , 'input': >, 'KeyboardInterrupt': }\n", "rename\n", "\t \n", "device_encoding\n", "\t \n", "P_WAIT\n", "\t 0\n", "O_CREAT\n", "\t 256\n", "spawnve\n", "\t \n", "linesep\n", "\t \r\n", "\n", "execv\n", "\t \n", "name\n", "\t nt\n", "spawnv\n", "\t \n", "listdir\n", "\t \n", "get_inheritable\n", "\t \n", "__all__\n", "\t ['altsep', 'curdir', 'pardir', 'sep', 'pathsep', 'linesep', 'defpath', 'name', 'path', 'devnull', 'SEEK_SET', 'SEEK_CUR', 'SEEK_END', 'fsencode', 'fsdecode', 'get_exec_path', 'fdopen', 'popen', 'extsep', '_exit', 'F_OK', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'R_OK', 'TMP_MAX', 'W_OK', 'X_OK', 'abort', 'access', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'device_encoding', 'dup', 'dup2', 'environ', 'error', 'execv', 'execve', 'fstat', 'fsync', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'link', 'listdir', 'lseek', 'lstat', 'mkdir', 'open', 'pipe', 'putenv', 'read', 'readlink', 'remove', 'rename', 'replace', 'rmdir', 'set_handle_inheritable', 'set_inheritable', 'spawnv', 'spawnve', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'symlink', 'system', 'terminal_size', 'times', 'times_result', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'write', 'makedirs', 'removedirs', 'renames', 'walk', 'execl', 'execle', 'execlp', 'execlpe', 'execvp', 'execvpe', 'getenv', 'supports_bytes_environ', 'spawnl', 'spawnle']\n", "getppid\n", "\t \n", "write\n", "\t \n", "isatty\n", "\t \n", "stat_float_times\n", "\t \n", "execvpe\n", "\t \n", "get_exec_path\n", "\t \n", "MutableMapping\n", "\t \n", "fstat\n", "\t \n", "remove\n", "\t \n", "supports_effective_ids\n", "\t set()\n", "get_terminal_size\n", "\t \n", "chmod\n", "\t \n", "__package__\n", "\t \n", "O_RANDOM\n", "\t 16\n", "R_OK\n", "\t 4\n", "makedirs\n", "\t \n", "X_OK\n", "\t 1\n", "O_WRONLY\n", "\t 1\n", "__doc__\n", "\t OS routines for NT or Posix depending on what system we're on.\n", "\n", "This exports:\n", " - all functions from posix, nt or ce, e.g. unlink, stat, etc.\n", " - os.path is either posixpath or ntpath\n", " - os.name is either 'posix', 'nt' or 'ce'.\n", " - os.curdir is a string representing the current directory ('.' or ':')\n", " - os.pardir is a string representing the parent directory ('..' or '::')\n", " - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\\\')\n", " - os.extsep is the extension separator (always '.')\n", " - os.altsep is the alternate pathname separator (None or '/')\n", " - os.pathsep is the component separator used in $PATH etc\n", " - os.linesep is the line separator in text files ('\\r' or '\\n' or '\\r\\n')\n", " - os.defpath is the default search path for executables\n", " - os.devnull is the file path of the null device ('/dev/null', etc.)\n", "\n", "Programs that import and use 'os' stand a better chance of being\n", "portable between different platforms. Of course, they must then\n", "only use functions that are defined by all platforms (e.g., unlink\n", "and opendir), and leave all pathname manipulation to os.path\n", "(e.g., split and join).\n", "\n", "cpu_count\n", "\t \n", "_putenv\n", "\t \n", "O_TEMPORARY\n", "\t 64\n", "terminal_size\n", "\t \n", "P_DETACH\n", "\t 4\n", "__name__\n", "\t os\n", "dup\n", "\t \n", "getlogin\n", "\t \n", "fsdecode\n", "\t .fsdecode at 0x01749B28>\n", "get_handle_inheritable\n", "\t \n", "close\n", "\t \n", "altsep\n", "\t /\n", "utime\n", "\t \n", "open\n", "\t \n", "execlpe\n", "\t \n", "fdopen\n", "\t \n", "supports_bytes_environ\n", "\t False\n", "unlink\n", "\t \n", "execle\n", "\t \n", "system\n", "\t \n", "renames\n", "\t \n", "spawnle\n", "\t \n", "O_RDONLY\n", "\t 0\n", "stat_result\n", "\t \n", "fsencode\n", "\t .fsencode at 0x01749AE0>\n", "removedirs\n", "\t \n", "uname_result\n", "\t \n", "_unsetenv\n", "\t at 0x01732CD8>\n", "abort\n", "\t \n", "umask\n", "\t \n", "_exit\n", "\t \n", "error\n", "\t \n", "getpid\n", "\t \n", "O_SEQUENTIAL\n", "\t 32\n", "walk\n", "\t \n", "readlink\n", "\t \n", "supports_dir_fd\n", "\t set()\n", "__file__\n", "\t C:\\Users\\smszw\\Anaconda3\\lib\\os.py\n", "F_OK\n", "\t 0\n", "P_OVERLAY\n", "\t 2\n", "times_result\n", "\t \n", "set_handle_inheritable\n", "\t \n", "kill\n", "\t \n", "getcwd\n", "\t \n", "fsync\n", "\t \n", "pipe\n", "\t \n", "TMP_MAX\n", "\t 32767\n", "statvfs_result\n", "\t \n", "O_EXCL\n", "\t 1024\n", "getcwdb\n", "\t \n", "extsep\n", "\t .\n", "st\n", "\t \n", "symlink\n", "\t \n", "supports_follow_symlinks\n", "\t {}\n", "sep\n", "\t \\\n", "rmdir\n", "\t \n", "closerange\n", "\t \n", "stat\n", "\t \n", "errno\n", "\t \n", "O_NOINHERIT\n", "\t 128\n", "__loader__\n", "\t <_frozen_importlib.SourceFileLoader object at 0x0171E650>\n", "P_NOWAIT\n", "\t 1\n", "environ\n", "\t environ({'JAVA_HOME': 'C:\\\\Program Files\\\\Java\\\\jdk1.8.0_60', 'FP_NO_HOST_CHECK': 'NO', 'USERDOMAIN': 'user-PC', 'PATH': 'C:\\\\ProgramData\\\\Oracle\\\\Java\\\\javapath;C:\\\\Windows\\\\system32;C:\\\\Windows;C:\\\\Windows\\\\System32\\\\Wbem;C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\;C:\\\\Program Files\\\\Git\\\\cmd;C:\\\\Program Files\\\\Microsoft SQL Server\\\\110\\\\Tools\\\\Binn\\\\;C:\\\\Program Files\\\\Microsoft SQL Server\\\\110\\\\DTS\\\\Binn\\\\;C:\\\\Program Files\\\\Microsoft SQL Server\\\\110\\\\Tools\\\\Binn\\\\ManagementStudio\\\\;C:\\\\Program Files\\\\nodejs\\\\;C:\\\\Program Files\\\\Brackets\\\\command;%USERPROFILE%\\\\.dnx\\\\bin;C:\\\\Program Files\\\\Microsoft DNX\\\\Dnvm\\\\;C:\\\\Users\\\\smszw\\\\Anaconda2\\\\Library\\\\bin;C:\\\\Program Files\\\\IronPython 2.7;C:\\\\Users\\\\smszw\\\\Anaconda3;C:\\\\Users\\\\smszw\\\\Anaconda3\\\\Scripts; C:\\\\apache-ant-1.9.6\\\\bin;C:\\\\Users\\\\smszw\\\\AppData\\\\Roaming\\\\npm', 'CLICOLOR': '1', 'HOMEPATH': '\\\\Users\\\\smszw', 'PAGER': 'cat', 'COMPUTERNAME': 'USER-PC', 'LOGONSERVER': '\\\\\\\\USER-PC', 'IPY_INTERRUPT_EVENT': '956', 'SESSIONNAME': 'Console', 'PROMPT': '$P$G', 'PROCESSOR_IDENTIFIER': 'x86 Family 6 Model 15 Stepping 6, GenuineIntel', 'COMSPEC': 'C:\\\\Windows\\\\system32\\\\cmd.exe', 'PROCESSOR_REVISION': '0f06', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC', 'VS140COMNTOOLS': 'C:\\\\Program Files\\\\Microsoft Visual Studio 14.0\\\\Common7\\\\Tools\\\\', 'NUMBER_OF_PROCESSORS': '2', 'TEMP': 'C:\\\\Users\\\\smszw\\\\AppData\\\\Local\\\\Temp', 'VBOX_MSI_INSTALL_PATH': 'C:\\\\Program Files\\\\Oracle\\\\VirtualBox\\\\', 'USERPROFILE': 'C:\\\\Users\\\\smszw', 'WINDOWS_TRACING_FLAGS': '3', 'JPY_PARENT_PID': '904', 'USERNAME': 'smszw', 'OS': 'Windows_NT', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\\\Windows', 'JPY_INTERRUPT_EVENT': '956', 'APPDATA': 'C:\\\\Users\\\\smszw\\\\AppData\\\\Roaming', 'PUBLIC': 'C:\\\\Users\\\\Public', 'PROGRAMFILES': 'C:\\\\Program Files', 'PROCESSOR_ARCHITECTURE': 'x86', 'TERM': 'xterm-color', 'WINDOWS_TRACING_LOGFILE': 'C:\\\\BVTBin\\\\Tests\\\\installpackage\\\\csilogfile.log', 'COMMONPROGRAMFILES': 'C:\\\\Program Files\\\\Common Files', 'TMP': 'C:\\\\Users\\\\smszw\\\\AppData\\\\Local\\\\Temp', 'GIT_PAGER': 'cat', 'WINDIR': 'C:\\\\Windows', 'LOCALAPPDATA': 'C:\\\\Users\\\\smszw\\\\AppData\\\\Local', 'PROCESSOR_LEVEL': '6', 'ASL.LOG': 'Destination=file', 'PROGRAMDATA': 'C:\\\\ProgramData', 'ALLUSERSPROFILE': 'C:\\\\ProgramData', 'HOMEDRIVE': 'C:', 'PSMODULEPATH': 'C:\\\\Windows\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\Modules\\\\;C:\\\\Program Files\\\\Microsoft SQL Server\\\\110\\\\Tools\\\\PowerShell\\\\Modules\\\\'})\n", "_exists\n", "\t \n", "__cached__\n", "\t C:\\Users\\smszw\\Anaconda3\\lib\\__pycache__\\os.cpython-34.pyc\n", "SEEK_SET\n", "\t 0\n", "times\n", "\t \n", "replace\n", "\t \n", "getenv\n", "\t \n", "strerror\n", "\t \n", "execvp\n", "\t \n", "_Environ\n", "\t \n", "lseek\n", "\t \n", "O_TRUNC\n", "\t 512\n", "O_APPEND\n", "\t 8\n", "mkdir\n", "\t \n", "path\n", "\t \n", "putenv\n", "\t \n", "__spec__\n", "\t ModuleSpec(name='os', loader=<_frozen_importlib.SourceFileLoader object at 0x0171E650>, origin='C:\\\\Users\\\\smszw\\\\Anaconda3\\\\lib\\\\os.py')\n", "startfile\n", "\t \n", "_get_exports_list\n", "\t \n", "waitpid\n", "\t \n" ] } ], "source": [ "import os\n", "\n", "for key, value in os.__dict__.items():\n", " print(key)\n", " print(\"\\t\", value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Reloading Modules\n", "**reload** currently only works on modules written in Python." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "\n", "from imp import reload # Python3\n", "\n", "reload(os)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- **reload** expects a module object. \n", " Thus, the module you want to reload must first be successfully imported..\n", "\n", "- **reload** change the module object in-place. \n", " Thus, every reference to it will be updated by a reload\n", " \n", "- **from** won't be affected by **reload**\n", " - **reload** should be used with **import** not **from**\n", "\n", "- **reload** applys to a single module, not recursive\n", "\n", "- **reload** returns the module object\n", "\n", "- **reload** also accepts a dotted path name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Why care about reloading modules?\n", "- Dynamic customization. \n", "- Useful in larger systems, especially when the cost of restarting the entire application. \n", " e.g. game servers, systems that must connect to servers over a network" ] } ], "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.0" } }, "nbformat": 4, "nbformat_minor": 1 }