[Python] Python modules act like singleton objects
Python modules act like singleton objects
Explanation
In Python, modules behave like singletons because they are only loaded once per program execution, no matter how many times they are imported. This means any module-level state (such as variables or configurations) is shared across all parts of the application.
Singleton
A singleton is a design pattern where a class has only one instance in the entire program. Any access to the class returns the same instance.
Logging module as an example
When importing and using logging, it's not required to create a new instance every time. Python loads the module once and stores it in sys.modules. Any future reference to logging refers to this already-loaded module.
import logging
logging.basicConfig(level=logging.INFO) # Configure logging (only done once)
logging.info("This is a log message")
Even if this module is imported elsewhere in the program, the configuration remains the same, providing that logging behaves like a singleton
Comments
Post a Comment