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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With