Ian George avatar Ian George committed 600f9cb

Making the code a little more pep8 compliant

Comments (0)

Files changed (4)

statemachine/fields.py

-from copy import deepcopy
 from django.db import models
-from fsm import State, FSM
+from fsm import FSM
 from django.forms.forms import pretty_name
 
 DEFAULT_STATE = "start"
 
+
 class FSM_StateField(models.Field):
     """
     Django models.Field subclass used to store a representation of
     def __init__(self, machine, default_choices_all=False, *args, **kwargs):
         """
         machine: instance of fsm.FSM
-        default_choices_all: 
+        default_choices_all:
 
         * If True sets choices to the results of all_state_choices
         * If False set choices to the results of exit_state_choices
 
         self.__machine_class = machine
         self.default_choices_all = default_choices_all
-        defaults = {'max_length': 50, 'default' : DEFAULT_STATE}
+        defaults = {'max_length': 50, 'default': DEFAULT_STATE}
         defaults.update(kwargs)
         super(FSM_StateField, self).__init__(self, **defaults)
 
         return name
 
     def all_state_choices(self):
+        """Returns a choices list of all the available states, useful
+        for the admin interface.
+
         """
-        Returns a choices list of all the available states, useful for the admin interface.
-        """
-        return [(name, pretty_name(name)) for name, state in self.machine.states.items()]
+        return [(name, pretty_name(name))
+                for name, state in self.machine.states.items()]
 
     def exit_state_choices(self):
-        """
-        Returns a choices list of only the available exit states from the current state.
+        """Returns a choices list of only the available exit states
+        from the current state.
+
         """
         state_choices = []
         if self.machine.state:
-            state_choices.append((self.machine.state,self.machine.state))
-            state_choices.extend([(name,name) for name in self.machine.state.exit_states])
+            state_choices.append((self.machine.state, self.machine.state))
+            state_choices.extend([(name, name)
+                                  for name in self.machine.state.exit_states])
 
         return state_choices
 
-try:
-    import south
-    south_available = True
-except ImportError:
-    south_available = False
-
-if south_available:
-    from south.modelsinspector import add_introspection_rules
-    default_machine = FSM()
-    add_introspection_rules([
-        (
-            [FSM_StateField], # Class(es) these apply to
-            [],         # Positional arguments (not used)
-            {           # Keyword argument
-                "machine": ["machine", {"default": default_machine}],
-                },
-            ),
-        ], ["^statemachine\.fields\.FSM_StateField"])
+from south.modelsinspector import add_introspection_rules
+default_machine = FSM()
+add_introspection_rules([
+    (
+        [FSM_StateField],  # Class(es) these apply to
+        [],         # Positional arguments (not used)
+        {"machine": ["machine", {"default": default_machine}], },
+    ),
+], ["^statemachine\.fields\.FSM_StateField"])

statemachine/fsm.py

 from copy import deepcopy
 from django.conf import settings
-from django.forms.forms import pretty_name
 from django.utils.datastructures import SortedDict
 
 # Django settings
 except AttributeError:
     STATE_MACHINE_DEFAULT = "start"
 
+
 #Some Exceptions
-class FSM_Exception(Exception): 
-    """ 
+class FSM_Exception(Exception):
+    """
     Base exception for the FSM implementation.
     """
     pass
-class FSM_TransitionNotAllowed(FSM_Exception): 
-    """
-    Raised when a state change is prevented, generally when an the attempted change isn't in the exit_states list.
+
+
+class FSM_TransitionNotAllowed(FSM_Exception):
+    """Raised when a state change is prevented, generally when an the
+    attempted change isn't in the exit_states list.
+
     """
     pass
+
+
 class FSM_StateDoesNotExist(FSM_Exception):
     """
     Raised when a change to a non-existent state is requested.
     """
-class FSM_NotAllowed(FSM_Exception): pass
+
+
+class FSM_NotAllowed(FSM_Exception):
+    pass
+
 
 class FSM_VerificationError(FSM_Exception):
