Hacker News new | past | comments | ask | show | jobs | submit login

It's basically a global / hoist with a more ergonomic way of accessing the state. Instead of a get_global_state() style function, you just have the Borg constructor.

Personally I'm a fan of dependency injection whenever possible. But borg pattern has gotten me out of a pinch (exactly) once.




Why not just make a global though?


My understanding is that Borgs can be subclassed, you can modify the behavior, use descriptors (setters/getters), etc. You also avoid the `global` keyword.

It's really not the most compelling reason. I recently found a cleaner way that actually achieves identity-equality, which I think is a much better way of going about things. Not actually using it anywhere at the moment, but I think it's neat.

    class Singleton(type):
        def __init__(cls, name, bases, dict):
            super(Singleton, cls).__init__(name, bases, dict)
            cls.instance = None

        def __call__(cls, *args, **kw):
            if cls.instance is None:
                cls.instance = super(Singleton, cls).__call__(*args, **kw)

            return cls.instance

    class MyClass(metaclass=Singleton):
        ...

    class MySubclass(MyClass):
        ...

    >>> MyClass() is MyClass()
    True
    
    >>> MySubclass() is MySubclass()
    True
    
    >>> MySubclass() is MyClass()
    False


Thank you for this. I love that you have little patterns in the back of your mind that you might use, but haven't yet.

Any others like that? An opportunity to ask someone about that is pretty rare.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: