Unsual Import ..from.. behaviour

(Joannah Nanjekye) #1

So recently while working with imports, I came across a weird scenario.

Given a code file calc.py with the code below:


def add (x, y):
	return x + y

print ("peeping")

def subtract (x, y):
	return x - y

I decide to import just the add function from this module and print result of the function.


from calc import add

print (add(4, 5))

The output also returns the results of the global print function.


Is this accepted behavior or it is something we need to fix ? if it is correct then any documentation for the same. I dint want to post this on the bug tracker as am not sure its a valid bug or its my misunderstanding of the language.

1 Like

(Neil Schemenauer) #2

It is accepted and documented behavior. It is the reason for the

if __name__ == '__main__'



(Gregory P. Smith) #3

This is expected. The first time a module is imported it is executed. The print function was part of the code executed when importing that module.


(Ryan Soklaski) #4

This can be surprising behavior when it is first encountered. Here is a useful discussion of what is going on when you import a module.