Why we should avoid using import star in Python

In Python programs, we should not use import * as this habit is not good, by using import * statement we corrupt our namespace, as import * imports all the function and classes (may be required or not required) into our own namespace. This tutorial will also give you an idea if you should use import * in Python or not.

This arises clash with the function defined by the user or with the other imported libraries and we don’t easily recognize which particular function came from which library. There is always a risk of function overriding or variable overriding.

Some more reasons why import * should not be taken into practice are:

  • It is difficult to know or recognize what is imported from which particular module and thus makes code readability very low.
  • Possibility of hidden bugs increases.
  • We cannot detect errors statically in the source code as pyflake like tools cannot be used.

As we know, Python allows the user to import any module needed. But if we talk about large programs or many lines of code we will not be able to recognize the user-defined function and different methods.

But if you still want to use it, you should always be careful and try to use it well in a  maintained order.

Example

Let’s take an example to see a more practical and easy way how it works.

from x import * 
def sub(a,b):
  return a-b
print(sub(3,2))

 

Suppose that there was a ‘sub’ function in module X, the error which arises is that the defined ‘sub’ function overrides the ‘sub’ function from module X. Hence, it is suggested not to use import * in practice.

 

I hope you understand the concept if you have any doubt you may drop a comment. Your feedback will be appreciated.

Leave a Reply

Your email address will not be published.