None Exception rasied in try except block [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 13 days ago.
Improve this question
I use a simple function:
def is_float(value):
try:
float(value) #float(value if value else "")
return True
except ValueError:
return False
to check if an value is float or not.
Now, even though the check is in an try except block, this error is raised if the value is None:
2023-02-06 09:47:27,021 app - ERROR:Exception ....
TypeError: float() argument must be a string or a number, not 'NoneType'.
Can someone explain why?
If you want to try it yourself, just execute the function with a None value and it will throw.

Option #1: Use Exception clause (broadest) instead to handle the None type.
def is_float(value):
try:
float(value)
return True
except Exception:
return False
Option #2: except the errors that you expect.
def is_float(value):
try:
float(value)
return True
except (TypeError, ValueError):
return False
Tests:
assert is_float(1.2)
assert is_float(3)
assert is_float(0)
assert not is_float(None)

Ah okay, nvm, I just saw my mistake.
except Exception as e:
would be what I wanted.
That was silly.

Related

Best Practices for re-raising the same error in Python [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a few functions in a call stack that will re-raise the same exception up the stack in the case of an error. I am familiar with the Python idiom that a standalone raise in a try/except block will re-raise the same exception being handled, but an exception will still be raised if a call is not in a try/except block.
Assuming that the exceptions are handled higher up in the call stack, would inbounds1() or inbounds2() be considered "better" practice, or neither?
import numpy as np
class ArrayShapeError(Exception):
...
def get_distance(points):
if points.ndim != 2 or points.shape[1] != 3:
raise ArrayShapeError("Parameter 'points' is not of shape (n, 3)")
return np.linalg.norm(points, axis=1)
# Implicit try/except
def inbounds1(points):
return get_distance(points) < 1
# Explicitly try/except and re-raise
def inbounds2(points):
try:
return get_distance(points) < 1
except ArrayShapeError:
raise
if __name__ == "__main__":
# Ok
print(inbounds1(np.random.rand(5, 3)))
print(inbounds2(np.random.rand(5, 3)))
# Raises ArrayShapeError
print(inbounds1(np.random.rand(5, 2)))
print(inbounds2(np.random.rand(5, 2)))
I would use inbounds2().
This is because re-raising the error is a good practice not only for insurance but also for readability for you and other people reading your code - it makes it clearer.
There's not a huge technical advantage as the error has already been raised.

Raise exception if condition is true in one-line? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a lot of assert statements I use to validate input data and state of the program. ie :
assert all((i.children is not None for i in items)), "Someone has no children."
I would like to use the same syntax but using specific Exception, ie:
if any((i.children is None for i in items)):
raise NoChildrenException("Someone has no children.")
Is there a one line syntax to achieve the same?
I tried :
if any((i.children is None for i in items)): raise NoChildrenException("Someone has no children.")
but that's not PEP8 valid.
or
def raise_if(condition, clazz, *args):
if condition:
raise(clazz(*args))
raise_if(any((i.children is None for i in items)), NoChildrenException, "Someone has no children.")
but that's a bit ugly.
UPDATE:
Thanks #Thomas. I fixed the examples in the problem description.
I think the closest to what I want to achieve is this one (based on #puchal's answer).
def raise_exc(exc):
raise exc
all((i.children is not None for i in items) or raise_exc(NoChildrenException("Someone has no children."))
I haven't thought about using or in this way.
Currently there is no way to do this that is also valid PEP8.
It doesn't get more pythonic than this:
if any(i.children is None for i in items):
raise NoChildrenException("Someone has no children.")
Note you have an error in your problem description - you have to negate the condition in your second code example. You can get rid of the two not by using any() like shown above.
There is no way to do it ellegantly.
I think the closest way to achieve it would be:
def raise_exc(clazz, msg=""):
raise clazz(msg)
all((i.children is not None for i in items)) or raise_exc(NoChildrenException, 'message')
The "correct" way to do this is without assert at all.
if any(i.children is None for i in items):
raise ValueError("Someone has no children") # Or whatever exception you feel is appropriate
In Python 3.8, you can capture which item had no children in the same line.
if any((childless:=i).children is None for i in items):
raise ValueError("%r is childless" % (childless,))
(The assignment expression operator := creates a variable in the scope where the generator expression is defined, not one local to the generator expression itself.)
Your second snippet is the most pythonic IMHO.
When I have to add a lot of validation rules I usually do something like this:
checks = {
lambda items: any(i.children is None for i in items): NoChildrenException("Someone has no children."),
lambda items: any(i.children.age >= 18 for i in items): AdultChildrenException("Someone has an adult children."),
lambda items: not bool(items): NoItemsException("No items given."),
}
for condition, exc in checks.items():
if condition(items):
raise exc
Moving all the checks (eventually having bigger functions instead of lambdas) in a separate .py file "validations.py".

simple function to return the type [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I wanted to write a simple little function to return the type to me. Unfortunately i get all those indentation errors( i use sublime text 2... no idea why i get those all the time)
def get_the_type(value):
if value== "NULL" or value=="":
return(type(None))
elif (value=="{"):
return (type([]))
elif isinstance(value,(int)):
return type(1))
elif isinstance(value,(float)):
return(type(1.1))
else:
return (type("bla"))
Can someone tell me where my error is ?
Indent inside the def and remove the extra paren:
def get_the_type(value):
if value== "NULL" or value == "":
return "NoneType"
elif value == "{":
return "dict" # maybe set?
elif isinstance(value, int):
return "int" # <- removed )
elif isinstance(value, float):
return "float"
else:
return "str"
Not sure if you want to use the type or just see what type it is, if you just want to see the type use strings as above. Also [] is a list and you have { as the value so that should maybe be a dict or set.
You're missing indentation of the if statement relative to the function definition.

Type Error: Unsupported operand types Int and NoneType [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hey guys I am working on a python program and I keep getting errors returned from the loop which is supposed to just reprompt the user to enter a number. The problem I am having is that it keeps returning a nonetype which cannot be used to operate on which I need to do in on of the other functions any help is appreciated. Thanks.
( Here's my code, Sorry ahead of time if it is not formatted correctly. )
def getTickets(limit):
ticketSold=int(input("How many tickets were sold? "))
if (ticketsValid(ticketSold,limit)):
return ticketSold
else:
getTickets(limit)
#This function checks to make sure that the sold tickets are within the Limit of seats
def ticketsValid(sold,limit):
if (sold>limit or sold<0):
print ("ERROR: There must be tickets less than "+str(limit)+" and more than 0")
return False
return True
# This function calculates the price of the tickets sold in the section.
def calcIncome(ticketSold,price):
return ticketSold*(price)
You are not returning getTickets(limit) inside your else block:
def getTickets(limit):
ticketSold=int(input("How many tickets were sold? "))
if (ticketsValid(ticketSold,limit)):
return ticketSold
else:
return getTickets(limit) # You need to use return here
Python functions return None by default, if nothing is returned. You have an else clause that calls a function, but does nothing with it, and the function ends there, therefore if it goes down that control flow path, you will return None from that function.

Python Function not returning [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm new to Python and am learning how it works through doing the exercises from project euler. Problem 2 is focused on the Fibonacci sequence for which I've created this recursive function:
def CalcFb(start,end):
if (end<=4000000):
CalcFb(end,start+end)
else:
print "Returning:",end
return end
print "Answer: {0}".format(CalcFb(start,start+1))
When I run the program I get the following output:
Returning: 5702887
Answer: None
I'm calling the function with:
start=1
I don't understand why "None" is being printed it should have printed 5702887. Can someone please help me to understand why this is happeneing?
Thanks
Dan
You are missing the return statement in the if-clause:
if (end<=4000000):
return CalcFb(end,start+end)
Otherwise you call your function recursively but only the last call returns a value and the second-to-last one does not return anything.
You are not returning any value when recursing...
def CalcFb(start,end):
if (end<=4000000):
return CalcFb(end,start+end) ### this needs to return a value as well
else:
print "Returning:",end
return end
for me its return 2
>>> def CalcFb(start,end):
... if (end<=4000000):
... CalcFb(end,start+end)
... else:
... print "Returning:",end
... return end
...
>>>
>>> start=1
>>> print "Answer: {0}".format(CalcFb(start,start+1))
Returning: 5702887
Answer: 2
Check indent.

Categories

Resources