2

so many data structures and classes have functions that return a "view" of the class. What this means is that it is not independent: it changes when the class instance does even after it has been declared

example:

>>> d
{'a': 1, 'c': 3, 'b': 2}
>>> keys = d.keys()
>>> kview = d.viewkeys()
>>> keys
['a', 'c', 'b']
>>> kview
dict_keys(['a', 'c', 'b'])
>>> d['d'] = 4
>>> keys
['a', 'c', 'b']
>>> kview
dict_keys(['a', 'c', 'b', 'd'])

so as you can see, a class dict_keys is created that is considered a "view" of the keys in the dictionary data structure because it updates as the data structure updates.

How can you make views to classes?

note:

this is not a question on dictionaries, this is a question on how to create "views" for any type of class. numpy arrays have an attribute t, which is simply a view on the same array, just transposed.

Community
  • 1
  • 1
Ryan Saxe
  • 17,123
  • 23
  • 80
  • 128

1 Answers1

1

Quoting from http://www.python.org/dev/peps/pep-3106/#specification

The view objects are not directly mutable, but don't implement hash(); their value can change if the underlying dict is mutated.

The only requirements on the underlying dict are that it implements getitem(), contains(), iter(), and len().

You can see a sample implementation there

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • yes but this is a more general question, not just how to do it for a dictionary-like class. +1 because I kind of get the idea, but I can't see a good general application – Ryan Saxe Oct 14 '13 at 02:53