Handling assertion in python - python

I can't understand why this code:
x='aaaa'
try:
self.assertTrue(x==y)
except:
print (x)
generates me this error
AssertionError: False is not True
It should be handle it by
print(x)
EDIT
original code is:
try:
self.assertTrue('aaaa'==self.compare_object_name[1])
except:
print ('aaa')
#Space_C0wb0y I can't give you full code because it is not my code, and I don't have a permission.

You should include the code that defines the assertTrue method. From the output you get, I'd say that it actually does not throw an exception, but deals with it internally (thus the error message being printed, and not your value).
You can use the built-in assert statement of Python, which works as expected:
x = 'aaaa'
y = 'bbb'
try:
assert(x == y)
except:
print (x)
Output:
>>>
aaaa

Related

Python print the value of specific parameter in the function

I only want to return and print the error when the function is called, but it seems that the whole functions are being run when I print the function.
My expected output is only:
false
list index out of range
but I am getting:
false
false
false
list index out of range
I tried calling the function like this but did not work: print(test(error))
Question: How can I only print the error parameter and not the other parameter outside the function? Here is my code, Thanks:
def test(error=None, parameter1=None):
array = []
try:
if parameter1 == True:
print("true")
array[0]
else:
print("false")
array[0]
except Exception as e:
error = e
return error
test()
if test() is not None:
print(test())
You're running the function twice, once in the if statement, and then again in the print() statement.
If you only want to run it once, assign the result to a variable.
err = test()
if not err:
print(err)
This is happening because python is read line by line. This means that it will check the condition for parameter1 == True before going onto your statement that returns an error. Restructure the code so that it checks for an error before printing out "false". Example:
def test(error=None, parameter1=None):
array = []
try:
array[0]
except Exception as e:
error = e
return error
if parameter1 == True:
print("true")
else:
print("false")
if test() is not None:
print(test())
Additionally, the act of writing the if test() will call the function, which is why it printed false the first time. Then you called print(test()) which called it a second time, resulting in two "false"s being printed out.

Python: Only running exception block when try block fails

I am having trouble understanding how to write a try except block that only runs one block or the other not just half the block and then move to the exception as seen in my example for emphasis I do not wish to run any portion of try if any line in try fails
x = 1
y = 1
try:
x = x+1
print(x)
x.append(1)
except:
print(x)
which returns
2
2
instead of returning
1
as I would of expected. This is problematic for me because I was foolishly under the impression that only except block would be executed upon try failure. I am scraping websites using beautiful soup and my allocation of a soup usually will throw the exception and the other block will run but unforeseen errors after this allows some lists to be appended then runs the exception block and appends them again. leaving me with lists of different lengths depending on where they fall within each block.
any help is much appreciated
You could reset the computed_result to value of x in except-block on error:
x = 1
y = 1
computed_value = 0
try:
computed_value = x + 1
#print(fallback_var)
computed_value.append(1)
print("Exceution succeed: keeping value")
except:
print("Exceution failed: resetting value")
computed_value = x
#print(x)
print(computed_value)
Let's go step by step:
Your code correctly executes x=x+1 (now x is 2).
Then it correctly executes print(x) (so it prints 2).
Then it tries to execute x.append(1) (and fails)
Since it has failed to append(1) it enters the except and executes print(x) (so it prints 2)
It outputs exactly what's expected.
This run both.
Your code
try:
x = x+1
print(x)
x.append(1)
except:
print(x)
When python start execution, it execute line by line
x = x + 1
After this x become 2.
then
print (x)
Print 2 as first in your output.
x.append(1)
Above statment raise exception which is caught by except clause in your code.
Please remember, x value is already change to 2 in x = x + 1 statment. In except when you do
print (x)
It print 2 again.

Python Modulo TypeError

I wanted to create simple code to test if number is odd or even.
I am using Python 2.7.3.
def oddoreven(a):
try: int(a)
except: return "Error"
if a%2==0: return 1
else: return 0
Instead the code fails with error: TypeError: not all arguments converted during string formatting. The error points to the line beginning with if a%2==0....
While researching this problem I found examples indicating that code like this should work. For example answers to this question offer similar code as solution: python - checking odd/even numbers and changing outputs on number size
So what is wrong with my code?
It's because you first test if a can be converted to an int (which is fine), but then you ignore this test and keep going with the string you provided in argument.
Python is a dynamically typed language, but also strongly typed, which means you can change the type of a variable after it's been declared, but this change has to be explicit (more about this here).
In your case, it means you can't do if a % 2 == 0 if a is a string.
You could do this for instance:
def oddoreven(a):
try:
my_int = int(a)
except TypeError:
return "The argument provided could not be converted into an int"
if my_int % 2 == 0:
return 1
else:
return 0
the int function doesn't change the a in-place, you need to assign it to a :
>>> def oddoreven(a):
... try: a=int(a)
... except: return "Error"
... if a%2==0: return 1
... else: return 0
...
>>> oddoreven('2')
1
>>> oddoreven('5')
0
>>> oddoreven('a')
'Error'
As user2357112 stated. (int)a does not convert a to a int. so when you check its modulus you still must convert it.
def oddoreven(a):
try: int(a)
except: return "Error"
if int(a)%2==0: return 1
else: return 0
print oddoreven(32)
works fine.
As a side note, catching any exception is generally frowned upon. You may want to narrow it down like:
def oddoreven(a):
try: int(a)
except TypeError: return "Error"
if int(a)%2==0: return 1
else: return 0
print oddoreven(32)

