Difference between import file and from file import * in Python


In python, it’s common to import functions from another file.
So what’s the difference of the these two cases.

The import src.myfile statement and from src.myfile import * statement are used for different purposes and have different effects on how the module’s functions and variables are imported.

The import src.myfile statement imports the src/myfile.py module as a whole, without making any of its functions or variables directly accessible in your code. Instead, you have to prefix any function or variable you want to use with the module name. For example, if src/myfile.py contains a function named myfunc, you can call it using the following code:

import src.myfile
result = src.myfile.myfunc(arg1, arg2, ...)

On the other hand, the from src.myfile import * statement imports all functions and variables defined in the src/myfile.py module into your current namespace. This means that you can use them directly in your code without prefixing them with the module name. For example, if src/myfile.py contains a function named myfunc, you can call it using the following code:

from src.myfile import *
result = myfunc(arg1, arg2, ...)

However, also notice that using import * is generally not recommended, as it can create naming conflicts and make it harder to read and understand your code. It’s usually better to use the import module_name syntax and prefix any functions or variables you use with the module name, or to use the from module_name import function_name, variable_name syntax to import only the specific functions or variables you need.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC