Python: Inheritance, File System, Error Handling 🎯
Tags: python, oop, webdev, learning
Published: 2021-01-13 10:50:48

Another week of Python has passed and once again, there are a lot of new topics to write about!

Every hour spent learning make me realize how powerful and complex this language is.

Let's dive in 🏊‍♂️ 

<h2>Table of Contents </h2> 
<ul>
<li><a href="#inheritance">Inheritance</a></li>
<li><a href="#eh">Error Handling</a></li>
<li><a href="#fs">File System</a></li>
</ul>

<h3 id="inheritance">Inheritance</h3>
Inheritance is a key aspect of the object-oriented programming paradigm.

In the last post, I introduced classes with a simple example. The idea here, is to create a "child" class that inherits from its "parent" class.

A child class has access to public attributes and methods of its parents.

```python
# Parent Class
class Vehicle:
    def __init__(self, color):
        self.color = color

    def info(self):
        print(f"Vehicle => color: {self.color}")


vehicle = Vehicle("red")
vehicle.info()  # Vehicle => color: red

# Child Classes
class Car(Vehicle):
    def __init__(self, color, brand):
        super().__init__(color)
        self.brand = brand
        self.wheels_count = 4

    def info(self):
        print(f"Car => color: {self.color} - brand: {self.brand} - wheels count: {self.wheels_count}")


class Bike(Vehicle):
    def __init__(self, color, brand):
        super().__init__(color)
        self.brand = brand
        self.wheels_count = 2

    def info(self):
        print(f"Bike => color: {self.color} - brand: {self.brand} - wheels count: {self.wheels_count}")


car = Car("blue", "Ferrari")
car.info()  # Car => color: blue - brand: Ferrari - wheels count: 4

bike = Bike("Yellow", "Yamaha")
bike.info()  # Bike => color: Yellow - brand: Yamaha - wheels count: 2
```

In the example above, we declare "Car" and "Bike" classes that derives from the "Vehicle" class. They both have access to "Vehicle"'s constructor (__init__) and the info() method.

Here I decided to override the constructor to add one more field and adapt the info method's behavior.

*NOTE:* The "super" keyword simply refer to the parent class.

<h3 id="eh">Error Handling</h3>
We are used to errors and programs wipe out as developers but if possible, you should ship a rock-solid, error-proof and bug free program to production. 

*From now, I assume that your Python code is correct and does not raise syntax error.*

If you run an unhandled exception, the program will probably crash and stop the execution straight away.

In order to avoid potential crashes, it is recommended to wrap error-prone code in a "try-except-else" block. 

![try except else](https://files.realpython.com/media/try_except_else_finally.a7fac6c36c55.png)

```python
try:
    # Code to execute
    raise Exception("An error occured.")  # Some code raise an exception.
except:
    # If there is an exception
    print("Something failed ❌")
else:
    # If no exception was raised
    print("Everything is Ok ✅")
finally:
    # Code to execute
    print("We made it 👍")
```

It ain't much, but it is enough to start working on your code's quality. Of course, it would not be a good practice to wrap your whole codebase in a massive try block...

<h3 id="fs">File System</h3>
Python offers a simple way to interact with local files and directories. 

The best practice for opening and closing files uses the with keyword. This keyword closes the file automatically after the nested code block completes.

```python
# text.txt
Hello

# main.py
with open("text.txt", "r") as file:
    print(file.read()) # Display "Hello" in the console.

with open("text.txt", "a") as file:
    file.write(" World!") # file.txt's content is "Hello World!" now.

with open("text.txt", "w") as file:
    file.write("Cool!") # file.txt's content is "Cool!" now.
```

The first argument is the target file and the second is the opening mode. 

![modes](https://geospatialtraining.com/wp-content/uploads/2011/09/python_file3.png)

It is also possible to interact with directories using "os" methods. The example below shows how to list every files in the current directory.

```python
# main.py
import os

with os.scandir("./") as entries:
    for entry in entries:
        print(entry.name)

# Displays in the console: 
# file.txt
# main.py
# .vscode
```

Another interesting method is "mkdir" that creates a new directory.

```python
# main.py
import os

try:
    os.mkdir("Test")
except:
    print("Directory already exists.")
else:
    print("Directory created ✅")
```

Here, it might be clever to wrap your code in a "try-except" block because the program will crash if a directory with the same name already exists.

thank you for reading 😇