Muhammad Usman
Muhammad Usman

Reputation: 10936

String match is not working in python

here is my Django code

print request.user.role
print request.user.role is "Super"
print request.user.role == "Super"
print "Super" is "Super"

and the output on console is

Super
False
False
False
True

I am wondering why it is not matching the exact string

Upvotes: 3

Views: 100

Answers (2)

pss
pss

Reputation: 744

Please do not use string comparison to check for user roles. This approach is error prone, may use more memory for new created strings and is dangerous overall. For example if value that represents role is not it's name you will have to keep track of name-value mapping yourself. Or if library will change it's mind and swap names to integers etc.

All libraries that provide such functionality has roles enum lying somewhere with all the values for roles. So, for example, in django-user-roles you can do

user.role.is_super # maybe role.is_Super
# or
from userroles import roles
user.role == roles.super # maybe roles.Super

This is much more readable and safer aproach.

Upvotes: 3

HavelTheGreat
HavelTheGreat

Reputation: 3386

It is because request.user.role is not a string. As a result, comparing it with a string "Super" will return false, as there is no implicit type comparison. You must convert it to a string if you want to compare it to one. To convert to a string, you can try this:

str(request.user.role)

Your last print returns true because you are just comparing the string "Super" to itself, evidently. Also as a side note, you only want to use is when comparing identities, not values.

Upvotes: 4

Related Questions