Preventing Python Code from Importing Certain Modules

How to prevent modules code execution from imported module in python?

How to prevent modules code execution from module in python?

You can't, when you import a module, it runs everything that is called in the global scope.

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



Leave a reply



Submit