pythonmethodsbuilt-in

Iterating over built-in attributes of foo.py module. I got an error


I'm doing a loop: "for atribute in dir(foo):"

however i can not use 'atribute' variable as it were built-in atributes of foo. Why is that?

When

print(__name__)         # <class 'str'>

and

for atribute in dir(foo):
   print(atribute)        # is <class 'str'> too

...so why I get an error as below?

import foo

for atribute in dir(foo):
    print(foo.atribute)

#AttributeError: module 'foo' has no attribute 'atribute'

Solution

  • The method from you for statement, differs from the method of foo. Imagine having a list; when you iterate over it with the variable x you obviously can't do list.x. In some way or another, you are doing exactly this. A way to get an attribute from a string is the getattr function. In your case it would be used like so:

    import foo
    
    for method in dir(foo):
        print(getattr(foo, method))
    

    Here is a usefull link about this function.