How to check if a function returns multiple values ​​in Python?

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) # takes more than 5 minutes to run
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)
    # I throw TypeError: 'int' object is not iterable
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) # runs fast
if len(r) != 2:
    raise ValueError("There are supposed to be two outputs")
# Now we run it for real
r = demo_function(data) # takes more than 5 minutes to run

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):
    # make sure data_processor returns exactly two things!
    verify_data_processor(data_processor)
    x, y =  data_processor(data)
    return x, y

, , .

+4
1

. , tuple, . Python , Python . , . , , :

def howmany(n):
    return n*('foo',)

, nargout(howmany)?

python - return x, y, , , , return n*(1,)? , , , , , .

, : , , ?

+5

Source: https://habr.com/ru/post/1687061/


All Articles