getting assigned variables when exception is raised, python exception handeling

I would like to find a way to get the variables I assigned before an exception is made. E.G if the code is
try:
a=b
c=d
e=f
except:
bla bla
And an exception is generated at "e=f," I still want a=b and c=d
Is it possible? I realize I could make this multiple try statements but is there something I can do in one step?
Yes, it is perfectly possible. Below is a demonstration:
>>> try:
... a = 1
... b = 2
... c = 1/0 # This will raise a ZeroDivisionError
... except ZeroDivisionError:
... print 'an error occurred'
...
an error occurred
>>> a # a still exists
1
>>> b # so does b
2
>>> c # only c is undefined
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>>
try/except is designed to execute the code in the try-block normally until an exception is raised. When that happens, the try-block is immediately exited. This means that only the code after the line that raised the exception is ignored.
The best you can do is to limit the number of expressions inside your try block.
If you need to know where the exception is raised, you are probably better off using multiple try...except's like you mentioned in your queestion, since there is no (practical) way to know where the exception was raised.
If the expressions are of the same type, you may want to put them in lists though, and loop over them, like:
vars = [a, b, c]
values = [1, 2, 0]
for i, (var, value) in enumerate(zip(vars, values)):
try:
var /= value
except ZeroDivisionError:
print 'The exception was raised on the {}. iteration'.format(i)
continue
try:
a = "foo"
c = "bar"
e = unknown_function()
except:
pass
print a, c # prints "foo bar"
Both a and c are set, you can simply use their values after the exception is handled. e is not set to anything as an exception was raised when that line was executed.
If I understand you correctly, this will happen by default. Raising an exception does not magically undo everything that has already happened inside the try block. In your example, if an error occurs on the assignment of e, a and c will still have the values they were assigned.
try:
a = b
c = d
e = f # oh noes! error! Try block skips to the end!
except: pass
print (a) #but a and c are still there
print (c)
This is a straight forward method without much of a hassle . This is the best way out when you cant predict what type of error can occur, or multiple errors can occur .
try :
a=10
except :
print "bla A"
try :
b=20
except:
print "bla B"
try:
c=d
except :
print "bla C"
Is it something like this that you want ?
import sys
code = """
b = 100
d = 200
a=b
c=d
e=10/0
g=e
h = 100
"""
for line in filter(None,code.splitlines()):
print line
try:
exec line
except:
sys.excepthook(sys.exc_info()[0],sys.exc_info()[1],None)
result
b = 100
d = 200
a=b
c=d
e=10/0
ZeroDivisionError: integer division or modulo by zero
g=e
NameError: name 'e' is not defined
h = 100

Tuple with missing value

I have a function in python that does error checking on a string. If the function finds an error it will return a tuple with an error code and an identifier for that error. Later in the program I have the function that handles the error. It accepts the tuple into two variables.
errCode, i = check_string(s,pathType)
check_string is the function that produces the tuple. What I want it to does is return just zero if there is no error. When a zero is returned the above code seems to fail because there is nothing for the variable i.
Is there an easy way to get this to work or do I just need to have the program return a tuple of 0 and 0 if no error is found?
I would use the exception system for this.
class StringError(Exception):
NO_E = 0
HAS_Z = 1
def string_checker(string):
if 'e' not in string:
raise StringError('e not found in string', StringError.NO_E)
if 'z' in string:
raise StringError('z not allowed in string', StringError.HAS_Z)
return string.upper()
s = 'testing'
try:
ret = string_checker(s)
print 'String was okay:', ret
except StringError as e:
print 'String not okay with an error code of', e.args[1]
You could use None as the value for error
def check_string(s,pathType):
# No error
return (None, i)
Why not simply check the length of the tuple before trying to retrieve the values?
err_tup = check_String(s, pathType)
if len(err_tup) == 2:
errCode, i = err_tup
else: # assuming it can only be 1 otherwise
errCode = err_tup
This would work without making any changes to the rest of your code that generates the tuple, and is semantically clear.
Based on "Simple is better than complex."
If you are going to return zero:
foo = func()
if not foo:
print 'No errors'
else:
# foo is tuple

Categories