Class extension and. Exception handling. Genome 559

Similar documents
Class extension and. Exception handling. Genome 559

Exception Handling. Genome 559

Exceptions CS GMU

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

ECE 364 Software Engineering Tools Lab. Lecture 8 Python: Advanced I

Introduction to: Computers & Programming: Exception Handling

Python File Modes. Mode Description. Open a file for reading. (default)

CIS192 Python Programming

CIS192 Python Programming

CSC148: Week 2

Exceptions & a Taste of Declarative Programming in SQL

CSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray

Introduction to python

CIS192 Python Programming

Idioms and Anti-Idioms in Python

CS 11 python track: lecture 4

CS Programming Languages: Python

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

An Introduction to Python

Review 3. Exceptions and Try-Except Blocks

CS 11 python track: lecture 2

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Python for Astronomers. Errors and Exceptions

Lecture #12: Quick: Exceptions and SQL

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

CSE : Python Programming

Try and Error. Python debugging and beautification

CIS192 Python Programming

Lecture 21. Programming with Subclasses

Introduction to Computer Programming for Non-Majors

LECTURE 4 Python Basics Part 3

Exception Handling and Debugging

Lecture 21. Programming with Subclasses

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

1 Lecture 6: Conditionals and Exceptions

Lecture 18. Classes and Types

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

A Little Python Part 3

Python for Informatics

file_object=open( file_name.txt, mode ) f=open( sample.txt, w ) How to create a file:

Chapter 9: Dealing with Errors

MEIN 50010: Python Strings

Object Oriented Programming

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

SCHEME INTERPRETER GUIDE 4

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

FILE HANDLING AND EXCEPTIONS

#11: File manipulation Reading: Chapter 7

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

Classes and Objects. Object Oriented Programming. Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein

CSC148: Week 1

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

MITOCW watch?v=flgjisf3l78

Getting Started with Python

Exam 2, Form A CSE 231 Spring 2014 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Exam 2, Form B CSE 231 Spring 2014 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Exceptions & error handling in Python 2 and Python 3

F21SC Industrial Programming: Python: Classes and Exceptions

Lecture 21. Programming with Subclasses

Python debugging and beautification

Strings. Genome 373 Genomic Informatics Elhanan Borenstein

Introduction to Computer Programming for Non-Majors

Advanced Python. Executive Summary, Session 1

Structure and Flow. CS 3270 Chapter 5

COP 3330 Final Exam Review

COMP 204: Sets, Commenting & Exceptions

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce

Exceptions. raise type(message) raise Exception(message)

Final Exam Version A

Functions. Python Part 3

MEIN 50010: Python Flow Control

Introduction to Computer Programming for Non-Majors

redis-lua Documentation

UNIVERSITETET I OSLO

COLUMNS. Thinking about Type Checking

Python. Executive Summary

Fundamentals of Programming (Python) Getting Started with Programming

Slide Set 15 (Complete)

6.001 Notes: Section 15.1

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CSE : Python Programming. Packages (Tutorial, Section 6.4) Announcements. Today. Packages: Concretely. Packages: Overview

Strings. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Introduction to Python

Introduction to Python programming, II

CS 11 python track: lecture 3. n Today: Useful coding idioms

Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop())

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Modules and scoping rules

Classes and Objects. Object Oriented Programming. Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

Object Model Comparisons

Control Structures 1 / 17

COMP 204: Sets, Commenting & Exceptions

Python for C programmers

Transcription:

Class extension and Exception handling Genome 559

Review - classes 1) Class constructors - class myclass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = myclass('student', 'teacher') 2) str () method and how Python print works 3) Other core Python class functions - add () mul () sub () etc. # used for the '+' operator # used for the '*' operator # used for the '-' operator

Extending Classes Suppose you want to build on a class that Python (or someone else) has already written for you? get their code and copy it into your own file for modification OR use the extension mechanism provided for you by Python

