I started learning Python just today using Python 2.7 and I have a question here about global variables True and False:
It seems I can overwrite the value of True and False as this:
False = True
# now the value of variable False is also true.
True = False
# because the value of False is true, after this the value of True is still true.
if True(or False):
print 'xxxx'
else:
print 'yyyy'
Now wether we put True or we put False as the if condition, it always prints 'xxxx'.
Then how to recover from that fault situation? I imagine that we could use something like:
True = 1==1
False = 1!=1
but that seems bit dodgy to me. Is there any better way to do that?
Thanks.
(Also, it seems in Python 3.3 this action is no longer allowed?)
They're not "global" variables as such - they're built-ins.... They're available in __builtin__
(no s) - and you can do what you will "for a joke". Note that doing this kind of thing is mostly for mocking/profilers and things of that kin...
And no, you can't do that in the 3.x series, because True
and False
are keywords, not (sort of) singletons like in 2.x
The way to "recover" from this is to not let it happen.
That said, you can always use the bool()
type to access True
and False
again. (bool()
always returns one of the two boolean singletons.)
Example:
>>> bool
<type 'bool'>
>>> bool(1)
True
>>> bool(1) is bool('true')
True
>>> True = False
>>> True
False
>>> True is False
True
>>> False is bool()
True
>>> True = bool(1)
>>> True is bool(1)
True
>>> True is False
False
>>> True is bool()
False
>>> bool()
False
>>> True is bool(2)
True
>>> True is bool('true')
True
>>>
If this is a simple True = 'something'
binding, then what happens is that a new name True
is created in the current namespace--the __builtins__
module is not altered. In this case you can simply delete (unbind) the "True" name in your namespace. Then Python will use the one defined in __builtins__
again.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> True is __builtins__.True
True
>>> True = 'redefined'
>>> __builtins__.True is True
False
>>> del True
>>> __builtins__.True is True
True
None of this is possible in Python 3 because True
and False
are no longer names (variables) but keywords.
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