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

Importing module on python / jupyter

I made very simple test.py -file and I want to use it as module:

def add(a,b):
    return a+b

def mult(a,b):
    return a*b

When I run another notebook and try to import it, the import is "succesful".

import numpy as np
import test 

x= int(input("enter value x"))
y= int(input("enter value x"))

array1= np.array([x,y])
array2= np.array([-x,-y])  

answer1 = add(x,y)
answer2 = mult(x,y)

print(answer1, answer2)

However, when I run my code it comes back:

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

"NameError: name 'add' is not defined"

I can by-pass this by editing my code:

from test import add, mult

and then it will work.

I do not quite understand why I can’t run the whole file? Could someone enlight me?

Because there is function like:

if __name__ == '__main__':

that is used to not return results from the module? For me that makes no sense when I can’t run the whole file as import?

I know this is bit vague question, but I appreciate your time

>Solution :

If you want to use import test and get what you’re asking for, then you want to write:

answer1 = test.add(x,y)
answer2 = test.mult(x,y)

and it’ll work. This is because you have just imported the module into your current namespace and you need to access the contents of that module using name of that module followed by . , i.e., test. in your case. Had you used from test import add, mult, then that means you would have not imported the module test but the functions add, mult into your namespace and hence could directly access them.

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