Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior when defining a value for True in Python

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?

like image 823
heyitsbmo Avatar asked Oct 28 '13 15:10

heyitsbmo


2 Answers

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.

like image 95
heyitsbmo Avatar answered Oct 15 '22 02:10

heyitsbmo


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
like image 37
vartec Avatar answered Oct 15 '22 03:10

vartec