7

I saw this question but it uses the ?? operator as a null check, I want to use it as a bool true/false test.

I have this code in Python:

if self.trait == self.spouse.trait:
    trait = self.trait
else:
    trait = defualtTrait

In C# I could write this as:

trait = this.trait == this.spouse.trait ? this.trait : defualtTrait;

Is there a similar way to do this in Python?

Community
  • 1
  • 1
jb.
  • 9,921
  • 12
  • 54
  • 90
  • 1
    In C# you only need the ? operator to do that. – Winston Ewert Oct 07 '11 at 19:56
  • In C# It looks like you're using the ?? operator where you could otherwise use the ? operator. Regardless, if your code works, and you understand it, I don't see any reason to deviate. It's explicit, and clear. Sure, you could turn it into a one-liner as a few have demonstrated, but the result is effectively the same. – Austin Marshall Oct 07 '11 at 21:57
  • @WinstonEwert you are quite right. My mistake. I'll edit my question to make it helpful to other people. – jb. Oct 07 '11 at 23:36

2 Answers2

14

Yes, you can write:

trait = self.trait if self.trait == self.spouse.trait else defaultTrait

This is called a Conditional Expression in Python.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
1

On the null-coalescing operator in C#, what you have in the question isn't a correct usage. That would fail at compile time.

In C#, the correct way to write what you're attempting would be this:

trait = this.trait == this.spouse.trait ? self.trait : defaultTrait

Null coalesce in C# returns the first value that isn't null in a chain of values (or null if there are no non-null values). For example, what you'd write in C# to return the first non-null trait or a default trait if all the others were null is actually this:

trait = this.spouse.trait ?? self.trait ?? defaultTrait;
Scott Lawrence
  • 6,993
  • 12
  • 46
  • 64
  • Right, I was thinking the ?: conditional operator and wrote out the ?? null-coalescing operator. My bad. – jb. Oct 07 '11 at 23:40