3 ms·
That’s clever, but illustrates something not widely appreciated: When you import a module, Python executes it. For instance, `def` isn’t syntax that says “hey
by kstrauser 3y ago
That’s clever, but illustrates something not widely appreciated:
When you import a module, Python executes it. For instance, `def` isn’t syntax that says “hey compiler, this is a function!” It’s a statement that’s executed at runtime to define a function. You can put any code you want at the top level of a module and it’ll get executed when the Python interpreter gets to that line.
- sigg3 3y agoIMO 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.
- filmor 3y agoPython 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.
- lordmauve 3y agoPython 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.
- kstrauser 3y agoIt’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.