-    """
-    Verification error, raised when FSM.verify() fails, should contain a list of failed states.
+    """Verification error, raised when FSM.verify() fails, should
+    contain a list of failed states.
+
     """
     def __init__(self, message, states=None):
+        super(FSM_VerificationError, self).__init__()
         self.message = message
         self.states = states
 
         else:
             return self.message
 
+
 def get_declared_states(bases, attrs, with_base_states=True):
     """
     *Taken pretty much verbatim from django.forms*
     used.
 
     """
-    states = [(state_name, attrs.pop(state_name)) for state_name, obj in attrs.items() if isinstance(obj, State)]
+    states = [(state_name, attrs.pop(state_name))
+              for state_name, obj in attrs.items()
+              if isinstance(obj, State)]
     for name, state in states:
         state.name = name
     states.sort(key=lambda x: x[1].creation_counter)
 
-    # If this class is subclassing another StateMachine, add that StateMachine's states.
-    # Note that we loop over the bases in *reverse*. This is necessary in
-    # order to preserve the correct order of statess.
+    # If this class is subclassing another StateMachine, add that
+    # StateMachine's states.  Note that we loop over the bases in
+    # *reverse*. This is necessary in order to preserve the correct
+    # order of statess.
     if with_base_states:
         for base in bases[::-1]:
             if hasattr(base, 'base_states'):
 
     return SortedDict(states)
 
+
 class DeclarativeStatesMetaclass(type):
     """
     *Taken pretty much verbatim from django.forms*
     """
     def __new__(cls, name, bases, attrs):
         attrs['base_states'] = get_declared_states(bases, attrs)
-        new_class = super(DeclarativeStatesMetaclass,
-                     cls).__new__(cls, name, bases, attrs)
+        new_class = super(
+            DeclarativeStatesMetaclass,
+            cls
+        ).__new__(cls, name, bases, attrs)
         return new_class
 
+
 class State(object):
     """
-    Represents each individual state of the machine. 
+    Represents each individual state of the machine.
 
-    exit_states: 
+    exit_states:
         a list of strings representing allowed transitions from this state
 
-    entry_action(exited_state, model): 
-        a function to run on entry into the state. 
+    entry_action(exited_state, model):
+        a function to run on entry into the state.
 
-    exit action(target_state, model): 
+    exit action(target_state, model):
         a function to run on exit from the state, must return
         FSM_TransitionNotAllowed if conditions for the transition are not
-        met. 
+        met.
 
     """
     name = ""
     exit_action = None
     creation_counter = 0
 
-    def __init__(self, label=None, exits_to=None, entry_action=None, exit_action=None, **kwargs):
+    def __init__(self, label=None, exits_to=None,
+                 entry_action=None, exit_action=None, **kwargs):
         self.label = label
         self.exit_states = exits_to or []
         self.entry_action = entry_action
         self.exit_action = exit_action
         for k, v in kwargs.items():
             setattr(self, k, v)
-            
 
     def __unicode__(self):
         if self.label:
         return self.name
 
     def exit(self, target_state, *args, **kwargs):
-        """ 
-        Checks states and exits if possible, if not possible it raises FSM_TransitionNotAllowed 
+        """Checks states and exits if possible, if not possible it
+        raises FSM_TransitionNotAllowed
+
         """
         if self.exit_action:
             self.exit_action(target_state, *args, **kwargs)
         """
         if self.entry_action:
             return self.entry_action(exited_state, *args, **kwargs)
-        
+
+
 class FSM(object):
     """
     Simple FSM implementation. Takes a declarative approach to
     defining states, and their interactions and capabilities.
 
-    
     """
     __metaclass__ = DeclarativeStatesMetaclass
 
             return self.states[self.__state]
 
     def setstate(self, value):
-        raise FSM_NotAllowed("State is read only, please use change() to change state")
+        raise FSM_NotAllowed("State is read only, use change() instead.")
     state = property(getstate, setstate)
 
     def set_initial_state(self, state):
             self.__state = self.states.keys()[0]
 
     def available_states(self):
-        """
-        Returns a list containing the available exit states from the current state
+        """Returns a list containing the available exit states from
+        the current state
+
         """
         return [self.states[s] for s in self.state.exit_states]
