Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 a coding style question
#1
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?
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#2
I am using the second one.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Quote
#3
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'
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures

Quote
#4
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).
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)