Module helps to keep everything modular and separate. For instance many modules have a read() function since this is a common thing to do. Without using the <module>.<function> (...) syntax there would be no way to know which one to call.
In [1]:
# import os module
import os
os.getcwd()
Out[1]:
In [4]:
# The following command provides the details of the imported package definition
# help(os.listdir())
In [7]:
# save the following code as example.py
def add(a,b):
return a+b
# now you can import example.py
# import example
# example.add(5,4)
In [10]:
import math as m
print(m.pi)
In [11]:
from math import pi
print(pi) # please note the dot operator is not required
To import all definitions from the module just specify '*' as below. Please note that this not a good practice as it can lead to duplicate definitions for an identifier.
In [12]:
from math import *
print(pi)
In [13]:
import sys
sys.path
Out[13]:
In [14]:
# my_module.py
# print('This code got executed')
# import imp
# import my_module
# This code got executed
# import my_module
# import my_module
# imp.reload(my_module)
In [2]:
print(dir(os))
In [20]:
import math
print(math.__doc__)
math.__name__
Out[20]:
A package is just a way of collecting related modules together within a single tree-like hierarchy.
Like we organise the files in directories, Python has packages for directories and modules for files. Similar, as a directory can contain sub-directories and files, a python package can have sub-package and modules.
A directory must contain a file named __init.py in order for python to consider the directory as a package. This file can be empty but in general it is used for initialisation code for that package.
The following are different ways of importing the packages.
In [25]:
# examples
import math
from math import pi
print(pi)