Ignore exception in Python [duplicate] - python

This question already has answers here:
How to properly ignore exceptions
(12 answers)
Closed 9 years ago.
I have try-except block in python, and I want to do nothing when exception occurs. My code is as follows:
for i in range(len(grid)):
for j in range(len(grid[i])):
try:
count = count > int(grid[i][j]) ? count : int(grid[i][j])
except:
//Do nothing here
How do I do nothing when exception is caught.
Thanks.

pass is the keyword you are looking for.

Let us write the code properly.
We want to iterate over each cell of the grid. So do that. Don't create lists of numbers (range) that you iterate over and then use to index back in. Python's for-loops work directly with the container. It is convenient and easy to understand and good. Don't fight that.
There is no ?: construct in Python. There is a x if y else z construct, but that is not appropriate here. You are clearly trying to set count to the maximum of its current value and the cell value. There is a built-in function for that.
You really want the maximum of all of those cells. So ask for that directly; don't assume that you have to implement the high-water-mark algorithm yourself. You don't. (This also protects you from having to pick an initial value for count, which might be wrong.) We don't need to iterate with an explicit loop for this. We can specify the list of values to pass to max with a generator expression.
You want to "ignore" values that can't be converted to integers. Notwithstanding that there probably is something wrong with your other code if the existence of such values could possibly occur in the first place: we can simply make a test, and filter out the values that fail the test.
Thus:
def is_integral(value):
try:
int(value)
return True
except:
return False
# Now, get the maximum of all the integral values:
count = max(
int(cell) for row in grid for cell in row
if is_integral(cell)
)

You can use pass, but also ... is synonymous in Python 3.x, which can be nice for writing psuedocode.
I see a lot of people use pass where they truly need to do nothing, while using ... where they are using it as a placeholder.
class SomeInterface:
def do_something(self):
pass
class SomeImplementation(SomeInterface):
def do_something(self)
...
This makes it easy to search for ... and find areas where you have unimplemented code, without the false positives from pass.
Note that passing on an exception is generally a bad practice, as you will virtually always want to act on exceptions. You should definitely, at the very least, specify the exact exception(s) you want to catch, as otherwise you will catch all exceptions, potentially causing bugs you can't detect if a different exception rears it's head.

for i in range(len(grid)):
for j in range(len(grid[i])):
try:
count = count > int(grid[i][j]) ? count : int(grid[i][j])
except:
pass

result = x if a > b else y
Is the ternary operator
The do nothing statement is
pass

Related

Analyze 'return' statement inside function

Sometimes inside one function we need to use the return statement several times.
When developer changes a function with multiple returns inside, it's easy to oversee some parts of code where yet another return was "hidden".
If unit tests do not cover all possible paths, disaster is guaranteed - it's only a question of time.
def my_function():
'''Multiple "return" inside'''
if condition 1:
return 1, 2, 3
if condition 2:
return 2, 3, 4
return 5 # this is wrong: only 1 value returned, while 3-tuple expected
Let's assume here: last return is wrong, because other callers expect tuple of 3 items.
I wonder if you know an easy way how to catch such parts of code automatically? I thought I could use AST, but I could not find any useful example of this.
This question is about automatic code analysis and listing such cases found - could be with running a separate script.
Of course I could write a try-to-guess parser (with e.g. regex) and then 'manually' check all unclear cases, but maybe there is a simpler way...
Depending on what version of Python you're using and what you really want to achieve, there are several ways to refactor the code.
One way, as has been already suggested, is to use Type Hints in Python 3.
Another way is refactor your code such that instead of using multiple return statements, you call other more atomic methods that handle those conditions and return the appropriate values. You use exception handling in those atomic methods to make sure the output is as desired, or raise an exception if final return type is unexpected.
def my_function():
'''Multiple "return" inside'''
if condition 1:
output = func_handle_condition_one()
if condition 2:
output = func_handle_condition_two()
output = some_other_value
if type(output) is not tuple:
raise TypeError("Invalid type for output")
return output
Additionally, ensure that you're using the right constructs for your conditions (such as whether you want to use multiple if or the if-elif-else construct). You could even re-factor your calling code to call the right function instead of calling one that has so many conditional statements.
Why not set a variable that gets returned at the end and check for its length
def my_function():
'''Multiple "return" inside'''
return_value=(0,0,0)
if condition 1:
return_value=(1, 2, 3)
elif condition 2:
return_value=(2, 3, 4)
else:
return_value=5 # this is wrong: only 1 value returned, while 3-tuple expected
try:
if len(return_value)==3:
return return_value
else:
print("Error: must return tuple of length 3")
except:
print("Error: must return tuple")
My proposal for the final type check of the result would be:
assert isinstance(return_value, tuple) and len(return_value) == 3
Advantage: as assert is easily switched off after debugging phase; still succinct statement for formulating the expectation.

