Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ipython tab completion for custom dict class

Tags:

python

I've been using the following in my code:

class Structure(dict,object):
""" A 'fancy' dictionary that provides 'MatLab' structure-like
referencing. 

"""
def __getattr__(self, attr):
    # Fake a __getstate__ method that returns None
    if attr == "__getstate__":
        return lambda: None
    return self[attr]

def __setattr__(self, attr, value):
    self[attr] = value

def set_with_dict(self, D):
    """ set attributes with a dict """
    for k in D.keys():
        self.__setattr__(k, D[k])

All in all it works for my purposes, but I've noticed that only way tab completion works is for methods in another custom class that inherited from Structure, and not for attributes. I also did this test, and I find the result a little strange:

In [2]: d = Structure()
In [3]: d.this = 'that'
In [4]: d.this
Out[4]: 'that'
In [5]: d.th<tab>
NOTHING HAPPENS

In [6]: class T():
   ...:     pass
   ...: 

In [7]: t = T()
In [8]: t.this = 'cheese'
In [9]: t.th<tab>
COMPLETES TO t.this
Out[9]: 'cheese'

What would I need to add to my class to get the tab completion to work for the attributes?

like image 988
John Avatar asked Dec 13 '12 23:12

John


1 Answers

Add this method:

def __dir__(self):
    return self.keys()

See here: http://ipython.org/ipython-doc/dev/config/integrating.html

And here: http://docs.python.org/2/library/functions.html

like image 84
goodside Avatar answered Oct 23 '22 06:10

goodside