I am using autoreload
with a singleton pattern below:
# solo.py
%load_ext autoreload
%aimport
%autoreload 2
from types import ModuleType
from typing import Any
class Singleton(type):
__ins__ = {}
def __new__(cls, name: str = 'Singleton', bases: tuple = (), namespace: dict = {}, **kwargs):
insdict = namespace.get('__ins__', cls.__ins__)
insdict.update(cls.__ins__)
namespace.update(__ins__=insdict)
newinst = super().__new__(cls, name, bases, namespace, **kwargs)
cls.__ins__[name] = newinst
return newinst
def __instancecheck__(self, __instance: Any) -> bool: return super().__instancecheck__(__instance)
def __subclasscheck__(self, __subclass: type) -> bool: return super().__subclasscheck__(__subclass)
def __eq__(cls, ins) -> bool: return isinstance(ins, (cls, cls.__class__))
def __hash__(cls) -> int: return hash(cls.__name__)
def __repr__(cls) -> str: return f'<singleton {cls.__name__}>'
def __call__(cls, *args, **kwargs):
insdict, insname = cls.__ins__, cls.__name__
if insname not in insdict:
insdict[insname] = super().__call__(*args, **kwargs)
cls.__ins__ = insdict
return insdict[insname]
class EmptyModule(ModuleType, metaclass=Singleton):
...
In another notebook where I import this code and run a simple function:
%load_ext autoreload
%aimport -solo
%autoreload 2
from .solo import EmptyModule
def foo():
EmptyModule is EmptyModule
return 'hi'
foo()
# hi
foo()
yields
autoreload of solo failed: Traceback (most recent call last):
File "/Users/<USER>/mambaforge/envs/<ENV>/lib/python3.11/site-packages/IPython/extensions/autoreload.py", line 276, in check
superreload(m, reload, self.old_objects)
File "/Users/<USER>/mambaforge/envs/<ENV>/lib/python3.11/site-packages/IPython/extensions/autoreload.py", line 500, in superreload
update_generic(old_obj, new_obj)
File "/Users/<USER>/mambaforge/envs/<ENV>/lib/python3.11/site-packages/IPython/extensions/autoreload.py", line 397, in update_generic
update(a, b)
File "/Users/<USER>/mambaforge/envs/<ENV>/lib/python3.11/site-packages/IPython/extensions/autoreload.py", line 365, in update_class
update_instances(old, new)
File "/Users/<USER>/mambaforge/envs/<ENV>/lib/python3.11/site-packages/IPython/extensions/autoreload.py", line 323, in update_instances
object.__setattr__(ref, "__class__", new)
TypeError: can't apply this __setattr__ to Singleton object
Any idea what this is and how to resolve it?