5 ms·
Interesting. I sort of assumed Python had singletons natively, because I'm so used to using them in Ruby. This guy doesn't do it here, but you can make singlet
by SlyShy 16y ago
Interesting. I sort of assumed Python had singletons natively, because I'm so used to using them in Ruby.
This guy doesn't do it here, but you can make singletons relatively painless in Python by using decorators.
- torial 16y agoLooks like decorators were after the article was written: http://www.python.org/dev/peps/pep-0318/ http://www.python.org/dev/peps/pep-0318/ E.g. 2/28/2003 vs 6/5/2003
- SlyShy 16y agoYeah, it wasn't meant as a criticism of the article. More of a "Python can do nice things too" shout out to other Rubyists. I don't know about them, but I find myself translating code between Ruby and Python for various reasons and it is nice to learn the parallels in idioms and such. So, upvoted.
- sophacles 16y agoOr just use modules. Seriously, it is a true singleton.
- SlyShy 16y 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 16y 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 16y agoThank you for explaining. :)
- njharman 16y ago> No matter how many times you import foo Just don't reload it.
- sophacles 16y 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 16y agofrom foo import bar
- moe 16y 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.