Hidden vocabulary

I have a dictionary that is passed to me from a function, I do not have access to the code. There is a key in this dictionary called 'time' . I can print d['time'] and it prints the expected value. However, when I repeat the dictionary, this key is skipped. Also d.keys() does not include it. If that matters, the other keys are numeric.

How would I recreate this? How do you see hidden keys without knowing the name? Could this be reversed?

print type(d) returns <type 'dict'>

+5
source share
4 answers

Python can do almost anything in response to accessing an element, since any class can override __getitem__ (and subclasses under __missing__ , __missing__ ). If the documentation does not apply to it, there is no clear way to find out which "private keys" are available in any given object without checking the source code.

+1
source

Simple reproduction:

 class fake_dict(dict): def __getitem__(self, item): if item == 'time': return 'x' d = fake_dict({'a': 'b', 'c': 'd'}) assert isinstance(d, dict) assert 'time' not in d.keys() print d # {'a': 'b', 'c': 'd'} assert d['time'] == 'x' 
+2
source

First of all: do not assume that this is a dictionary, check it, the type of the function bult-in (d) will tell you the class / type of the object d. Note: do not use type to check type, to use isststance function.

To answer the question: yes, this can be done, see this: http://www.diveintopython3.net/special-method-names.html#acts-like-dict

Also, if you study dicts, do not forget about dict.items, which is similar to keys, but displays keys and values.

Finally, do not use debugging printing, use https://docs.python.org/2/library/pdb.html or https://pypi.python.org/pypi/ipdb .

this simple combination

 import pdb; pdb.set_trace() 

will provide you with an interactive console where you need it ...

Therefore, I would say that this is very possible. This is roughly a getitem ... And no, its very likely irreversible.

+1
source

As others have said, this can be implemented in any way. Perhaps the most trivial is defaultdict , although this will add keys to the search:

 import time from collections import defaultdict with_hidden_key = defaultdict(time.time, { "foo": 123, "bar": 1024, "bash": "YOLO", }) 
 list(with_hidden_key) #>>> ['foo', 'bar', 'bash'] with_hidden_key["time"] #>>> 1433546635.5777457 list(with_hidden_key) #>>> ['foo', 'bar', 'time', 'bash'] 

Features depend on what is actually happening.

0
source

All Articles