Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python Modules Intro

Yura Hulpa
February 19, 2016

Python Modules Intro

Introduction into Python Modules for the students of NULP Lviv University

Yura Hulpa

February 19, 2016
Tweet

More Decks by Yura Hulpa

Other Decks in Programming

Transcript

  1. How import work? 1.Find module 2. Compile into byte code

    3. Execute program code of module to make it accessible
  2. __init__.py The __init__.py files are required to make Python treat

    the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
  3. Byte code? Byte code - .pyc files If byte code

    of corresponding .py file is not older than .py, it will be used. If older - compile once more. Also possible to use .pyc files without corresponding .py files.
  4. Run stage All variable assignments, function definition etc., are executed

    when you use import statement Example: if in module that is being imported print function is called you will see that print when module is imported
  5. Why to use modules? 1. Code reuse 2. System namespace

    partitioning 3. Implementing shared services and data
  6. Search path 1. Program home directory 2. PYTHONPATH 3. Standard

    library dirs 4. Site-packages directory
  7. How import could be resolved • A source code file

    named b.py 
 • A byte code file named b.pyc 
 • An optimized byte code file named b.pyo (a less common format) 
 • A directory named b, for package imports
 • A compiled extension module, coded in C, C++, or another language, and dy- namically linked when imported (e.g., b.so on Linux, or b.dll or b.pyd on Cygwin and Windows) 
 • A compiled built-in module coded in C and statically linked into Python 
 • A ZIP file component that is automatically extracted when imported 
 • An in-memory image, for frozen executables (Frozen modules are modules wri en in Python whose compiled byte-code object is incorporated into a custom-built Python interpreter by Python’s freeze utility. See Tools/freeze/ for now)
 • A Java class, in the Jython version of Python 
 • A .NET component, in the IronPython version of Python 

  8. Tips, tricks and rumours 1.Asterisk import from os import *

    2. from usage with reload 3.Importing functions with same names from different modules 4. Top level assignments(assignments created outside function, class namespace) creates module a ributes 5.Namespaces could be accused as dictionaries(__dict__, dir(os))