Jesse Whitehouse Developer | Analyst

Import Methods in Python

What’s the difference between import, import from, and import * in Python1?

import module

Assume that function do_something() is defined in myModule. You import myModule into main.py with the statement: import myModule. To call the function you would use the expression myModule.do_something().

You can use the as modifier in your import statement to enhance readability. For example, import myModule as mod would let you call the function with mod.do_something().

from module import

Assume that function do_something() is defined in myModule. You can import just one function with the statement from myModule import do_something(). To call the function, you do not need to prefix the function call with a .

Instead, you call the function normally with the expression do_something().

You can use the as modifier here too. from myModule import do_something() as do lets you call do_something(_args_) with the expression do(_args_).

import *

Star import behaves like import from. Functions imported this way do not require a prefix when called. But this method imports all the functions in the selected module. If myModule contains the functions do_something(), add_something(), and make_something() you can call these functions without a prefix.

Star imports are convenient if you interact with Python in the shell. It’s cumbersome to import specific functions with import from or to type the module prefix of each function with import module. However, you should avoid star imports in your own modules. A complicated algorithm becomes difficult to debug and maintain if functions like do_something() are defined elsewhere in the file structure. This becomes more important if you import many modules.

For example, if the top of your module looks this:

from module1 import *
from module2 import *
from module3 import *
from module4 import *

and you call do_something() in the script body, you have to search through the imported modules to find the function definition. Star imports are hostile to the person reading your code, whether that’s a team member on your project or you in six months.

  1. See this useful response on Stack Overflow or the Python Docs for more information.