Skip to content

Commit

Permalink
Python 2/3 compatibility (#284)
Browse files Browse the repository at this point in the history
  • Loading branch information
jdeschenes authored and jwiggins committed Aug 6, 2017
1 parent 73829e9 commit 8cb8dd4
Show file tree
Hide file tree
Showing 136 changed files with 942 additions and 728 deletions.
7 changes: 4 additions & 3 deletions enable/abstract_window.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

# Major library imports
import six.moves as sm
from numpy import dot

# Enthought library imports
Expand Down Expand Up @@ -134,7 +135,7 @@ def _init_gc(self):
gc.clear(self.bgcolor_)
else:
# Fixme: should use clip_to_rects
update_union = reduce(union_bounds, self._update_region)
update_union = sm.reduce(union_bounds, self._update_region)
gc.clip_to_rect(*update_union)
return

Expand Down Expand Up @@ -264,7 +265,7 @@ def _handle_key_event(self, event_type, event):
if history is not None and len(history) > 0:
# Assemble all the transforms
transforms = [c.get_event_transform() for c in history]
total_transform = reduce(dot, transforms[::-1])
total_transform = sm.reduce(dot, transforms[::-1])
key_event.push_transform(total_transform)
elif self.mouse_owner_transform is not None:
key_event.push_transform(self.mouse_owner_transform)
Expand Down Expand Up @@ -313,7 +314,7 @@ def _handle_mouse_event(self, event_name, event, set_focus=False):
if history is not None and len(history) > 0:
# Assemble all the transforms
transforms = [c.get_event_transform() for c in history]
total_transform = reduce(dot, transforms[::-1])
total_transform = sm.reduce(dot, transforms[::-1])
mouse_event.push_transform(total_transform)
elif self.mouse_owner_transform is not None:
mouse_event.push_transform(self.mouse_owner_transform)
Expand Down
11 changes: 6 additions & 5 deletions enable/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from __future__ import generators

# Major library imports
import six.moves as sm

# Enthought library imports
from traits.api import TraitError
Expand Down Expand Up @@ -82,11 +83,11 @@ def str_to_font ( object, name, value ):
face_name = []
for word in value.split():
lword = word.lower()
if font_families.has_key( lword ):
if lword in font_families:
family = font_families[ lword ]
elif font_styles.has_key( lword ):
elif lword in font_styles:
style = font_styles[ lword ]
elif font_weights.has_key( lword ):
elif lword in font_weights:
weight = font_weights[ lword ]
elif lword == 'underline':
underline = 1
Expand All @@ -103,7 +104,7 @@ def str_to_font ( object, name, value ):
underline = underline)
except:
pass
raise TraitError, ( object, name, 'a font descriptor string',
raise TraitError(object, name, 'a font descriptor string',
repr( value ) )

str_to_font.info = ( "a string describing a font (e.g. '12 pt bold italic " +
Expand Down Expand Up @@ -239,7 +240,7 @@ def send_event_to ( components, event_name, event ):
setattr( component, pre_event_name, event )
if event.handled:
return len( components )
for i in xrange( len( components ) - 1, -1, -1 ):
for i in sm.range( len( components ) - 1, -1, -1 ):
setattr( components[i], event_name, event )
if event.handled:
return i
Expand Down
2 changes: 1 addition & 1 deletion enable/canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def remove(self, *components):
component.container = None
self._components.remove(component)
else:
raise RuntimeError, "Unable to remove component from container."
raise RuntimeError("Unable to remove component from container.")

# Check to see if we need to compact.
x, y, x2, y2 = self._bounding_box
Expand Down
17 changes: 10 additions & 7 deletions enable/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,21 +376,24 @@ def __init__(self, **traits):
# may override the bulk default.
padding = traits.pop('padding', None)
padding_traits = {}
for name in traits.keys():
# Use .keys() so we can modify the dict during iteration safely.
if name in ['padding_top', 'padding_bottom', 'padding_left',
'padding_right']:
for name in ['padding_top',
'padding_bottom',
'padding_left',
'padding_right']:
try:
padding_traits[name] = traits.pop(name)
except KeyError:
pass

if traits.has_key("container"):
if "container" in traits:
# After the component is otherwise configured, make sure our
# container gets notified of our being added to it.
container = traits.pop("container")
super(Component,self).__init__(**traits)
super(Component, self).__init__(**traits)
self._set_padding_traits(padding, padding_traits)
container.add(self)
else:
super(Component,self).__init__(**traits)
super(Component, self).__init__(**traits)
self._set_padding_traits(padding, padding_traits)
return

Expand Down
8 changes: 5 additions & 3 deletions enable/constraints_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#------------------------------------------------------------------------------
from collections import deque

import six

# traits imports
from traits.api import Any, Bool, Callable, Dict, Either, Instance, List, \
Property
Expand Down Expand Up @@ -243,7 +245,7 @@ def __components_changed(self, new):
""" Make sure components that are added can be used with constraints.
"""
# Clear the component maps
for key, item in self._component_map.iteritems():
for key, item in six.iteritems(self._component_map):
item.on_trait_change(self._component_size_hint_changed,
'layout_size_hint', remove=True)
self._component_map = {}
Expand Down Expand Up @@ -293,7 +295,7 @@ def _build_layout_table(self):
zero_offset = (0, 0)
offset_table = [zero_offset]
layout_table = []
queue = deque((0, child) for child in self._component_map.itervalues())
queue = deque((0, child) for child in six.itervalues(self._component_map))

# Micro-optimization: pre-fetch bound methods and store globals
# as locals. This method is not on the code path of a resize
Expand Down Expand Up @@ -321,7 +323,7 @@ def _build_layout_table(self):
running_index += 1
if isinst(item, Container_):
if item.transfer_layout_ownership(self):
for child in item._component_map.itervalues():
for child in six.itervalues(item._component_map):
push((running_index, child))

return offset_table, layout_table
Expand Down
4 changes: 2 additions & 2 deletions enable/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def __init__(self, *components, **traits):
Component.__init__(self, **traits)
for component in components:
self.add(component)
if "bounds" in traits.keys() and "auto_size" not in traits.keys():
if "bounds" in traits and "auto_size" not in traits:
self.auto_size = False

if 'intercept_events' in traits:
Expand Down Expand Up @@ -130,7 +130,7 @@ def remove(self, *components):
component.container = None
self._components.remove(component)
else:
raise RuntimeError, "Unable to remove component from container."
raise RuntimeError("Unable to remove component from container.")

# Check to see if we need to compact.
if self.auto_size:
Expand Down
6 changes: 4 additions & 2 deletions enable/coordinate_box.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@

import six

# Enthought library imports
from traits.api import HasTraits, Enum, Instance, Property, Tuple

Expand Down Expand Up @@ -162,7 +164,7 @@ def _get_width(self):

def _set_width(self, val):

if isinstance(val, basestring):
if isinstance(val, six.string_types):
try:
val = float(val)
except:
Expand All @@ -177,7 +179,7 @@ def _get_height(self):
return self.bounds[1]

def _set_height(self, val):
if isinstance(val, basestring):
if isinstance(val, six.string_types):
try:
val = float(val)
except:
Expand Down
2 changes: 1 addition & 1 deletion enable/enable_traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
'dot': array( [ 2.0, 2.0 ] ),
'long dash': array( [ 9.0, 5.0 ] )
}
__line_style_trait_map_keys = __line_style_trait_values.keys()
__line_style_trait_map_keys = list(__line_style_trait_values.keys())
LineStyleEditor = EnumEditor( values=__line_style_trait_map_keys)

def __line_style_trait( value='solid', **metadata ):
Expand Down
3 changes: 2 additions & 1 deletion enable/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
For a list of all the possible event suffixes, see interactor.py.
"""
import six.moves as sm

# Major library imports
from numpy import array, dot
Expand Down Expand Up @@ -103,7 +104,7 @@ def net_transform(self):
if len(self._transform_stack) == 0:
return affine.affine_identity()
else:
return reduce(dot, self._transform_stack[::-1])
return sm.reduce(dot, self._transform_stack[::-1])

def current_pointer_position(self):
"""
Expand Down
2 changes: 1 addition & 1 deletion enable/example_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
if not ETSConfig.toolkit:
for toolkit, toolkit_module in (('wx', 'wx'), ('qt4', 'PyQt4')):
try:
exec "import " + toolkit_module
exec("import " + toolkit_module)
ETSConfig.toolkit = toolkit
break
except ImportError:
Expand Down
4 changes: 3 additions & 1 deletion enable/gadgets/vu_meter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@

import math

import six.moves as sm

from traits.api import Float, Property, List, Str, Range
from enable.api import Component
from kiva.trait_defs.kiva_font_trait import KivaFont
Expand Down Expand Up @@ -37,7 +39,7 @@ class VUMeter(Component):

# Values of the percentage-based ticks; these are drawn and labeled along
# the bottom of the curve axis.
percent_ticks = List(range(0, 101, 20))
percent_ticks = List(list(sm.range(0, 101, 20)))

# Text to write in the middle of the VU Meter.
text = Str("VU")
Expand Down
6 changes: 3 additions & 3 deletions enable/graphics_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class EnableGCMixin(object):
window = None #Instance(AbstractWindow)

def __init__(self, *args, **kwargs):
if kwargs.has_key("window"):
if "window" in kwargs:
self.window = kwargs.pop("window")
super(EnableGCMixin, self).__init__(*args, **kwargs)
return
Expand Down Expand Up @@ -59,8 +59,8 @@ def clear_clip_region(self, color, update_region):
return

def alpha(self, alpha):
raise NotImplementedError, \
"The alpha() method is not compatible with DisplayPDF; use clear() instead."
raise NotImplementedError(
"The alpha() method is not compatible with DisplayPDF; use clear() instead.")

def stretch_draw(self, image, x, y, dx, dy):
"Draws an image 'stretched' to fit a specified area"
Expand Down
5 changes: 3 additions & 2 deletions enable/layout/ab_constrainable.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
#------------------------------------------------------------------------------
from abc import ABCMeta

import six


@six.add_metaclass(ABCMeta)
class ABConstrainable(object):
""" An abstract base class for objects that can be laid out using
layout helpers.
Expand All @@ -14,5 +17,3 @@ class ABConstrainable(object):
which are `LinearSymbolic` instances.
"""
__metaclass__ = ABCMeta

22 changes: 12 additions & 10 deletions enable/layout/layout_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
from collections import defaultdict
from uuid import uuid4

import six
import six.moves as sm

from kiwisolver import Variable, Constraint

from traits.api import HasTraits, Instance, Range
Expand Down Expand Up @@ -84,12 +87,12 @@ def is_spacer(item):
#------------------------------------------------------------------------------
# Deferred Constraints
#------------------------------------------------------------------------------
@six.add_metaclass(ABCMeta)
class DeferredConstraints(object):
""" Abstract base class for objects that will yield lists of
constraints upon request.
"""
__metaclass__ = ABCMeta

def __init__(self):
""" Initialize a DeferredConstraints instance.
Expand All @@ -104,9 +107,9 @@ def __or__(self, other):
strength.
"""
if isinstance(other, (float, int, long)):
if isinstance(other, (float, six.integer_types)):
self.default_string = float(other)
elif isinstance(other, basestring):
elif isinstance(other, six.string_types):
if other not in STRENGTHS:
raise ValueError('Invalid strength %r' % other)
self.default_strength = other
Expand Down Expand Up @@ -653,12 +656,12 @@ def _get_constraints(self, component):
row_vars = []
col_vars = []
cn_id = self.constraints_id
for idx in xrange(num_rows + 1):
for idx in sm.range(num_rows + 1):
name = 'row' + str(idx)
var = Variable('{0}|{1}'.format(cn_id, name))
row_vars.append(var)
constraints.append(var >= 0)
for idx in xrange(num_cols + 1):
for idx in sm.range(num_cols + 1):
name = 'col' + str(idx)
var = Variable('{0}|{1}'.format(cn_id, name))
col_vars.append(var)
Expand Down Expand Up @@ -719,7 +722,7 @@ def _get_constraints(self, component):
for cell in cells:
if cell.start_row == cell.end_row:
row_map[cell.start_row].append(cell.item)
for items in row_map.itervalues():
for items in six.itervalues(row_map):
if len(items) > 1:
helpers.append(AlignmentHelper(self.row_align, *items))

Expand All @@ -731,7 +734,7 @@ def _get_constraints(self, component):
for cell in cells:
if cell.start_col == cell.end_col:
col_map[cell.start_col].append(cell.item)
for items in row_map.itervalues():
for items in six.itervalues(row_map):
if len(items) > 1:
helpers.append(AlignmentHelper(self.col_align, *items))

Expand All @@ -745,14 +748,13 @@ def _get_constraints(self, component):
#------------------------------------------------------------------------------
# Abstract Constraint Factory
#------------------------------------------------------------------------------
@six.add_metaclass(ABCMeta)
class AbstractConstraintFactory(object):
""" An abstract constraint factory class. Subclasses must implement
the 'constraints' method implement which returns a LinearConstraint
instance.
"""
__metaclass__ = ABCMeta

@staticmethod
def validate(items):
""" A validator staticmethod that insures a sequence of items is
Expand Down Expand Up @@ -1072,12 +1074,12 @@ def from_items(cls, items, anchor_name, spacing):
#------------------------------------------------------------------------------
# Spacers
#------------------------------------------------------------------------------
@six.add_metaclass(ABCMeta)
class Spacer(object):
""" An abstract base class for spacers. Subclasses must implement
the 'constrain' method.
"""
__metaclass__ = ABCMeta

def __init__(self, amt, strength=None):
self.amt = max(0, amt)
Expand Down
Loading

0 comments on commit 8cb8dd4

Please sign in to comment.