0

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ln2khanal
  • 949
  • 1
  • 8
  • 16

2 Answers2

3

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!'
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

You can use dir,

>>> import time
>>> if '__name__' in dir(time):
...     print 'Method found'
... 
Method found
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
  • If you closely see my post, you will definitely you find that your answer is not my solution. I already could do other things with your style. Anyway thanks for your reply. – ln2khanal Apr 04 '13 at 11:51