Python calls all print functions from imported file

Hi everyone,

today I learnt about the import statement and tried it with two python files. One, let’s call it contains 2 defined functions that I wrote and two random print statements. I imported code1 to, which is the second python file, using import code1. When I try to call a function in via print(code1.function()), I get not only the function called but also both of the print statements executed, which I don’t want. Could anyone please help me with how you make it so when you call a function (in code 2) that is imported (from code1 )that the other print statements from the original file (code1) don’t get executed in code2? Thanks a lot!

Python executes all code from the imported file, so there’s no way to pick at the import which parts to run or not.

You can put those two calls inside of separate function (which could be called from different files if needed) and/or put them after the check if file is run as standalone or if it’s being imported.

For the second approach it is needed to check the __name__ variable. For example:

if __name__  == '__main__':
    # code to execute when file is run standalone

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.