Skip to content

Jupyter's autoreload fails when subclassing Box #146

@tasercake

Description

@tasercake

This is a little obscure and probably not that common of a use case, but I'd like to subclass Box to modify the __str__ method.

I'm also using this in a Jupyter notebook, and for the sake of convenience I'd like to use the autoreload extension so I don't have to keep re-running my import statements after every change to external files.

Steps to reproduce:

  • Create a python module where you subclass Box
# sub.py
from box import Box
class Sub(Box):
    pass
  • In a Jupyter notebook, load the autoreload extension with mode 2
%load_ext autoreload
%autoreload 2
  • In the notebook, import the new class and instantiate an object from it
from sub import Sub
d = Sub()
  • Re-save the python file containing the subclass definition (this notifies autoreload that something in the module has changed), then re-run the aforementioned notebook cell

This results in

[autoreload of sub failed: Traceback (most recent call last):
  File "/opt/anaconda/miniconda3/envs/ai/lib/python3.7/site-packages/IPython/extensions/autoreload.py", line 245, in check
    superreload(m, reload, self.old_objects)
  File "/opt/anaconda/miniconda3/envs/ai/lib/python3.7/site-packages/IPython/extensions/autoreload.py", line 410, in superreload
    update_generic(old_obj, new_obj)
  File "/opt/anaconda/miniconda3/envs/ai/lib/python3.7/site-packages/IPython/extensions/autoreload.py", line 347, in update_generic
    update(a, b)
  File "/opt/anaconda/miniconda3/envs/ai/lib/python3.7/site-packages/IPython/extensions/autoreload.py", line 317, in update_class
    update_instances(old, new)
  File "/opt/anaconda/miniconda3/envs/ai/lib/python3.7/site-packages/IPython/extensions/autoreload.py", line 280, in update_instances
    ref.__class__ = new
  File "/opt/anaconda/miniconda3/envs/ai/lib/python3.7/site-packages/box/box.py", line 369, in __setattr__
    raise BoxKeyError(f'Key name "{key}" is protected')
box.exceptions.BoxKeyError: 'Key name "__class__" is protected'
]

I've tried and failed to find the cause of the error (apart from the fact that __class__ is part of Box._protected_keys)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions