Juancho Datu
What is a Module? File containing Python definitions and statements with the suffix ‘.py’ in the current directory For example file name: markov.py Name becomes the global variable __name__ Import into Python interpreter with: import markov Access functions in the module with: markov.mca(alice30.txt)
More about Modules Global variables in module don’t affect the user’s global variables Module variables can be accessed modulename.itemname Modules can import other modules from markov import * Placed at the beginning of importing module * imports all names
Executing as Scripts Can run a Python module with: python markov.py Sets ‘__name__’ to ‘__main__’ if __name__ == "__main__": import sys markov(str(sys.argv[1])) Can be run as a script if above is placed at end of module $ python markov.py alice30.txt
Module Search Path Can be modified in Unix /usr/local/lib/python Can be listed in: Environment variable ‘PYTHONPATH’
‘Compiled’ Python Files.pyc file created when.py is complied ‘byte-compiled’ version of the.py module Can optimize code with –O or –OO flag Creates.pyo files Program doesn’t run faster with.pyc or.pyo The modules are just loaded faster
Standard Modules Comes with library of standard modules ‘sys’ module sys.path can be used to modify PYTHONPATH >>> import sys >>> sys.path.append(‘[Path to be added]')
dir() Function Returns sorted list of all the names defined by the module >>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions']
Packages Collection of modules __init__.py starts the list of modules in a package
Packages cont. Import individual modules import sound.effects.echo If ‘__init__.py’ includes __all__ = ["echo", "surround", "reverse"] Then the following statement would import those listed above from sound.effects import * ‘__path__’ attribute is initialized with the list containing name of the directory holding package’s ‘__init__.py’ Can be modified to extend set of modules in a package
Intra-package References Sometimes modules in different subpackages need to reference a module in another subpackage If ‘sound.filters.vocoder’ module needed to use ‘echo’ in the ‘sound.effects’ package: from sound.effects import echo Can also use implicit relative imports from. import echo from..filters import equalizer
Questions?