Skip to content
Advertisement

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:

"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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement