Skip to content

Types of Boxes

Chris Griffith edited this page Mar 22, 2020 · 7 revisions
Argument Default Modifies Keys Description
conversion_box true no Make keys such as "my key" attribute accessible, into .my_key
default_box false no If a key doesn't exist on lookup, it will be created with an empty Box as the value
box_dots false no Makes my_box.a.b.c also be accessible via my_box["a.b.c"]
camel_killer_box false yes Got PeskyAndAnnoyingKeys? Turn them into less pesky_and_annoying_keys
frozen_box false no After the first insert of data, make the box unchangeable, and hashable!

Conversion Box

By default, Box is now a conversion_box that adds automagic attribute access for keys that could not normally be attributes. It can of course be disabled with the keyword argument conversion_box=False.

movie_box.movies.Spaceballs["personal thoughts"] = "It was a good laugh"
movie_box.movies.Spaceballs.personal_thoughts
# 'It was a good laugh'

movie_box.movies.Spaceballs.personal_thoughts = "On second thought, it was hilarious!"
movie_box.movies.Spaceballs["personal thoughts"]
# 'On second thought, it was hilarious!'

# If a safe attribute matches a key exists, it will not create a new key
movie_box.movies.Spaceballs["personal_thoughts"]
# KeyError: 'personal_thoughts'

Keys are modified in the following steps to make sure they are attribute safe:

  1. Convert to string (Will encode as UTF-8 with errors ignored)
  2. Replaces any spaces with underscores
  3. Remove anything other than ascii letters, numbers or underscores
  4. If the first character is an integer, it will prepend a lowercase 'x' to it
  5. If the string is a built-in that cannot be used, it will prepend a lowercase 'x'
  6. Removes any duplicate underscores

This does not change the case of any of the keys.

bx = Box({"321 Is a terrible Key!": "yes, really"})
bx.x321_Is_a_terrible_Key
# 'yes, really'

These keys are not stored anywhere, and trying to modify them as an attribute will actually modify the underlying regular key's value.

Warning: duplicate attributes possible

If you have two keys that evaluate to the same attribute, such as "a!b" and "a?b" would become .ab, there is no way to discern between them, only reference or update them via standard dictionary modification.

Default Box

supplemental argument default description
default_box_attr Box What will be used as the default value for missing keys
default_box_none_transform true If a key exists, but has a value of None return the default attribute instead
default_box_no_key_error true Unlikecollections.defaultdict, don't even raise KeyError during pop or del

Box Dots

Camel Killer Box

Frozen Box