Your DevOps study space

Real explanations. Videos with tests. Fresh exams every time. Keep the streak alive and watch the XP stack up.

OOP & error handling · Python Docs · StackwisePlanDevOps OOP & error handling · Python Docs · StackwiseCodePython OOP & error handling · Python Docs · StackwiseBuildDocker OOP & error handling · Python Docs · StackwiseTestDevOps OOP & error handling · Python Docs · StackwiseReleaseGit OOP & error handling · Python Docs · StackwiseDeployKubernetes OOP & error handling · Python Docs · StackwiseOperateLinux OOP & error handling · Python Docs · StackwiseMonitorDevOps

Pick a topic

Eight tracks, each with docs, a cheat sheet, videos and tests.

How it works

One loop, repeated until it sticks.

Jump back in

Picked up from where you left off.

Free forever

Your DevOps journey starts with one click.

Sign in with Google or GitHub to open every chapter, video, test and challenge. Your progress is saved wherever you learn.

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.
  • finally is 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

  1. Write a class Counter with an add() method that adds one, and a value attribute 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)   # 2
  2. Write safe_int(text, default=0) that returns the number in text, or default if it isn't a number.

    Show an answer
    def safe_int(text, default=0):
        try:
            return int(text)
        except ValueError:
            return default
  3. Read servers.txt and print how many lines it has, but print no servers.txt yet instead 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")

Questions

Pick an answer. Get it wrong and you can try again right away, no waiting. 10 questions per topic - pick a filter below, then use Recreate questions for a fresh set on that topic.

Fresh questions every time

Exam

A mixed test across the whole site, shuffled so you never know which topic comes next. When you submit, every mistake comes with the reason and a jump to the exact moment in the video that explains it.

30 questions 6 topics 20 minute limit Up to 70 XP
1–4 answer · ←→ move
History

Essay

0 / 200-250 words
Sample answer
History
0:00 / 0:00
Not started

on YouTube
Subscribe

Topic progress

Activity

Achievements

Settings

Your profile and your account.

Profile details

* Required. Saved in this browser until you sign in.

Letters, numbers, dots, dashes and underscores.
0 / 160

Account

Checking…

App

Install Stackwise on your phone or computer. It opens in its own window from your home screen, and the Docs and cheat sheets you've opened keep working without internet.

Only admins can see this

Dashboard

Sign-ups, activity, messages and reviews in one place.

Prove it

Certificates

Pass a topic's test and get a certificate with its own public page you can share or add to LinkedIn. Each test is 10 questions drawn at random and graded on the server; you need 8 right, you have 15 minutes, and you get one try per topic a day.

From first command to production

Linux for DevOps

A path through Linux the way DevOps engineers use it: ten stages, every command explained with its flags, examples, real output and mistakes, the combinations engineers chain together, and incidents worked through step by step. Practise everything in a safe lab folder.

Before the interview

Interview prep

Questions that come up in real DevOps interviews, with the kind of answer that lands. Say yours out loud first, then compare. Each one links to the chapter that goes deeper.

    Private to you

    My notes

    Everything you wrote down while watching and reading, in one place. Saved to your account, never shown to anyone.