Pythonic way to get boolean value of object - python

I'd like opinions on the most idiomatic way to write a function that returns True if an object is truthy, and False otherwise. For example:
is_truthy(True) # True
is_truthy(False) # False
is_truthy(123) # True
is_truthy(0) # False
is_truthy("some string") # True
is_truthy("") # False
The best I've come up with is this:
def is_truthy(obj):
return not not obj
Can anybody do better?

is_truthy = bool
The builtins got you covered.

You can do it like this:
bool(obj)

If you need a bool it's because you will end up using it in if statements and the like. I don't think you need to encapsulate anything within an is truthy function; just use the bool directly. I.e. rather than:
if is_truthy(my_bool):
# do something
simply do:
if my_bool:
# do something

Related

How to check if an attribute is True in Python

I want to look if an object.est_devoilee is True : I need to make conditions.
If object.devoiler is True : do that.
If object.devoiler is not True: do that.
At first, my objet have self.est_devoilee = False and when I use object.devoiler, it becomes self.est_devoilee = True with that def :
def devoiler(self):
self.est_devoilee = True
I have tried
if object.devoiler() == True:
I have tried
if case.devoiler() is not True:
But I feel it's not really checking if self.est_devoilee have been used before. It's as if it always returns true because def devoiler(self): does not return a boolean? I only want to check if object.est_devoilee = True but I don't know how!
Sorry for my spelling, I am french. Thank you!
The devoiler() method is not used to get the value of the attribute, it just sets it to True. If you want to check it, just access the attribute:
if case.est_devoiler:
# do something

What is the difference between None and boolean (True, False) in python's default argument values?

In function definitions, one can define a boolean default argument's values as argument=None or argument=False.
An example from pandas concat:
def concat(
objs,
axis=0,
join="outer",
join_axes=None,
ignore_index=False,
keys=None,
levels=None,
names=None,
verify_integrity=False,
sort=None,
copy=True,
):
While both usages can be found, why would one be using one over the other?
Is there any PEP on this?
True and False are specific bool values. Use default False when you have a bool field and you want the default to be False.Don't use False as a value for a non-bool field.
None is used as a generic placeholder when the value will be set later. It can be typed as Optional[T], which is equivalent to Union[T, None].
You might be thinking of None and False as similar because they're both "falsy" (bool(x) returns False), but the same is true of several other values, [] () {} 0 0.0, etc and we don't use them like None either.
In your example, True/False are used where the field takes a boolean value. None is used where the field takes an Optional[List]. (The exception is sort: Optional[bool], which is being used temporarily as an ad-hoc compatibility tool for a deprecated behavior.)
True and False are boolean values, so in this context None can make sense if you have a boolean variable that can be in an 'unknown' state. Strictly spoken, such a variable would not be boolean, but in reality, this can be quite handy.
For example:
# In the beginning, we simply don't know if it's true or not
is_cat_alive = None
# But later we will determine the status
is_cat_alive = check_cat_in(box)
Note that if you are using a boolean like this, then if is_cat_alive will be false when is_cat_alive is either False or None which makes sense but might not be what you want to know. So to explicitly check for a dead cat, you would have to use if is_cat_alive == False.
None is similar to a null value if you know anything about those. Someone might say it's equal to 0, but None means that it is nothing. Say age = None for example. age is a variable, but it is equal to nothing. False is an actual value. True and False can be used as an indicator such as
def name_check(name)
if name == "Brittany":
return True
else:
return False
Calling that function with "Brittany" as the name parameter would return True which could be used in other conditions as well. Hope this helped! Good luck!
Look at the following code:
my_string = ''
my_other_string = None
my_final_string = 'I am a string'
If you were using these within python in something like an if statement they would actually equal the following:
my_string = False
my_other_string = None
my_final_string = True
Hope that helps

How to write a method like islower , isupper?

I want to write a method which i can use with strings same like we use "word".isupper return False, "word".islower return True, so I want to define a class and want to use like "word".isspecial()
so if i have a list of special characters :
special=["&","*",")("]
and I want that if I have a word I can check like ")(".method() and it return True as we do with "string".islower() which return True
I know I can do this with simple loop and in operator but I want to know how I can do like ")(".method()
What I tried is buggy:
class Lower:
def check(self,x):
for i in lower:
if x==i:
return True
check1=Lower()
check1.check()
print(check1.check(special,")("))
You can write a function to do what you want like this:
import string
special_set = set(string.punctuation)
def isspecial(s):
return all(c in special_set for c in s)
print(isspecial(")("))
print(isspecial(")(*)(&)(*&)*&"))
print(isspecial(")(*)(&)(*&)*&x"))
This will output, as expected:
True
True
False
Note I've used string.punctuation to build the set of "special characters". You can define this set by hand if you like.
Really, this is the Pythonic way to do what you want - there's no reason to have to have a method doing this. If you really insist, you can look at this question for more information, but beware it will become messy.

Is using min/max on boolean lists in Python bad?

So I have a condition I want to happen only when all items in a list evaluate to true. An example of this might be something like a list of functions which return a boolean (not actually my situation but easier to explain):
def foo():
# do something
def bar():
# do something
def baz():
# do something
fncs = [foo, bar, baz]
if <every element in [fnc() for fnc in fncs] evaluates to true>:
# do something
I know I can definitely do this:
all_true = True
for fnc in fncs:
if not fnc():
all_true = False
if all_true:
# do something
But, I was wondering if this is poor form:
if min([fnc() for fnc in fncs]):
# do something
Alternatively, I could try to select all false elements during list comprehension and check whether the list is occupied (this works because bool(arr) where arr is a list returns False if and only if arr is empty):
if not [None for fnc in fncs if not fnc()]:
# do something
I feel like the "min" is a lot cleaner than the last method, and while the first one is easiest to understand for novices it should be pretty clear what's going on. I could alternately make it clearer through aliasing:
all_true = min
if all_true([fnc() for fnc in fncs]):
# do something
I'm sure I missed other ways to do this as well. I'm wondering what method would be most desirable.
Thanks for the help!
Using min is not "bad", but it is unclear what you are trying to do and will do unnecessary work. You should use all instead.
if all(fnc() for fnc in fncs):
# do something
This will return True if all values are True, and False otherwise. It has the added benefit of quitting early if any value is False, unlike min which must run through the entire sequence at least once.
If you find that you need to evaluate if the are all False, I recommend any (well, not any(...), specifically) which has a similar "quit as soon as possible" behavior.
You're probably looking for all built-in function:
print all(f() for f in [foo, bar, baz])

How can I do a IF using a function that returns two variables?

I mean, if I have a function like this:
def example(foo, bar)
...
return False, True
How can I compare the 2 returns?
if example(foo, bar):
I know that I can do this:
bool1, bool2 = example(foo,bar)
if bool1 and bool2:
...
But, can I compare the 2 of them without seting them in a variable?
Use all.
if all(example(foo, bar)):
# do something
If you need just one positive result you can use any.
It depends on what you want to check. If you can send them to another function to do the checks, it will work without variables. Say if you want to check they're both True:
if all(example()):
...
or any() for one of them.
But if you say want to compare them with each other, you'd call the function twice:
if example()[0] == example()[1]:
and that's usually not desirable. So there I'd simply use the variable.
simply use
if (True, True) == example(foo, bar):
use all command:
if all(example(foo,bar)):
# All returned values are True

Categories