-4

I am new to python please suggest me the solution

I have two python files first is imtest.py as follows:

d = dict()

if __name__ == '__main__':
    def salry(a):
        d["f"] = a

    print (d)

second is testim.py as follows:

import imtest 

a= 90
b = 200
imtest.salry(a)
imtest.salry(b)

When I am trying to run testim.py, it's giving error as :

AttributeError: module 'imtest' has no attribute 'salry'

Then I have modified second file testim.py as follows:

from imtest import salry

a= 90
b = 200
salry(a)
salry(b)

Now I am getting error as

ImportError: cannot import name 'salry'

What could be the error why I am not able to import that function?

Piyush S. Wanare
  • 4,703
  • 6
  • 37
  • 54
  • salry is defined inside of the `if __name__ ...` scope, so it's not available. – hellow Aug 02 '18 at 07:30
  • Remove the `if __name__ == '__main__':` in `imtest` and define he function `salary` outside – Sruthi Aug 02 '18 at 07:30
  • You're putting the salry(a) inside the `if __name__=='__main__':` you can't import this function, this should be in the outer scope. – user2906838 Aug 02 '18 at 07:31

4 Answers4

1

The __name__ magic variable has different value depending on whether the module is executed as a script (python imtest.py) or imported from another module. In the first case, __name__ is set to "__main__", in the second case it gets the module's name ("imtest" in your case). The result is that everything in the if __name__ == "__main__": block is only executed when using imtest.py as a script. When you import it from testim.py this part is not executed, so the def salry statement is not executed, so the function is not defined, so you cannot import it.

The solution is quite obvious: put the function definition outside this block:

d = dict()

def salry(a):
    d["f"] = a

if __name__ == '__main__':
    print (d)
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
0

If you want your salary function to be available to other modules, it needs to be in outer scope, so:

d = dict()

def salry(a):
    d["f"] = a

    print (d)
Shan
  • 369
  • 2
  • 9
-1

Instead of this you have to this

d = dict()
def salry(a):
    d["f"] = a
    print(d)

now you can use it as from imtest import salry Now it works fine

utks009
  • 573
  • 4
  • 14
-1

Your imtest.py file is imported in your testim.py file, it's not the file that you're running. So it's not your main file, therefore the condition (name == 'main') will be false, and the salry function won't be defined.

You must remove the if statement:

d = dict()
def salry(a):
    d["f"] = a
    print (d)
Jacques Ung
  • 157
  • 2
  • 6