Python, a secure and comprehensive programming language!

13 November 2019
AUSY - Langage de Programmation Python
A secure language...

Below are a few examples of common programming errors in C/C++. All these programmes compile with unexpected results at runtime.

It goes without saying that none of these problems occur in Python:

Board 1 : C and C ++ programming errors
  • There are no pointers in Python.
  • It’s impossible to declare a variable without initialising (standard operation).
  • A table overflow will result in a “clean” error as shown below:

a={1:1}

a[2] →

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

KeyError: 2

In Python, code errors generally bring up a call stack and a clear description of the error

Even though the standard GCC C/C++ compiler has improved in many respects, if you are using old compilers (i.e. from several decades ago) then these types of errors can cause the computer to restart (in the author’s personal experience).

 

A truly “object-oriented” language

Paradigms

Prosaically, “programming paradigms” make it possible to formulate the problem to be solved. Below are the main ones:

  • Imperative programming describes the sequence of operations that change a programme’s state (Cobol, Basic, Pascal, C, Ada).
  • Object-oriented programming models the world using classes that illustrate concepts, and “instances” of classes that have their own internal data and which can be modified by certain methods (Java, Ruby).
  • Declarative programming means that the software components are independent of the context and do not have an internal state:
    • Functional programming means that each statement is a mathematical equation and any state or modifiable data is avoided (Haskell).
    • Logical programming (See “What’s behind Python?”).
  • Event-driven programming (QT libraries and graphic interfaces in general but only for so-called “generalist” languages).

Python can implement all these paradigms except the last one. Let’s look at the object aspect a little more closely.

 

Object, inheritance (and polymorphism)

class Dog:

    def __init__(self, name):

        self.name = name

    def speak(self):

        print("woof")

 

mydog=Dog("Fido")

 

This small Python programme defines the dog object. The __init_() function is often wrongly called an object builder (as in other languages) when it is actually an initiator.

The Dog class has a “speak” method and a “name” attribute. These are basic object concepts (in Python or others).

Inheritance (in object-oriented programming) is the property of a class that makes it possible to specialise another class.

class Animal:

    def speak(self):

        assert False, "Not implemented"

 

class Dog(Animal):

    # This notation means that Dog inherits from Animal

    # The same code as before

A dog is now a “specialisation” of an animal. A dog is a particular animal but still an animal. The Dog class inherits from the Animal class. A “Dog” is just a particular “Animal”. We can’t talk about an animal if we don’t know its type (i.e. its class); hence the forced error at the Animal class level. The Dog class “specialises” the “speak” method of the Animal class - hence the term polymorphism.

Small aside: the “assert” statement, which is not exclusive to Python, is a must in all serious programming languages. It stops the programme if a condition is not met making it far easier to detect and correct programming errors.

We can now define another class: pets. So, our script becomes:

class Animal:

    def speak(self):

        assert False, "Not implemented"

 

class Dog(Animal):

    def speak(self):

        print("woof")

 

class Pet:

    def visit_vet(self):

        print(f"{self.name} is happy to visit the vet")

 

class PetDog(Dog, Pet):

    def __init__(self, name):

        self.name = name

 

mydog=PetDog("Fido")

 

So, Fido is an animal, a dog and a pet. Instances of the “PetDog” class directly inherit from the “Pet” and “Dog” classes, and indirectly from the “Animal” class.

The option to have multiple inheritances is what distinguishes Python from its competitor, Java. For reasons of simplicity, Java only implements a simple form of inheritance. And while C++ does offer a multiple inheritance option, it can be somewhat dangerous for less experienced developers (i.e. the ‘diamond problem’ that we will not discuss here).

 

A language that comes with batteries...

 

Definition

This means that the language comes with a truckload of libraries meaning you can create interesting things very quickly and easily.

Firstly, there are the standard libraries that you can access with this statement:

import enum

place it at the beginning of a file to access the programme’s functions and objects.

It would be rather tedious to describe the standard library here as it contains around a hundred different elements. Therefore, the author of this article will only list the most relevant ones and ones that he has actually used.

 

Let’s take a look at the “natural” extensions of the language:

  • “enum” for listed types,
  • “copy” for copies of objects (deep or shallow copies),
  • “datetime” for dating,
  • “time” for time – typically a passive waiting period of one second: time.sleep (1)
  • “random” for a random generation (except in cryptography).

We have already mentioned the “collections” and “itertools” modules at the beginning of the article. (see “What’s behind Python ”).

