This isn't a practical problem - I'm just curious about some strange behavior I've observed, and wondering if I understand the "is" operator correctly.
Here's some predictable Python interpreter output:
>>> True is True
True
>>> (1==1) is True
True
Now let's define a variable called True:
>>> True = 'abc'
>>> True == 'abc'
True
>>> True is 'abc'
True
The interpreter will still return "True" for boolean operations, but the results of boolean operations are considered equivalent to neither 'abc' nor True.
>>> (1==1)
True
>>> (1==1) is 'abc'
False
>>> (1==1) is True
False
Can anyone explain this strange behavior?
As often happens on here, I think I figured out the answer while I was typing up the question.
There are two "True"s: one is a boolean value, and the other is the variable called True; initially, they're equal to each other. This is why boolean operations like (1==1) can still return True even when the variable called True has been changed - they're returning the boolean value True. Yet they're not equal to the new value of the "True" variable, which is a string.
That's happening is namespaceing and interactive console hiding it.
Initially you have normal True
, which is part of __builtin__
module.
When you redefine True
, you're actually defining it in a current module, which in that case is just default one __main__
.
Thus you actually have two different objects. __builtin__.True
and __main__.True
.
In [1]: import __builtin__, __main__
In [2]: True = "a bad idea"
In [3]: __main__.True
Out[3]: 'a bad idea'
In [4]: __builtin__.True
Out[4]: True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With