Ian Kelly <ian.g.ke...@gmail.com>: > On Thu, May 28, 2015 at 9:01 AM, Marko Rauhamaa <ma...@pacujo.net> wrote: >> Anssi Saari <a...@sci.fi>: >> >>> Do you have an example of state pattern using nested classes and >>> python? With a quick look I didn't happen to find one in any >>> language. >> >> Here's an sampling from my mail server: > > I think I would be more inclined to use enums. This has the advantages > of not creating a new set of state classes for every connection > instance and that each state is a singleton instance, allowing things > like "if self.state is SMTPConnectionState.IDLE". It could look > something like this: > > class SMTPConnectionState(Enum): > > class IDLE: > @classmethod > def handle_command(cls, conn, cmd): > # ... > > class SPF_HELO: > @classmethod > def terminate(cls, conn): > # ...
Really, the main expressive choice is whether you use an inner class (and get the advantages of a closure) or an outer class (and get potential performance advantages). When I have coded state machines for C or Java, I have noticed that nothing beats enums and switch statements performance-wise, and expressively, they're not that bad, either. Python doesn't have a switch statement, so the natural thing is to ride on method dispatching (whether via inner or outer classes). However, I must say the exception "idiom" someone mentioned on this forum way back has its lure: try: raise self.state except IDLE: #... except SPF_HELO: #... Marko -- https://mail.python.org/mailman/listinfo/python-list