Here are the features found in classic Python applications resulting in powerful and practical systems. They are the sort of tasks that programmers encounter regularly. We have illustrated them here using a simple example.

 

Log

The “logging” feature is used to log messages (critical errors, warnings, explanations, etc.).

Example of a logging.py file:

import logging

logging.basicConfig(format = '%(asctime)s %(levelname)-10s %(processName)s %(name)s %(message)s', filename = “my.log”)

logging.warning(“The kid’s all alone”)

logging.error(“The kid’s playing with matches”)

logging.critical(“The house is on fire”)

 

Content of the my.log file after runtime:

2018-06-12 08:46:22,942             WARNING MainProcess               root The kid’s all alone

2018-06-12 08:46:22,942             ERROR      MainProcess               root The kid’s playing with matches

2018-06-12 08:46:22,942             CRITICAL   MainProcess               root The house is on fire

 

Analysing arguments

The “argparse” module is used to analyse the programme’s arguments: parameters with values, with information or not, exclusive or not, etc.

 

args.py file example:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("--verbose", help="increase verbosity",

                    action="store_true")

args = parser.parse_args()

if args.verbose:

    print("My life story")

 

Execution:

$ python3 example_args.py -h

usage: example_args.py [-h] [--verbose]

$ python3 example_args.py

$ python3 example_args.py --verbose

python3 example_args.py

My life story

 

Configuration file

The “configparser” feature analyses the content of a text file for configuring applications with paragraphs and value pair attributes.

config.ini file:

[Jérémie]

favourite_language = Python

 

config.py file example:

import configparser

config = configparser.ConfigParser()

config.read('config.ini')

favourite = config.get('Jérémie', 'favourite_language')

print(f'Favourite = {favourite}')

 

Execution:

python3 example_config.py

Favourite = Python

 

Backup and restoration - a piece of cake!

The “pickle” feature allows you to save any kind of simple or complex data structure in a file and retrieve it at a later date. This operation could take many development hours in another language.

pickle_save.py file example:

import pickle

test_list = ['egg', 'ham', 'spam']

with open('test_pickle.pkl', 'wb') as pickle_out: 

    pickle.dump(test_list, pickle_out)

print(f“Saved: {test_list}”)

 

pickle_load.py file example:

import pickle

with open('test_pickle.pkl', 'rb') as pickle_in: 

    unpickled_list = pickle.load(pickle_in)

print(f“Loaded: {unpickled_list}”)

 

Execution:

python3 example_pickle_save.py

Saved: ['egg', 'ham', 'spam']

 

python3 example_pickle_load.py

Loaded: ['egg', 'ham', 'spam']

 

These four modules make developing far easier.

 

External libraries

Then we have external libraries of which there are many. They are listed on the Python Package Index site (“Pypi”). They can be installed with a small command:

pip3 install <library>

Currently, the Pypi website has around 170,000 projects.

Notably (used by the author):

- “pillow” converts images

- “pyQT” builds a graphic interface

- “matplotlib” displays plots in a version’s file system

- “psutil” gets real-time information about system changes

- “beautiful soup” captures content about an internet broadcast group

 

When all else fails.

Python has a very active community of users who are more than happy to answer your technical questions. The “stackoverflow” website (not specifically linked to Python) is the best place to ask a question when all else has failed.

 

Example of Python goodies...

For illustrative purposes, we will focus on two very important and pleasant features of the language.

Text display format

There have been several methods for writing information on the screen (we won’t discuss the differences between Python 2 and Python 3 here).

Example of Python goodies - AUSY

 

List comprehensions

List comprehensions, with an indentation, are Python’s trademark. This involves creating a sequence (a list, a set, a tuple, a dictionary - basic types in Python) with a single statement.

List of comprehension in Python - AUSY

NB: Guido Van Rossum (the creator of Python) recommends using list comprehensions. Important! Don’t compose overly complex formulas!

 

Photo Jérémie Lefrançois, consultant en Python - AUSY
Jérémie Lefrançois, an AUSY consultant since 2004, wrote his first programmes in Basic on a ZX Spectrum back in 1982. He gained a postgraduate qualification in IT in 1989 and has worked with many computer languages on a personal and professional basis. He enjoys exploring and comparing the possibilities of different languages - especially Python - which has been his favourite language since 2014. He takes a keen interest in monitoring developments in this dynamic language, which he likes for its ease of implementation.

 

 

And you may be interested in our offer Big Data.

Let’s have a chat about your projects.

bouton-contact-en