Python's pathlib module (www.pythonmorsels.com)
from norambna@programming.dev to python@programming.dev on 18 Nov 2024 17:28
https://programming.dev/post/21864360

via mastodon.social/@treyhunner/113504959975116212

#python

threaded - newest

pnutzh4x0r@lemmy.ndlug.org on 18 Nov 2024 17:51 next collapse

Path objects also override the / operator to join paths

This is both cool and gross… gives me C++ vibes (operator overloading abuse).

Diplomjodler3@lemmy.world on 18 Nov 2024 18:20 next collapse

They could have chosen a better operator. But the functionality is fantastic. Makes working with paths so much easier. And you can even use slashes on windows paths.

leds@feddit.dk on 18 Nov 2024 21:37 collapse

It makes the code so much more clean and readable since you’re dropping multiple levels of brackets , for example

os.path.join( a, b, os.path.dirname©)

Becomes

a / b / c.parent

I really like it

Diplomjodler3@lemmy.world on 18 Nov 2024 22:13 collapse

I always hated os.path. pathlib is just so much better.

Fred@programming.dev on 18 Nov 2024 22:10 next collapse

Scapy is another library where they redefined / to layer packets, such that you can write:

IP(dst="172.23.34.45") / UDP() / DNS(…)

Then Scapy has magic so that on serialisation, the UDP layer knows defaults to dport=53 if the upper layer is DNS, and it can access the lower layer to compute its checksum.

And don’t forget that strings have a custom % (as in modulo) operator for formatting:

"Hello %s" %(username)

Of course in modern Python, f-strings will almost always be more convenient

Midnitte@beehaw.org on 18 Nov 2024 23:44 collapse

A great joy when working with people on a combination of Windows/MacOS/Linux.

Hell, even great when your laptop is windows and desktop (or even raspberry pi) is Linux

eager_eagle@lemmy.world on 18 Nov 2024 17:52 collapse

Nice, mypath.open() is a more semantic alternative to open(my path)

joyjoy@lemm.ee on 18 Nov 2024 18:34 next collapse

Don’t forget about the helper functions mypath.read_text() and mypath.write_text(content)

eager_eagle@lemmy.world on 18 Nov 2024 18:41 collapse

that’s already in the cheatsheet

ulterno@programming.dev on 19 Nov 2024 10:15 collapse

Today I realised, we all prefer semantics matching oriental language semantics.
English: Open my path.
Same sentence in Hindi semantics would be: My path open.