Friday Finking: Source code organisation

DL Neil PythonList at DancesWithMice.info
Thu Jan 2 15:09:46 EST 2020


On 3/01/20 7:36 AM, Terry Reedy wrote:
> On 1/2/2020 2:46 AM, Cameron Simpson wrote:
> 
>> Inline code under the if...__main__ stuff cannot be called as a function;
> 
> Which makes it difficult to test app startup.
> 
>> I usually consider the main() function a reusable component. 
> 
> Which, if called (at least optionally) with a list of string arguments 
> (sys.argv) as Cameron suggested, makes it easy to test with various 
> lists of strings.


NB I agree with suggestion that 'important stuff' is better placed at 
'top' of source-code. Preceding comment assumes that main() is to be a 
word/name which catches the eye and has 'importance' attached. However, 
the Python idiom is "if __name__ == '__main__'" and (paradoxically?) 
that usually goes at the 'bottom'.

I think we've previously discussed if __name__ == '__main__' and/vs main().


Continuing the discussion, above:-


def start_up( args ): etc

def do_it( args ): etc

def close_down( args ): etc

if __name__ == '__main__':
    start_up( sys.argv )
    do_it( etc )
    close_down( etc )


1. app startup remains test-able
2. each component is reusable
3. sys.argv may be passed with all flexibility
4. separation of concerns, etc, observed

NB above for casual illustration only - if start_up() is more than 
trivial, seems likely that others would be better implemented as context 
manager, etc, etc...
-- 
Regards =dn


More information about the Python-list mailing list