3 ms·
Or just use modules. Seriously, it is a true singleton.
by sophacles 17y ago
Or just use modules. Seriously, it is a true singleton.
- SlyShy 17y agoI just use classes, so I'm not sure what you took my meaning to be. I'm certainly not requiring the singleton library.
- sophacles 17y agoA module is a singleton. No matter how many times you import foo, the namespace foo is always the same. If you reassign foo.bar in in code in module x, then later access foo.bar from module y, it will be the value assigned in X. This is not amenable to inheritance tho, however there is a strong argument against inheritance in singletons anyway. Further, the borg pattern is considered "more pythonic" in the case of inheritable singletons, as frequently what is desired in such cases is shared state vs instead of shared identity.
- SlyShy 17y agoThank you for explaining. :)
- njharman 17y ago> No matter how many times you import foo Just don't reload it.
- sophacles 17y agoWell, as far as I am concerned, if import foo is the same as instantiating foo, then reload is calling destructor then instantiation again. How is this worth comment? In a discussion of c++ singletons would you comment "Just dont call delete fooptr; fooptr = new foo();"?
- mdg 17y agofrom foo import bar
- moe 17y agoIf you reassign foo.bar in in code in module x, then later access foo.bar from module y, it will be the value assigned in X. In the general case, yes. Unfortunately, due to some quirks in the module loader, assigning bar right inside foo might not yield the expected result, though. This is actually one of the python warts that annoys me the most.