Is executing code when importing a module in Python a bad practice?
📁 question, AI
I've come across mentions several times that executing code when importing a module is a bad practice. However, I couldn't find any explanation for this statement anywhere. There are two questions.
First: why is executing code when importing a module considered a bad practice?
Second: what counts as code execution in the context of this statement? Assigning values to global variables, executing functions, or something else? After all, defining classes and functions in this module, as well as importing other modules (in this module that we are importing), can't this also be considered "code execution"?
By default, the stack size in Python is limited to 1000 calls. This is usually sufficient. If you are writing a recursive algorithm (you like it, or you are porting code from Lisp, or you are a fan), this limitation can seriously ruin your mood.
The limit can be relaxed by calling . This call will increase the limit, but it is not omnipotent. In Python, the number of calls is also limited by the amount of memory allocated for the stack. The stack size cannot be changed from within the program. If the stack overflows, the operating system stops the interpreter.
The choice is sad: either the program hits the interpreter's own limit and gets an exception
RecursionError: maximum recursion depth exceeded in comparison
Log in to leave an answer