O'Reilly logo

Python Unlocked by Arun Tigeraniya

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

State pattern

Key 10: Changing execution based on state.

State machines are very useful for an algorithm whose vector-flow of control depends on the state of the application. Similar to when parsing a log output with sections, you may want to change the parser logic on every next section. It is also very useful to write code for network servers/clients who enable certain commands in a certain scope:

def outputparser(loglines): state = 'header' program,end_time,send_failure= None,None,False for line in loglines: if state == 'header': program = line.split(',')[0] state = 'body' elif state == 'body': if 'send_failure' in line: send_failure = True if '======' in line: state = 'footer' elif state == 'footer': end_time = line.split(',')[0] return program, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required