1

I am not sure which part I am doing wrong but somehow I am trying to compare two values and I am 100% sure they matches but somehow code would not execute.

Let's say I have this model (please forgive for a bit typos for models and field names)

class TestOne(models):
    gender = models.Charfield(max_length=10, choices=GENDER_CHOICES)

my choices

GENDER_CHOICES = (("MALE", "MALE"), ("FEMALE", "FEMALE"))

I am so sure my gender field is MALE for the object so I am doing this statement as check that if it's MALE do something.

if a.gender is `MALE`:
    # do something here

but it never reaches it as true. I checked a.gender is a unicode type so I even did str(a.gender) to make sure it's also a string but still no luck.

Am I doing anything wrong here?

P.S. I did a print with a.gender and made sure that the output is MALE

Thanks in advance

Dora
  • 6,776
  • 14
  • 51
  • 99

1 Answers1

6

Don't do:

if a.gender is 'MALE':
# equivalent to:
# id(a.gender) == id('MALE')

Do instead:

if a.gender == 'MALE':

The 'is' keyword checks object identity, i.e. whether two variables/objects reference the identical memory address. '==' checks equality as defined in the class' '__eq__' method, which in your case will perform the expected string comparison.

Check Is there a difference between `==` and `is` in Python? for detailed explanation.

user2390182
  • 72,016
  • 6
  • 67
  • 89