[Python-Dev] PEP 572: Assignment Expressions

Steven D'Aprano steve at pearwood.info
Tue Apr 24 19:19:11 EDT 2018


On Tue, Apr 24, 2018 at 10:42:35PM +0200, Sven R. Kunze wrote:

> gcd(diff, n) is to me a perfect name, and please don't tell me g is 
> better. ;)

Sorry, gcd(diff, n) is not the "perfect name", and I will tell you that 
sometimes g is better.

Which would you prefer to see and read?

g = gcd(diff, n)
result = [g, g+2, 3*g, g**5]

or:

result = [gcd(diff, n), gcd(diff, n)+2, 3*gcd(diff, n), gcd(diff, n)**5]

Forget about the inefficiency of calculating the same result over and 
over again. Just think about reading the code, especially aloud. If you 
were describing the code to a colleague, would you really repeat the 
phrase "gcd of diff, n" *four* separate times? I don't know about you, 
but I wouldn't, and I wouldn't want to read it four separate times.

Think about having to edit it. Would you rather edit it in one place or 
four? Even close together, in a single expression, it is annoying to 
have "gcd(diff, n)" repeated over and over again.


> To me it seems, that many people consider function_of_parameter a better 
> name than function(parameter). IMO it isn't.

Of course not. But in some contexts, p is a much better name than 
function(parameter). In other contexts, something more descriptive will 
be a better name:

    page_count = (len(document.chapter[previous_chapter].pages()) 
                  + len(document.chapter[this_chapter].pages()))

page_count is a MUCH better name than repeating 

    (len(document.chapter[previous_chapter].pages())
     + len(document.chapter[this_chapter].pages()))

over and over again, even if it is a pure function.



> I've seen lots of code where people do things like foo_of_bar = 
> bar['foo']. Because they don't want another dict access, or they think 
> it better reflects the concept. But it does not as does not g. Writing 
> gcd(diff, n) twice is not more repeating as is writing foo_of_bar twice. 
> Because gcd is a pure function

You might know that, but how does somebody reading the code know 
which functions are pure and which are not? How does the compiler know?

It's easy to say that you recognise gcd as a pure function. How about 
len(document.chapter[this_chapter].pages()), is that a pure function?



-- 
Steve


More information about the Python-Dev mailing list