raise an exception in python

Estimated reading time: 4 minutes

In a computer programme, there is a lot of different moving parts, that the programmer has created themselves.

And depending on the sophistication of the code written exceptions can occur, that no one has an understanding of what they mean!

As part of the process of building out the logic , knowledge will lie with the computer programmer,

but the errors that they know about and programme for, may not always be understood by everyone,

if the computer programme does not handle them correctly.

This is usually because the error message they code to explain the problem, are not always designed with ease of understandability.

Step into the frame, the ability to create your own error messages with understandable explanations.

Good programmers have a lot of traits that makes what they develop so powerful, but sometimes the simple things can really cause confusion.

Looking at the following code:

def checkvalue():
    try:
        integervalues = input("Type something to test this out: ")
        if integervalue != "55" and integervalue.isdecimal():
            raise ValueError
        elif integervalue.isalpha():
            raise TypeError
        else:
            print("55 entered correctly")
    except ValueError:
        raise ValueError("Integervalue needs to be fifty five")
    except TypeError:
        raise TypeError("Number needs to be entered")
    finally:
        print("All checks completed")


checkvalue()
It returns:
NameError: name 'integervalue' is not defined

The problem with the above code is that the variable used has a misspelling.

Luckily we can easily see that the variable “integervalue” is misspelt with an extra “s”, removing that will fix the issue

Say we took the above code, without the try and except:

from distlib.compat import raw_input
def checkvalue():
    integervalue =raw_input("Type something to test this out: ")

    if integervalue == int(55):
        print("success")
    else:
        print("integervalue needs to be a fifty five")


checkvalue()
It returns:
Type something to test this out: aa
integervalue needs to be a fifty five

In essence, both do the same thing, above all the first piece of code allows for better customization.

This allows us to test for specific types of errors, and allows for more specific error trapping like:

  • Value Error
  • Type Error

The above two are just examples you can use for built in exceptions coded to trap errors.

But what if we want to create our own exception list?

The simple way around this is to build your own class that has the errors you need to capture.

Then you reference that class in the try/except and bingo, there you have it.

The first step is to build classes with the errors you want to catch:

class ValueTooSmall(Exception):
    """Raised when the input value is too small"""
    pass
class ValueLength(Exception):
    """Raised when the value entered is empty"""
    pass
class ValueAlphabetic(Exception):
    """Raised when the value is alphabetic"""
    pass

Then create a function that will hold all the try except logic to check for the errors

try:
        integervalue = input("Type something to test this out: ") # Creates a string here
        if len(integervalue) == 0:
            raise ValueLength
        elif integervalue.isalpha():
            raise ValueAlphabetic
        elif int(integervalue) != 55 and int(integervalue) < 10: # converting to integer to allow comparison
            raise ValueTooSmall
        elif int(integervalue) != 55 and int(integervalue) > 10: # converting to integer to allow comparison
            raise ValueError
        else:
            print("55 entered correctly")
    except ValueError:
        raise ValueError("Integervalue needs to be fifty five")
    except TypeError:
        raise TypeError("Number needs to be entered")
    except ValueTooSmall:
        raise ValueTooSmall("Number needs to be greater than 10")
    except ValueLength:
        raise ValueLength("Number needs to be entered, can't be empty")
    except ValueAlphabetic:
        raise ValueAlphabetic("You cannot enter an alphabetic value")
    finally:

Putting it all together

class ValueTooSmall(Exception):
    """Raised when the input value is too small"""
    pass
class ValueLength(Exception):
    """Raised when the value entered is empty"""
    pass
class ValueAlphabetic(Exception):
    """Raised when the value is alphabetic"""
    pass

