Hacker News new | ask | show | jobs
by sigg3 1045 days ago
IMO Python imports behave like the bash source command.

This is why people use the `if __name__ == "__main__"` so the majority of people will address it in all their scripts even if they don't know the reason why.

It's a feature not a bug IMO. You can use importing a .py file as a singleton hack. You can also use `refresh` to re-load a module, to clear it of any runtime overrides.

3 comments

Python inports collect the locals in the "module script" and store them in a module object, which is then made available to the module that ran `import`. That module object is cached, so reimporting the module another time will not run the code again.

`source` is much more primitive.

Python imports are much more principled than sourcing bash though. They are executed in a new namespace, and subsequent imports reference that namespace directly instead of re-evaluating the code.

C extensions don't significantly change matters because the module is still constructed by procedural C code.

It’s definitely a feature! Just one that’s often not understood. If you include a file in a C program, that codes just sitting there until you call it (more or less, yada yada #define, etc.). If you import a Python module, it executes the code in it. That code is typically a set of statements that defines functions and classes, but it could be anything.