Organize Code

Source File

Python

 

Defining module

Python 2.7
# logger.py 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:
    err(msg)
  elif type == 1:
    warn(msg)
  else:
    info(msg)

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

logger.info('logger.py')  # INFO: logger.py

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('logger.py')         # INFO: logger.py

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('logger.py')         # INFO: logger.py

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

 

__import__

Python 2.7
logger = __import__('logger')

logger.info('logger.py')  # INFO: logger.py

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
 

Aliasing

Python 2.7
import logger as Log
from logger import info as printInfo

Log.info('logger.py')     # INFO: logger.py
printInfo('logger.py')    # INFO: logger.py

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