1.

What are the different ways of importing a module?

Answer»

Python’s import mechanism makes it possible to use CODE from one script in another. Any Python script (having .py extension) is a module. Python offers more than one way to import a module or class/function from a module in other script.

Most COMMON practice is to use ‘import’ keyword. For example, to import functions in math module and CALL a function from it:

>>> import math >>> math.sqrt(100) 10.0

Another way is to import specific function(s) from a module instead of populating the namespace with all contents of the imported module. For that purpose we need to use ‘from module import function’ syntax as below:

>>> from math import sqrt, exp >>> sqrt(100) 10.0 >>> exp(5) 148.4131591025766

Use of wild card ‘*’ is also permitted to import all functions although it is discouraged; instead, BASIC import statement is preferred.

>>> from math import *

Python library also has __import__() built-in function. To import a module using this function:

>>> m=__import__('math') >>> m.log10(100) 2.0

Incidentally, import keyword internally calls __import__() function.

Lastly we can use importlib module for importing a module. It contains __import__() function as an alternate implementation of built-in function. The import_module() function for dynamic IMPORTS is as below:

>>> mod=input('name of module:') name of module:math >>> m=importlib.import_module(mod) >>> m.sin(1.5) 0.9974949866040544


Discussion

No Comment Found