Why importing star is a bad idea in python

PythonServer Side ProgrammingProgramming

Importing all methods from a module in Python is a bad idea because of the following reasons.

  • It is difficult to find a parent module of the method which we used in the programs.
  • We are not allowed to create our functions with the names of methods.

Let's see an example. Below we write a function called add in the sample.py.

## sample.py file
def add(a, b):
return a + b

Example

Save the above file in the same directory as below Python file.

## let's assume we have module called sample
from sample import *

def add(*nums):
   return sum(nums)

print(add(1, 2, 3, 4, 5))

Output

If you run the above program, it will generate the following results.

15

If we have the same method called add in sample package then, it will be difficult for us to find the exact method which was named in the large programs. We can also get errors with the parameters.

Example

The above program called local function instead of the sample package method. If we want to invoke the sample package method, then we have to import sample as follows.

## let's assume we have module called sample
import sample

def add(*nums):
   return sum(nums)

print(sample.add(1, 2))

Output

If you run the above program, it will generate the following results.

3

Python allows us to import the modules as we want. But, in large programs, we will be confused with the names of the methods and user-defined functions. If you can manage the names of methods and user-defined functions, then import them at your convenience.

raja
Published on 04-Jul-2019 12:11:44
Advertisements