Skip to content

Commit

Permalink
updates for simultaneous python3 and python2.7 compatibility
Browse files Browse the repository at this point in the history
updates for simultaneous python3 and python2.7 compatibility

fixes to ensure no api changes between 2.7 and 3.x
  • Loading branch information
jbohren committed Mar 18, 2013
1 parent 7dc4857 commit fdf99b1
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 42 deletions.
28 changes: 14 additions & 14 deletions smach/src/smach/concurrence.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def __init__(self,
errors += "\n\tDefault outcome '%s' is unregistered." % str(default_outcome)

# Check if outcome maps only contain outcomes that are registered
for o in outcome_map.keys():
for o in outcome_map:
if o not in outcomes:
errors += "\n\tUnregistered outcome '%s' in and_outcome_map." % str(o)

Expand Down Expand Up @@ -205,13 +205,13 @@ def execute(self, parent_ud = smach.UserData()):

# Spew some info
smach.loginfo("Concurrence starting with userdata: \n\t%s" %
(str(self.userdata.keys())))
(str(list(self.userdata.keys()))))

# Call start callbacks
self.call_start_cbs()

# Create all the threads
for (label, state) in self._states.iteritems():
for (label, state) in ((k,self._states[k]) for k in self._states):
# Initialize child outcomes
self._child_outcomes[label] = None
self._threads[label] = threading.Thread(
Expand Down Expand Up @@ -253,7 +253,7 @@ def execute(self, parent_ud = smach.UserData()):
children_preempts_serviced = True

# Service this preempt if
for (label,state) in self._states.iteritems():
for (label,state) in ((k,self._states[k]) for k in self._states):
if state.preempt_requested():
# Reset the flag
children_preempts_serviced = False
Expand All @@ -273,8 +273,8 @@ def execute(self, parent_ud = smach.UserData()):

# Determine the outcome from the outcome map
smach.logdebug("SMACH Concurrence determining contained state outcomes.")
for (container_outcome, outcomes) in self._outcome_map.iteritems():
if all([self._child_outcomes[label] == outcomes[label] for label in outcomes.keys()]):
for (container_outcome, outcomes) in ((k,self._outcome_map[k]) for k in self._outcome_map):
if all([self._child_outcomes[label] == outcomes[label] for label in outcomes]):
smach.logdebug("Terminating concurrent split with mapped outcome.")
outcome = container_outcome

Expand All @@ -297,7 +297,7 @@ def execute(self, parent_ud = smach.UserData()):
self._child_outcomes = {}

# Call termination callbacks
self.call_termination_cbs(self._states.keys(), outcome)
self.call_termination_cbs(list(self._states.keys()), outcome)

# Copy output keys
self._copy_output_keys(self.userdata, parent_ud)
Expand Down Expand Up @@ -362,7 +362,7 @@ def __getitem__(self,key):
return self._states[key]

def get_initial_states(self):
return self._states.keys()
return list(self._states.keys())

def set_initial_state(self, initial_states, userdata):
if initial_states > 0:
Expand All @@ -373,18 +373,18 @@ def set_initial_state(self, initial_states, userdata):
self.userdata.update(userdata)

def get_active_states(self):
return [label for (label,outcome) in self._child_outcomes.iteritems() if outcome is None]
return [label for (label,outcome) in ((k,self._child_outcomes[k]) in self._child_outcomes) if outcome is None]

def get_internal_edges(self):
int_edges = []
for (container_outcome, outcomes) in self._outcome_map.iteritems():
for (s,o) in outcomes.iteritems():
int_edges.append([o,s,container_outcome])
for (container_outcome, outcomes) in ((k,self._outcome_map[k]) for k in self._outcome_map):
for state_key in outcomes:
int_edges.append([outcomes[state_key],state_key,container_outcome])
return int_edges

def check_consistency(self):
for (co,cso) in self._outcome_map.iteritems():
for state_label,outcome in cso.iteritems():
for (co,cso) in ((k,self._outcome_map[k]) for k in self._outcome_map):
for state_label,outcome in ((k,cso[k]) for k in cso):
if outcome not in self._states[state_label].get_registered_outcomes():
raise smach.InvalidTransitionError(
'Outcome map in SMACH Concurrence references a state outcome that does not exist. Requested state outcome: \'%s\', but state \'%s\' only has outcomes %s' %
Expand Down
2 changes: 1 addition & 1 deletion smach/src/smach/iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def execute(self, parent_ud):

while not smach.is_shutdown():
try:
item = it.next()
item = next(it)
except:
outcome = self._exhausted_outcome
break
Expand Down
24 changes: 12 additions & 12 deletions smach/src/smach/state_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def add(label, state, transitions = None, remapping = None):
registered_outcomes = state.get_registered_outcomes()

# Get a list of the unbound transitions
missing_transitions = dict([(o,None) for o in registered_outcomes if o not in transitions.keys()])
missing_transitions = dict([(o,None) for o in registered_outcomes if o not in transitions])
transitions.update(missing_transitions)
smach.logdebug("State '%s' is missing transitions: %s" % (label,str(missing_transitions)))

Expand Down Expand Up @@ -206,9 +206,9 @@ def _update_once(self):
last_state_label = self._current_label

# Make sure the state exists
if self._current_label not in self._states.keys():
if self._current_label not in self._states:
raise smach.InvalidStateError("State '%s' does not exist. Available states are: %s" %
(str(self._current_label),str(self._states.keys())))
(str(self._current_label),str(list(self._states.keys()))))

# Check if a preempt was requested before or while the last state was running
if self.preempt_requested():
Expand Down Expand Up @@ -332,7 +332,7 @@ def execute(self, parent_ud = smach.UserData()):

# Spew some info
smach.loginfo("State machine starting in initial state '%s' with userdata: \n\t%s" %
(self._current_label,str(self.userdata.keys())))
(self._current_label,str(list(self.userdata.keys()))))


# Call start callbacks
Expand Down Expand Up @@ -391,7 +391,7 @@ def get_children(self):

def __getitem__(self,key):
if key not in self._states:
smach.logerr("Attempting to get state '%s' from StateMachine container. The only available states are: %s" % (key, self._states.keys()))
smach.logerr("Attempting to get state '%s' from StateMachine container. The only available states are: %s" % (key, str(list(self._states.keys()))))
raise KeyError()
return self._states[key]

Expand All @@ -415,8 +415,8 @@ def get_initial_states(self):

def get_internal_edges(self):
int_edges = []
for (from_label,transitions) in self._transitions.iteritems():
for (outcome,to_label) in transitions.iteritems():
for (from_label,transitions) in ((k,self._transitions[k]) for k in self._transitions):
for (outcome,to_label) in ((k,transitions[k]) for k in transitions):
int_edges.append([outcome,from_label,to_label])
return int_edges

Expand All @@ -431,7 +431,7 @@ def check_state_spec(self, label, state, transitions):
"""
# Make sure all transitions are from registered outcomes of this state
registered_outcomes = state.get_registered_outcomes()
for outcome in transitions.keys():
for outcome in transitions:
if outcome not in registered_outcomes:
raise smach.InvalidTransitionError("Specified outcome '"+outcome+"' on state '"+label+"', which only has available registered outcomes: "+str(registered_outcomes))

Expand All @@ -442,7 +442,7 @@ def check_consistency(self):
with relevant information.
"""
# Construct a set of available states
available_states = set(self._states.keys()+list(self.get_registered_outcomes()))
available_states = set(list(self._states.keys())+list(self.get_registered_outcomes()))

# Grab the registered outcomes for the state machine
registered_sm_outcomes = self.get_registered_outcomes()
Expand All @@ -453,13 +453,13 @@ def check_consistency(self):
# Check initial_state_label
if self._initial_state_label is None:
errors = errors + "\n\tNo initial state set."
elif self._initial_state_label not in self._states.keys():
elif self._initial_state_label not in self._states:
errors = errors + "\n\tInitial state label: '"+str(self._initial_state_label)+"' is not in the state machine."

# Generate state specifications
state_specs = [
(label, self._states[label], self._transitions[label])
for label in self._states.keys()]
for label in self._states]
# Iterate over all states
for label,state,transitions in state_specs:
# Check that all potential outcomes are registered in this state
Expand All @@ -475,7 +475,7 @@ def check_consistency(self):
+"' references unknown states: "+str(list(missing_states)))

# Check terminal outcomes for this state
terminal_outcomes = set([o for o,s in transitions.iteritems() if ((s is None) or (s == ''))])
terminal_outcomes = set([o for o,s in ((k,transitions[k]) for k in transitions) if ((s is None) or (s == ''))])
# Terminal outcomes should be in the registered outcomes of this state machine
missing_outcomes = terminal_outcomes.difference(registered_sm_outcomes)
# Check number of missing outcomes
Expand Down
12 changes: 6 additions & 6 deletions smach/src/smach/user_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def update(self, other_userdata):

def extract(self, keys, remapping):
ud = UserData()
reverse_remapping = dict([(v,k) for (k,v) in remapping.iteritems()])
reverse_remapping = dict([(remapping[k],k) for k in remapping])
if len(reverse_remapping) != len(remapping):
smach.logerr("SMACH userdata remapping is not one-to-one: " + str(remapping))
for k in keys:
Expand All @@ -46,7 +46,7 @@ def __setitem__(self, key, item):
self._data[key] = item

def keys(self):
return self._data.keys()
return list(self._data.keys())

def __contains__(self,key):
return key in self._data
Expand All @@ -62,15 +62,15 @@ def __getattr__(self, name):
with self._locks[name]:
temp = self._data[name]
except:
smach.logerr("Userdata key '%s' not available. Available keys are: %s" % (name, self._data.keys()))
smach.logerr("Userdata key '%s' not available. Available keys are: %s" % (name, str(list(self._data.keys()))))
raise KeyError()

