Python — Avoid “from module import *”

Useful Python programming tips

Tony
3 min readNov 12, 2022

--

In Python coding, you often use the import keyword to make code in one module available in another. Have a good understanding of import in Python are important, it will help you to structure your code effectively.

Using import properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.

There are two common ways to import modules: import statement and from … import statement. If possible, you should avoid using the from module import * statement.

Why Avoid “from module import *”

Let’s me quick show you one example, first of all, let’s compare the amount of objects that loaded by import and from module import * statements.

import

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> import math
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math']

from math import *

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> from math import *
>>> dir()
['__annotations__'

--

--

Tony
Tony

No responses yet