try clause vs if else clause [duplicate]

This question already has answers here:
`if key in dict` vs. `try/except` - which is more readable idiom?
(11 answers)
Closed 6 years ago.
Often, I come across cases where I find both if-else and try-except clauses can be used to solve a problem. As a result, I have some confusion deciding(and justifying) the use of a particular clause to accomplish the task at hand.
For example, let us consider a trivial situation:
In []: user = {"name": "Kshitij", "age": 20 }
# My motive is to print the user's email if it is available.
# In all other cases, a warning message needs to be printed
# Method-01 : Using try clause
In []: try:
...: print(a["email"])
...: except KeyError:
...: print("No EMAIL given")
...:
No EMAIL given
# Method-02 : Using if-else clause
In []: if "email" in a:
print(a["email"])
...: else:
...: print("No EMAIL given")
...:
No EMAIL given
I would like to know how can I decide a more Pythonic method among the two and justify it. Also, some pointers to how can one differentiate among several methods to solve similar scenarios would be really helpful.
try/catch and if/else are not interchangeable. the former is for catching errors that might be thrown. no if statement can do that. if/else is for checking if a condition is true or false. errors thrown in an if/else block will not be caught and the program will crash.
You should use exceptions if this case is an exception and not the normal case.
if/then: for internal application flow control. Errors are unlikely to be fatal
vs
try/except: for system calls and API calls where the state of the receiver is external to the code. Failures are likely to be fatal and need to handled explicitly
If you're looking for "Pythonic", neither of those is.
print a["email"] if "email" in a else "No EMAIL given"
Now that's Pythonic. But, back to the question: First of all, you decide what to do - I'm not aware of any writing conventions between those two. But, as I see it:
if-else is used mainly for detecting expectable behaviour - I mean, if "email" is not in a, it's excpectable. So we will use if-else.
An example would be your code.
But, for example, if we want to check if a string contains a numeric value, we will try to convert it to a number. If it failed, well, it's a bit harder to predict it using an if statement, so we will use try-except.
Here's a short example for that:
def is_numeric(string):
try:
a = float(string)
return True
except:
return False
of course there is a better way to check if a string is numeric, that was just an example use of try-except.

Beginner at Python : Exiting inner for loop soon as completing the job [duplicate]

This question already has answers here:
How can I break out of multiple loops?
(39 answers)
Closed 8 years ago.
After finding the first list1[k] > list2[m,0] I want to increase the the value of list2[m,1]. The main thing is that after the first found value and increase of list2[m,1] I dont want to continue the inner for loop. I tried to use break at the end but it didnt work.Any suggestions?
for k in range(0, rang+1):
for m in range(0, len(dir)): # len(dir) is the row number of list2
if list1[k] > list2[m,0]:
list2[m,1] += 1
It sounds like you want a "multi-level break", a statement that can break out of two or more loops at once.
Some languages have such a thing, but Python doesn't.
But there are a few things you can do instead, in order from the usually-best solution down to don't-ever-do-this.
Refactor this into a function. When you return from a function, it breaks out of any loops you're in, all the way to the edge of the function.
Use a custom exception. For example, class BreakException(Exception): pass. Then wrap a try: / except BreakException: pass around the outer loop. Then just raise BreakException() to break. When you raise an exception, it breaks out of any loops you're in, all the way to the except statement.
Use explicit flags to keep track of what you're doing. Put doublebreak = False before the inner loop, and if doublebreak: break after the inner loop, then do doublebreak = True; break inside the inner loop.
Google for some bytecode hacks that add a way to do multi-level breaks (with some slightly ugly syntax) to the language, and build an import hook around them. (Or maybe use MacroPy instead.)
Google for the even uglier hacks that add goto support to Python; you can easily simulate labeled breaks with goto, and labeled breaks are usually a good substitute for multi-level breaks.

