Python Forum
a coding style question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Forum & Off Topic (https://python-forum.io/forum-23.html)
+--- Forum: Bar (https://python-forum.io/forum-27.html)
+--- Thread: a coding style question (/thread-20909.html)



a coding style question - Skaperen - Sep-06-2019

this a question about the style choice you use for your coding in any language. when you have a case of setting a variable to the result of an expression when a condition is met, or to a literal value otherwise, do you set it to the literal and maybe change it, or do you use if/else to set it either way?

IOW, do you code it like this:
    location_name = 'nowhere'
    if location_code:
        location_name = lookup_location(location_code)
or like this:
  
    if location_code:
        location_name = lookup_location(location_code)
    else:
        location_name = 'nowhere'
?

or maybe like this:
    location_name = lookup_location(location_code) if location_code else 'nowhere'
don't assume that i mean that calling a function is always the expression. maybe this is the case of a big complicated expression. would the level of complication determine your choice?


RE: a coding style question - wavic - Sep-06-2019

I am using the second one.


RE: a coding style question - ichabod801 - Sep-06-2019

I use the third one if the expressions are simple, otherwise I use the second one. I sometimes use the first one, but only in complicated situations where a plain else won't work. For example, if I have:

if something:
   this = 'this'
elif something_else:
   calculate_something()
   if sub_thing:
      this = 'that'
   elif sub_other_thing:
      this = 'spam'
   else:
      this = 'roger'
else:
   this = 'roger'
I might instead do this:

this = 'roger'
if something:
   this = 'this'
elif something_else:
   calculate_something()
   if sub_thing:
      this = 'that'
   elif sub_other_thing:
      this = 'spam'



RE: a coding style question - nilamo - Sep-10-2019

I prefer the first. It makes it clear that the value is relevant outside of the if-block, whereas if it exists entirely indented, it appears at a glance as if it's not relevant outside that block.

Or the ternary version if it's simple. But if it isn't simple, it should probably be pulled out into it's own function anyway (something like lookup_location_name).