def checkvalue():
    try:
        integervalue = input("Type something to test this out: ") # Creates a string here
        if len(integervalue) == 0:
            raise ValueLength
        elif integervalue.isalpha():
            raise ValueAlphabetic
        elif int(integervalue) != 55 and int(integervalue) < 10: # converting to integer to allow comparison
            raise ValueTooSmall
        elif int(integervalue) != 55 and int(integervalue) > 10: # converting to integer to allow comparison
            raise ValueError
        else:
            print("55 entered correctly")
    except ValueError:
        raise ValueError("Integervalue needs to be fifty five")
    except TypeError:
        raise TypeError("Number needs to be entered")
    except ValueTooSmall:
        raise ValueTooSmall("Number needs to be greater than 10")
    except ValueLength:
        raise ValueLength("Number needs to be entered, can't be empty")
    except ValueAlphabetic:
        raise ValueAlphabetic("You cannot enter an alphabetic value")
    finally:
        print("All checks completed")


checkvalue()

You will notice that the Classes we created are referenced within the code to call the exact exception we are looking to capture.

What are the benefits of approaching it this way:

  • You can capture exceptions tailored to the code you are writing.
  • Controls can easily be created and implemented so that specific errors with your data can be flagged straight away.
  • If you are going to be looking to catch the same exceptions in numerous places, this methodology will help to implement a better structure to handle those.
  • You can start to build a centralised repository of centralised exceptions and how to handle them.
  • All contributors to your project know how to raise an exception in python , you do not get multiple different v

create read update delete using Tkinter

Estimated reading time: 3 minutes

CRUD ( create, read, update, delete) is a programming acronym notably for how to manage updates to a database.

It is commonly used when talking about storing data on a database and follows the following rules:

  • The ability to create or add new records.
  • Be able to read and or retrieve the records.
  • If an update is needed, then allow those updates to be posted to the database successfully.
  • To ensure records are maintained correctly and deleted where a delete request is requested.

Generally speaking, it is related to persistent storage principles and you can find more information here basic functions of persistent storage (datacadamia.com)

Given these points when using graphical user interfaces, and trying to introduce crud functionality to your database applications, together with the design of the application, should yield:

  • Good database design.
  • Reducing complexity.
  • Eliminate duplication.
  • Have consistency.

We have spoken about the use of CRUD, but what are its benefits?

Security roles can be enabled

In addition, CRUD brings they bring structure to what actually can happen on a server, in essence, the ability to apply updates is managed tightly.

Helps put structure around what an application can do

Equally important, in building an application for use by users, knowing what they will do can prompt the designers to ask questions about what the user will actually do.

For example probably when Twitter was been designed, the things that probably where thought of :

Create a tweet – Functionality for the user to create and post a tweet, that gets saved to the database.

Read a tweet – Load all tweets from the database to the users interface.

Update – Allow a user to update their account profile or tweet timeline.

Delete – A user can delete their own tweets, their profile and or account.

Data flows between servers can be managed easier

Similarly, with the modern use of technology and processes moving online, data flows around between lots of people and organizations.

With this in mind, the need to send and receive data has to be managed more efficiently and securely.

As a result, data coming into the server can be controlled as to where it is received, and updated to. This can be accomplished by security roles discussed above.

Using classes with CRUD

The use of Python classes is commonly seen in many applications, for this reason we have used them again below.

Uniquely classes will only help to enhance your computer programme and organization of code, as a result of removing duplication and simplifying the code.

Classes are a very useful way to manage the structure of your code, thus keeping everything centralized.

Sooner or later if this was not implemented the project would become too difficult to manage, and maintenance and updates would become difficult to manage.

In the below video we take you through the steps involved in applying this methodology, using an SQLite database.

We use Python Classes to manage the different requests by the user, the details can be found here

  • Main Tkinter window creation
  • Exporting data to Excel
  • Updating the records
  • Filter the records based on user choice
  • Deletion of a record.

When applying these updates, we have written the code that will apply the following SQL updates:

  • Select
  • Update
  • Insert
  • Delete

As can be seen these four SQL commands are the commonly used across any application to perform these requests in a CRUD application.

python classes

Estimated reading time: 4 minutes

