Python Forum
Duplicate output when calling a custom function from the same file? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Duplicate output when calling a custom function from the same file? (/thread-18236.html)



Duplicate output when calling a custom function from the same file? - road2knowledge - May-10-2019

Hi folks,

I'm new to programming and python, and I don't understand why if you call a custom function from the same file it's defined in, you get duplicate output.

e.g. a file "question.py" containing the following:
def double(number):
    return number * 2

from question import double
print(double(1))
And if I were to manually input "double(2)" after running the module, the output seems perfectly normal (just one 4).
Why is that? And is there a way to avoid the duplicate apart from calling the function from a separate py file?

I know this must have been asked before, but I couldn't find it via forum search or Google (the queries all return questions related to list modification).

Thanks in advance for clearing up my confusion!


RE: Duplicate output when calling a custom function from the same file? - buran - May-10-2019

First of all - you don't need to import it if it is in the same module.
it is executed twice, because it is executed once during the import (line 4) and once when you call it on line 5. Remember that even if you use from ... import ... it's always the whole module being imported, but only the particular name imported is visible.

In more general context - if you have code that you don't want executed during import - that's where the if __name__ == '__main__': comes in handy:

let's say you have module named module1.py :

def double(number):
    return number * 2
 
if __name__ == '__main__':
    print(double(1))
and in another module named module2.py:

from module1 import double
print(double(2))
if you run module1 from command line then the body of the if __name__ == '__main__': would be executed and will print 2.
if you run module2 from command line, it will be imported (the whole module, but only name double will be visible), that part (line 5) will not be executed during the import and the only code executed would print 4.
(May-10-2019, 07:38 AM)road2knowledge Wrote: is there a way to avoid the duplicate apart from calling the function from a separate py file
Note that if you have in module1
def double(number):
    return number * 2

print(double(1))
and in separate module module2.py have

from module1 import double
print(double(2))
you will still get double output (i.e. being in separate file will not stop print(double(1)) being executed during the import in module2


RE: Duplicate output when calling a custom function from the same file? - road2knowledge - May-10-2019

Thank you so much explaining all that!
I think I finally understand it now.