1

If I had a dict object say values = {'a': 'alpha', 'b': 'bravo'}.

I've seen use cases where one may do values['a'] to get the value of the a key.

Now I am aware this is a normal way to access dict values, but I have also seen it used with objects such as a Tk.Scrollbar['command'] = yadayada.

Is there a name or documentation for this practice of using [ ] with objects?

2 Answers2

3

The [ ] is called indexing or slicing (or sometimes array/sequence/mapping-like access). The x[idx] = val is called index or slice assigment.

The methods that are responsible how the instance acts when indexed or sliced are:

  • __getitem__,
  • __setitem__ and
  • __delitem__.
  • (In Python-2.x there is also __getslice__, ... but these are deprecated since python 2.0 - if you don't inherit from a class that uses these you shouldn't need those)

For example (missing any actual implementation, just some prints):

class Something(object):
    def __getitem__(self, item):
        print('in getitem')
    def __setitem__(self, item, newvalue):
        print('in setitem')
    def __delitem__(self, item):
        print('in delitem')

For example:

>>> sth = Something()
>>> sth[10]  
in getitem
>>> sth[10] = 100  
in setitem
>>> del sth[10]  
in delitem
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • 1
    `__getslice__` has been deprecated since Python *2.0*, but it was still used by built-in types, so one needs to override it when subclassing those. – chepner May 20 '17 at 17:36
  • @chepner That's correct. I just wanted to mention `__getslice__` without going into details - so I haven't double checked what I've written there. I updated the answer. – MSeifert May 20 '17 at 17:39
  • 1
    It's not called "slicing" unless the slice syntax is used (i.e. there is at least one `:` in the `[]`). – Iguananaut May 20 '17 at 18:08
0

This is briefly described in the python tkinter documentation. Tkinter does it simply as a convenience, the feature has no name that is specific to tkinter.

https://docs.python.org/3.6/library/tkinter.html#setting-options

Options control things like the color and border width of a widget. Options can be set in three ways:

At object creation time, using keyword arguments

fred = Button(self, fg="red", bg="blue")

After object creation, treating the option name like a dictionary index

fred["fg"] = "red"
fred["bg"] = "blue"

Use the config() method to update multiple attrs subsequent to object creation

fred.config(fg="red", bg="blue")

For more general purpose information outside of the context of tkinter, see A python class that acts like dict

Community
  • 1
  • 1
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685