Python Advanced Course
Part IV
Stefano Alberto Russo
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
● Part I: Object Oriented Programming
○ What is OOP?
○ Logical Example
○ Attributes and methods
○ Why to use objects
○ Defining objects
● Part II: Improving your code
○ Extending objects
○ Lambdas
○ Comprehensions
○ Iterables
○ Properties
Outline
● Part III: Exceptions
○ What are exceptions?
○ Handling exceptions
○ Raising exceptions
○ Creating custom exceptions
● Part IV: logging and testing
○ The Python logging module
○ Basics about testing
○ The Python unit-testing module
○ Test-driven development
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
Exceptions
→ What are “exceptions”?
Exceptions are the “errors” in Python.
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
Exceptions
→ What are “exceptions”?
Exceptions are the “errors” in Python.
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
Exceptions
→ What are “exceptions”?
Exceptions are the “errors” in Python.
And they are…
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
Exceptions
→ What are “exceptions”?
Exceptions are the “errors” in Python.
And they are… objects
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
As objects, they leverage inheritance.
→ They all extend the base class “Exception”
Examples:
Exception
ArithmeticError
FloatingPointError
ZeroDivisionError
AttributeError
SyntaxError
NameError
TypeError
ValueError
Exceptions
→ What are “exceptions”?
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
The try-except construct allows to handle exceptions. To “catch” them.
Exceptions
→ Handling exceptions
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
The try-except construct allows to handle exceptions. To “catch” them.
Exceptions
→ Handling exceptions
Cannot convert my_var to float
my_var = 'Hello'
try:
my_var = float(my_var)
except:
print('Cannot convert my_var to float')
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
I can react to errors (exceptions):
Exceptions
→ Handling exceptions
Cannot convert my_var to float
Will use the default value of 0.0
my_var = 'Hello'
try:
my_var = float(my_var)
except:
print('Cannot convert my_var to float')
print('Will use the default value of 0.0')
my_var = 0.0
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
…and I can get the exception inside the “except” branch:
Exceptions
→ Handling exceptions
Got error in converting: "could not convert string to float: 'Hello'"
Will use the default value of 0.0
my_var = 'Hello'
try:
my_var = float(my_var)
except Exception as e:
print('Got error in converting: "{}"'.format(e))
print('Will use the default value of 0.0')
my_var = 0.0
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
…and I can get the exception inside the “except” branch:
Exceptions
→ Handling exceptions
Got error in converting: "could not convert string to float: 'Hello'"
Will use the default value of 0.0
my_var = 'Hello'
try:
my_var = float(my_var)
except Exception as e:
print('Got error in converting: "{}"'.format(e))
print('Will use the default value of 0.0')
my_var = 0.0
To use the exception inside the “except”, I
always have to specify which exception I want
to handle, if I want to handle them all then I use
the base class Exception.
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
I can indeed handle multiple exceptions in a chain:
Exceptions
→ Handling exceptions
try:
my_var = float(my_var)
except TypeError:
print('Wrong type for float conversion: "{}"'.format(type(my_var)))
except ValueError:
print('Wrong value for float conversion: "{}"'.format(my_var))
except Exception as e:
print('Got generic error in converting: "{}"'.format(e))
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
There are two more useful constructs the “else” and the “finally”:
Exceptions
→ Handling exceptions
my_file = open('/tmp/tmp.txt', 'w')
try:
my_file.write(my_string)
except Exception as e:
print('Got error in writing to file: "{}"'.format(e))
else:
print('Success!')
finally:
my_file.close()
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
Exceptions can be raised by you as well:
Exceptions
→ Raising exceptions
def concat(a,b):
if not isinstance(a, str):
raise TypeError('First argument not of type string')
if not isinstance(b, str):
raise TypeError('Second argument not of type string')
return a+b
print(concat('Hello', 67))
...
TypeError: First argument not of type string
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
You can define custom exceptions by extending the base Exception class
Exceptions
→ Custom exceptions
class PortfolioError(Exception):
pass
class EmptyPortfolioError(PortfolioError):
pass
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
Exceptions
→ Raising exceptions
def do_stuff(portfolio):
try:
first_portfolio_item = portfolio[0]
except IndexError:
raise EmptyPortfolioError('Portfolio is empty') from None
do_stuff([])
...
__main__.EmptyPortfolioError: Portfolio is empty
And you can also catch and re-raise
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
End of part III
→ Questions?
Next: exercise 3
Stefano Alberto Russo - @stefanoarusso - sarusso.github.io
Exercise 3
Add proper exception handling and raising to the IncrementModel
and FitIncrementModel.
Try to score up in the autograding!

