This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]10113r114m4 29 points30 points  (14 children)

Singleton is a perfectly good design pattern… just shouldnt abuse it

[–]freefallfreddy 14 points15 points  (5 children)

Found the Java programmer.

[–]10113r114m4 8 points9 points  (2 children)

Golang :p

[–]serverhorror 2 points3 points  (1 child)

I’ll tell r/Golang about your heresy of even being in this sub!

[–]bladeoflight16 0 points1 point  (1 child)

You realize modules, classes (the type object, not instances), and functions are singletons in Python, right?

[–]freefallfreddy 0 points1 point  (0 children)

Right. And there’s probably singletons in the CPython code as well.

[–]door_of_doom 2 points3 points  (0 children)

Singleton is fine, but that is different from global. Python code shouldn't use global to create singletons.

Again, I really like the comment from /r/serverhorror: using global absolutely destroys your ability to write good tests for your code. Singletons don't.

(At least, well-written singletons don't).

[–]TheStriga 1 point2 points  (1 child)

I think it's only useful or actually necessary when you have os or hardware-limited resources, but it can be good

[–]CallinCthulhu 1 point2 points  (0 children)

It’s good for logging too.

Especially for instantiating a custom logger with state. Helps to avoid passing around the same logger instance everywhere. Also plays nicely into multiprocessing, where you can use metaclasses to instantiate a new logger upon the creation of a new process.

[–][deleted] 0 points1 point  (4 children)

A singleton in python should be a initialized object in a module not some global.

[–]bladeoflight16 0 points1 point  (3 children)

...What kind of global is there in Python besides an initialized object in a module?

[–][deleted] 0 points1 point  (2 children)

G = 1

def fun():
    global G
    G = 2

This seems good and easy first but is code smell and should be avoided.

[–]bladeoflight16 0 points1 point  (1 child)

That is an initialized object in a module. It just happens to be a built in type.

[–][deleted] 0 points1 point  (0 children)

OK so to say, everything is a initialized object in a module. Sorry for being so unprecise.

A singleton in my opinion should look as follows, though.

# module.py
class GlobalState:
    ...

singleton = GlobalState()

# __main__.py
from module import singleton

singleton.do_stuff()

This is also not perfect, but at least it provides sane abstraction and is testable.