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

7

u/[deleted] Mar 30 '21 edited Mar 30 '21

What works for me is I tend to write down on paper a high level overview of how the program will work.

When writing the code, I put some info at the start of a function to tell me some useful stuff like

def get_some_shit(a,b):
 '''
    Descr: This function takes two integers and adds them together
    Parameters: 
        a -> int
        b -> int
    Return:
        dict
            {'final': a+b, 'other': 'test123'}
 '''
 c = {'final': a+b, 'other': 'test123'}
 return c

Not sure if it's just a facet of my plugin for VSCode but when typing the function name, it then shows me the information detailed at the function header for quick reference

You can always specify the param type in Python3 for function args such as:

def get_some_shit(a: int, b: int):
 pass

But Python2 does not support, for ease I use my method to remove the chance that it won't work on Python2

7

u/Ran4 Mar 30 '21

for ease I use my method to remove the chance that it won't work on Python2

Supporting Python2 is almost always a bad idea today.

1

u/[deleted] Mar 30 '21

As far as I'm aware there's no harm in doing so

1

u/[deleted] Mar 31 '21

The harm is you lose the potential benefits of type hinting (and other features not supported in 2)