Python Advanced Course - part III.pdf for Python

  • 1.
    Python Advanced Course PartIV Stefano Alberto Russo
  • 2.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io ● Part I: Object Oriented Programming ○ What is OOP? ○ Logical Example ○ Attributes and methods ○ Why to use objects ○ Defining objects ● Part II: Improving your code ○ Extending objects ○ Lambdas ○ Comprehensions ○ Iterables ○ Properties Outline ● Part III: Exceptions ○ What are exceptions? ○ Handling exceptions ○ Raising exceptions ○ Creating custom exceptions ● Part IV: logging and testing ○ The Python logging module ○ Basics about testing ○ The Python unit-testing module ○ Test-driven development
  • 3.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io Exceptions → What are “exceptions”? Exceptions are the “errors” in Python.
  • 4.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io Exceptions → What are “exceptions”? Exceptions are the “errors” in Python.
  • 5.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io Exceptions → What are “exceptions”? Exceptions are the “errors” in Python. And they are…
  • 6.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io Exceptions → What are “exceptions”? Exceptions are the “errors” in Python. And they are… objects
  • 7.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io As objects, they leverage inheritance. → They all extend the base class “Exception” Examples: Exception ArithmeticError FloatingPointError ZeroDivisionError AttributeError SyntaxError NameError TypeError ValueError Exceptions → What are “exceptions”?
  • 8.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io The try-except construct allows to handle exceptions. To “catch” them. Exceptions → Handling exceptions
  • 9.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io The try-except construct allows to handle exceptions. To “catch” them. Exceptions → Handling exceptions Cannot convert my_var to float my_var = 'Hello' try: my_var = float(my_var) except: print('Cannot convert my_var to float')
  • 10.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io I can react to errors (exceptions): Exceptions → Handling exceptions Cannot convert my_var to float Will use the default value of 0.0 my_var = 'Hello' try: my_var = float(my_var) except: print('Cannot convert my_var to float') print('Will use the default value of 0.0') my_var = 0.0
  • 11.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io …and I can get the exception inside the “except” branch: Exceptions → Handling exceptions Got error in converting: "could not convert string to float: 'Hello'" Will use the default value of 0.0 my_var = 'Hello' try: my_var = float(my_var) except Exception as e: print('Got error in converting: "{}"'.format(e)) print('Will use the default value of 0.0') my_var = 0.0
  • 12.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io …and I can get the exception inside the “except” branch: Exceptions → Handling exceptions Got error in converting: "could not convert string to float: 'Hello'" Will use the default value of 0.0 my_var = 'Hello' try: my_var = float(my_var) except Exception as e: print('Got error in converting: "{}"'.format(e)) print('Will use the default value of 0.0') my_var = 0.0 To use the exception inside the “except”, I always have to specify which exception I want to handle, if I want to handle them all then I use the base class Exception.
  • 13.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io I can indeed handle multiple exceptions in a chain: Exceptions → Handling exceptions try: my_var = float(my_var) except TypeError: print('Wrong type for float conversion: "{}"'.format(type(my_var))) except ValueError: print('Wrong value for float conversion: "{}"'.format(my_var)) except Exception as e: print('Got generic error in converting: "{}"'.format(e))
  • 14.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io There are two more useful constructs the “else” and the “finally”: Exceptions → Handling exceptions my_file = open('/tmp/tmp.txt', 'w') try: my_file.write(my_string) except Exception as e: print('Got error in writing to file: "{}"'.format(e)) else: print('Success!') finally: my_file.close()
  • 15.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io Exceptions can be raised by you as well: Exceptions → Raising exceptions def concat(a,b): if not isinstance(a, str): raise TypeError('First argument not of type string') if not isinstance(b, str): raise TypeError('Second argument not of type string') return a+b print(concat('Hello', 67)) ... TypeError: First argument not of type string
  • 16.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io You can define custom exceptions by extending the base Exception class Exceptions → Custom exceptions class PortfolioError(Exception): pass class EmptyPortfolioError(PortfolioError): pass
  • 17.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io Exceptions → Raising exceptions def do_stuff(portfolio): try: first_portfolio_item = portfolio[0] except IndexError: raise EmptyPortfolioError('Portfolio is empty') from None do_stuff([]) ... __main__.EmptyPortfolioError: Portfolio is empty And you can also catch and re-raise
  • 18.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io End of part III → Questions? Next: exercise 3
  • 19.
    Stefano Alberto Russo- @stefanoarusso - sarusso.github.io Exercise 3 Add proper exception handling and raising to the IncrementModel and FitIncrementModel. Try to score up in the autograding!