Cute python: Increase efficiency with a generator based state machine and a collaborative program

Source: Internet
Author: User
Tags final generator range sin in python

The simple generator introduced in Python 2.2 can be used to simplify the state machine and emulate the collaboration program. David describes an abstract pattern of state machine processing in an earlier section of the "Lovely Python" column. Since then, the introduction of simple generators has provided some more natural examples of describing machines. A collaborative program is a "foreign" flow mechanism that is rarely supported by widely used languages (even stackless Python does not support it). However, the Python generator almost fully supports the collaboration program, with little emulation of any additional steps. In this article, David explains all the relevant concepts through a descriptive code sample.

It will take you a while to fully "understand" the new builder of Python 2.2. Even if you've written about simple generators in the previous section of "Cute Python," I can't say I fully understand the "complete structure (Gestalt)" of the generator. This article describes some additional patterns for the generator to use, and hopefully it will give me and the reader a deeper understanding of the concept of "recoverable function".

Simple generators have many advantages. In addition to being able to express the process of a class of problems in a more natural way, the generator greatly improves many inefficiencies. In Python, function calls are expensive; In addition to other factors, it takes some time to resolve the list of function arguments (in addition to other things, analyze positional and default parameters). Initialization of the frame object also takes some steps to build (there are more than 100 C language programs, as Tim Peters said on Comp.lang.python), and I haven't checked the Python source code myself yet. Conversely, restoring a generator is rather labour-saving; The parameters are parsed, and the frame object is "idle" for recovery (with little additional initialization required). Of course, if speed is the most important, you should not use a dynamic language that has been compiled with bytecode, but it's better to be faster than slow even if the speed is not the primary consideration.

Recall state Machine

In another article in front of "cute Python," I introduced the StateMachine class, how many state handlers are required for a given machine, and how many state handlers it allows the user to add. In the model, one or more states are defined as final (end state), and only one state is defined as the initial state (the call class method configures this). Each handler has a required structure, the handler performs a series of actions, and then, in a moment, it returns to the loop in the Statemachine.run () method with a token that indicates the next state to want. Similarly, using the cargo variable allows a state to pass some (unhandled) information to the next state.

The typical use of the StateMachine Class I'm introducing is to use input in a stateful fashion. For example, I used a text processing tool (txt2html) to read several lines of content from a file, and it needs to be handled in a special way, depending on the category to which each row belongs. However, you often need to look at the context provided in the previous lines to determine which category the current row belongs to (and how it should be handled). The implementation of this procedure built on the StateMachine class can define a handler that reads a few lines and then processes the rows in a way that resembles a. Soon, a condition was met, so that the next batch of several lines should be handled by the B-processing program. A passes control back to the. Run () loop, indicating that the switch to the B state--and any extra rows that B should handle before reading an extra few lines--is not handled correctly by any A. Finally, a handler passes its control to a state that is specified as final, processing the Stop (halt).

For the specific code examples in the previous section, I used a simplified application. I handle the stream of numbers generated by an iterative function, rather than the processing of multiple lines of content. Each state handler prints only those numbers in the desired range of numbers (and some messages about the active state). When a number in a digital stream reaches a different range, a different handler takes over "processing." For this part, we'll look at another way to implement the same digital stream processing with a generator (with some extra tricks and functionality). However, a more complex generator example might handle the input stream more like the one mentioned in the previous paragraph. Let's take a look at the previous state machine's version of the deletion code:

Listing 1. statemachine_test.py

from statemachine import StateMachine
def ones_counter(val):
  print "ONES State:  ",
  while 1:
    if val <= 0 or val >= 30:
      newState = "Out_of_Range" ; break
    elif 20 <= val < 30:
      newState = "TWENTIES";   break
    elif 10 <= val < 20:
      newState = "TENS";     break
    else:
      print " @ %2.1f+" % val,
    val = math_func(val)
  print " >>"
  return (newState, val)
# ... other handlers ...
def math_func(n):
  from math import sin
  return abs(sin(n))*31
if __name__== "__main__":
  m = StateMachine()
  m.add_state("ONES", ones_counter)
  m.add_state("TENS", tens_counter)
  m.add_state("TWENTIES", twenties_counter)
  m.add_state("OUT_OF_RANGE", None, end_state=1)
  m.set_start("ONES")
  m.run(1)

Readers should look at the previous article if they are interested in how the StateMachine class is imported and how its methods work.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.