Recently on our Data Analytics Ireland YouTube channel, we have been working hard to enhance our video content and delivery. As part of that process, we also looked at ways to understand classes and use them more efficiently.

In how to create a class in python we provided a video tutorial of the steps involved in Python on how to implement a class within your project.

Here in this blog posting, we will go through the different aspects of classes, and provide a practical example of Object-Oriented Programming, and how it can help you to manage and reduce the code you may have to write.

Before we start, the first question we should ask is, what is a class?

According to the Official Python Website  “Classes provide a means of bundling data and functionality together”.

So in essence, what they are really saying is that they are used to centralise information and functionality around a python object.

Python Objects

So how would we describe an object? An object is anything that can have attributes attached to it and have some functionality that allows the object to function. Most objects will have methods associated with them, and these are the functionality of the object. So let’s step back a second and show this in a piece of code:

“Car ” above is the object, and it has attributes of type, color, wheels and doors. Other attributes can be added at any point. So you may add why is start structuring like this important?

The pure and simple answer is organisation!

The reason behind this way is that as the car and its details are all in one place it encourages:

  • Consistency – everything about a car is documented in one place.
  • No duplication – If you were referencing the object car in a number of places in your code, for each update, you would have to change it in each place, it makes the updates long and harder as you have to remember where you put it in the different parts of your computer program.
  • Can be called from anywhere – As we have one version of the object car, now anywhere in our code we can call it and use its attributes, as there is only one version makes the program a lot easier to manage.

Methods and Functions

Now that we have looked at attributes, what about the methods and functions that can be contained within them?

The methods and functions will operate like any other method or function, but the difference when they come to objects is:

They are specific to that object!

python classes

In the above code, you will see that there are three methods, and all are specific to the object car.

For example, you would not expect to see any methods that would relate to

  • pumping up the wheels.

         or

  • changing a bulb.

purely because this object car is only concerned with the functionality of the car.

To build on my point above around no duplication, if this object was not created, this last piece of code:

  • might have to be maintained and duplicated a number of times within your code, this is where the classes come into their own.

So say I want to use the class and its attributes, how would I go about doing that?

In section  9.3.5. Class and Instance Variables on Python classes, it states the following:

Instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

Anywhere in your code, all you need to do is create a variable and equal it to the class, see below.

Lines 22,23,24, all can now use the methods that are in the class, and their respective functionality.

As can be seen, lines 25,26,27,28 all bring in the attributes of the class to be used, by putting them in under the “def__init__” method.

And here is the output of the above. After initiating the class, we have assigned its attributes into a new variable.

And there you go we have initialised the class Car and used its attributes and methods outside the class in our regular programming,

Consequently, this could be done anywhere in our program, multiple times, but only having to use one class.

You can see this working below:

how to create an instance of a class

Estimated reading time: 1 minute

Here in how to create an instance of a class, as described herein, how to create a class in Python, we will further explore the instance of class and how this can be used within a program to assign values to an object. This allows that object to inherit those values contained within the class, making it easier to have consistency regards functionality and data.

This video covers off

(a) creating an instance of a class

(B) Using the __init__ within the class

(C) define the constructor method __init__

(D) Creating an object that calls a class and uses the class to process some piece of data.

What are the benefits of this?

  • You only need to create one class that holds all the attributes required.
  • That class can be called from anywhere within a program, once an instance of it is created.
  • You can update the class, and once completed, those new values will become available to an instance of that class.
  • Makes for better management of objects and their properties, not multiple different versions contained within a program

 

 

How to create a class in Python

Estimated reading time: 1 minute

How to create a class in Python : In this video explaining classes will be the main topic on how they are constructed,  we explain how to create an instance of a class. Also, we look at what class attributes are and how they can be used to assign key data that can be called anywhere within a program.

The steps involve the following:

(a) Create a class

(B) Assign attributes to the class

(C) Create a method within the class ( similar to a function)

(D) Create an instance of a class to call its attributes and methods.

This video is a follow on from object oriented programming – Python Classes explained