wtfpython icon indicating copy to clipboard operation
wtfpython copied to clipboard

Calling the function without calling it

Open AkshitMehra1 opened this issue 4 years ago • 4 comments

â–¶ Calling the function without calling it

Make a file test.py Add the following code

def print_HelloWorld():
    print("Hello World")
print_HelloWorld()
print("Hello")

Make another file called try.py Add the following code and then run this file

import test

Output

Hello World Hello

See without even calling the function we get the ouput.

💡 Explanation:

This is the magic of import statement in python. Whenever we import a file all the code that is outside of main runs. This is why whatever we write in test.py it will run in when we are importing the file to any other program. To overcome this, we use:

if __name__=='_main__':

and then write everything in the main function. This will stop running the code that is in the imported file.

We can change the test.py file to

def print_HelloWorld():
  print("Hello World")
if __name__=="__main__":
  print_HelloWorld()
  print("Hello")

Output

>>>

Now we get the desired result and nothing is called when we import the test.py file.

AkshitMehra1 avatar Aug 31 '21 10:08 AkshitMehra1

I don't really understand this one, you are literally calling a function here image

IamMusavaRibica avatar Jan 08 '22 23:01 IamMusavaRibica

I don't really understand this one, you are literally calling a function here image

Actually, I am not running this file. I ran another file in which this file is imported and this code executes automatically.

AkshitMehra1 avatar Jan 09 '22 07:01 AkshitMehra1

Actually, I am not running this file. I ran another file in which this file is imported and this code executes automatically.

That is absolutely expected behaviour. Code is executed upon import.

sebix avatar Jan 09 '22 10:01 sebix

Exactly. And the output goes to the main file's sys.stdout, not anywhere else (and if the imported file changes it , it also affects the main file)

IamMusavaRibica avatar Jan 09 '22 12:01 IamMusavaRibica