Modules and Packages:
1
                           Module
                           s
              • Any Python source
                       # spam.py
                                  file is a module
                       def
                       grok(x):
                           ...
                       def
                       blah(x):
                           ...
               • You use
                       import to
                       execute
                       and
                       access it
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com   2
                        import spam
                                             Namespaces
              • Each module is its own isolated world
                    # spam.py                                                     #
                    eggs.py
                    x = 42
                    def blah():                          These definitions of x   x foo():
                                                                                     = 37
                                                                                    print(x
                    def                                       are different
                                                                                    )
                             print(x)
               • What happens in a module, stays in a module
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com                            3
                    Global
              • GlobalVariables
                       variables bind inside the same module
                     #
                     spam.py
                       x = 42
                     def
                     blah():
                         prin
                         t(x)
               • Functi
                      ons
                      record
                      their
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com   4
                      definit
                               Module Execution
              • When a module is imported, all of the
                     statements in the module execute one after
                     another until the end of the file is reached
              • The contents of the module namespace are all
                     of the global names that are still defined at the
                     end of the execution process
              • If there are scripting statements that carry out
                     tasks in the global scope (printing, creating
                     files, etc.), you will see them run on import
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com       5
                            from module import
                 • Lifts selected symbols out of a module after
                         importing it and makes them available
                         locally
                           from math import sin, cos
                           def rectangular(r,
                               theta):    x = r *
                               cos(theta)
                           y = r * sin(theta)
                               return x, y
                   • Allows parts of a module to be used without
                          having to type the module prefix
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com   6
                  *
                  • Takes all symbols from a module and places
                           them into local scope
                               from math import *
                               def rectangular(r,
                                   theta):    x = r *
                                   cos(theta)
                               y = r * sin(theta)
                                   return x, y
                   • Sometimes useful
                   • Usually considered bad style (try to avoid)
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com   7
                                           Commentary
                 • Variations on import do not change the way
                        that modules work
                         import math as m
                         from math import cos,
                         sin from math import *
                         ...
                 • import always
                        executes the entire
                        file
                 • Modules are still
                        isolated
                        environments
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com   8
                                      Module Names
              • File names have to follow the rules
                      Yes
                         # good.py                                   # 2bad.py
                      No
                         ...                                         ...
               • Comment:This mistake comes up a lot when
                      teaching Python to newcomers
               • Must be a valid identifier name
               • Also: avoid non-ASCII characters
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com               9
                          Naming Conventions
                 • It is standard practice for package and
                         module names to be concise and lowercase
                               foo.p    not     MyFooModule.p
                                            y                        y
                  • Use a leading underscore for modules that
                         are meant to be private or internal
                                            _foo.py
                  • Don't use names that match common
                         standard library modules (confusing)
                                             projectname/
                                                   math.py
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com       10
                 Module Search
            • If Path
                 a file isn't on the path, it won't import
                        >>> import sys
                        >>> sys.path
                        ['',
                         '/usr/local/lib/python34.zip',
                         '/usr/local/lib/python3.4',
                         '/usr/local/lib/python3.4/plat-darwin',
                         '/usr/local/lib/python3.4/lib-dynload',
                         '/usr/local/lib/python3.4/site-
                         packages']
              • Sometimes you might hack it
                         import sys
                         sys.path.append("/project/foo/myfiles"
                         )
                                                                 ... although doing   11
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com
                                                                 so feels "dirty"
                                        Module Cache
              • Modules only get loaded once
              • There's a cache behind the scenes
                    >>>        spa
                    import     m
                    >>>        sys
                    True
                    import     in
                    >>> sys.modules['spam']
                               sys
                    <module
                    'spam' 'spam'
                               .mo from
                    'spam.py'> dul
                    >>>        es
              • Consequence:             If you make a change to the
                     source and repeat the import, nothing happens
                     (often frustrating to newcomers)
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com     12
                   Module
              • YouReloading
                   can force-reload a module, but you're
                     never supposed to do it
                       >>> from importlib import reload
                       >>> reload(spam)
                       <module 'spam' from 'spam.py'>
                       >>>
              • Apparently zombies are spawned if you do this
              • No, seriously.
              • Don't. Do. It.
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com   13
                                                 main                   check
              • If a file might run as a main program, do
                      this
                      # spam.py
                      ...
                      if name == ' main ':
                          # Running as the main program
                          ...
                • Such code won't run on library import
                      import spam                                    # Main code doesn't
                      execute               bash % python spam.py          # Main code
                      executes
Copyright (C) 2015, David Beazley (@dabeaz). http://www.dabeaz.com                         14