• @[email protected]
    link
    fedilink
    English
    46 hours ago

    Path objects also override the / operator to join paths

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

    • Fred
      link
      fedilink
      21 hour ago

      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

    • Diplomjodler
      link
      25 hours ago

      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.

      • @[email protected]
        link
        fedilink
        22 hours ago

        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(c))

        Becomes

        a / b / c.parent

        I really like it

        • Diplomjodler
          link
          21 hour ago

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

  • Eager Eagle
    link
    English
    16 hours ago

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

    • unalivejoy
      link
      fedilink
      English
      15 hours ago

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

      • Eager Eagle
        link
        English
        15 hours ago

        that’s already in the cheatsheet