Python module import

Let’s recap some of the most common syntaxs in Python (related to modules and classes).

Search path

First thing first, Python search for modules from some certain directories:

  1. The directory containing the input script (or the current directory when no file is specified).
  2. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  3. The installation-dependent default.

(Look the Python official tutorial for further information.)

Module import

There are several different methods to import stuff from a Module.

  1. import my_module In this case, you can use all the methods defined in your module, but explicitly declare the name of your module is necessary.
import my_module
  1. from my_module import my_func Almost the same with previous one, except that you can directly call the function.
from my_module import my_func
  1. from my_module import * Now you can use any methods included in you module (can be dangerous!).
from my_module import *

A useful trick (also common in real world code) is, methods with a name started with _ (underscore) will not be imported by:

   from my_module import *

And that’s it for today!

Written on May 31, 2016