HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Parsing a text file of nested structures using a state machine

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filetextnestedparsingusingstatemachinestructures

Problem

My goal is to have something really simple with as small an amount of code as possible. The real code is used to parse a text file of nested structures. This code is highly simplified but is the general way that the state machine would work.

Is there a replacement for the global?

# python doesn't support enums but can do this way
class state:
    OUT = 0
    DNARRAY = 1            # under "DN array" heading
    CSTA_REQUEST = 2       # aPDU-rose : invoke :
    CSTA_RESPONSE = 3      # aPDU-rose : retResult :
    END_OF_FILE   = 4

currentstate = state.OUT

def do_out():
    print "doing OUT - transitioning to DNARRAY"
    global currentstate
    currentstate = state.DNARRAY

def do_dnarray():
    print "doing dn array - transitioning to csta request"
    global currentstate
    currentstate = state.CSTA_REQUEST    

def do_csta_request():
    print "doing csta request - transitioning to csta response"
    global currentstate
    currentstate = state.CSTA_RESPONSE

def do_csta_response():
    print "doing csta response - transitioning to END_OF_FILE"
    global currentstate
    currentstate = state.END_OF_FILE   

statemap = {state.OUT : do_out,
           state.DNARRAY : do_dnarray,
           state.CSTA_REQUEST : do_csta_request,
           state.CSTA_RESPONSE : do_csta_response,
}

def decisions():
    while(currentstate != state.END_OF_FILE):
        statemap[currentstate]()

    print "done!"

decisions()

Solution

The obvious answer is to make currentstate an explicit return value from your functions, for example:

def do_out():
    print "doing OUT - transitioning to DNARRAY"
    return state.DNARRAY


Then handle it appropriately in the final loop:

def decisions():
    currentstate = state.OUT
    while(currentstate != state.END_OF_FILE):
        currentstate = statemap[currentstate]()
    print "done!"

Code Snippets

def do_out():
    print "doing OUT - transitioning to DNARRAY"
    return state.DNARRAY
def decisions():
    currentstate = state.OUT
    while(currentstate != state.END_OF_FILE):
        currentstate = statemap[currentstate]()
    print "done!"

Context

StackExchange Code Review Q#61343, answer score: 2

Revisions (0)

No revisions yet.