r/learnpython • u/brushygiraffe • Mar 30 '21
How are you ‘planning’ your code?
There’s a thousand videos on Youtube on how to code Python - but they seem to be more like function references - which you can look up in the documentation?
How you guys and girls think through what you’re about to write?
Should I write 90 lines of code then reorganise it into functions? Or start writing functions and then finally ‘use’ the functions at the bottom of your code/script?
Is there a best practice way of doing this? I’m trying to make it easier for myself so everything works like ‘lego’ - otherwise I find I get really confused
Should I write down the steps as comments and then fill in the code after?
‘’’ getjson() Function will accept json string and return TSV def getjson():
‘’’ getinputs() function will read argv[1:] and return the first parameter, or exit with error message if none specified def getinputs():
‘’’ writetosql() function will accept TSV and write it to final.db def writetosql():
‘’’ Run the functions inputs=getinputs() tsv=getjson(inputs) writetosql(tsv)
1
u/thedjotaku djotaku Mar 30 '21
Depends how rigorous you want to be. And the scope of your project. The "best" way is to write your unit tests first and then write code that passes those tests. When all tests pass, you're done. And you know everything will work well if you wrote good tests. I've done some projects like that and it can be satisfying to see your tests pass one-by-one as you code your solution.
But, most of the time, I just have an idea of what I want to do (I need to automate signing up for a spot at the gym, I need to automate backups, I need to generate graphs of focal lengths of my photos) and then I start coding. Once I have something that works, I start refactoring. That is, now that I know how it works, I start making it "good", "elegant" code. Maybe I realized there's something I need to do in more than one place, so I make that into a function. Maybe I made something into a class, but that's too complex so I take it out of the class. Or as I add type annotations I realize I was being too lazy with my inputs or something. The longer I've been coding in Python the less of these refactors I need to make when I'm done.