Import a python module without running it

In another.py, move the code that you don’t want to be ran into a block that only runs when the script is explicitly called to run and not just imported

def my_func(x):
    return x

if __name__ == '__main__':
    # Put that needs to run here

Now if you are in your_script.py, you can import the another module and the my_func function will not run at import.

from another import my_func # Importing won't run the function.
my_func(...) # You can run the function by explicitly calling it.

Leave a Comment