Import a python module without running it

Solution 1:

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.

Solution 2:

You could move the function in question to another file and import it into your file.

But the fact that you are running everything on import makes me think you need to move most of the stuff in your imported module into functions and call those only as need with a main guard.

def print_one():
    print "one"

def print_two():
    print "two"

def what_i_really_want_import():
    print "this is what I wanted"


if __name__ == '__main__':

    print_one()
    print_two()

rather than what you probably have, which I guess looks like

print "one"

print "two"

def what_i_really_want_import():
    print "this is what I wanted"

With the main guard anything in a function will not be executed at import time, though you can still call it if you need to. If name == "main" really means "am I running this script from the command line?" On an import, the if conditional will return false so your print_one(), print_two() calls will not take place.

There are some good reasons to leave things in a script to execute on import. Some of them are constants, initialization/configuration steps that you want to take place automatically. And having a module-level variable is an elegant way to achieve a singleton.

def print_one():
    print "one"

def print_two():
    print "two"


time_when_loaded = time.time()

class MySingleton(object):
    pass

THE_ANSWER = 42
singleton = MySingleton()

But by and large, don't leave too much code to execute on load, otherwise you'll end up with exactly these problems.

Solution 3:

In the other python script , which you are going to import, you should put all the code that needs to be executed on running the script inside the following if block -

if '__main__' == __name__:

Only when running that python file as a script, the __name__ variable will be __main__ . When you import the script, any code inside this if condition would not run.