-        
+
     def verify(self):
         """
         Check that all the states named in exit_states exist.

statemachine/models.py

-from copy import deepcopy
-
 from django.db import models
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.contenttypes import generic
 from django.contrib.auth.models import User
-from django.utils.functional import lazy
-from django.conf import settings
 
-from fsm import FSM_Exception, FSM
-from fields import FSM_StateField
 
 ##################################################
 # Models
     #optional notes
     notes = models.CharField(max_length=500, null=True, blank=True)
 
+
 class StateMachineWithHistory(models.Model):
     """
     Abstract base class for a model requiring a state machine field
     Class needs a FSM_StateField called status
     """
-    state_history = generic.GenericRelation(StateMachineHistory, content_type_field='machine_type', object_id_field='machine_id')
+    state_history = generic.GenericRelation(StateMachineHistory,
+                                            content_type_field='machine_type',
+                                            object_id_field='machine_id')
 
     def __init__(self, *args, **kwargs):
         super(StateMachineWithHistory, self).__init__(*args, **kwargs)
             s.to_state = self.status.state
             s.user = user
             s.notes = notes
-            s.save() 
-
+            s.save()
 
     class Meta:
         abstract = True

statemachine/tests.py

 from django.db import models
 from django.test import TestCase
-from django.test.client import Client
 
-from models import StateMachineWithHistory
-from fields import FSM_StateField
-import fsm
+from statemachine.models import StateMachineWithHistory
+from statemachine.fields import FSM_StateField
+from statemachine import fsm
+
 
 class TestMachine(fsm.FSM):
     start = fsm.State(exits_to=['step1a', 'step1b', 'step1c'])
-    step1a = fsm.State(exits_to=['step2',])
-    step1b = fsm.State(exits_to=['step2',])
-    step1c = fsm.State(exits_to=['step2',])
-    step2 = fsm.State(exits_to=['end', 'step3'])
-    step3 = fsm.State(exits_to=['end',])
+    step1a = fsm.State(exits_to=['step2', ])
+    step1b = fsm.State(exits_to=['step2', ])
+    step1c = fsm.State(exits_to=['step2', ])
+    step2 = fsm.State(exits_to=['end', 'step3', ])
+    step3 = fsm.State(exits_to=['end', ])
     end = fsm.State()
 
+
 class TestStateMachine(StateMachineWithHistory):
     status = FSM_StateField(TestMachine)
     field1 = models.IntegerField()
     field2 = models.CharField(max_length=25)
 
+
 class StateMachineTests(TestCase):
     def test_verify(self):
         """ Should raise a FSM_VerificationError """
         testmachine = TestStateMachine(field1=100, field2="LALALALALA")
-        testmachine.status.states["random"] = (fsm.State("random", ["doesntexist", "alsodoesnexist"]))
+        testmachine.status.states["random"] = (fsm.State("random", [
+            "doesntexist", "alsodoesnexist"]))
         with self.assertRaises(fsm.FSM_VerificationError):
             testmachine.status.verify()
 
     def test_save_fail(self):
-        """Should raise a StateMachineNotAllowed, messing with the state outside of the machine."""
+        """Should raise a StateMachineNotAllowed, messing with the
+        state outside of the machine.
+
+        """
         testmachine = TestStateMachine(field1=100, field2="LALALALALA")
         testmachine.save(None)
         with self.assertRaises(fsm.FSM_NotAllowed):
-            testmachine.status.state = "Testing"    
+            testmachine.status.state = "Testing"
             testmachine.save(None)
 
     def test_full_transition(self):
         testmachine.save(None)
         #check we are starting at "start"
         self.assertEqual(testmachine.status.state.name, "start")
-        
+
         with self.assertRaises(fsm.FSM_TransitionNotAllowed):
             testmachine.status.change("step3")
 
         testmachine = TestStateMachine.objects.get(pk=fsm_id)
 
         self.assertEqual(testmachine.state_history.count(), 3)
-        self.assertEqual(testmachine.state_history.all()[1].notes, "Some notes!")
+        self.assertEqual(testmachine.state_history.all()[1].notes,
+                         "Some notes!")
 
     def test_entry_action(self):
         """ Tests an action set to run on entry to a state """
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.