Big static method secret
This has never been written about before.
It's a secret about using static methods in Python, and in fact, it's the most valuable way to use them in this language.
You know about static methods, right? It's basically a function contained inside a class.
- class AudioFile:
- def __init__(self, name, track_number):
- self.path = self.make_filename(name, track_number)
- @staticmethod
- def make_filename(name, index):
- return f"{index} {name}.mp3"
That's different from a normal method, because static methods can't refer to "self" - they shouldn't even be called methods, really. It's just a regular function, indented in the class.
For various reasons - such as class methods (those of you who got into Pythonic OOP know all about that) - static methods aren't so important in Python. Not compared to how other languages critically needed 'em.
But there's one REALLY great use for them in Python, and I've never heard anyone talk about it:
They are KILLER for unit tests.
If you're not too familiar with unit tests, I'm planning to talk about them more in the coming weeks. But if you are, you know that when you're testing a method of a class, you have to go through some trouble before you do any actual testing.
Creating instances, getting them in the state that's needed, setting up fixtures...
And then, you can finally assert that the method is behaving.
Or, you can skip all that...
Take the complexity that's the heart of what you really need to test. Package it in a static method, with no side effects. Just data in, and data out. So the methods of your class use that static method internally...
And then your unit test exercises that static method!
Because remember, a static method is a slightly-disguised regular function...
And a regular function, with no side effects, is the EASIEST THING in the world to write a unit test for.
If that turned on a light bulb for you... maybe you'll want to look the tests you wrote recently. See if you can simplify them, by adding a static method to the class being tested.