Every useful script tends to grow. It gains options, more people start using it and, before you notice, it has become part of a process. At that point, the techniques that worked for a ten-line script are no longer enough. It is time to turn to object-oriented programming, automated tests, more careful error handling and packaging. These techniques let the whole team maintain the tool with confidence, not only the person who wrote it.
This is the third guide in the track and the most demanding one. The focus is still defensive, on well-built tools for operations, analysis and automation. It also covers secure coding, because a badly written security tool can end up becoming a problem itself.
Organizing with object-oriented programming
When the tool deals with concepts that combine data and behavior, object-oriented programming helps keep things organized. Instead of scattering dictionaries and loose functions through the code, you model the concept as a class that holds the data and the operations tied to it. A scan finding, for example, has its own fields and rules and becomes a class almost naturally:
from dataclasses import dataclass@dataclassclass Finding: host: str severity: str description: str def is_critical(self) -> bool: return self.severity == "critical"finding = Finding("web-01", "critical", "Exposed admin port")print(finding.is_critical())The class makes the code clearer and harder to misuse: anyone reading it can see that a finding has a host, a severity and a description, and that the rule for what counts as critical lives next to the data. You do not need to turn everything into a class, but for the tool's core concepts, classes are worth the effort.
Tests that build confidence
A team only truly trusts a tool that has tests. An automated test checks that the code does what it promises and repeats that check on every change, which keeps a fix from breaking something else without anyone noticing. In security this matters more, because a tool that gets it wrong can miss a risk or raise a false alarm. Here are two simple tests with pytest:
from tool import Findingdef test_critical_finding(): finding = Finding("web-01", "critical", "example") assert finding.is_critical() is Truedef test_non_critical_finding(): finding = Finding("web-02", "low", "example") assert finding.is_critical() is FalseWriting tests changes the way you program. The code tends to become more modular, since only well-separated code is easy to test. And you gain the freedom to improve the tool without fear, because the tests tell you if something important broke. Start with the core rules, such as the one that decides what is critical.
Error handling and reliability
In production, the tool will run into the unexpected: a file that does not exist, an API that is down, data in an odd format. If these cases are not handled clearly, the tool fails in mysterious ways and nobody understands why. Error handling exists to deal with them on purpose: record what happened and, when there is no way to continue, stop in a predictable way. Hiding the error is the opposite of that.
Record important events with the logging module instead of scattering print calls, so the tool leaves a useful trail for an investigation. And catch specific errors (FileNotFoundError, for example) instead of catching everything at once. Handling that is too generic tends to swallow real bugs along with the cases you anticipated.
Type hints and static security analysis
Annotating function types (type hints) makes the code's intent explicit and lets you find errors before the tool runs. A type checker like mypy warns you when you pass a string where the function expected a number, and a linter like ruff catches style problems and common defects. They are cheap safety nets, and their value grows as the tool gets bigger and more people work on the code.
In a security tool, two more checkers deserve a permanent place. Bandit analyzes the Python code itself for insecure patterns, such as dangerous functions or secrets written in the source. The pip-audit tool compares your dependencies against databases of known vulnerabilities. Running both as part of your workflow keeps a tool built to reduce risk from introducing one. The four commands look like this:
ruff check . # style and common defectsmypy . # type checkingbandit -r . # insecure patterns in the codepip-audit # vulnerabilities in dependenciesPackaging and distributing securely
Once the tool matures, it is worth packaging it, so other people can install and use it without copying loose files around. That means declaring dependencies and versions, defining an entry point and documenting how to use it. The benefit is reproducibility: a well-defined package runs the same way on your machine and on a colleague's.
- Declare dependencies with defined versions
- Pin versions for reproducible builds
- Review the third-party libraries you add
- Track vulnerability advisories for your dependencies
- Document how to install and use the tool
The dependency chain needs attention too. Every third-party library that goes into the tool is code you are now running, so choose carefully, pin versions and follow vulnerability advisories. Picture a security tool compromised through one of its dependencies: it ends up working against its own purpose.
Completing the Python track
Object-oriented programming, decorators, generators and tests are the techniques that take you from scripts to tools that last. They require a solid foundation, and that is where the track comes full circle. If you already write organized code and want to go further, Valor Final's Curso de Python Avançado (in Portuguese) is the last step in this free track.
The course is for people who already know the intermediate material, and it covers exactly object-oriented programming, decorators, generators and tests, the subjects that hold up a reliable tool. With the full track, from basic to advanced, you have the foundation to write security automation and tools your team can rely on every day.
Practical checklist
- Model the tool's core concepts as classes
- Write automated tests for the main rules
- Add type hints and run a checker such as mypy
- Run bandit on the code and pip-audit on the dependencies
- Handle errors on purpose, without hiding real failures
- Record events with logging instead of scattered print calls
- Catch specific errors instead of everything at once
- Declare and pin dependency versions
- Review third-party libraries and track their vulnerabilities
- Document how to install and use the tool
Best practices
- Use classes for the tool's core concepts and plain functions for the rest
- Test first the rules that cause the most damage if they break
- Make the tool fail predictably and leave a record of the error
- Treat dependencies as part of the security surface
- Package the tool so it runs the same on any machine
Common mistakes
- Catching every error with generic handling
- Real bugs disappear along with the expected cases, and nobody finds out.
- Building a tool without any tests
- Any change can break something without anyone noticing.
- Adding dependencies indiscriminately
- The tool ends up running third-party code of dubious origin.
- Not pinning library versions
- An update changes the tool's behavior without warning anyone.
Valor Final's Python track (in Portuguese)
Valor Final's three free courses, all taught in Portuguese, make up the full track. The advanced course closes the sequence with the subjects that support building reliable tools.
Curso de Python Básico
FreeFree Python course for people who have never programmed. From the very first lesson you write real code, right in the browser, without installing anything. Course in Portuguese.
Valor Final View courseCurso de Python Intermediário
FreeSecond course in the track. It is for people who already know the basics (variables, conditionals, loops, lists and functions) and want to keep going. Course in Portuguese.
Valor Final View courseCurso de Python Avançado
FreeThird course in the track. It is for people who already write well-organized code and want to go deeper into object-oriented programming, decorators, generators and testing. Course in Portuguese.
Valor Final View course
Authorship and review
Cesar Gargiulo
CEO and founder of GUARDIASEC. Technical and editorial lead for the content published in this library.
Published on . Found a technical error? Write to [email protected] and we will correct it and keep a record of the change.