OOP & error handling
Classes let you bundle data with the functions that work on it, which is how most Python libraries are organised. Error handling lets a script deal with things going wrong (a missing file, a server that doesn't answer) instead of crashing.
Classes and objects
A class is a blueprint; an object (or instance) is one thing built from it. The class defines what data each object holds (attributes) and what it can do (methods, functions that belong to it).
class Server:
def __init__(self, name, ip):
self.name = name # attributes stored on this object
self.ip = ip
self.up = False
def start(self):
self.up = True
return f"{self.name} ({self.ip}) is up"
web = Server("web-01", "10.0.0.5") # __init__ runs here
web.start() # 'web-01 (10.0.0.5) is up'
__init__ runs automatically when an object is created and sets it up. self is the object itself: self.name means "this server's name", so each object keeps its own values.
Inheritance
A class can be based on another one and inherit all its attributes and methods, then add or override what's different. That avoids copying code between similar classes.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof"
class Puppy(Dog): # Puppy inherits from Dog
def bark(self): # overrides one method
return f"{self.name} says yip"
Exceptions: when things go wrong
When Python hits a problem it can't continue from, it raises an exception, such as ZeroDivisionError, FileNotFoundError, KeyError (missing dict key), ValueError (like int("abc")) or TypeError. If nothing handles it, the program stops and prints a traceback that shows where it happened, read from the bottom up.
try:
with open("config.json") as f:
config = json.load(f)
except FileNotFoundError:
print("no config, using defaults")
config = {}
except json.JSONDecodeError as e:
print("config is broken:", e)
raise # re-raise: this one should stop the script
else:
print("config loaded") # only if nothing went wrong
finally:
print("done") # always runs, error or not
- Catch specific exceptions. A bare
except:also hides typos and real bugs. raise ValueError("port must be a number")raises your own error.finallyis for clean-up that must happen no matter what, like closing a connection.
A class you'd actually write
Use a class when some data and the functions that work on it belong together, and you'll have several of them. A health check for a list of URLs is a good fit: each check has a URL, remembers its last result, and knows how to run itself.
import urllib.request
class HealthCheck:
def __init__(self, url, timeout=5):
self.url = url
self.timeout = timeout
self.last_status = None
def run(self):
try:
with urllib.request.urlopen(self.url, timeout=self.timeout) as r:
self.last_status = r.status
except Exception as e:
self.last_status = f"failed: {e}"
return self.last_status
def __repr__(self): # how it looks when printed
return f"HealthCheck({self.url!r}, last={self.last_status})"
checks = [HealthCheck("https://example.com"), HealthCheck("https://example.org")]
for c in checks:
c.run()
print(checks)
If there's no state to remember and you only need one action, a plain function is simpler. Plenty of good DevOps scripts never define a class at all.
with: clean-up that always happens
with open(...) as f: opens a file and guarantees it's closed when the block ends, even if an error happens inside it. The same pattern is used for network connections, locks and temporary folders, so whenever a library offers with, use it.
with open("hosts.txt") as f:
hosts = [line.strip() for line in f if line.strip()]
# the file is closed here, whatever happened above
Your own exceptions
For problems specific to your script, define your own exception type. Code calling yours can then catch exactly that problem and nothing else:
class ConfigError(Exception):
pass
def load_port(config):
if "port" not in config:
raise ConfigError("config has no 'port'")
return int(config["port"])
try:
port = load_port({})
except ConfigError as e:
print("Fix your config:", e)
Try it yourself
Write a class
Counterwith anadd()method that adds one, and avalueattribute that starts at 0.Show an answer
class Counter: def __init__(self): self.value = 0 def add(self): self.value += 1 c = Counter() c.add(); c.add() print(c.value) # 2Write
safe_int(text, default=0)that returns the number intext, ordefaultif it isn't a number.Show an answer
def safe_int(text, default=0): try: return int(text) except ValueError: return defaultRead
servers.txtand print how many lines it has, but printno servers.txt yetinstead of crashing if it doesn't exist.Show an answer
try: with open("servers.txt") as f: print(len(f.readlines())) except FileNotFoundError: print("no servers.txt yet")