caesar0301 / treelib

An efficient implementation of tree data structure in python 2/3.
http://treelib.readthedocs.io/en/latest/
Other
802 stars 185 forks source link

Issues with `__getitem__` #8

Closed dbrgn closed 11 years ago

dbrgn commented 11 years ago

Today I stumbled across a problem when using treelib with Django.

In Django templates, when you use the . operator, it queries an object's __getitem__ before it looks at the attributes. This is used to access dictionary keys using the dot.

In the case of a treelib Tree object, this makes it impossible to directly access tree.root, because Django first does tree['root'], which returns None.

The question is whether the direct lookup functionality is too much of a convenience to get rid of it (explicit is better than implicit).

If you think the functionality should be kept, there could be a disable_getitem (or similar) parameter in the constructor that would be checked in __getitem__. If it is set, __getitem__ would then delegate the functionality to getattr(self, key).

What do you think? If you agree about the last part, I could create a pull request.

caesar0301 commented 11 years ago

It's a history for me to use Django. So I can just confirm your problem from above. But I don't think it much convenience to access dict using . operation, as you said, explicit better than implicit.

Its great to be compatible with Django by disable_getitem option. And the similar functionality has already been implemented by get_node(self, nid). It would be better if u can make a reliable test and a pull about the compatibility. Thanks ahead~ :)

dbrgn commented 11 years ago

Getitem is for the brackets ([]), not for the dot. Which would mean that you can't access your nodes using tree[node_id] anymore.

I'll provide a pull request for an optional disable_getitem option, if you want you can make it the default.