cdgriffith / Box

Python dictionaries with advanced dot notation access
https://github.com/cdgriffith/Box/wiki
MIT License
2.64k stars 107 forks source link

Make Box slicable! #196

Closed lgblkb closed 2 years ago

lgblkb commented 3 years ago

data = Box(qwe=123, asd=234, q=1) print(data[:-1]) -> Box(qwe=123, asd=234)

philipsd6 commented 3 years ago

I don't see the value in this. As far as I can see, Box is a drop-in replacement for a dict and you can't slice dicts, so why would you think you can slice a Box?

If the Box is built up in an ordered fashion (as dicts are insertion ordered in Python3/Cython) why not just do this?

data = Box(qwe=123, asd=234, q=1)
Box(item for i, item in enumerate(data.items()) if i <= 1)

But more likely in a dict, you're interested in keys so:

data = Box(qwe=123, asd=234, q=1)
b1 = Box(item for item in data.items() if item[0] not in ['q'])
b2 = Box(item for item in data.items() if item[0] in ['qwe', 'asd'])
b1 == b2
True
cdgriffith commented 3 years ago

This is honestly so silly I love it. I don't see any time I would ever personally use it, but it's such a simple tack on, I'm thinking "Why not?"

Should be able to just catch when a slice is passed into __getitem__, as it will raise a type error normally (aka won't slow most normal operations down)

        except TypeError as err:
            if isinstance(item, slice):
                new_box = self._box_config["box_class"](**self.__box_config())
                for x in list(super().keys())[item.start:item.stop:item.step]:
                    new_box[x] = self[x]
                return new_box
            raise err
cdgriffith commented 2 years ago

Adding these features in 6.0, currently have a release candidate that can be installed and tested with:

pip install python-box[all]==6.0.0rc2 --upgrade 

6.0 is ushering in Cython speedups on supported platforms, so please let me know if you run into any issues!

cdgriffith commented 2 years ago

Box 6 has been released with this added, thanks for opening the issue!