[Python-ideas] adding possibility for declaring a function in Matlab's way

Géza kgeza7 at gmail.com
Sat Feb 12 04:48:38 CET 2011


It would be nice if you could write a function header like this (besides, of 
course, the current way):

def result=functionname(params):
       ...
       result=something

This would suffice for most functions, since you usually return one type of 
value, and it can be very convenient in certain cases. This is the way it is 
done e.g. in Matlab, which also has a huge user base.

Some more details to the idea:
- The return values are initialized to None.
- Setting the return values does not need to be the last line in the 
function.
- You can use the "return" statement just as before, but without arguments, 
to return from anywhere in the code.
- If you specify arguments to the "return" statement, Python stops with an 
exception.
- The return value can be a tuple: def (result1, result2, 
result3)=functionname(parameters)

Some advantages:
- You can easily see what the function returns, without having to read the 
function body, or hoping to find it in the comments.
- You can initialize the return values (if None is not good enough), and 
then care about the cases where they change.
- If you change the setup of the return value (e.g. insert a new item into 
the tuple), you do not need to change the "return" statement at possibly 
several places in the function body.
- It is very easy to write the function call prototype: just copy the 
function declaration without the "def" and final colon. Python GUIs will be 
able to do the same, thus not only giving you the function parameter 
template automatically, but also the return value template.

Some disadvantages:
- I suggest it as an addition to the current way, so there isn't any serious 
disadvantage. One person may decide to use one way, one the other.
- Of course, if you mix the two types of function declarations in your 
software, you may need to look at the function header to see which one you 
used in the specific case.
- You need to be aware of both ways when reading someone else's code ---  
which is not hard, as both ways are quite easy to read.

The idea at this stage of Python development may be surprising, but I hope 
that nevertheless you will consider it seriously.
There has been a lot of experience and developlment regarding this in 
connection with Matlab,
and I am sure that many of you know better than me how it would fit into 
Python's philosophy, and what consequences adding it may have.

Thanks for your time, and best regard!
Géza 




More information about the Python-ideas mailing list