17db96d56Sopenharmony_ci.. _tut-modules:
27db96d56Sopenharmony_ci
37db96d56Sopenharmony_ci*******
47db96d56Sopenharmony_ciModules
57db96d56Sopenharmony_ci*******
67db96d56Sopenharmony_ci
77db96d56Sopenharmony_ciIf you quit from the Python interpreter and enter it again, the definitions you
87db96d56Sopenharmony_cihave made (functions and variables) are lost. Therefore, if you want to write a
97db96d56Sopenharmony_cisomewhat longer program, you are better off using a text editor to prepare the
107db96d56Sopenharmony_ciinput for the interpreter and running it with that file as input instead.  This
117db96d56Sopenharmony_ciis known as creating a *script*.  As your program gets longer, you may want to
127db96d56Sopenharmony_cisplit it into several files for easier maintenance.  You may also want to use a
137db96d56Sopenharmony_cihandy function that you've written in several programs without copying its
147db96d56Sopenharmony_cidefinition into each program.
157db96d56Sopenharmony_ci
167db96d56Sopenharmony_ciTo support this, Python has a way to put definitions in a file and use them in a
177db96d56Sopenharmony_ciscript or in an interactive instance of the interpreter. Such a file is called a
187db96d56Sopenharmony_ci*module*; definitions from a module can be *imported* into other modules or into
197db96d56Sopenharmony_cithe *main* module (the collection of variables that you have access to in a
207db96d56Sopenharmony_ciscript executed at the top level and in calculator mode).
217db96d56Sopenharmony_ci
227db96d56Sopenharmony_ciA module is a file containing Python definitions and statements.  The file name
237db96d56Sopenharmony_ciis the module name with the suffix :file:`.py` appended.  Within a module, the
247db96d56Sopenharmony_cimodule's name (as a string) is available as the value of the global variable
257db96d56Sopenharmony_ci``__name__``.  For instance, use your favorite text editor to create a file
267db96d56Sopenharmony_cicalled :file:`fibo.py` in the current directory with the following contents::
277db96d56Sopenharmony_ci
287db96d56Sopenharmony_ci   # Fibonacci numbers module
297db96d56Sopenharmony_ci
307db96d56Sopenharmony_ci   def fib(n):    # write Fibonacci series up to n
317db96d56Sopenharmony_ci       a, b = 0, 1
327db96d56Sopenharmony_ci       while a < n:
337db96d56Sopenharmony_ci           print(a, end=' ')
347db96d56Sopenharmony_ci           a, b = b, a+b
357db96d56Sopenharmony_ci       print()
367db96d56Sopenharmony_ci
377db96d56Sopenharmony_ci   def fib2(n):   # return Fibonacci series up to n
387db96d56Sopenharmony_ci       result = []
397db96d56Sopenharmony_ci       a, b = 0, 1
407db96d56Sopenharmony_ci       while a < n:
417db96d56Sopenharmony_ci           result.append(a)
427db96d56Sopenharmony_ci           a, b = b, a+b
437db96d56Sopenharmony_ci       return result
447db96d56Sopenharmony_ci
457db96d56Sopenharmony_ciNow enter the Python interpreter and import this module with the following
467db96d56Sopenharmony_cicommand::
477db96d56Sopenharmony_ci
487db96d56Sopenharmony_ci   >>> import fibo
497db96d56Sopenharmony_ci
507db96d56Sopenharmony_ciThis does not add the names of the functions defined in ``fibo``  directly to
517db96d56Sopenharmony_cithe current :term:`namespace` (see :ref:`tut-scopes` for more details);
527db96d56Sopenharmony_ciit only adds the module name ``fibo`` there. Using
537db96d56Sopenharmony_cithe module name you can access the functions::
547db96d56Sopenharmony_ci
557db96d56Sopenharmony_ci   >>> fibo.fib(1000)
567db96d56Sopenharmony_ci   0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
577db96d56Sopenharmony_ci   >>> fibo.fib2(100)
587db96d56Sopenharmony_ci   [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
597db96d56Sopenharmony_ci   >>> fibo.__name__
607db96d56Sopenharmony_ci   'fibo'
617db96d56Sopenharmony_ci
627db96d56Sopenharmony_ciIf you intend to use a function often you can assign it to a local name::
637db96d56Sopenharmony_ci
647db96d56Sopenharmony_ci   >>> fib = fibo.fib
657db96d56Sopenharmony_ci   >>> fib(500)
667db96d56Sopenharmony_ci   0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
677db96d56Sopenharmony_ci
687db96d56Sopenharmony_ci
697db96d56Sopenharmony_ci.. _tut-moremodules:
707db96d56Sopenharmony_ci
717db96d56Sopenharmony_ciMore on Modules
727db96d56Sopenharmony_ci===============
737db96d56Sopenharmony_ci
747db96d56Sopenharmony_ciA module can contain executable statements as well as function definitions.
757db96d56Sopenharmony_ciThese statements are intended to initialize the module. They are executed only
767db96d56Sopenharmony_cithe *first* time the module name is encountered in an import statement. [#]_
777db96d56Sopenharmony_ci(They are also run if the file is executed as a script.)
787db96d56Sopenharmony_ci
797db96d56Sopenharmony_ciEach module has its own private namespace, which is used as the global namespace
807db96d56Sopenharmony_ciby all functions defined in the module. Thus, the author of a module can
817db96d56Sopenharmony_ciuse global variables in the module without worrying about accidental clashes
827db96d56Sopenharmony_ciwith a user's global variables. On the other hand, if you know what you are
837db96d56Sopenharmony_cidoing you can touch a module's global variables with the same notation used to
847db96d56Sopenharmony_cirefer to its functions, ``modname.itemname``.
857db96d56Sopenharmony_ci
867db96d56Sopenharmony_ciModules can import other modules.  It is customary but not required to place all
877db96d56Sopenharmony_ci:keyword:`import` statements at the beginning of a module (or script, for that
887db96d56Sopenharmony_cimatter).  The imported module names, if placed at the top level of a module
897db96d56Sopenharmony_ci(outside any functions or classes), are added to the module's global namespace.
907db96d56Sopenharmony_ci
917db96d56Sopenharmony_ciThere is a variant of the :keyword:`import` statement that imports names from a
927db96d56Sopenharmony_cimodule directly into the importing module's namespace.  For example::
937db96d56Sopenharmony_ci
947db96d56Sopenharmony_ci   >>> from fibo import fib, fib2
957db96d56Sopenharmony_ci   >>> fib(500)
967db96d56Sopenharmony_ci   0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
977db96d56Sopenharmony_ci
987db96d56Sopenharmony_ciThis does not introduce the module name from which the imports are taken in the
997db96d56Sopenharmony_cilocal namespace (so in the example, ``fibo`` is not defined).
1007db96d56Sopenharmony_ci
1017db96d56Sopenharmony_ciThere is even a variant to import all names that a module defines::
1027db96d56Sopenharmony_ci
1037db96d56Sopenharmony_ci   >>> from fibo import *
1047db96d56Sopenharmony_ci   >>> fib(500)
1057db96d56Sopenharmony_ci   0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
1067db96d56Sopenharmony_ci
1077db96d56Sopenharmony_ciThis imports all names except those beginning with an underscore (``_``).
1087db96d56Sopenharmony_ciIn most cases Python programmers do not use this facility since it introduces
1097db96d56Sopenharmony_cian unknown set of names into the interpreter, possibly hiding some things
1107db96d56Sopenharmony_ciyou have already defined.
1117db96d56Sopenharmony_ci
1127db96d56Sopenharmony_ciNote that in general the practice of importing ``*`` from a module or package is
1137db96d56Sopenharmony_cifrowned upon, since it often causes poorly readable code. However, it is okay to
1147db96d56Sopenharmony_ciuse it to save typing in interactive sessions.
1157db96d56Sopenharmony_ci
1167db96d56Sopenharmony_ciIf the module name is followed by :keyword:`!as`, then the name
1177db96d56Sopenharmony_cifollowing :keyword:`!as` is bound directly to the imported module.
1187db96d56Sopenharmony_ci
1197db96d56Sopenharmony_ci::
1207db96d56Sopenharmony_ci
1217db96d56Sopenharmony_ci   >>> import fibo as fib
1227db96d56Sopenharmony_ci   >>> fib.fib(500)
1237db96d56Sopenharmony_ci   0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
1247db96d56Sopenharmony_ci
1257db96d56Sopenharmony_ciThis is effectively importing the module in the same way that ``import fibo``
1267db96d56Sopenharmony_ciwill do, with the only difference of it being available as ``fib``.
1277db96d56Sopenharmony_ci
1287db96d56Sopenharmony_ciIt can also be used when utilising :keyword:`from` with similar effects::
1297db96d56Sopenharmony_ci
1307db96d56Sopenharmony_ci   >>> from fibo import fib as fibonacci
1317db96d56Sopenharmony_ci   >>> fibonacci(500)
1327db96d56Sopenharmony_ci   0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
1337db96d56Sopenharmony_ci
1347db96d56Sopenharmony_ci
1357db96d56Sopenharmony_ci.. note::
1367db96d56Sopenharmony_ci
1377db96d56Sopenharmony_ci   For efficiency reasons, each module is only imported once per interpreter
1387db96d56Sopenharmony_ci   session.  Therefore, if you change your modules, you must restart the
1397db96d56Sopenharmony_ci   interpreter -- or, if it's just one module you want to test interactively,
1407db96d56Sopenharmony_ci   use :func:`importlib.reload`, e.g. ``import importlib;
1417db96d56Sopenharmony_ci   importlib.reload(modulename)``.
1427db96d56Sopenharmony_ci
1437db96d56Sopenharmony_ci
1447db96d56Sopenharmony_ci.. _tut-modulesasscripts:
1457db96d56Sopenharmony_ci
1467db96d56Sopenharmony_ciExecuting modules as scripts
1477db96d56Sopenharmony_ci----------------------------
1487db96d56Sopenharmony_ci
1497db96d56Sopenharmony_ciWhen you run a Python module with ::
1507db96d56Sopenharmony_ci
1517db96d56Sopenharmony_ci   python fibo.py <arguments>
1527db96d56Sopenharmony_ci
1537db96d56Sopenharmony_cithe code in the module will be executed, just as if you imported it, but with
1547db96d56Sopenharmony_cithe ``__name__`` set to ``"__main__"``.  That means that by adding this code at
1557db96d56Sopenharmony_cithe end of your module::
1567db96d56Sopenharmony_ci
1577db96d56Sopenharmony_ci   if __name__ == "__main__":
1587db96d56Sopenharmony_ci       import sys
1597db96d56Sopenharmony_ci       fib(int(sys.argv[1]))
1607db96d56Sopenharmony_ci
1617db96d56Sopenharmony_ciyou can make the file usable as a script as well as an importable module,
1627db96d56Sopenharmony_cibecause the code that parses the command line only runs if the module is
1637db96d56Sopenharmony_ciexecuted as the "main" file:
1647db96d56Sopenharmony_ci
1657db96d56Sopenharmony_ci.. code-block:: shell-session
1667db96d56Sopenharmony_ci
1677db96d56Sopenharmony_ci   $ python fibo.py 50
1687db96d56Sopenharmony_ci   0 1 1 2 3 5 8 13 21 34
1697db96d56Sopenharmony_ci
1707db96d56Sopenharmony_ciIf the module is imported, the code is not run::
1717db96d56Sopenharmony_ci
1727db96d56Sopenharmony_ci   >>> import fibo
1737db96d56Sopenharmony_ci   >>>
1747db96d56Sopenharmony_ci
1757db96d56Sopenharmony_ciThis is often used either to provide a convenient user interface to a module, or
1767db96d56Sopenharmony_cifor testing purposes (running the module as a script executes a test suite).
1777db96d56Sopenharmony_ci
1787db96d56Sopenharmony_ci
1797db96d56Sopenharmony_ci.. _tut-searchpath:
1807db96d56Sopenharmony_ci
1817db96d56Sopenharmony_ciThe Module Search Path
1827db96d56Sopenharmony_ci----------------------
1837db96d56Sopenharmony_ci
1847db96d56Sopenharmony_ci.. index:: triple: module; search; path
1857db96d56Sopenharmony_ci
1867db96d56Sopenharmony_ciWhen a module named :mod:`spam` is imported, the interpreter first searches for
1877db96d56Sopenharmony_cia built-in module with that name. These module names are listed in
1887db96d56Sopenharmony_ci:data:`sys.builtin_module_names`. If not found, it then searches for a file
1897db96d56Sopenharmony_cinamed :file:`spam.py` in a list of directories given by the variable
1907db96d56Sopenharmony_ci:data:`sys.path`.  :data:`sys.path` is initialized from these locations:
1917db96d56Sopenharmony_ci
1927db96d56Sopenharmony_ci* The directory containing the input script (or the current directory when no
1937db96d56Sopenharmony_ci  file is specified).
1947db96d56Sopenharmony_ci* :envvar:`PYTHONPATH` (a list of directory names, with the same syntax as the
1957db96d56Sopenharmony_ci  shell variable :envvar:`PATH`).
1967db96d56Sopenharmony_ci* The installation-dependent default (by convention including a
1977db96d56Sopenharmony_ci  ``site-packages`` directory, handled by the :mod:`site` module).
1987db96d56Sopenharmony_ci
1997db96d56Sopenharmony_ciMore details are at :ref:`sys-path-init`.
2007db96d56Sopenharmony_ci
2017db96d56Sopenharmony_ci.. note::
2027db96d56Sopenharmony_ci   On file systems which support symlinks, the directory containing the input
2037db96d56Sopenharmony_ci   script is calculated after the symlink is followed. In other words the
2047db96d56Sopenharmony_ci   directory containing the symlink is **not** added to the module search path.
2057db96d56Sopenharmony_ci
2067db96d56Sopenharmony_ciAfter initialization, Python programs can modify :data:`sys.path`.  The
2077db96d56Sopenharmony_cidirectory containing the script being run is placed at the beginning of the
2087db96d56Sopenharmony_cisearch path, ahead of the standard library path. This means that scripts in that
2097db96d56Sopenharmony_cidirectory will be loaded instead of modules of the same name in the library
2107db96d56Sopenharmony_cidirectory. This is an error unless the replacement is intended.  See section
2117db96d56Sopenharmony_ci:ref:`tut-standardmodules` for more information.
2127db96d56Sopenharmony_ci
2137db96d56Sopenharmony_ci.. %
2147db96d56Sopenharmony_ci    Do we need stuff on zip files etc. ? DUBOIS
2157db96d56Sopenharmony_ci
2167db96d56Sopenharmony_ci.. _tut-pycache:
2177db96d56Sopenharmony_ci
2187db96d56Sopenharmony_ci"Compiled" Python files
2197db96d56Sopenharmony_ci-----------------------
2207db96d56Sopenharmony_ci
2217db96d56Sopenharmony_ciTo speed up loading modules, Python caches the compiled version of each module
2227db96d56Sopenharmony_ciin the ``__pycache__`` directory under the name :file:`module.{version}.pyc`,
2237db96d56Sopenharmony_ciwhere the version encodes the format of the compiled file; it generally contains
2247db96d56Sopenharmony_cithe Python version number.  For example, in CPython release 3.3 the compiled
2257db96d56Sopenharmony_civersion of spam.py would be cached as ``__pycache__/spam.cpython-33.pyc``.  This
2267db96d56Sopenharmony_cinaming convention allows compiled modules from different releases and different
2277db96d56Sopenharmony_civersions of Python to coexist.
2287db96d56Sopenharmony_ci
2297db96d56Sopenharmony_ciPython checks the modification date of the source against the compiled version
2307db96d56Sopenharmony_cito see if it's out of date and needs to be recompiled.  This is a completely
2317db96d56Sopenharmony_ciautomatic process.  Also, the compiled modules are platform-independent, so the
2327db96d56Sopenharmony_cisame library can be shared among systems with different architectures.
2337db96d56Sopenharmony_ci
2347db96d56Sopenharmony_ciPython does not check the cache in two circumstances.  First, it always
2357db96d56Sopenharmony_cirecompiles and does not store the result for the module that's loaded directly
2367db96d56Sopenharmony_cifrom the command line.  Second, it does not check the cache if there is no
2377db96d56Sopenharmony_cisource module.  To support a non-source (compiled only) distribution, the
2387db96d56Sopenharmony_cicompiled module must be in the source directory, and there must not be a source
2397db96d56Sopenharmony_cimodule.
2407db96d56Sopenharmony_ci
2417db96d56Sopenharmony_ciSome tips for experts:
2427db96d56Sopenharmony_ci
2437db96d56Sopenharmony_ci* You can use the :option:`-O` or :option:`-OO` switches on the Python command
2447db96d56Sopenharmony_ci  to reduce the size of a compiled module.  The ``-O`` switch removes assert
2457db96d56Sopenharmony_ci  statements, the ``-OO`` switch removes both assert statements and __doc__
2467db96d56Sopenharmony_ci  strings.  Since some programs may rely on having these available, you should
2477db96d56Sopenharmony_ci  only use this option if you know what you're doing.  "Optimized" modules have
2487db96d56Sopenharmony_ci  an ``opt-`` tag and are usually smaller.  Future releases may
2497db96d56Sopenharmony_ci  change the effects of optimization.
2507db96d56Sopenharmony_ci
2517db96d56Sopenharmony_ci* A program doesn't run any faster when it is read from a ``.pyc``
2527db96d56Sopenharmony_ci  file than when it is read from a ``.py`` file; the only thing that's faster
2537db96d56Sopenharmony_ci  about ``.pyc`` files is the speed with which they are loaded.
2547db96d56Sopenharmony_ci
2557db96d56Sopenharmony_ci* The module :mod:`compileall` can create .pyc files for all modules in a
2567db96d56Sopenharmony_ci  directory.
2577db96d56Sopenharmony_ci
2587db96d56Sopenharmony_ci* There is more detail on this process, including a flow chart of the
2597db96d56Sopenharmony_ci  decisions, in :pep:`3147`.
2607db96d56Sopenharmony_ci
2617db96d56Sopenharmony_ci
2627db96d56Sopenharmony_ci.. _tut-standardmodules:
2637db96d56Sopenharmony_ci
2647db96d56Sopenharmony_ciStandard Modules
2657db96d56Sopenharmony_ci================
2667db96d56Sopenharmony_ci
2677db96d56Sopenharmony_ci.. index:: pair: module; sys
2687db96d56Sopenharmony_ci
2697db96d56Sopenharmony_ciPython comes with a library of standard modules, described in a separate
2707db96d56Sopenharmony_cidocument, the Python Library Reference ("Library Reference" hereafter).  Some
2717db96d56Sopenharmony_cimodules are built into the interpreter; these provide access to operations that
2727db96d56Sopenharmony_ciare not part of the core of the language but are nevertheless built in, either
2737db96d56Sopenharmony_cifor efficiency or to provide access to operating system primitives such as
2747db96d56Sopenharmony_cisystem calls.  The set of such modules is a configuration option which also
2757db96d56Sopenharmony_cidepends on the underlying platform.  For example, the :mod:`winreg` module is only
2767db96d56Sopenharmony_ciprovided on Windows systems. One particular module deserves some attention:
2777db96d56Sopenharmony_ci:mod:`sys`, which is built into every Python interpreter.  The variables
2787db96d56Sopenharmony_ci``sys.ps1`` and ``sys.ps2`` define the strings used as primary and secondary
2797db96d56Sopenharmony_ciprompts::
2807db96d56Sopenharmony_ci
2817db96d56Sopenharmony_ci   >>> import sys
2827db96d56Sopenharmony_ci   >>> sys.ps1
2837db96d56Sopenharmony_ci   '>>> '
2847db96d56Sopenharmony_ci   >>> sys.ps2
2857db96d56Sopenharmony_ci   '... '
2867db96d56Sopenharmony_ci   >>> sys.ps1 = 'C> '
2877db96d56Sopenharmony_ci   C> print('Yuck!')
2887db96d56Sopenharmony_ci   Yuck!
2897db96d56Sopenharmony_ci   C>
2907db96d56Sopenharmony_ci
2917db96d56Sopenharmony_ci
2927db96d56Sopenharmony_ciThese two variables are only defined if the interpreter is in interactive mode.
2937db96d56Sopenharmony_ci
2947db96d56Sopenharmony_ciThe variable ``sys.path`` is a list of strings that determines the interpreter's
2957db96d56Sopenharmony_cisearch path for modules. It is initialized to a default path taken from the
2967db96d56Sopenharmony_cienvironment variable :envvar:`PYTHONPATH`, or from a built-in default if
2977db96d56Sopenharmony_ci:envvar:`PYTHONPATH` is not set.  You can modify it using standard list
2987db96d56Sopenharmony_cioperations::
2997db96d56Sopenharmony_ci
3007db96d56Sopenharmony_ci   >>> import sys
3017db96d56Sopenharmony_ci   >>> sys.path.append('/ufs/guido/lib/python')
3027db96d56Sopenharmony_ci
3037db96d56Sopenharmony_ci
3047db96d56Sopenharmony_ci.. _tut-dir:
3057db96d56Sopenharmony_ci
3067db96d56Sopenharmony_ciThe :func:`dir` Function
3077db96d56Sopenharmony_ci========================
3087db96d56Sopenharmony_ci
3097db96d56Sopenharmony_ciThe built-in function :func:`dir` is used to find out which names a module
3107db96d56Sopenharmony_cidefines.  It returns a sorted list of strings::
3117db96d56Sopenharmony_ci
3127db96d56Sopenharmony_ci   >>> import fibo, sys
3137db96d56Sopenharmony_ci   >>> dir(fibo)
3147db96d56Sopenharmony_ci   ['__name__', 'fib', 'fib2']
3157db96d56Sopenharmony_ci   >>> dir(sys)  # doctest: +NORMALIZE_WHITESPACE
3167db96d56Sopenharmony_ci   ['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',
3177db96d56Sopenharmony_ci    '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
3187db96d56Sopenharmony_ci    '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',
3197db96d56Sopenharmony_ci    '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',
3207db96d56Sopenharmony_ci    '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',
3217db96d56Sopenharmony_ci    'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',
3227db96d56Sopenharmony_ci    'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',
3237db96d56Sopenharmony_ci    'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
3247db96d56Sopenharmony_ci    'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
3257db96d56Sopenharmony_ci    'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',
3267db96d56Sopenharmony_ci    'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',
3277db96d56Sopenharmony_ci    'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',
3287db96d56Sopenharmony_ci    'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
3297db96d56Sopenharmony_ci    'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
3307db96d56Sopenharmony_ci    'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',
3317db96d56Sopenharmony_ci    'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
3327db96d56Sopenharmony_ci    'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix',
3337db96d56Sopenharmony_ci    'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags',
3347db96d56Sopenharmony_ci    'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr',
3357db96d56Sopenharmony_ci    'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info',
3367db96d56Sopenharmony_ci    'warnoptions']
3377db96d56Sopenharmony_ci
3387db96d56Sopenharmony_ciWithout arguments, :func:`dir` lists the names you have defined currently::
3397db96d56Sopenharmony_ci
3407db96d56Sopenharmony_ci   >>> a = [1, 2, 3, 4, 5]
3417db96d56Sopenharmony_ci   >>> import fibo
3427db96d56Sopenharmony_ci   >>> fib = fibo.fib
3437db96d56Sopenharmony_ci   >>> dir()
3447db96d56Sopenharmony_ci   ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
3457db96d56Sopenharmony_ci
3467db96d56Sopenharmony_ciNote that it lists all types of names: variables, modules, functions, etc.
3477db96d56Sopenharmony_ci
3487db96d56Sopenharmony_ci.. index:: pair: module; builtins
3497db96d56Sopenharmony_ci
3507db96d56Sopenharmony_ci:func:`dir` does not list the names of built-in functions and variables.  If you
3517db96d56Sopenharmony_ciwant a list of those, they are defined in the standard module
3527db96d56Sopenharmony_ci:mod:`builtins`::
3537db96d56Sopenharmony_ci
3547db96d56Sopenharmony_ci   >>> import builtins
3557db96d56Sopenharmony_ci   >>> dir(builtins)  # doctest: +NORMALIZE_WHITESPACE
3567db96d56Sopenharmony_ci   ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
3577db96d56Sopenharmony_ci    'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
3587db96d56Sopenharmony_ci    'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
3597db96d56Sopenharmony_ci    'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
3607db96d56Sopenharmony_ci    'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
3617db96d56Sopenharmony_ci    'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
3627db96d56Sopenharmony_ci    'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
3637db96d56Sopenharmony_ci    'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
3647db96d56Sopenharmony_ci    'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
3657db96d56Sopenharmony_ci    'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
3667db96d56Sopenharmony_ci    'NotImplementedError', 'OSError', 'OverflowError',
3677db96d56Sopenharmony_ci    'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
3687db96d56Sopenharmony_ci    'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
3697db96d56Sopenharmony_ci    'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
3707db96d56Sopenharmony_ci    'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
3717db96d56Sopenharmony_ci    'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
3727db96d56Sopenharmony_ci    'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
3737db96d56Sopenharmony_ci    'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
3747db96d56Sopenharmony_ci    '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
3757db96d56Sopenharmony_ci    'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
3767db96d56Sopenharmony_ci    'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
3777db96d56Sopenharmony_ci    'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
3787db96d56Sopenharmony_ci    'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
3797db96d56Sopenharmony_ci    'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
3807db96d56Sopenharmony_ci    'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
3817db96d56Sopenharmony_ci    'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
3827db96d56Sopenharmony_ci    'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
3837db96d56Sopenharmony_ci    'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
3847db96d56Sopenharmony_ci    'zip']
3857db96d56Sopenharmony_ci
3867db96d56Sopenharmony_ci.. _tut-packages:
3877db96d56Sopenharmony_ci
3887db96d56Sopenharmony_ciPackages
3897db96d56Sopenharmony_ci========
3907db96d56Sopenharmony_ci
3917db96d56Sopenharmony_ciPackages are a way of structuring Python's module namespace by using "dotted
3927db96d56Sopenharmony_cimodule names".  For example, the module name :mod:`A.B` designates a submodule
3937db96d56Sopenharmony_cinamed ``B`` in a package named ``A``.  Just like the use of modules saves the
3947db96d56Sopenharmony_ciauthors of different modules from having to worry about each other's global
3957db96d56Sopenharmony_civariable names, the use of dotted module names saves the authors of multi-module
3967db96d56Sopenharmony_cipackages like NumPy or Pillow from having to worry about
3977db96d56Sopenharmony_cieach other's module names.
3987db96d56Sopenharmony_ci
3997db96d56Sopenharmony_ciSuppose you want to design a collection of modules (a "package") for the uniform
4007db96d56Sopenharmony_cihandling of sound files and sound data.  There are many different sound file
4017db96d56Sopenharmony_ciformats (usually recognized by their extension, for example: :file:`.wav`,
4027db96d56Sopenharmony_ci:file:`.aiff`, :file:`.au`), so you may need to create and maintain a growing
4037db96d56Sopenharmony_cicollection of modules for the conversion between the various file formats.
4047db96d56Sopenharmony_ciThere are also many different operations you might want to perform on sound data
4057db96d56Sopenharmony_ci(such as mixing, adding echo, applying an equalizer function, creating an
4067db96d56Sopenharmony_ciartificial stereo effect), so in addition you will be writing a never-ending
4077db96d56Sopenharmony_cistream of modules to perform these operations.  Here's a possible structure for
4087db96d56Sopenharmony_ciyour package (expressed in terms of a hierarchical filesystem):
4097db96d56Sopenharmony_ci
4107db96d56Sopenharmony_ci.. code-block:: text
4117db96d56Sopenharmony_ci
4127db96d56Sopenharmony_ci   sound/                          Top-level package
4137db96d56Sopenharmony_ci         __init__.py               Initialize the sound package
4147db96d56Sopenharmony_ci         formats/                  Subpackage for file format conversions
4157db96d56Sopenharmony_ci                 __init__.py
4167db96d56Sopenharmony_ci                 wavread.py
4177db96d56Sopenharmony_ci                 wavwrite.py
4187db96d56Sopenharmony_ci                 aiffread.py
4197db96d56Sopenharmony_ci                 aiffwrite.py
4207db96d56Sopenharmony_ci                 auread.py
4217db96d56Sopenharmony_ci                 auwrite.py
4227db96d56Sopenharmony_ci                 ...
4237db96d56Sopenharmony_ci         effects/                  Subpackage for sound effects
4247db96d56Sopenharmony_ci                 __init__.py
4257db96d56Sopenharmony_ci                 echo.py
4267db96d56Sopenharmony_ci                 surround.py
4277db96d56Sopenharmony_ci                 reverse.py
4287db96d56Sopenharmony_ci                 ...
4297db96d56Sopenharmony_ci         filters/                  Subpackage for filters
4307db96d56Sopenharmony_ci                 __init__.py
4317db96d56Sopenharmony_ci                 equalizer.py
4327db96d56Sopenharmony_ci                 vocoder.py
4337db96d56Sopenharmony_ci                 karaoke.py
4347db96d56Sopenharmony_ci                 ...
4357db96d56Sopenharmony_ci
4367db96d56Sopenharmony_ciWhen importing the package, Python searches through the directories on
4377db96d56Sopenharmony_ci``sys.path`` looking for the package subdirectory.
4387db96d56Sopenharmony_ci
4397db96d56Sopenharmony_ciThe :file:`__init__.py` files are required to make Python treat directories
4407db96d56Sopenharmony_cicontaining the file as packages.  This prevents directories with a common name,
4417db96d56Sopenharmony_cisuch as ``string``, from unintentionally hiding valid modules that occur later
4427db96d56Sopenharmony_cion the module search path. In the simplest case, :file:`__init__.py` can just be
4437db96d56Sopenharmony_cian empty file, but it can also execute initialization code for the package or
4447db96d56Sopenharmony_ciset the ``__all__`` variable, described later.
4457db96d56Sopenharmony_ci
4467db96d56Sopenharmony_ciUsers of the package can import individual modules from the package, for
4477db96d56Sopenharmony_ciexample::
4487db96d56Sopenharmony_ci
4497db96d56Sopenharmony_ci   import sound.effects.echo
4507db96d56Sopenharmony_ci
4517db96d56Sopenharmony_ciThis loads the submodule :mod:`sound.effects.echo`.  It must be referenced with
4527db96d56Sopenharmony_ciits full name. ::
4537db96d56Sopenharmony_ci
4547db96d56Sopenharmony_ci   sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
4557db96d56Sopenharmony_ci
4567db96d56Sopenharmony_ciAn alternative way of importing the submodule is::
4577db96d56Sopenharmony_ci
4587db96d56Sopenharmony_ci   from sound.effects import echo
4597db96d56Sopenharmony_ci
4607db96d56Sopenharmony_ciThis also loads the submodule :mod:`echo`, and makes it available without its
4617db96d56Sopenharmony_cipackage prefix, so it can be used as follows::
4627db96d56Sopenharmony_ci
4637db96d56Sopenharmony_ci   echo.echofilter(input, output, delay=0.7, atten=4)
4647db96d56Sopenharmony_ci
4657db96d56Sopenharmony_ciYet another variation is to import the desired function or variable directly::
4667db96d56Sopenharmony_ci
4677db96d56Sopenharmony_ci   from sound.effects.echo import echofilter
4687db96d56Sopenharmony_ci
4697db96d56Sopenharmony_ciAgain, this loads the submodule :mod:`echo`, but this makes its function
4707db96d56Sopenharmony_ci:func:`echofilter` directly available::
4717db96d56Sopenharmony_ci
4727db96d56Sopenharmony_ci   echofilter(input, output, delay=0.7, atten=4)
4737db96d56Sopenharmony_ci
4747db96d56Sopenharmony_ciNote that when using ``from package import item``, the item can be either a
4757db96d56Sopenharmony_cisubmodule (or subpackage) of the package, or some  other name defined in the
4767db96d56Sopenharmony_cipackage, like a function, class or variable.  The ``import`` statement first
4777db96d56Sopenharmony_citests whether the item is defined in the package; if not, it assumes it is a
4787db96d56Sopenharmony_cimodule and attempts to load it.  If it fails to find it, an :exc:`ImportError`
4797db96d56Sopenharmony_ciexception is raised.
4807db96d56Sopenharmony_ci
4817db96d56Sopenharmony_ciContrarily, when using syntax like ``import item.subitem.subsubitem``, each item
4827db96d56Sopenharmony_ciexcept for the last must be a package; the last item can be a module or a
4837db96d56Sopenharmony_cipackage but can't be a class or function or variable defined in the previous
4847db96d56Sopenharmony_ciitem.
4857db96d56Sopenharmony_ci
4867db96d56Sopenharmony_ci
4877db96d56Sopenharmony_ci.. _tut-pkg-import-star:
4887db96d56Sopenharmony_ci
4897db96d56Sopenharmony_ciImporting \* From a Package
4907db96d56Sopenharmony_ci---------------------------
4917db96d56Sopenharmony_ci
4927db96d56Sopenharmony_ci.. index:: single: __all__
4937db96d56Sopenharmony_ci
4947db96d56Sopenharmony_ciNow what happens when the user writes ``from sound.effects import *``?  Ideally,
4957db96d56Sopenharmony_cione would hope that this somehow goes out to the filesystem, finds which
4967db96d56Sopenharmony_cisubmodules are present in the package, and imports them all.  This could take a
4977db96d56Sopenharmony_cilong time and importing sub-modules might have unwanted side-effects that should
4987db96d56Sopenharmony_cionly happen when the sub-module is explicitly imported.
4997db96d56Sopenharmony_ci
5007db96d56Sopenharmony_ciThe only solution is for the package author to provide an explicit index of the
5017db96d56Sopenharmony_cipackage.  The :keyword:`import` statement uses the following convention: if a package's
5027db96d56Sopenharmony_ci:file:`__init__.py` code defines a list named ``__all__``, it is taken to be the
5037db96d56Sopenharmony_cilist of module names that should be imported when ``from package import *`` is
5047db96d56Sopenharmony_ciencountered.  It is up to the package author to keep this list up-to-date when a
5057db96d56Sopenharmony_cinew version of the package is released.  Package authors may also decide not to
5067db96d56Sopenharmony_cisupport it, if they don't see a use for importing \* from their package.  For
5077db96d56Sopenharmony_ciexample, the file :file:`sound/effects/__init__.py` could contain the following
5087db96d56Sopenharmony_cicode::
5097db96d56Sopenharmony_ci
5107db96d56Sopenharmony_ci   __all__ = ["echo", "surround", "reverse"]
5117db96d56Sopenharmony_ci
5127db96d56Sopenharmony_ciThis would mean that ``from sound.effects import *`` would import the three
5137db96d56Sopenharmony_cinamed submodules of the :mod:`sound.effects` package.
5147db96d56Sopenharmony_ci
5157db96d56Sopenharmony_ciIf ``__all__`` is not defined, the statement ``from sound.effects import *``
5167db96d56Sopenharmony_cidoes *not* import all submodules from the package :mod:`sound.effects` into the
5177db96d56Sopenharmony_cicurrent namespace; it only ensures that the package :mod:`sound.effects` has
5187db96d56Sopenharmony_cibeen imported (possibly running any initialization code in :file:`__init__.py`)
5197db96d56Sopenharmony_ciand then imports whatever names are defined in the package.  This includes any
5207db96d56Sopenharmony_cinames defined (and submodules explicitly loaded) by :file:`__init__.py`.  It
5217db96d56Sopenharmony_cialso includes any submodules of the package that were explicitly loaded by
5227db96d56Sopenharmony_ciprevious :keyword:`import` statements.  Consider this code::
5237db96d56Sopenharmony_ci
5247db96d56Sopenharmony_ci   import sound.effects.echo
5257db96d56Sopenharmony_ci   import sound.effects.surround
5267db96d56Sopenharmony_ci   from sound.effects import *
5277db96d56Sopenharmony_ci
5287db96d56Sopenharmony_ciIn this example, the :mod:`echo` and :mod:`surround` modules are imported in the
5297db96d56Sopenharmony_cicurrent namespace because they are defined in the :mod:`sound.effects` package
5307db96d56Sopenharmony_ciwhen the ``from...import`` statement is executed.  (This also works when
5317db96d56Sopenharmony_ci``__all__`` is defined.)
5327db96d56Sopenharmony_ci
5337db96d56Sopenharmony_ciAlthough certain modules are designed to export only names that follow certain
5347db96d56Sopenharmony_cipatterns when you use ``import *``, it is still considered bad practice in
5357db96d56Sopenharmony_ciproduction code.
5367db96d56Sopenharmony_ci
5377db96d56Sopenharmony_ciRemember, there is nothing wrong with using ``from package import
5387db96d56Sopenharmony_cispecific_submodule``!  In fact, this is the recommended notation unless the
5397db96d56Sopenharmony_ciimporting module needs to use submodules with the same name from different
5407db96d56Sopenharmony_cipackages.
5417db96d56Sopenharmony_ci
5427db96d56Sopenharmony_ci
5437db96d56Sopenharmony_ci.. _intra-package-references:
5447db96d56Sopenharmony_ci
5457db96d56Sopenharmony_ciIntra-package References
5467db96d56Sopenharmony_ci------------------------
5477db96d56Sopenharmony_ci
5487db96d56Sopenharmony_ciWhen packages are structured into subpackages (as with the :mod:`sound` package
5497db96d56Sopenharmony_ciin the example), you can use absolute imports to refer to submodules of siblings
5507db96d56Sopenharmony_cipackages.  For example, if the module :mod:`sound.filters.vocoder` needs to use
5517db96d56Sopenharmony_cithe :mod:`echo` module in the :mod:`sound.effects` package, it can use ``from
5527db96d56Sopenharmony_cisound.effects import echo``.
5537db96d56Sopenharmony_ci
5547db96d56Sopenharmony_ciYou can also write relative imports, with the ``from module import name`` form
5557db96d56Sopenharmony_ciof import statement.  These imports use leading dots to indicate the current and
5567db96d56Sopenharmony_ciparent packages involved in the relative import.  From the :mod:`surround`
5577db96d56Sopenharmony_cimodule for example, you might use::
5587db96d56Sopenharmony_ci
5597db96d56Sopenharmony_ci   from . import echo
5607db96d56Sopenharmony_ci   from .. import formats
5617db96d56Sopenharmony_ci   from ..filters import equalizer
5627db96d56Sopenharmony_ci
5637db96d56Sopenharmony_ciNote that relative imports are based on the name of the current module.  Since
5647db96d56Sopenharmony_cithe name of the main module is always ``"__main__"``, modules intended for use
5657db96d56Sopenharmony_cias the main module of a Python application must always use absolute imports.
5667db96d56Sopenharmony_ci
5677db96d56Sopenharmony_ci
5687db96d56Sopenharmony_ciPackages in Multiple Directories
5697db96d56Sopenharmony_ci--------------------------------
5707db96d56Sopenharmony_ci
5717db96d56Sopenharmony_ciPackages support one more special attribute, :attr:`__path__`.  This is
5727db96d56Sopenharmony_ciinitialized to be a list containing the name of the directory holding the
5737db96d56Sopenharmony_cipackage's :file:`__init__.py` before the code in that file is executed.  This
5747db96d56Sopenharmony_civariable can be modified; doing so affects future searches for modules and
5757db96d56Sopenharmony_cisubpackages contained in the package.
5767db96d56Sopenharmony_ci
5777db96d56Sopenharmony_ciWhile this feature is not often needed, it can be used to extend the set of
5787db96d56Sopenharmony_cimodules found in a package.
5797db96d56Sopenharmony_ci
5807db96d56Sopenharmony_ci
5817db96d56Sopenharmony_ci.. rubric:: Footnotes
5827db96d56Sopenharmony_ci
5837db96d56Sopenharmony_ci.. [#] In fact function definitions are also 'statements' that are 'executed'; the
5847db96d56Sopenharmony_ci   execution of a module-level function definition adds the function name to
5857db96d56Sopenharmony_ci   the module's global namespace.
586