Two doubtful warnings.

The following code runs, but PyCharm issues two warnings. 

I used the debugger to confirm that __init__ happens before __call__, yet the following warning is issued:
warning: Local variable 'instance' might be referenced before assignment

I used isinstance to verify that the object types are as intended yet there is a warning on the second check:
Expected type 'Union[type, Tuple[Union[type, Tuple[Any, ...]], ...]]', got 'Multiton' instead



class Multiton:
""" When init parameters match, reuse an old initialized object instead of making a new one. """
def __init__(self, cls):
self.instances = list()
self.cls = cls

def __call__(self, *args, **kwargs):
# make a key with the parameters
key = (args, kwargs)

# search for a matching old instance
found = False
for instance in self.instances:
if instance['key'] == key:
found = True

# if not found then create a new instance
if not found:

instance = {'key': key, 'object': self.cls(*args, **kwargs)}

return instance['object']

def __instancecheck__(self, other):
return isinstance(other, self.cls)

class YourClass:

def __init__(self, number):
self.number = number

yc_1 = YourClass(1)
yc_2 = YourClass(2)
yc_two = YourClass(2)

assert yc_1 != yc_2
assert yc_2 == yc_two

assert not isinstance(yc_1, Multiton)
assert isinstance(yc_1, YourClass)



Comment actions Permalink

Hi, the first warning is probably a duplicate of

For the second warning, it does seem incorrect, I suggest to submit a bug report at


Please sign in to leave a comment.