Skip to content
Advertisement

Is it possible to import a function from another script without importing the variables from such file?

I have two scripts 1 and 2, I would need these two script to work independently from one another, but I also need script 2 to be able to use the function in script 1 if needed. I tried to automate as much as possible, so each script has a number of variables inside already defined.

Here is an oversimplified example of the scrips that I am talking about.

Script 1:

def plustwo(n):
    out = n + 2
    print(out)

m=3
plustwo(m)

Result:
5

Script 2:

from file import plustwo

z=5
plustwo(z)

Result: 
5
7

As you can see, when I import the function from script 1, even if I use from file import plustwo, also the variable is imported, this causes script 2 to return two results, one with variable m (5) and another with variable z (7).

Do I necessarily need to create a third script, identical to script 2 but without the m variable? Is there a way to exclude such variable from the import? (I just want the function from script 2, so that I can use script 1 with the variables it already has.)

Advertisement

Answer

In script 1, you can add if __name__ == '__main__':, so that it only executes

m=3
plustwo(m)

if the program is run directly from script1.py.

In the end, you only need to modify script 1 a little bit:

def plustwo(n):
    out = n + 2
    print(out)

if __name__ == '__main__':
    m=3
    plustwo(m)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement