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

Show parent comments

1

u/fergal-dude Mar 30 '21

This is a really well written into. You've got to have a bit of intermediate knowledge to know what it means, but you've got me googling config files now. I've seen yaml config files before, but I didn't understand them.

Can you explain this line please?

python data_processor.py --url www.reddit.com --interval 30

I'm assuming this begins a python file (data_processor), but what purpose do the --url and --interval serve? are they command line commands?

Thanks for any help understanding this.

2

u/duffer_dev Mar 30 '21

These are command line arguments for the code. Think of them as input parameters for the script that you can pass when running the code. The library ArgumentParser gives a convenient way of adding such arguments with flags in python

1

u/fergal-dude Mar 30 '21

Interesting, so you are literally filling in variables with those flags when you run the program?

1

u/duffer_dev Mar 30 '21

Kind of. Think something like sys.argv, but with more options. For example if I want to process another website's data, I can simple change the parameter, '--url' with the website I want. That way , I don't have to change the code. It's like passing variable into a function. Only this time, you are passing variable to your script from the command line

I've updated the code to include the URL parameter