Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain this python "for" statement: methodList = [method for method in dir(object) if callable(getattr(object, method))]

Tags:

python

list

I am trying to use introspection to get a list of my objects functions. I have been reading "Dive into Python", and the aforementioned statement:

methodList = [method for method in dir(object) if callable(getattr(object, method))]

does the trick. The problem is, I have no idea what it is doing. To me it looks like some extreme shorthand for looping, testing, and adding elements to a list. If I am correct, which part of the statement does what?!

In other words, can some one please translate it to English.

like image 476
Chris D. Avatar asked Sep 29 '26 06:09

Chris D.


2 Answers

Another way to look at this:

methodList = []
for method in dir(object):  # for every attribute in object
                            # note that methods are considered attributes
    if callable(getattr(object, method)) # is it callable?
        methodList.append(method)
return methodList

The construct itself is a list comprehension with a filter.

See: dir(), callable(), getattr(), list comprehensions

like image 149
NullUserException Avatar answered Sep 30 '26 20:09

NullUserException


This is an example of list comprehensions in Python.

[f(y) for y in z]

means make a list of elements f(y) for each element y in list z. You can add an optional filte rexpression giving

[f(y) for y in z if g(y)]

which means make a list of all elements f(y) for elements y in z where g(y) is true.

Translated, this gives

[method for method in dir(object) if callable(getattr(object,method)]

means make a list of all elements "method" in dir(object) where getattr(object,method) is callable.

like image 41
Barry Wark Avatar answered Sep 30 '26 18:09

Barry Wark