Search code examples
pythonpython-2.7getattr

Getattr on package in Python


In Python, is there an equivalent of doing getattr() on a module for packages? In other words, is there a way to search for a function within a package like the one below?

Intents/
|-- __init__.py
|-- foo.py
|-- bar.py
|-- baz.py

Solution

  • You can use getattr to get any object from a python module:

    In [4]: cat bla.py
    
    def foo():
        pass
    
    In [5]: import bla
    
    
    In [6]: getattr( bla, 'foo')
    Out[6]: <function bla.foo>
    

    So you can walk all modules in a package, and try... except with getattr to find which module contains the desired class or function (you can also import any other top level object)