Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if there's something "waiting for" the return value of a function

Tags:

python

I'm wondering if anyone can think up a way to check if a function needs to return a meaningful value in Python. That is, to check whether the return value will be used for anything. I'm guessing the answer is no, and it is better to restructure my program flow. The function in question pulls its return values from a network socket. If the return value is not going to get used, I don't want to waste the resources fetching the result.

I tried already to use tracebacks to discover the calling line, but that didn't work. Here's an example of what I had in mind:

>>> def func():
...  print should_return()
...
>>> func()
False
>>> ret = func()
True

The function "knows" that its return value is being assigned.

Here is my current workaround:

>>> def func(**kwargs):
...   should_return = kwargs.pop('_wait', False)
...   print should_return
...
>>> func()
False
>>> ret = func(_wait=True)
True
like image 646
Violet Avatar asked Feb 27 '12 02:02

Violet


2 Answers

All functions return a value when they complete.

If you're asking if they should return at all, then you are actually asking about The Halting Problem

like image 26
Arafangion Avatar answered Oct 16 '22 16:10

Arafangion


The very second line of the body of import this says it all: "explicit is better than implicit". In this case, if you provide an optional argument, the code will be more obvious (and thus easier to understand), simpler, faster and safer. Keep it as a separate argument with a name like wait.

While with difficulty you could implement it magically, it would be nasty code, prone to breaking in new versions of Python and not obvious. Avoid that route; there lieth the path unto madness.

like image 179
Chris Morgan Avatar answered Oct 16 '22 15:10

Chris Morgan