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
Related
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
Let's say we have the following code which detects the stars rating of a document. If the stars rating is 50.0 it'll indicate it using stars_indicator = True and we would like to 'do something' in such case, if the stars rating is 10.0 it'll indicate it using stars_indicator = False and we would like to 'do something else' in this case.
stars_indicator = sentiment_indicator = None
if document[stars] == 50.:
stars_indicator = True
elif document[stars] == 10.:
stars_indicator = False
How can we check if we should 'do something' or 'do something else'?
Checking if it's True is simple
if stars_indicator:
# do something
The trivial approach for checking if it's False or None will be
if not stars_indicator:
# do something else
But in this way the if condition won't distinguish between the two options and will 'do something else' if stars_indicator False or None.
A much better way is to explicitly check for False or None with is:
if stars_indicator is None:
While others have answered how to check if your variable is True, False or None, I would like to point out that in your code snippet it would probably be easier if you just work without your stars_indicator:
if document[stars] == 50.:
# Do what you would do if stars_indicator was True
elif document[stars] == 10.:
# Do what you would do if stars_indicator was False
else:
# Do what you would do if stars_indicator was None
In this way you do not need to encode your results in a variable just to then having to interpret your variable again. Of course this is all based on the code snippet you provided.
The right approach for this kind of problem is using isinstance()
if isinstance(stars_indicator, bool) and not stars_indicator:
# do something else
isinstance(stars_indicator, bool) will first make sure that the variable is not None and only than will make sure that it's False.
This is an issue I had and wanted to share its solution.
I have the following assignments in my __init__() method:
self.seat, self.feet, self.backrest, self.stabilizer_bar, self.packaged = False
I would like to make it compliant to PEP8, but the line is too long. I thought about using one line for each assignment, but it doesn't feel pythonic to type False 5 times.
What's the recommended way to wrap the line above?
EDIT:
I've changed False * 5 to False thanks to your comments. But still, how do I wrap the line?
Try wrapping the left side in parentheses, then splitting it. That usually works.
def __init__(self):
(self.seat, self.feet, self.backrest,
self.stabilizer_bar, self.packaged) = False, False, False, False, False
I don't know how this behaves in actual production code, but a quick run in PyScripter returns no error.
If you have a really long list of assignments, why not trying:
def __init__(self):
for prop in ['seat', 'feet', 'backrest', 'stabilizer_bar', 'packaged']:
setattr(self, prop, False)
In this specific case, I'd write the assignments line by line:
self.seat = False
self.feet = False
self.backrest = False
self.stabilizer_bar = False
self.packaged = False
Now assuming rather than False you have a function returning a tuple, I'd write it this way:
(self.seat, self.feet, self.backrest,
self.stabilizer_bar, self.packaged) = my_function()
as in TrueError's answer.
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
I have the following code in python:
def update(request, id):
success = 0
try:
product = Mattress.objects.get(id=id)
success = 1
except Mattress.DoesNotExist:
pass
if success == 1:
return render_to_response("success.html")
else:
return render_to_response('failure.html')
Is this code a valid way to check the "success" boolean. If the code passes through the try statement, will "success" be changed to 1 or is it remaining at 0?
Answering your question:
Are booleans mutable in python?
Yes and no. Variables that are assigned a boolean value are (probably always, and definitely in this case) mutable, yes. They're also not restricted to being assigned boolean values, as variables are not staticly typed.
But the booleans True and False themselves are not mutable. They are singletons that cannot be modified.
Looking at your actual code:
if success = 1:
Is not valid syntax, you want a == there. Also, idiomatically speaking you should not use 0 and 1 for success and failure values you should use True and False. So you should refactor to something like this:
def update(request):
success = False
try:
product = Mattress.objects.get(id=id)
success = True
except Mattress.DoesNotExist:
pass
if success:
return render_to_response("success.html")
else:
return render_to_response('failure.html')
Yes. success will be changed to 1 on success.
There are a few things wrong with this snippet.
Firstly, you're not using a boolean type. Python's booleans are True and False.
Second, you're not comparing in your if statement. That line isn't valid in Python 3. What you're looking for is: if success == 1: or if success == True:
You would still be able to assign a boolean value to a variable regardless of boolean immutability. I believe they are stored as a primitive type, so they're as immutable as any other primitive type.
You should consider using an actual boolean and not an integer. You can set success to true or false and Python will interpret them as keywords to the values of 1 and 0. Using numbers can be a bit tricky as some languages interpret things different. In some languages 0 is false but any value besides 0 is considered true. However the answer to your question is yes, it will work just fine.
Probably the question you are asking is not even related with the problem you are trying to solve. I think there is a a Pythonic way to achieve what you want by:
def update(request):
try:
product = Mattress.objects.get(id=id)
except Mattress.DoesNotExist:
template_name = 'failure.html'
else:
template_name = 'success.html'
return render_to_response(template_name)
Basically if the exception is thrown, i.e., the template you will render will be 'failure.html'. On the other hand, if the query is performed successfully, 'success.html' will be rendered.