In Python the True
and False
(and None
too) are called singleton objects. They exist in the process once and only once. Any assignment to these value will always be assigned to the same object. So this means any variable that are assigned to True
ARE the same version of True
(because there is only one version).
x = True
y = True
x is y
# True
(x is y) is True
# True
Generally, you don't use the either syntax in your question. If you want to check the if a value is True
, you just pass it as is:
x = True
if x:
print('hello world')
This is cleaner, simpler, and easier to read than:
x = True
if x == True:
print('i am a computer')
Because you are adding an additional evaluation that does not need to take place. In the above example, Python evaluate x == True
to True
, then evaluates if True
to continue the if
block.
Except....
The one exception I have seen is sometime you want code to accept either a string or a boolean value, and make a decision based on what is passed. Matplotlib has a bit of this. In this case you might use x is True
.
Here is an example of a version number loosener that accepts string or bools.
def format_version(version, how):
allowed = ('full', 'major', 'minor', 'none', 'true', 'false', True, False)
if how not in allowed
raise ValueError(
"Argument `how` only accepts the following values: {}".format(allowed)
)
n = version.count('.')
if (n == 0) or (how=='full') or (how is True):
return version
if n == 1:
major, minor = version.split('.')
subs = ''
if version.count('.') >= 2:
major, minor, subs = version.split('.', 2)
if how == 'major':
return major + '.*'
if how == 'minor':
if not subs:
return '{0}.{1}'.format(major, minor)
return '{0}.{1}.*'.format(major, minor)
Here are specifically checking if True
is passed because a simple boolean check on a string will be true as well. To be clear, this is not a good pattern, it just happens because you want your user to be able to pass a True/False value.
A better way of handling this is to convert to string, and then check the strings. Like this:
def format_version(version, how):
how = str(how).lower()
allowed = ('full', 'major', 'minor', 'none', 'true', 'false')
if how not in allowed
raise ValueError(
"Argument `how` only accepts the following values: {}".format(allowed)
)
n = version.count('.')
if (n == 0) or (how == 'full') or (how == 'true'):
return version
if n == 1:
major, minor = version.split('.')
subs = ''
if version.count('.') >= 2:
major, minor, subs = version.split('.', 2)
if how == 'major':
return major + '.*'
if how == 'minor':
if not subs:
return '{0}.{1}'.format(major, minor)
return '{0}.{1}.*'.format(major, minor)