2

I want to test the type of this object:

import operator
print type(operator.add)

This will give the result:

<type 'builtin_function_or_method'>

but I cannot say:

if type(operator.add) == <type 'builtin_function_or_method'>:

How can I express the right hand side?

Yan King Yin
  • 1,189
  • 1
  • 10
  • 25
  • 8
    The `types` module should help: `isinstance(operator.add, (types.BuiltinFunctionType, types.BuiltinMethodType))` – vaultah Dec 03 '15 at 15:14

1 Answers1

1

I am not sure if this is what you want, but I will give it a try!

If you want to check if a variable is a function, you can use:

hasattr(object,'__call__')

Likewise if you want to check if type(operator.add) is a function, you can do:

if (hasattr(operator.add,'__call__')):
    print("function")

This checks the attributes of the object you give it and checks if it can be called. You can replace operator.add with any variable and checks if it is a function. I hope this helps Yan!

Edit: Another thing you might want to try using is the id() function in python. id() checks the id in memory and is liable to change each time you run you program, but if you store it ahead of time, I think it might work:

correct = id(operator.add)
if(id(operator.add) == correct):
    print("is correct")
mmghu
  • 595
  • 4
  • 15