The world’s leading publication for data science, AI, and ML professionals.

Ultra Concise Python Code - Shaving Code and Finding Better Mental Health

I would call this: razor fine code but "fine" makes ambiguous what we're talking about here. It's tight python code. Its job is expression…

I would call this: razor fine Code but "fine" makes ambiguous what we’re talking about here. It’s tight python code. Its job is expression in few lines. But whether it’s fine or good is your call. It’s your mental health call. Let us set the stage:

When reviewers have had the misfortune to inspect my code they’ve cut themselves on what one supervisor (now deceased) called "strong aversion to declaring variables twice." That supervisor would slip on a slimy avocado stone rather than give a compliment. He wasn’t giving one. No, he didn’t like my list comprehensions [i for i in range(....)], frequent lambdas (l = lambda x: ...) or my hair cut (-). Good – my first instinct – because his code was terrible! But I had cause to think after he signed into github for the last time and rested his account with the ground. It’s sorta polite to review our struggles with someone when their repo is snapped shut. To accompany the ultra dark and widely monospaced material theme of morning – you understand. Well… I reflected, and eventually I understood. He despised his job (++ according to his terminal modus-operandi). Sure, I didn’t have to fill my code with one-line-loops and decorated classes. And, I could get a hair cut too. But then, I realised: I liked it. My way of writing code made me happy. The pop, snap and crackle of ultra-concise code was good code – good for me – you’ll find it good for you too.

Nobody likes repeating themselves – its good practice not to. But I had a tendency to bend good practice towards my old inner-Italian: Sorta di Estremo. Python 3.8 precipitated a change in public behaviour with the introduction of its new "walrus" assignment operator := . Suddenly we could make code super compact, stuffing new variables like socks into pockets to use later on the same day.

a = 12 if (list_length := len(super_duper_long_list)) > 20000000 else list_length

(Requires Python 3.8+ because of := assignment expression)

Now – how finger licking good is it to be able to declare a variable slap bang in the middle of an if statement then go on to use it in the same statement? It’s marvellous. In the above case we avoid counting the length of the list twice. A noble cause. Pat on the back for performance. Yeah we could have got the length of the list before the if statement. But then we’d have added in an extra-line. Does that matter? Well, if we’re guided by the principle of writing sharp and concise code then it matters. Because people that are guided by principles – that have rules guiding how they act under specific circumstances – and that see good results from those principles, they are happy people.

Being a razor-fine coder is being a coder that adheres to the principle of writing concise and efficient clean code and believing in it. They like functions that fit screens without scrolling.

We can argue that the definition of the variable and its use are kept together with this syntax. Togetherness is unarguably a very fine thing isn’t it? A marriage of content and form. But sophistics aside for a moment we’re also avoiding the bug and frustration of a variable being moved or assigned to something else… elsewhere. Small ‘m’ for minor advantage perhaps. But wait – haven’t we all arrived at the point in a programs life when code becomes so untidy that we can’t bare to look the cursor in the eye within the messy source file, let alone introduce the change or find the problem that lurks around there somewhere. Sure you have. It’s a silly assignment mistake (usually). Well, if you’re even half a code-folding kind-of-cowboy as me i’m sure you’ll see the tragic-magic of concise code. That’s what the ‘Walrus’, aka := operator nails into the syntax to rebreathe into the IDE – call it KonMari tidiness of code – considerably better for our mental health.

Well I’ll be – it is a tiny bit more difficult to refactor the concise line. But as programmers we write lines to express intention. It maybe our intention or intention of the computational sort but the line is how we float it out there. Even if it’s the final effects, the outcomes and influences of our code that "bug" and concern us later in the development – its with lines of code we paint our programs. Other tools like kid-visual coding and AI translation might be breaking out here and there. But right now our code is about brush strokes and the best basis for it, is concision.

Want another chocolaty example?

max([l for p in glob.glob(parent_dir + "*") for l in p if style_1_name in p if l.isnumeric()])

This little list-comprehension gets the file path containing the largest number (I particularly like the naughty treat of a double and triple list comprehensions like this – but can someone please think of an elegant way to extend this to handle file paths containing numbers >9). Tight, razor thin code might do the job cuttingly – a few decent variable names might polish a few snags – but tight code does the job best. Why? Aside from having to actually think about what we’re writing, aside from being more efficient, it becomes a crazy fun game making our code tidy-tight and functional.

Think of these as similar in concept to a small mathematical proof. Even if they’re somewhat less difficult. Programming returns to the game we once played out of choice (for fun!). These boiled down lines become small enough challenges to solve multiple times a day, rewarding enough to encourage more practice. Yet unlike most games of adulthood – these actually have a purpose. The outcome is super tidy code thats inherently easier to return to and review. But the "game" element of this razored coding practice isn’t a minor or side benefit to scoff at.

I wish i’d discovered earlier in life that the people who enjoy their work aren’t those with the attention spans of kings. Rather, they’re the ones that know their stuff and it’s those stuff-knowing people that give the final program claws. Sure, it’ll still need wings to fly, but unless we give it claws it won’t survive its first user.

"It makes super long lines in the IDE though man" said a hippyish friend that this time I got the pleasure of supervising. But what of it? "The truth of a long line is only a syntactic truth. Its totally valid Python to write our listy code like this:"

image_paths = [p for f in [glob.glob(f"{t}/*" if t[-1] != "/"else f"{t}*") for t in directory_paths]
for p in f if p[-3:] == "jpg"or p[-3:] == "png"]

"A bargin at twice the price – five for the price of one mi old mucka"[1]. It’s us that defines the presentation in either long form or the tight and bright way of a whisper. All that matters is that we’re encouraged to squeeze more and keep disciplined with this from. That’s toned code.

Our infinite loop

Why’s it critical to us that our work is concise? We’re simply prouder of more concise code – it makes us take respect in our work and thereby taking more respect and care… we’re happier in our jobs. Considerably. This is a feedback loop, one leading to us being more motivated to explore new and uncomfortable areas of the project, the language, the domain. Sure, there’s loads of rabbit holes – but you my literary friend aren’t an Alice. You’re the very best programmer your company and interests can beg, borrow or steal. It shows in your work.

[1] I never actually said that bit. But it’s fun to think I did


Related Articles