Skip to content

Commit

Permalink
Merge pull request #22 from tonysyu/feature/python-3-compatibility
Browse files Browse the repository at this point in the history
Add Python 3 compatibility
  • Loading branch information
tonysyu committed Aug 8, 2014
2 parents 97e4032 + e4397c4 commit 1d4b50c
Show file tree
Hide file tree
Showing 27 changed files with 92 additions and 57 deletions.
6 changes: 4 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ language: python
python:
- "2.6"
- "2.7"
- "3.4"
# command to install dependencies
install:
install:
- pip install future
- pip install .
# command to run tests
script:
script:
- python examples/plot_all_styles.py
2 changes: 1 addition & 1 deletion doc/examples/layout/plot_figaspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
aspect_functions = {'mpltools.layout.figaspect': layout.figaspect,
'matplotlib.pyplot.figaspect': plt.figaspect}

for label, figaspect in aspect_functions.items():
for label, figaspect in list(aspect_functions.items()):
figsize = figaspect(0.5)
fig, ax = plt.subplots(figsize=figsize)

Expand Down
18 changes: 11 additions & 7 deletions doc/ext/docscrape.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
"""Extract reference documentation from the NumPy source tree.
"""
from __future__ import print_function
from future import standard_library
standard_library.install_hooks()
from future.builtins import object

import inspect
import textwrap
import re
import pydoc
from StringIO import StringIO
from io import StringIO
from warnings import warn

class Reader(object):
Expand Down Expand Up @@ -113,7 +117,7 @@ def __getitem__(self,key):
return self._parsed_data[key]

def __setitem__(self,key,val):
if not self._parsed_data.has_key(key):
if key not in self._parsed_data:
warn("Unknown section %s" % key)
else:
self._parsed_data[key] = val
Expand Down Expand Up @@ -198,7 +202,7 @@ def _parse_see_also(self, content):

def parse_item_name(text):
"""Match ':role:`name`' or 'name'"""
print text
print(text)
m = self._name_rgx.match(text)
if m:
g = m.groups()
Expand Down Expand Up @@ -370,7 +374,7 @@ def _str_index(self):
idx = self['index']
out = []
out += ['.. index:: %s' % idx.get('default','')]
for section, references in idx.iteritems():
for section, references in idx.items():
if section == 'default':
continue
out += [' :%s: %s' % (section, ', '.join(references))]
Expand Down Expand Up @@ -427,7 +431,7 @@ def __init__(self, func, role='func', doc=None, config={}):
argspec = inspect.formatargspec(*argspec)
argspec = argspec.replace('*','\*')
signature = '%s%s' % (func_name, argspec)
except TypeError, e:
except TypeError as e:
signature = '%s()' % func_name
self['Signature'] = signature

Expand All @@ -449,8 +453,8 @@ def __str__(self):
'meth': 'method'}

if self._role:
if not roles.has_key(self._role):
print "Warning: invalid role %s" % self._role
if self._role not in roles:
print("Warning: invalid role %s" % self._role)
out += '.. %s:: %s\n \n\n' % (roles.get(self._role,''),
func_name)

Expand Down
2 changes: 1 addition & 1 deletion doc/ext/docscrape_sphinx.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def _str_index(self):
return out

out += ['.. index:: %s' % idx.get('default','')]
for section, references in idx.iteritems():
for section, references in idx.items():
if section == 'default':
continue
elif section == 'refguide':
Expand Down
6 changes: 4 additions & 2 deletions doc/ext/numpydoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
.. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard
"""
from future.builtins import str
from future.builtins import object

import re
import pydoc
Expand All @@ -34,7 +36,7 @@ def mangle_docstrings(app, what, name, obj, options, lines,
lines[:] = title_re.sub(u'', u"\n".join(lines)).split(u"\n")
else:
doc = get_doc_object(obj, what, u"\n".join(lines), config=cfg)
lines[:] = unicode(doc).split(u"\n")
lines[:] = str(doc).split(u"\n")

if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \
obj.__name__:
Expand Down Expand Up @@ -115,7 +117,7 @@ def __init__(self, *a, **kw):
self.wrap_mangling_directives()

def wrap_mangling_directives(self):
for name, objtype in self.directive_mangling_map.items():
for name, objtype in list(self.directive_mangling_map.items()):
self.directives[name] = wrap_mangling_directive(
self.directives[name], objtype)

Expand Down
8 changes: 5 additions & 3 deletions doc/tools/apigen.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
project, then adapted for use first in NIPY, then in skimage, and then in
mpltools.
"""
from __future__ import print_function
from future.builtins import object

# Stdlib imports
import os
Expand Down Expand Up @@ -176,7 +178,7 @@ def _parse_module(self, uri):
''' Parse module defined in *uri* '''
filename = self._uri2path(uri)
if filename is None:
print filename, 'erk'
print(filename, 'erk')
# nothing that we could handle here.
return ([],[])
f = open(filename, 'rt')
Expand Down Expand Up @@ -260,7 +262,7 @@ def generate_api_doc(self, uri):
# get the names of all classes and functions
functions, classes = self._parse_module_with_import(uri)
if not len(functions) and not len(classes) and DEBUG:
print 'WARNING: Empty -', uri # dbg
print('WARNING: Empty -', uri) # dbg
return ''

# Make a shorter version of the uri that omits the package name for
Expand Down Expand Up @@ -488,7 +490,7 @@ def write_index(self, outdir, froot='gen', relative_to=None):
relpath = (outdir + os.path.sep).replace(relative_to + os.path.sep, '')
else:
relpath = outdir
print "outdir: ", relpath
print("outdir: ", relpath)
idx = open(path,'wt')
w = idx.write
w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
Expand Down
7 changes: 4 additions & 3 deletions doc/tools/build_modref_templates.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python
"""Script to auto-generate our API docs.
"""
from __future__ import print_function
# stdlib imports
import os, sys

Expand All @@ -13,7 +14,7 @@
#*****************************************************************************

def abort(error):
print '*WARNING* API documentation not generated: %s'%error
print('*WARNING* API documentation not generated: %s'%error)
exit()


Expand Down Expand Up @@ -47,7 +48,7 @@ def assert_source_and_install_match(package):

try:
__import__(package)
except ImportError, e:
except ImportError as e:
abort("Cannot import mpltools")

#assert_source_and_install_match(package)
Expand All @@ -59,4 +60,4 @@ def assert_source_and_install_match(package):
]
docwriter.write_api_docs(outdir)
docwriter.write_index(outdir, 'api', relative_to='source/api')
print '%d files written' % len(docwriter.written_modules)
print('%d files written' % len(docwriter.written_modules))
5 changes: 3 additions & 2 deletions examples/plot_all_styles.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Note that `test_artists_plot` calls `matplotlib.pyplot.tight_layout` so subplot
spacing is not tested for this plot.
"""
from __future__ import print_function

import os
import os.path as pth
Expand Down Expand Up @@ -72,13 +73,13 @@ def test_simple_plot():


# Only show styles defined by package, not by user.
base_styles = style.baselib.keys()
base_styles = list(style.baselib.keys())
for sty in base_styles:
# reset matplotlib defaults before applying new style
plt.rcdefaults()

style.use(sty, use_baselib=True)
print "Plotting tests for '%s' style" % sty
print("Plotting tests for '%s' style" % sty)

fig = test_artists_plot()
fig.savefig(pth.join(PATH, 'test_artists_png', sty + '.png'))
Expand Down
3 changes: 2 additions & 1 deletion mpltools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
Dictionary of package configuration settings.
"""
import _config
from __future__ import absolute_import
from . import _config
config = _config.config

__version__ = '0.2dev' # must be kept consistent with setup.py
1 change: 1 addition & 0 deletions mpltools/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""
from future.builtins import object
import warnings
import matplotlib.animation as _animation

Expand Down
3 changes: 2 additions & 1 deletion mpltools/annotation/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
from _slopemarker import *
from __future__ import absolute_import
from ._slopemarker import *

2 changes: 2 additions & 0 deletions mpltools/annotation/_slopemarker.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import division
from future.builtins import str
import numpy as np
import matplotlib.pyplot as plt

Expand Down
10 changes: 6 additions & 4 deletions mpltools/color.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import division
from future.builtins import zip
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
Expand Down Expand Up @@ -70,12 +72,12 @@ def __init__(self, name, color_data, index=None, **kwargs):

# Adapt color_data to the form expected by LinearSegmentedColormap.
color_data = dict((key, [(x, y, y) for x, y in zip(index, value)])
for key, value in color_data.iteritems())
for key, value in color_data.items())
LinearSegmentedColormap.__init__(self, name, color_data, **kwargs)


def rgb_list_to_colordict(rgb_list):
colors_by_channel = zip(*rgb_list)
colors_by_channel = list(zip(*rgb_list))
channels = ('red', 'green', 'blue', 'alpha')
return dict((color, value)
for color, value in zip(channels, colors_by_channel))
Expand Down Expand Up @@ -107,7 +109,7 @@ def color_mapper(parameter_range, cmap=None, start=None, stop=None):
"""
if cmap is None:
cmap = config['color']['cmap']
if isinstance(cmap, basestring):
if isinstance(cmap, str):
cmap = getattr(plt.cm, cmap)

crange = list(CMAP_RANGE.get(cmap.name, (0, 1)))
Expand Down Expand Up @@ -160,7 +162,7 @@ def colors_from_cmap(length=50, cmap=None, start=None, stop=None):
"""
if cmap is None:
cmap = config['color']['cmap']
if isinstance(cmap, basestring):
if isinstance(cmap, str):
cmap = getattr(plt.cm, cmap)

crange = CMAP_RANGE.get(cmap.name, (0, 1))
Expand Down
3 changes: 2 additions & 1 deletion mpltools/io/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""
Module for Input/Ouput
"""
from core import *
from __future__ import absolute_import
from .core import *
5 changes: 3 additions & 2 deletions mpltools/io/core.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import os
import matplotlib.pyplot as plt

Expand All @@ -23,7 +24,7 @@ def save_all_figs(directory='./', fmt='png', default_name='untitled%i'):
>>> save_all_figs('plots/', fmt=['pdf','png'])
"""
if isinstance(fmt, basestring):
if isinstance(fmt, str):
fmt = [fmt]

for fignum in plt.get_fignums():
Expand All @@ -40,5 +41,5 @@ def save_all_figs(directory='./', fmt='png', default_name='untitled%i'):
for a_fmt in fmt:
savename = '%s.%s' % (savepath, a_fmt)
plt.savefig(savename)
print("Saved '%s'" % savename)
print(("Saved '%s'" % savename))

3 changes: 2 additions & 1 deletion mpltools/layout.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
Expand Down Expand Up @@ -80,7 +81,7 @@ def clear_frame(ax=None):

ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
for spine in ax.spines.itervalues():
for spine in ax.spines.values():
spine.set_visible(False)


Expand Down
5 changes: 3 additions & 2 deletions mpltools/special/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
Module for special-purpose plots.
"""
from hinton import *
from errorfill import *
from __future__ import absolute_import
from .hinton import *
from .errorfill import *
2 changes: 1 addition & 1 deletion mpltools/special/errorfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def errorfill(x, y, yerr=None, xerr=None, color=None, ls=None, lw=None,
alpha_fill *= alpha

if color is None:
color = ax._get_lines.color_cycle.next()
color = next(ax._get_lines.color_cycle)
if ls is None:
ls = plt.rcParams['lines.linestyle']
if lw is None:
Expand Down
4 changes: 3 additions & 1 deletion mpltools/special/hinton.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import division
from future.builtins import zip
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import collections
Expand Down Expand Up @@ -64,7 +66,7 @@ def hinton(inarray, max_value=None, use_default_ticks=True):
neg = np.where(values < 0)
for idx, color in zip([pos, neg], ['white', 'black']):
if len(idx[0]) > 0:
xy = zip(cols[idx], rows[idx])
xy = list(zip(cols[idx], rows[idx]))
circle_areas = np.pi / 2 * np.abs(values[idx])
squares = SquareCollection(sizes=circle_areas,
offsets=xy, transOffset=ax.transData,
Expand Down
Loading

0 comments on commit 1d4b50c

Please sign in to comment.