[Tutor] Use case of assignment expression
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Apr 28 05:22:35 EDT 2021
On 28/04/2021 04:12, Manprit Singh wrote:
> Consider an example to find the words from a given sentence having given
> word as prefix, program should return -1 if no such words found in the
> sentence.
Thats a terrible definition of a function.
Functions should return the same kind of object regardless
of the outcome (if that is not possible for some reason
then raise an error) the options here should therefore be:
1) return a list of matching words or an empty list
2) return the indices of matching words or -1 if no matches
(or raise an IndexError)
3) return a boolean result
4) return the first matching word or the empty string.
This is especially important in OOP since you want the
returned object to be polymorphic and avoid any
type-checking code structures.
> def word_found(string, wd):
> if word := [ele for ele in string.split() if ele.startswith(wd)]:
> return word
> else:
> return -1
There is no good reason for the assignment operator here.
You could just do (assuming we really have to return -1!)
def word_found(string, wd):
return ([ele for ele in string.split()
if ele.startswith(wd)]
or -1)
> My question is regarding assignment expressions used in function
> definition. Is this the appropriate use of assignment expression?
I try to avoid assignment expressions due to a pathological fear of
them from C. They are one of the most common causes of hard to find
bugs in C. Python's variant is much less bug prone but my past
experience is so seared into my conscious mind that I still
avoid them as far as possible.
Certainly in this case there is no need for it so I'd avoid it.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list