r/learnpython • • 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)

349 Upvotes

107 comments sorted by

View all comments

11

u/brews Mar 30 '21

A bit more advanced but it might be worth checking out Test-Driven Development.

2

u/baubleglue Mar 30 '21

Yes, probably it is not for beginners. I've tried it for my first big project, completely broke my code to make it testable. I think when the code is already generally structured, then you may give it a shot.

2

u/ffrkAnonymous Mar 30 '21

I'm learning ttd and the more I practice, the more I feel it should be taught to beginners, those with short simple code, not starting with big projects. Literally, test does the code output "Hello world".

2

u/DoozerMarch Mar 30 '21

There is a real knack to writing tests. When I started out they often got in the way when I wanted to change code structure. This still happens sometimes but it seems like less with experience. Keeping them really thin and simple seems to help. Avoiding the temptation to write integration tests muddled along side unit tests seems to be key. The mock library is good for this.

2

u/ffrkAnonymous Mar 30 '21

I've become quite a fan of ttd Https://Obeythetestinggoat.com

Im still a beginner, but it's helped me to organize, each "step" is a test (expected failure), and helps me extend my code. I can put in placeholder code and replace it without worry.

At the very least, if nothing else , I have documented code that explains and show what each function does.

I'm practicing TDD on advent of code and I have no idea what I'm doing, especially the latter exercises. ttd (and version control) let's me experiment.

1

u/brews Mar 30 '21

Yeah, +1 for the goat.

I think the testing goat guys have a pretty good book on python architecture patterns that came out this year or last year.