How to prevent modules code execution from imported module in python?
You can't, when you import a module, it runs everything that is called in the global scope.How to prevent modules code execution from module in python?
You can change it so that it's easy to call or not:
def main():
Fu().baz()
if __name__ == '__main__':
main()
And then when you want it called you import it and call main()
and it will still automatically run when you run it as the main module. Why is Python running my module when I import it, and how do I stop it?
Because this is just how Python works - keywords such as class
and def
are not declarations. Instead, they are real live statements which are executed. If they were not executed your module would be empty.
The idiomatic approach is:
# stuff to run always here such as class/def
def main():
pass
if __name__ == "__main__":
# stuff only to run when not called via 'import' here
main()
It does require source control over the module being imported, however. Python: How do I disallow imports of a class from a module?
The convention is to use a _ as a prefix:
class PublicClass(object):
pass
class _PrivateClass(object):
pass
The following:from module import *
Will not import the _PrivateClass.But this will not prevent them from importing it. They could still import it explicitly.
from module import _PrivateClass
how to stop the import of a python module
You can just conditionally import the module:
if thing == otherthing:
import module
This is entire valid syntax in python. With this you can set a flag on a variable at the start of your project that will import modules based on what you need in that project. How to prevent execution of main Python code when importing a function
Quite simply:
# test.py
import sys
def testfunction(string):
print(string)
if __name__ == "__main__":
sys.exit(0)
The magic variable __name__
is set either to the module name (when the file is imported as a module) or to "__main__"
when it's executed as a script.
Related Topics
Should I Be Adding the Django Migration Files in the .Gitignore File
Stop Matplotlib Repeating Labels in Legend
Lookup Values by Corresponding Column Header in Pandas 1.2.0 or Newer
Method Not Allowed Flask Error 405
Split Dataframe into Relatively Even Chunks According to Length
Splitting List Based on Missing Numbers in a Sequence
Cartesian Product of a Dictionary of Lists
How to Access Class Member Variables in Python
Numpy Array Dtype Is Coming as Int32 by Default in a Windows 10 64 Bit MAChine
Is 'Import Module' Better Coding Style Than 'From Module Import Function'
Why Results of Map() and List Comprehension Are Different
Scale Matplotlib.Pyplot.Axes.Scatter Markersize by X-Scale
How to Increase Jupyter Notebook Memory Limit
Best Way to Make Django's Login_Required the Default