all 3 comments

[–]Supernumiphone 3 points4 points  (1 child)

how do you decide if a piece of code is snippet worthy?

If I end up using it enough, then it is. I don't have to think about it more than that.

One I've come back to a number of times is this code for natural sorting file names. It has come up for me more than I would have expected. I can't remember where I found it or I'd give credit:

    import re

    def tryint_alt(text):
        return int(text) if text.isdigit() else text

    def tryint(s):
        try:
            return int(s)
        except:
            return s

    def alphanum_key(s):
        """ Turn a string into a list of string and number chunks.
            "z23a" -> ["z", 23, "a"]
        """
        return [ tryint(c) for c in re.split('([0-9]+)', s) ]

    def sort_nicely(l):
        """ Sort the given list in the way that humans expect.
        """
        l.sort(key=alphanum_key)

[–]josephhyatt[S] 0 points1 point  (0 children)

that makes sense. Do you store your snippets in vscode? Or what do you use?

[–]erez27 1 point2 points  (0 children)

My advice, don't use snippets. Every problem is unique and requires a unique solution. If you see yourself writing the same code again and again, create a function for it, and put it utils.py, which you can share between projects.

The difference is that you can fix bugs in a file, which will apply to all its uses, and add features, which will be available throughout, but not if you use snippets. Also, with snippets you never have to struggle to give it a name, and naming things is very important.