简体   繁体   中英

__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 eg 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.

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!'

You can use dir ,

>>> import time
>>> if '__name__' in dir(time):
...     print 'Method found'
... 
Method found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM