Because this is just how Python works - keywords such as class
and def
are not declarations. Instead, they are real live statements which are executed. If they were not executed your module would be .. empty :-)
Anyway, the idiomatic approach is:
# stuff to run always here such as class/def
def main():
pass
if __name__ == "__main__":
# stuff only to run when not called via 'import' here
main()
See What is if __name__ == "__main__"
for?
It does require source control over the module being import
ed, however.
Happy coding.