Organize Code

Source File



Defining module

Python 2.7
# file

def err(msg): print("ERR: " + msg)
def warn(msg): print("WARN: " + msg)
def info(msg): print("INFO: " + msg)

def logMsg(msg, type):
  if type == 0:
  elif type == 1:

Python code can be organized in separate .py files, and then each file can be imported in other .py files.


Import module

Python 2.7
import logger'')  # INFO:

The import statement imports a specified module and creates a reference to that module object in the current namespace.

The builtin dir method lists all the imported objects from a module.

dir(logger)   # ['err','info','logMsg','warn', ...]

Import module items

Python 2.7
from logger import info, err

info('')         # INFO:

The from-import statement imports specified objects from a module and it creates a reference to those objects.

Here we are importing info and err functions from logger module.


Import module items using wildcard

Python 2.7
from logger import *

info('')         # INFO:

The * in the from-import statement, imports all public objects inside a module and creates a reference to each of them.



Python 2.7
logger = __import__('logger')'')  # INFO:

The builtin __import__ function works similar to import with these differences:

  • Importing modules are specified as strings
  • Needs to be explicitly assigned to a variable


Python 2.7
import logger as Log
from logger import info as printInfo'')     # INFO:
printInfo('')    # INFO:

You can rename references of the imported objects using as keyword in your import statement.