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

4

u/duffer_dev Mar 30 '21 edited Mar 30 '21

Over the years I've developed this procedure when starting with a new module or project. I call it the "Top-Down" approach or main first approach. This is very similar to what most of the other comments have suggested.

I first start with the main file that is going to be executed. It helps to organize the code organically. Once you have the main written with essential setups or function call, I then implement the internal functions/classes. I avoid the temptation of implementing internal functions, classes initially. Just create an empty template

Always have the end result in your mind. A few question that you should ask yourself

  1. How is this module/project going to be used

  2. How is it going to executed/deployed

  3. What are the command line arguments, configurable parameters i want in my module

Start with a template setup.py and an empty start start script with just a main function in it. For e.g , If i am building an application that fetches some data from a website, processes it and then stores the processed data , the code would be

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

I've added an additional parameter just for demonstration purpose. If I want these parameter in a config file, I'll create a config file, say config.json

{
    'url' : 'www.reddit.com,
    'interval' : 30.0 
}

My code would then run like

python data_processor.py --config config.json

This already gives me an idea of what the command line arguments would be. I then implement the main file . which could look something like this

from argparse import ArgumentParser
import json

def main(config):
    ...

if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument('-c', '--config') # and some other params
    parser.add_argument('-u', '--url')
    args = parser.parser_args()

    with open(args.config) as f:
        config = json.load(f)
    main(config) 

I have not implemented the main function yet, but i already have a working code for running and testing my script. From here on, start implementing how the execution would proceed. For example you want to parse some data and store it in a file or database. The main function can thus look like

def main(config):
    url = config['url']
    db_connector = DataBaseHandler()
    data = get_data(url)
    processed_data = process_data(data)
    db_connector.store(processed_data)

Even at this point, the functions are not implemented. But the design of the code is getting created on it's own with this "top-down" approach. I could have empty functions in a separate file which look something like this. Lets call it, data_handler.py

class DataBaseHandler:
    def __init__(self):
        ...
    def store(self, data):
        ...

def get_data(url):
    ...

def process_data(url):
    ...

I can still run my code and test it. Although nothing happens, the steps are becoming more and more clear. If I want to just test a small function in a separate file, i add an if __name__ == "__main__" block in that file and call that function with some predefined parameters. for e.g the file data_handler.py can have something like this

if __name__ == "__main__":
    data = "some data"
    processed = process_data(data)
    print(processed)

You can the run just the data_handler.py to test how this function is behaving.

The top down approach builds your code is a more systematic manner. Also, the imports and parameters are added consistently. You also reduce going back and forth between function calls and modifying parameters and other parts of implementation to fit the function caller. This is a very basic approach that i follow for my work

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