Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading