I would not say that this is really a bad practice at all, you just need to approach this matter wisely, to understand what it means, to use it without thinking.
Reasons to limit this matter, if you think about it, I see the following:
Explicit is better than implicit . You lose control over when this code will be executed, and this may be important. Modules in Python can be imported not only at the top level, but also inside a function or method, which means that the module code will be executed not during the application start, but during the launch of such a function and the execution of the import
instruction in it. The functions importing a module, moreover, may not be one, and which of them, and when executed first in your huge application, may not be entirely obvious.
Despite the fact that the module code is executed once at the first boot (in fact, at subsequent imports, it does not even load), to make it run more than once is not so difficult. A good example (not the only way to do it) is considered here .
Your code will be re-executed when you reload your module using reload
, which may also be undesirable if this code has certain side effects.
This code can be executed for a long time, which will entail a slowdown in the loading of the module and, as a consequence, the launch of the application.
At the same time, I want to note that in general this possibility (in moderate quantities) is used everywhere, and, in moderate quantities again, in most cases, there are no problems. For example, a function decorator is the execution of custom code during module loading. Although, if the decorator does not just "change" the decorated function, but has side effects, it may (but not necessarily be far from) a source of problems if you do not understand all these mechanisms.
For the second question, assigning values (and not the results of user function calls) to global variables, creating functions and classes, importing other modules, that is, in some way, declarative code (which causes execution of not your user logic, but interpreter logic) The context of this statement is not considered code execution.
In general, the moral is that you just need to clearly understand the possible consequences of code execution when importing a module into Python, and it is reasonable to use this opportunity. The original statement about the inadmissibility of this is akin to saying that the goto
is an absolute evil. Yes, thoughtless use is fraught with enormous problems, but at the same time in the same Linux kernel goto
for those things where it is really appropriate is used everywhere.