nobody's blog

Using Pathlib with Pain

Margret Riegert12 May 2022 views

The crunch of finals has been upon us for the past week as we wrap up the semester, my last semester at Tufts. I couldn’t help but notice all the expressions of pain due to the stress of finals from my friends - pain that made me want to make a lame joke about French bread: 🥖. No actual joke, just an expression that I know the word for bread in French and how I couldn’t wait for this all to be over.

Staring at the emoji though, I realized that it looked like a forward slash. So me and my weird, sleep-deprived brain wondered if it’d be possible to use it instead of / for building paths in in Python, like this:

from pathlib import Path
r = Path('🥖')
home_dir = r 🥖 "home" 🥖 "user"
bin_dir = r 🥖 "usr" 🥖 "bin"

How cool would that be?! And after a bit of research and testing, it turns out it’s completely possible! Using pythonji and some infix operators, here’s the little script I wrote:

$ cat pain.🐍 
#!/usr/bin/env pythonji

from pathlib import Path as 📉

class 🔨:
    def __init__(self, function):
        self.function = function
    def __add__(self, other):
        return self.function(other)

    def __radd__(self, other):
        return type(self)(lambda x, self=self, other=other: self.function(other, x))

    def __call__(self, value1, value2):
        return self.function(value1, value2)

🥖 = 🔨(lambda x, y: x / y)
r = 📉('/')
l = r +🥖+ "home" +🥖+ "margret" +🥖+ "dev" +🥖+ "linux"

$ ./pain.🐍 

Of course while it’s not exactly just the French bread emoji (being surrounded with +), it’s definitely a lot closer than I thought I would get originally. And while infix operators may technically be a “hack” on Python, I love their flexibility to do weird stuff like this. Off to finish the rest of my finals!

I created the cover photo using Carbon, for those interested.

© 2020-2022 Margret Riegert
Unless otherwise noted, content is under a CC BY 4.0 license.