Inconsistent result when using a for loop in a Python function called and executing it manually

I noticed inconsistent behavior when using a function callable()with the following code:

>>> x = 4
>>> for i in dir(x):
...    if '__' in i:
...        continue
...    else:
...        print i, callable(i)

I get the following results:

bit_length False
conjugate False
denominator False
imag False
numerator False
real False

But when the function is used manually callable():

>>> callable(x.bit_length)
True

What am I missing here?

+4
source share
2 answers

dir(object) returns a list of strings , so what you basically do is callable("bit_length")obviously wrong (strings aren’t callable).

Instead, you can do the following:

for name in dir(obj):
    if "__" in name:
        continue
    attr = getattr(obj, name)
    print name, callable(attr)
+4
source

, "i" ( "dir" ). . "x" "i" .

+1

All Articles