This question has already been asked , but I want to ask something subtly different.
How to determine if a python function returns multiple values without calling the function ? Is there a way to find out something more than compile time rather than run time? (I understand that python is an interpreted language)
Out of the question:
r = demo_function(data)
if (not len(r) == 2) or (not isinstance(r, tuple)):
raise ValueError("I was supposed to return EXACTLY two things")
So:
try:
i, j = demo_function(data)
except ValueError:
raise ValueError("Hey! I was expecting two values.")
except TypeError:
s1 = "Hey! I was expecting two values."
s2 = "Also, TypeError was thrown, not ValueError"
raise ValueError(s1 + s2)
The following types of work, but extremely inelegant:
r = demo_function(extremely_pruned_down_toy_data)
if len(r) != 2:
raise ValueError("There are supposed to be two outputs")
r = demo_function(data)
There are tools in python that do similar things. For example, we can find out if a class object has a specific attribute:
prop_str = 'property'
if not hasattr(obj, prop_str):
raise ValueError("There is no attribute named" + prop_str + " NOOOOoooo! ")
In addition, we can find out how many INPUTS functions have:
from inspect import signature
sig = signature(demo_function)
p = sig.parameters
if len(p)) != 2:
raise ValueError("The function is supposed to have 2 inputs, but it has" + str(p))
Basically I want the following:
p = nargout(demo_function)
if p != 2:
raise ValueError("The function is supposed to have 2 outputs, but it has" + str(p))
, , , . , .
EDIT:
juanpa.arrivillaga ,
[...] , , : , , ?
, . - :
def process_data(data_processor, data):
x, y = data_processor(data)
return x, y
process_data
, data_processor
MUST . , .
def process_data(data_processor, data):
verify_data_processor(data_processor)
x, y = data_processor(data)
return x, y
, , .