← Back to context

Comment by saila

7 days ago

The call to logging.basicConfig happens at import time, which could cause issues in certain scenarios. For a one-off script, it's probably fine, but for a production app, you'd probably want to set up logging during app startup from whatever your main entry point is.

The Python standard library has a configparser module, which should be used instead of custom code. It's safer and easier than manual parsing. The standard library also has a tomllib module, which would be an even better option IMO.

Regarding your first paragraph, we still don't understand what the issue actually is.

  • Logging configuration is done at import time for "utils" module.

    Imagine code like this:

    main.py:

      import logging
      logging.basicConfig(...)
    
      logging.info("foo") # uses above config
      
      if __name__ == "__main__":
          import utils # your config is overridden with the one in utils
          logging.info("bar") # uses utils configuration
          ...
    

    Or two "commands", one importing utils and another not: they would non-obviously use different logging configuration.

    It gets even crazier: you could import utils to set the configuration, override it, but a second import would not re-set it, as module imports are cached.

    Basically, don't do it and no unexpected, confusing behaviour anywhere.

    • As a non Python developer, what would be the use-case(s) for importing a module inside of the main function instead of importing it at the top of main.py with the others?

      1 reply →