0

I am trying to call a function 'myfunction()' defined in another py file 'file2.py' in same directory using below code

from file2 import *

myfunction()

Unfortunately, its executing my function twice. The import statement is also executing the function. Any insights on how to avoid this?

2
  • 3
    does file2 call myfunction anywhere? Commented Feb 7, 2020 at 11:10
  • You can try using as word like this from file2 import myfunction as myfunc Commented Feb 7, 2020 at 11:12

3 Answers 3

5

Probably you are calling inside your file2.py your function myfunction()

when you do

from file2 import *

you are loading every definitions (class, def, etc), and of course, every function called inside that .py.

To avoid this problem you can call your function myfunction() in your file2.py inside this scope:

if __name__ == '__main__':
    myfunction()

in this way it will not be executed when imported, but only if the file2.py is executed directly:

python3 file2.py
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!.. Exactly this was the issue!
1
#File name = file2
class file3:
   def method():
      print ("printing statement")
      return "Hello world"

Main file name file1.py

from file2 import *
print(file3.method())

You can define function and write return statement to avoid extra printing

Comments

0

Check your file2 and look for anything with myfunction() in it. If there is something like it, just remove it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.