return temp

def __setattr__(self, name, value):
"""Overload setattr to be thread safe."""
# If we're still in __init__ don't do anything special
if name[0] == '_' or not self.__dict__.has_key('_UserData__initialized'):
if name[0] == '_' or '_UserData__initialized' not in self.__dict__:
return object.__setattr__(self, name, value)

if not name in self._locks.keys():
Expand Down Expand Up @@ -111,7 +111,7 @@ def __getitem__(self, name):
return get_const(attr)

def __setattr__(self, name, value):
if not self.__dict__.has_key('_const__initialized'):
if '_const__initialized' not in self.__dict__:
return object.__setattr__(self, name, value)
smach.logerr("Attempting to set '%s' but this member is read-only." % name)
raise TypeError()
Expand Down Expand Up @@ -170,7 +170,7 @@ def __getattr__(self, name):
return getattr(self._ud, self._remap(name))

def __setattr__(self, name, value):
if name[0] == '_' or not self.__dict__.has_key('_Remapper__initialized'):
if name[0] == '_' or '_Remapper__initialized' not in self.__dict__:
return object.__setattr__(self, name, value)
if name not in self._output:
smach.logerr("Writing to SMACH userdata key '%s' but the only keys that were declared as output from this state were: %s." % (name, self._output))
Expand Down
4 changes: 2 additions & 2 deletions smach_ros/src/smach_ros/action_server_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def execute_cb(self, goal):
self.userdata[self._goal_key] = goal

# Store mapped goal slots in local userdata
for from_key,to_key in self._goal_slots_map.iteritems():
for from_key,to_key in ((k,self._goal_slots_map[k]) for k in self._goal_slots_map):
self.userdata[to_key] = getattr(goal,from_key)

# Run the state machine (this blocks)
Expand All @@ -232,7 +232,7 @@ def execute_cb(self, goal):
result = self.userdata[self._result_key]

# Store mapped slots in result
for from_key,to_key in self._result_slots_map.iteritems():
for from_key,to_key in ((k,self._result_slots_map) for k in self._result_slots_map):

This comment has been minimized.

Copy link
@jbohren

jbohren Jan 7, 2014

Author Member

Should be self._result_slots_map[k]

setattr(result,from_key,self.userdata[to_key])

# If any of the result members have been returned to the parent ud
Expand Down
9 changes: 4 additions & 5 deletions smach_ros/src/smach_ros/introspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,7 @@ def local_cb(msg, msg_response):
local_data._data = pickle.loads(msg_response.local_data)
ud_match = all([\
(key in local_data and local_data._data[key] == initial_userdata._data[key])\
for (key,value)\
in initial_userdata._data.iteritems()])
for key in initial_userdata._data])

rospy.logdebug("STATE MATCH: "+str(state_match)+", UD_MATCH: "+str(ud_match))

Expand Down Expand Up @@ -178,7 +177,7 @@ def _structure_pub_loop(self):

def _publish_structure(self, info_str = ''):
path = self._path
children = self._container.get_children().keys()
children = list(self._container.get_children().keys())

internal_outcomes = []
outcomes_from = []
Expand Down Expand Up @@ -209,7 +208,7 @@ def _publish_status(self, info_str = ''):
# Construct messages
with self._status_pub_lock:
path = self._path
children = self._container.get_children().keys()
children = list(self._container.get_children().keys())

#print str(structure_msg)
# Construct status message
Expand Down Expand Up @@ -287,7 +286,7 @@ def construct(self, server_name, state, path):
path = ''

# Get a list of children that are also containers
for (label, child) in state.get_children().iteritems():
for (label, child) in state.get_children().items():
# If this is also a container, recursei into it
if isinstance(child, smach.container.Container):
self.construct(server_name, child, path+'/'+label)
Expand Down
4 changes: 2 additions & 2 deletions smach_ros/src/smach_ros/service_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,15 +135,15 @@ def execute(self, ud):
if self._request_key in ud:
self._request = ud[self._request_key]
else:
rospy.logerr("Requested request key '%s' not in userdata struture. Available keys are: %s" % (self._request_key, str(ud.keys())))
rospy.logerr("Requested request key '%s' not in userdata struture. Available keys are: %s" % (self._request_key, str(list(ud.keys()))))
return 'aborted'

# Write request fields from userdata if set
for key in self._request_slots:
if key in ud:
setattr(self._request,key,ud[key])
else:
rospy.logerr("Requested request slot key '%s' is not in userdata strcture. Available keys are: %s" % (key, str(ud.keys())))
rospy.logerr("Requested request slot key '%s' is not in userdata strcture. Available keys are: %s" % (key, str(list(ud.keys()))))
return 'aborted'

# Call user-supplied callback, if set, to get a request
Expand Down

0 comments on commit fdf99b1

Please sign in to comment.