Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python __getattr__ autocompletion

__getattr__ can be used to define attributes of objects. E.g. the following code will return 'bar'.

class Test(object):
    def __getattr__(self, key):
        if key == 'foo':
            return 'bar'
t = Test()
t.foo

To make life a bit easier I would like be able to type t. in ipython and then tab-complete the attribute name. I don't seem to be able to find how this can be done, while it seems to be possible. E.g. run the following code in ipython

import pandas
df = pandas.DataFrame(data={'foo': ('bar',)})

Typing df. and tab-completing allows to select the foo option. I could not find how pandas does this in its code, so I'm asking here. What should I add to my Test class such that tab-completion will work?

like image 560
Octaviour Avatar asked May 24 '17 15:05

Octaviour


1 Answers

You can achieve this with __dir__ method. below is an example for a class that contains a DataFrame

def __dir__(self):
    return self.df.keys()
like image 160
Jev Avatar answered Nov 13 '22 18:11

Jev