When Importing A Function It Runs The Whole Script?
Solution 1:
import
ing a file is equivalent to running it.
When you import
a file (module), a new module object is created, and upon executing the module, every new identifier is put into the object as an attribute.
So if you don't want the module to do anything upon importing, rewrite it so it only has assignments and function definitions.
If you want it to run something only when invoked directly, you can do
A = whatever
defb():
...
if __name__ == '__main__'# write code to be executed only on direct execution, but not on import# This is because direct execution assigns `'__main__'` to `__name__` while import of any way assigns the name under which it is imported.
This holds no matter if you do import module
or from module import function
, as these do the same. Only the final assignment is different:
import module
does:
- Check
sys.modules
, and if the module name isn't contained there, import it. - Assign the identifier
module
to the module object.
from module import function
does
- Check
sys.modules
, and if the module name isn't contained there, import it. (Same step as above). - Assign the identifier
function
to the module object's attributefunction
.
Solution 2:
You can check if the module is imported or executed with the __name__
attribute. If the script is executed the attribute is '__main__'
.
It is also good style to define a main function that contains the code that should be executed.
def main()
# do something
pass
if __name__ == '__main__'
main()
Post a Comment for "When Importing A Function It Runs The Whole Script?"