Best post on import and from statement in python – 1

Import and from statement in python

Although we can code and program logic in python and it is comparatively easy. As a programmer we can program any logic simple example like: time delay, power function, finding square root, finding factorial, etc. but the question arises,
“What if we have written these programming logic in another .py file and we want to access those logic from that particular file?”
Or Most of the time we will see that the programming logic we are searching for is already written in either python’s default modules or we can get such modules from the internet.

In both the cases we need an option to incorporate complete file (module) or part (class or method) from file. There is one solution for the above problems and that is the “import” statement.

As the name says, “import” statement allows us to add another file (module) completely or to add part (class or method) from a file in our program.

“Import” statements load all the required files (module) or class or methods at the beginning (it is good practice to add an “import” statement at the beginning of the file).

Because of the “import” statement we don’t have to write the same programming logic again and again wherever we need, we just have to create one file (module) and write all programming logic in it and access this file using the “import” statement in other files wherever we need.

Below are the different types by which we can use the “import” statement.

Import single module

This will include the entire file (module) in our program with its methods but classes and this makes the program heavy and execution slow.

"""
Author : ITVoyagers (itvoyagers.in)

Date :5th September 2020

Description : Program to show use of import statement

"""
>>>import math # it will include entire time module in our program with its methods and classes
>>>math.sqrt(25)

Output

5

In the above example we have used sqrt() from the math module which helps us to find the square root of any numeric value.

Import multiple modules

This will include all the files (modules) in our program with their methods but classes and this makes the program heavy and execution slow.
We have to separate each module using comma as shown below:

"""
Author : ITVoyagers (itvoyagers.in)

Date :5th September 2020

Description : Program to show use of import statement for multiple values

"""
>>>import time,math # it will include entire time and math module in our program with their methods and classes
>>>time.sleep(5)
>>>math.sqrt(25)  

Output

5

from … import statement

Now we know that we can import the entire file in our program but it makes our program heavy and affects its execution speed. But what if we don’t want the entire file but rather we need a few methods or classes from the file? This is where “from” comes in the picture.
“From” allows us to select and include the exact method or class from a particular file.
Example

"""
Author : ITVoyagers (itvoyagers.in)

Date :5th September 2020

Description : Program to show use of from module import method

"""
>>>from math import sqrt
>>>sqrt(25)

Output

5

Now we can see that we didn’t use “math.sqrt()” instead we use “sqrt()” because we have included the “sqrt()” method directly in our program.

from … import * statement

What if we want to add all the methods and classes from one particular file and while using those methods and classes we don’t want to use the file’s name as prefix. This is where “*” comes into the scene. “*” allows us to add all the methods and classes from one particular file and we don’t have to use the file’s name as prefix while using those methods and classes.
Example

"""
Author : ITVoyagers (itvoyagers.in)

Date :5th September 2020

Description : Program to show use of from module import *

"""
>>> from math import *
>>> pi
3.141592653589793
>>> sqrt(5)
2.23606797749979
>>> 

import … as statement

Now what if we want to include the entire file and we want to use its multiple methods and classes but we find out that file name is too long and it is time consuming to add it as a prefix while calling method and class, same goes with method and class names.
E.g.
There is a module named “sound.effects.echo” now it is time consuming to type this name each and every time when we use its methods and classes.

We need “as” statement in such scenarios. “as” statement will let us allow to assign short name to file and this short name is known as aliases.
Example

"""
Author : ITVoyagers (itvoyagers.in)

Date :5th September 2020

Description : Program to show use of import module with aliases

"""
>>>import math as m
>>>m.sqrt(25)

Output

5

Difference between from and import statement

import module
1. One of the advantage of is, it requires low maintenance as it do not require any additional statement to start using functions present in module.
2. Typing module name to call its method in script can be tedious so aliases can be created for help.
example: module.func can be replaced with m.func
from module import abc
1. One of the advantage of is we require less typing and more control is over accessing methods present in module.
2. One drawback is we require to update import statement to use new method from the module.
3. We may loose the context about abc i.e less clarity is gained about pow() rather than math.pow().
Example

import p
p.xyz()
p.tuv()

Note: Here p is imported so both functions are accessible

from p import xyz
xyz()
tuv() #as tuv() is not imported it will raise and error

Note: Here p is importing specific function i.e xyz() so other function i.e tuv() is not accessible



For other python basics related posts:

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon.......



For other advanced python related posts:

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in 're' module(Part I)- Match vs Search
Functions in 're' module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
New posts coming soon.......

Leave a Comment