Importing modules

When you want to import a module you can use:

import  somemodule

Example:

import numpy

All functions and submodels are imported. To access to functions and submodule you will use:

numpy.array([1,2,3])

Alternatively you can use:

from somemodule import *

Example:

from numpy import *

In this case you import everything from the module and all functions will be loaded in the local namespace. You will use:

array([1,2,3])

This alternative however is not advisable, since it may result in ‘overlapping’ function names, where the latest imported function holds the position in memory.

If you want to import only a function from a module you can use:

from somemodule import somefunction

Example:

from numpy import abs

If you want to import two different modules, but in every module there is a function with the same name (for example open) you can use:

import somemodule as name1
import somemodule as name2

and use:

name1.open()
name2.open()

Example:

import numpy as np
import math as mt
np.exp()
mt.exp()

Alternatively you can also use:

from somemodule import open as name1
name1()

Example:

from math import exp as exp_mt
from numpy import exp as exp_nt
exp_mt()
exp_nt()
Back