Computer Science
Explain the difference between import <module>
and from <module> import
statements, with examples.
Answer
import <module> statement | from <module> import statement |
---|---|
It imports entire module. | It imports single, multiple or all objects from a module. |
To access one of the functions, we have to specify the name of the module and the name of the function, separated by a dot. This format is called dot notation. The syntax is : <module-name>.<function-name>() | To access functions, there is no need to prefix module's name to imported item name. The syntax is : <function-name> |
Imports all its items in a new namespace with the same name as of the module. | Imports specified items from the module into the current namespace. |
This approach does not cause any problems. | This approach can lead to namespace pollution and name clashes if multiple modules import items with the same name. |
For example: import math print(math.pi) print(math.sqrt(25)) | For example: from math import pi, sqrt print(pi) print(sqrt(25)) |
Related Questions
Why should the from <module> import <object> statement be avoided to import objects ?
What do you understand by standard library of Python ?
Create module tempConversion.py as given in Fig. 4.2 in the chapter. If you invoke the module with two different types of import statements, how would the function call statement for imported module's functions be affected ?
A function checkMain() defined in module Allchecks.py is being used in two different programs. In program 1 as
Allchecks.checkMain(3, 'A')
and in program 2 ascheckMain(4, 'Z')
. Why are these two function-call statements different from one another when the function being invoked is just the same ?