optimise and reformat py code