Is “finally” Useless in Python?

Is "finally" Useless In Python?

This works as expected.

try:
	raise ValueError('Bad Value')
except ValueError:
	print('Handle ValueError')
finally:
	print('Finally does something')

The nested raise Exception statement is unreachable.

try:
	raise ValueError('Bad Value')
except ValueError:
	print('Handle ValueError')
	raise Exception('This was not expected')

Finally gets executed in this case no matter what happens, even though we run into an error.

try:
	raise ValueError('Bad Value')
except ValueError:
	print('Handle ValueError')
finally:
	print('Finally does something')

Even though we tell the system to exit, finally still gets executed.

import sys

try:
	raise ValueError('Bad Value')
except ValueError:
	print('Handle ValueError')
	sys.exit('Terminating')
finally:
	print('Finally does something')

In short, finally will always run in spite of anything try and except might say.

WHAT Is “Pickle” In Python?! (EXTEMELY Useful!)

WHAT Is "Pickle" In Python?! (EXTREMELY Useful!)

Used to serialize and deserialize objects.

Here is an example using JSON and writing/reading a file

import pickle
import json

class Fruit:
	def __init__(self, name: str, calories: float):
		self.name = name
		self.calories = calories
		
	def describe_fruit(self):
		print(self.name, self.calories, sep=': ')

if __name__ == '__main__':
	fruit: Fruit = Fruit('Banana', 100)
	fruit.describe_fruit()
	
	fruit.calories = 150
	
	#One way to save
	with open('banana.json', 'w'): as file:
		data = {'name': fruit.name, 'calories': fruit.calories}
		json.dump(data, file)
		
	#One way to retrieve
	with open('banana.json', 'r') as file:
		data = json.load(file)
		print(data)

Let’s use pickle instead

import pickle
import json

class Fruit:
	def __init__(self, name: str, calories: float):
		self.name = name
		self.calories = calories
		
	def describe_fruit(self):
		print(self.name, self.calories, sep=': ')

if __name__ == '__main__':
	fruit: Fruit = Fruit('Banana', 100)
	fruit.describe_fruit()
	
	fruit.calories = 150
	
	with open('data.pickle', 'wb') as file:
		pickle.dump(fruit, file)
		
	with open('data.pickle', 'rb') as file:
		fruit: Fruit = pickle.load(file)
		
	fruit.describe_fruit()
	
	fruit.calories = 200
	fruit.describe_fruit()

Pickle data can be dangerous because the data inside of the pickle file is unknown until the pickle data is actually accessed/run. Only use pickle data where you know/trust the source.