cdgriffith / Box

Python dictionaries with advanced dot notation access

Home Page:https://github.com/cdgriffith/Box/wiki

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

assignment copies object

julie777 opened this issue · comments

It is my understanding that Box is supposed to function like a dict, except that it allows dot access to contents.
The example below shows how box copies the object instead of referencing it as a dict does. This is

  • non obvious and unexpected
  • I consider it a bug
>>> container2 = dict()
>>> item = Box(a=1)
>>> container1.item = item
>>> container2['item'] = item
>>> item['b'] = 8
>>> print('item', id(item), item)
item 3016209401552 {'a': 1, 'b': 8}   # add a new key, value pair to the original Box

# you can see that the container1 box has a copy of item instead of a reference
>>> print('container1 item', id(container1.item), container1.item)      
container1 item 3016209402432 {'a': 1}

# but dict works as expected
>>> print('container2 item', id(container2['item']), container2['item'])
container2 item 3016209401552 {'a': 1, 'b': 8}

This is covered a few times in the Overview

Any sub dictionaries or ones set after initiation will be automatically converted to a Box object.

All dicts (and lists) added to a Box will be converted on lookup to a Box (or BoxList), allowing for recursive dot notation access.

Standard objects and non dict or list items will be preserved just like a dict but for Box to work it must convert dict and list objects.

from box import Box
standard_object = object()
dict_with_object = {'obj': standard_object}
regular_dict = {}
my_box = Box()
regular_dict['item'] = dict_with_object
my_box.item = dict_with_object
print("regular", id(regular_dict['item']['obj']))
# regular 2625216093968
print("boxed", id(my_box['item']['obj']))
# boxed 2625216093968

I will leave this open for time being as there is a small wordage update change needed is now it's done on insertion and not on lookup.

Thanks