In python, a string is a string until you add special characters.
In browsing twitter this morning I came accross this tweet, that showed that you can use is
accross two strings if they do not contain special characters.
I popped open ipython
to play with this. I could confirm on 3.9.7
, short strings that I typed in worked as expected.
waylonwalker βͺmain v3.9.7 ipython
β― a = "asdf"
waylonwalker βͺmain v3.9.7 ipython
β― b = "asdf"
waylonwalker βͺmain v3.9.7 ipython
β― a is b
True
Using the upper()
method on these strings does break down.
waylonwalker βͺmain v3.9.7 ipython
β― a.upper() is b.upper()
False
waylonwalker βͺmain v3.9.7 ipython
β― a = "ASDF"
waylonwalker βͺmain v3.9.7 ipython
β― b = "ASDF"
waylonwalker βͺmain v3.9.7 ipython
β― a is b
True
If You can also see this in the id of the objects as well, which is the memmory address in CPython.
waylonwalker βͺmain v3.9.7 ipython
β― id(a)
140717359289568
waylonwalker βͺmain v3.9.7 ipython
β― id(b)
140717359289568
waylonwalker βͺmain v3.9.7 ipython
β― id(a.upper())
140717359581824
waylonwalker βͺmain v3.9.7 ipython
β― id(b.upper())
140717360337824
Finally just as the post shows if you add a special character in there it also breaks.
waylonwalker βͺmain v3.9.7 ipython
β― a = "ASDF!"
waylonwalker βͺmain v3.9.7 ipython
β― b = "ASDF!"
waylonwalker βͺmain v3.9.7 ipython
β― a is b
False
What should you do
First and foremost, these are the exact pitfalls that flake8
guards you against. So the very first things you should take away here is that there is a lot of wisdom and value in flake8
.
Second, the is
comparison should be used for things that you want to compare to exact memmory addresses. These include booleans and None. Don't use is
accross two assigned variables.
Top comments (0)