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

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.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: