[Tutor] Python best practices

spir denis.spir at free.fr
Mon Nov 30 17:34:34 CET 2009


ALAN GAULD <alan.gauld at btinternet.com> dixit:

> But as I said earlier the concept of multiple return 
> values in Python is similar to returning a struct in C.
> The key thing is that the function has a single purpose 
> so if returning multiple values or a struct the values 
> within that group should be related to the single purpose

It's not enough I guess that returned values are "related to the [func's] single purpose".

The cases when I do not mind returning multiple values are precisely the ones when I could build the equivalent of a struct / record / (named) tuple / object. One that makes sense. In other words, when the set of values together describe *one single thing*. In some cases it's not worth building a "struct" if the caller will then just unpack it for further process.
Eg it can makes sense to 
   return (position, color)
instead of:
   return Point(position, color)
(provided there is a Point type defined)

But there are cases when I feel uneasy returning multiple values even if each one is clearly related to the (single) purpose the the func. The typical case for me is a match func that needs together:
1. tell about match outcome (success/failure)
2. move ahead the pointer position in source
3. return node (match result)
There are indeed numerous ways to do this, even to avoid returning more than one thing (have tried several). My latest method is to (1) raise exception in case of failure (2) have a source object that itself holds its pointer (3) then the node only is returned.
But these means are tricks (esp. unsing exception, which is _always_ a trick) to hide multiple actions and returns. 
Also note that a stuct composed of outcome+position+node does not make any sense (try to name it! ;-).
I guess the only proper solution is to build a real state machine (on which parse data is stored), but this makes parse tree construction extremely complicated in the general case, compared to having nodes directly returned by match funcs.

Denis
________________________________

la vita e estrany

http://spir.wikidot.com/



More information about the Tutor mailing list