Search code examples
pythoniterationgetattr

__getattr__ within a module in python


I am working with python. I want to know whether or not any method is existed or not in same module. I think getattr() does this but I couldn't do. Here is sample code saying what really I want to do with.

#python module is my_module.py
def my_func():
    # I want to check the existence of exists_method
    if getattr(my_module, exists_method):
       print "yes method "
       return
    print "No method"
def exists_method():
    pass

My main task is to dynamically call defined method. If it is not defined, just skip operations with that method and continue. I have a dictionary of data from which on the basis of keys I define some necessary methods to operate on corresponding values. for e.g. data is {"name":"my_name","address":"my_address","...":"..."}. Now I define a method called name() which I wanted to know dynamically it really exists or not.


Solution

  • You need to look for the name as a string; and I'd use hasattr() here to test for that name:

    if hasattr(my_module, 'exists_method'):
        print 'Method found!"
    

    This works if my_module.exists_method exists, but not if you run this code inside my_module.

    If exists_method is contained in the current module, you would need to use globals() to test for it:

    if 'exists_method' in globals():
        print 'Method found!'