How to avoid for-in looping over None in Python

I know I can add some if blocks around to avoid this problem, but I am looking for a best practice or good/nice way to handle this kind of programming problem.
I am looping through the result of a function, without storing the result first in a separate variable; something like this:
for item in mycustimitemgetter.itter():
dosomething()
The itter function is returning None instead of an empty list [], and Python throws an exception per None. This is correct python behavior and nothing's wrong with it. But I'm looking for a best practice solution to:
a) keep the code clean and simple (not storing the result in a var and do if != None, etc..)
b) treat a None return value like an empty list i.e. do not run the loop and silently ignore the fact that function returned a None value.
Perhaps, use the fact that both [] and None evaluate as False, but lists with contents don't:
for item in (mycustimitemgetter.itter() or []):
dosomething()
You have a method called itter() which returns an iterable object. I would say that given the name of the function, it's reasonable to say "the returned value should always be iterable". So, if you're returning a list, you should return an empty list if you have no values.
Code there to be executed. There is nothing wrong with adding:
if retval is None:
return []
return retval
or
return retval or []
to the end of your itter() implementation, depending on the types in use.
Consider this: you wrote the code and you're facing this problem. What about someone else who's trying to use your code without knowing what you know. What do they expect?
Alternatively you should use Generators (if suitable). They contain a 'next' method (see the docs at the link), which you can return false if there are no values.

= Try Except Pattern?

I find this design pattern comes up a lot:
try: year = int(request.GET['year'])
except: year = 0
The try block can either fail because the key doesn't exist, or because it's not an int, but I don't really care. I just need a sane value in the end.
Shouldn't there be a nicer way to do this? Or at least a way to do it on one line? Something like:
year = int(request.GET['year']) except 0
Or do you guys use this pattern too?
Before you answer, I already know about request.GET.get('year',0) but you can still get a value error. Wrapping this in a try/catch block to catch the value error just means the default value appears twice in my code. Even worse IMO.
You're probably better off to use get()
year = int(request.GET.get("year", 0))
This will set year to what ever request.GET['year'] is, or if the key doesn't exist, it will return 0. This gets rid of your KeyError, but you could still have a ValueError from request.GET['year'], if it is not convert'able to an int.
Regarding your question (the try/except), a common idiom in Python is EAFP.
EDIT:
If you're really concerned, why not write your own method to do this:
def myGet(obj, key, type, defaultval):
try:
return type(obj.get(key, defaultval))
except ValueError:
return defaultval
# In your code
year = myGet(request.GET, 'year', int, 0)
Shouldn't there be a nicer way to do
this?
There is -- it's known as "a function"...:
def safeget(adict, key, type, default):
try: return type(adict.get(key, default))
except (ValueError, TypeError): return default
year = safeget(request.GET, 'year', int, 0)
FWIW, I don't think I've ever used this "pattern" -- the various error cases you're ignoring seem like they should be handled separately for UI reasons (a missing optional field defaulting is fine, but if somebody's mistakenly typed, say, 201o (the 0 and o keys being closed and, in some fonts, their results appearing similar), it generally doesn't seem nice to silently turn their input into 0. So, I don't think it's so frequent, nor highly advisable, to warrant anything like a special syntax form in the language, or even a built-in function.
But the nice thing about helper functions like safeget is that you and I can peacefully agree to disagree on the design issues involved (maybe we're just used to doing different kinds of software, for example!-) while letting each of us easily have exactly the helper functions each desires in their personal "utilities" modules!-)
I'd use a helper function:
def get_int(request, name, default=0):
try:
val = int(request.GET[name])
except (ValueError, KeyError):
val = default
return val
then:
year = get_int(request, 'year')
It keeps the complexity of the try/catch in one place, and makes for tidy functions, where you have one line per parameter in your view functions.
No way to do it in one line (that I can think of), but I'd do it like this, using get():
try:
year = int(request.GET.get("year", 0))
except ValueError:
year = 0
Also, it's generally better to catch a specific exception, not all exceptions.

Categories