Quantcast
Channel: What side-effects, if any, are okay when importing a python module? - Software Engineering Stack Exchange
Viewing all articles
Browse latest Browse all 5

Answer by bta for What side-effects, if any, are okay when importing a python module?

$
0
0

One big issue with your example logging code is that both those lines of code could fail for a multitude of reasons (read-only filesystem, invalid path, lack of filesystem permissions, etc). These errors will be extremely difficult to work with. I can technically wrap a import statement in a try block and catch any exceptions, but how am I supposed to handle those exceptions intelligently this early in my program? The import was the first line in the file, I don't even have any of my support code in scope yet. There's no clean way for me to try to fix the problem and retry the operation. There's also no clean way for me to provide your library with enough information to avoid the error in the first place (like a path to a usable log directory). If this functionality was instead inside a regular my_module.init_log() function, then handling these sorts of problems becomes a straightforward task.

Don't do anything during import that involves non-trivial error handling. You're just making it significantly harder to handle errors. You definitely don't want to take an otherwise-recoverable error and promote it to a fatal error simply because you wanted to run the code during import for some reason.


Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>