Extension formalism much like biological classification class Eukaryote class Animal (extends Eukaryote) add class method movementrate() class Insecta (extends Animal) add class method numberofwings() class Drosophila (extends Insecta) add class method preferredfruit() What methods are available for an object of type Drosophila? Drosophila is an Insecta so it has all the Insecta data structures and methods. Drosophila is also an Animal so it has all the Animal data structures and methods (and Eukaryote, though we didn't define any).

Writing a new Class by extension Writing a class (review): class Date: def init (self, day, month, year): <assign arguments to class variables> Extending an existing class: class to extend class HotDate(Date): def init (self, day, month, year, toothbrush): super(day, month, year) self.bringtoothbrush = toothbrush super - call the constructor for Date ALL OF THE DATA TYPES AND METHODS WRITTEN FOR Date ARE NOW AVAILABLE!

Class hierarchy class Eukaryote super is Eukaryote class Animal (extends Eukaryote) add class method movementrate() super is Animal class Insecta (extends Animal) add class method numberofwings() class Drosophila (extends Insecta) add class method preferredfruit() super is Insecta The next class up the hierarchy is the superclass (there can only be one). Each class down one level in the hierarchy (there can be more than one) is a subclass.

Exception Handling What if you want to enforce that a Date has integer values for day, month, and year? class Date: def init (self, day, month, year): self.day = day self.month = month self.year = year mydate = Date("Ides", "March", "XLIV BC") Does this code crash?

import sys Checking command line arguments intval = int(sys.argv[1]) How could you check that the user entered a valid argument? import sys try: intval = int(sys.argv[1]) except: two new reserved key words - try and except print "first argument must be parseable as an int value" sys.exit()

You can put try-except clauses anywhere. Python provides several kinds of exceptions (each of which is of course a class!). Some common exception classes: ZeroDivisionError # when you try to divide by zero NameError # when a variable name can't be found MemoryError # when program runs out of memory ValueError # when int() or float() can't parse a value IndexError # when a list or string index is out of range KeyError # when a dictionary key isn't found ImportError # when a module import fails SyntaxError # when the code syntax is uninterpretable (note - each of these is actually an extension of the base Exception class - any code shared by all of them can be written once for the Exception class!)

Example - enforcing format in the Date class class Date: def init (self, day, month, year): try: self.day = int(day) except ValueError: indicates only catches this type of exception print 'Date constructor: day must be an int value' try: self.month = int(month) except ValueError: print 'Date constructor: month must be an int value' try: self.year = int(year) except ValueError: print 'Date constructor: year must be an int value' FYI, if there are other types of exceptions, they will be reported by the default Python exception handler, with output you are very familiar with, e.g.: Traceback (most recent call last): File <pathname>, line X, in <module> <code line> <default exception report>

You may even want to force a program exit with information about the offending line of code: import traceback import sys class Date: def init (self, day, month, year): try: self.day = int(day) except ValueError: print 'Date constructor: day must be an int value' traceback.print_exc() sys.exit() special traceback function that prints other information for the exception

Create your own Exception class import exceptions class DayFormatException(exceptions.Exception): def str (self): print 'Day must be parseable as an int value' What does this mean? DayFormat extends the Python defined Exception class Remember that the str () function is what print calls when you try to print an object.

Using your own Exceptions class Date: def init (self, day, month, year): try: self.day = int(day) except: raise DayFormatException raise is a new reserved key word - it raises an exception. The DayFormatException will get returned to whereever the constructor was called - there it can be "caught" try: mydate = Date("Ides", "March", "IXIV") except: <do something> catch the exception raised by the Date constructor

Exceptions - when to use Any software that will be given to someone else, especially if they don't know Python. Private software that is complex enough to warrant. Just as with code comments, exceptions are a useful way of reminding yourself of what the program expects. They have NO computational cost (if no exception is thrown, nothing at all is computed).

Imagine some poor schmuck's frustration when they try to use your program: import sys val = int(sys.argv[1]) what the @!#&$! > parse_int.py hello Traceback (most recent call last): File "C:\Documents and Settings\jht\My Documents\parse_int.py", line 3, in <module> val = int(sys.argv[1]) ValueError: invalid literal for int() with base 10: 'hello' import sys try: val = int(sys.argv[1]) except ValueError: by the way, notice that the ValueError is an exception class print "first argument '" + sys.argv[1] + "' is not a valid integer" except IndexError: print "one integer argument required" > parse_int.py one integer argument required > parse_int.py hello first argument 'hello' is not a valid integer hey, nice feedback!

Exercise 1 Write a program check_args.py that gets two command line arguments and checks that the first represents a valid int number and that the second one represents a valid float number. Make useful feedback if they are not. > python check_args.py 3 help! help! is not a valid second argument, expected a float value > python check_args.py I_need_somebody 3.756453 I_need_somebody is not a valid first argument, expected an int value

import sys try: arg1 = int(sys.argv[1]) except ValueError: print "'sys.argv[1]' is not a valid first argument, expected an int value" sys.exit() try: arg2 = int(sys.argv[2]) except ValueError: print "'sys.argv[2]' is not a valid second argument, expected a float value" sys.exit() <do something with the arguments>

Exercise 2 Write a class fastadna that represents a fasta DNA sequence, with the name and the sequence itself stored as class variables (members). In the constructor, use exception handling to check that the sequence is valid (consists only of the characters 'A', 'C', 'G', 'T', or 'N' (either upper or lower case). Provide useful feedback if not.

import sys import re class fastadna: init (self, name, sequence): self.name = name match = re.match('[^acgtnacgtn]') if match!= None: print sequence, 'is an invalid DNA sequence' sys.exit() self.sequence = sequence

Challenge Exercises Rewrite Exercise 2 using proper Exception handling. Change your class definition from Exercise 2 so that it provides useful traceback information so that you can find where in your code you went wrong.