Search code examples
pythonreadabilityhuman-readable

Best way to write understandable and Python-friendly code


I have this code

def testing1(terms, request):
    dat = datetime.now(pytz.timezone(geo_timezone(request)))
    __start = terms['year']+'-'+terms['month']+'-'+terms['day']+'T'+'00:00:00'+dat.strftime('%z')[:-2]+':'+dat.strftime('%z')[-2:]
    __end = terms['year']+'-'+terms['month']+'-'+terms['day']+'T'+'23:59:59'+dat.strftime('%z')[:-2]+':'+dat.strftime('%z')[-2:]
    return __start, __end

testing({"month":12,"day":1, "year":"2015"}, request)

But I have a interrogant, whats is the best way to write this code, readable and friendly for the others programers?

Any suggestion for write code extensive in one line like this?

This suggestion is readable?

def testing2(terms, request):
        dat = datetime.now(pytz.timezone(geo_timezone(request)))
        __start = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
                  'T' + '00:00:00' + dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
        __end = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
                'T' + '23:59:59' + dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
        return __start, __end

Solution

  • The only hard part to read is where you build your string so I would use .format(). This way you can see the resulting layout and then all of the corresponding entries.

    __start = '{}-{}-{}T00:00:00{}:{}'.format(terms['year'],
                                              terms['month'],
                                              terms['day'],
                                              dat.strftime('%z')[:-2],
                                              dat.strftime('%z')[-2:])
    
    __end = '{}-{}-{}T23:59:59{}:{}'.format(terms['year'],
                                            terms['month'],
                                            terms['day'],
                                            dat.strftime('%z')[:-2],
                                            dat.strftime('%z')[-2:])