Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How can I get a list of function names from within __getattr__ function?

Tags:

python

How can I get the list of class functions from within __getattr__ function?

Python v2.7 if it matters.

Trying to use dir within __getattr__ leads to infinite recursion.

class Hal(object):
    def __getattr__(self, name):
        print 'I don\'t have a %s function' % name
        names = dir(self) # <-- infinite recursion happens here
        print 'My functions are: %s' % ', '.join(names)
        exit()
    def close_door(self):
        pass
x = Hal()       
x.open_door()

Here's the output I want:

I don't have a open_door function
My functions are: close_door, __getattr__, __init__, __doc__, ...

Any other solution which gets me the output I want will work fine. I want to do fuzzy string matching in the case when a function doesn't exist to try to suggest what the user might have meant.

like image 746
devtk Avatar asked Dec 13 '12 18:12

devtk


People also ask

What does Getattr () do in Python?

The getattr() function returns the value of the specified attribute from the specified object.

What does Getattr return?

The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

Which function can you use to see all the methods of an object in Python?

Find Methods of a Python Object Using the dir Method The first method to find the methods is to use the dir() function. This function takes an object as an argument and returns a list of attributes and methods of that object. From the output, we can observe that it has returned all of the methods of the object.


2 Answers

is there any reason why you can't do this?

names = dir(self.__class__)

are you expecting consumers to extend instances of Hal to have custom methods?

if you only want methods you've implemented, with no built-ins listed, you could try this too:

names = [prop for prop in dir(self.__class__) if prop[1] != "_"]
like image 74
Mike Corcoran Avatar answered Nov 06 '22 13:11

Mike Corcoran


names = self.__class__.__dict__

possibly?

>>> class A:
...   def hello(self,x):
...       print "hello ",x
...   def my_dir(self):
...       print self.__class__.__dict__
...
>>> A().my_dir()
{'__module__': '__main__', 'my_dir': <function my_dir at 0x029A5AB0>, 'hello': <
 function hello at 0x029A5CB0>, '__doc__': None}
like image 27
Joran Beasley Avatar answered Nov 06 '22 13:11

Joran Beasley