A type annotation isn't supposed to change what code does,
or so I thought:

#------------------------------------------------------------
class Borg:
        _instances:dict = {}

        def __new__(cls, *args, **kargs):
                # look up subclass instance cache
                if Borg._instances.get(cls) is None:
                        Borg._instances[cls] = object.__new__(cls)
                return Borg._instances[cls]


class WorkingSingleton(Borg):

        def __init__(self):
                print(self.__class__.__name__, ':')
                try:
                        self.already_initialized
                        print('already initialized')
                        return

                except AttributeError:
                        print('initializing')

                self.already_initialized = True
                self.special_value = 42


class FailingSingleton(Borg):

        def __init__(self):
                print(self.__class__.__name__, ':')
                try:
                        self.already_initialized:bool
                        print('already initialized')
                        return

                except AttributeError:
                        print('initializing')

                self.already_initialized = True
                self.special_value = 42

s = WorkingSingleton()
print(s.special_value)

s = FailingSingleton()
print(s.special_value)

#------------------------------------------------------------

Notice how Working* and Failing differ in the type annotation
of self.already_initialized only.

Output:

        WorkingSingleton :
        initializing
        42

        FailingSingleton :
        already initialized                             <====================== 
Huh ?
        Traceback (most recent call last):
          File 
"/home/ncq/Projekte/gm/git/gnumed/gnumed/client/testing/test-singleton.py", 
line 48, in <module>
            print(s.special_value)
                  ^^^^^^^^^^^^^^^
        AttributeError: 'FailingSingleton' object has no attribute 
'special_value'


Where's the error in my thinking (or code) ?

Thanks,
Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to