Built-in function to get value of object if callable?
Question
class Thing():
xyz = "I'm a string"
class Truc():
def xyz(self):
return "I'm a function"
def valueOrCalledValue(input):
if callable(input):
return input()
else:
return input
thing = Thing()
print valueOrCalledValue(thing.xyx)
>>> "I'm a string"
truc = Truc()
print valueOrCalledValue(truc.xyz)
>>> "I'm a function"
Is there a built-in function that does what my valueOrCalledValue
does?
Solution
Try properties using decorators to make it tidy.
OTHER TIPS
I don't know any built-in function to do that. Alternatively, you could do this in one line using a "if else" expression:
print my_thing() if callable(my_thing) else my_thing
assigning it to a variable works the same way:
my_var = my_thing() if callable(my_thing) else my_thing
Use this. It's simpler and always works for all possible variants on "callable".
def valueOrCalledValue(input):
try:
return input()
except TypeError:
return input
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow