diff --git a/doc/sphinxext/numpy_ext/docscrape_sphinx.py b/doc/sphinxext/numpy_ext/docscrape_sphinx.py index e44e770ef8..0f38188477 100644 --- a/doc/sphinxext/numpy_ext/docscrape_sphinx.py +++ b/doc/sphinxext/numpy_ext/docscrape_sphinx.py @@ -1,6 +1,7 @@ import re, inspect, textwrap, pydoc import sphinx from docscrape import NumpyDocString, FunctionDoc, ClassDoc +from nipype.external import six class SphinxDocString(NumpyDocString): def __init__(self, docstring, config={}): @@ -140,7 +141,7 @@ def _str_references(self): out = [] if self['References']: out += self._str_header('References') - if isinstance(self['References'], str): + if isinstance(self['References'], six.string_types): self['References'] = [self['References']] out.extend(self['References']) out += [''] diff --git a/examples/fmri_ants_openfmri.py b/examples/fmri_ants_openfmri.py index 8af4603a1b..eab0ebe77b 100755 --- a/examples/fmri_ants_openfmri.py +++ b/examples/fmri_ants_openfmri.py @@ -14,6 +14,8 @@ from nipype import config config.enable_provenance() +from nipype.external import six + from glob import glob import os @@ -443,7 +445,7 @@ def get_contrasts(contrast_file, task_id, conds): def check_behav_list(behav): out_behav = [] - if isinstance(behav, basestring): + if isinstance(behav, six.string_types): behav = [behav] for val in behav: if not isinstance(val, list): diff --git a/examples/fmri_openfmri.py b/examples/fmri_openfmri.py index 3f7ee4e424..174e55b96b 100755 --- a/examples/fmri_openfmri.py +++ b/examples/fmri_openfmri.py @@ -14,6 +14,7 @@ from nipype import config config.enable_provenance() +from nipype.external import six from glob import glob import os @@ -237,7 +238,7 @@ def get_contrasts(contrast_file, task_id, conds): def check_behav_list(behav): out_behav = [] - if isinstance(behav, basestring): + if isinstance(behav, six.string_types): behav = [behav] for val in behav: if not isinstance(val, list): diff --git a/nipype/algorithms/modelgen.py b/nipype/algorithms/modelgen.py index e763cc7538..19a2d5887f 100644 --- a/nipype/algorithms/modelgen.py +++ b/nipype/algorithms/modelgen.py @@ -30,6 +30,7 @@ isdefined) from nipype.utils.filemanip import filename_to_list from .. import config, logging +from nipype.external import six iflogger = logging.getLogger('interface') def gcd(a, b): @@ -422,7 +423,7 @@ def _concatenate_info(self, infolist): for i, f in enumerate(self.inputs.functional_runs): if isinstance(f, list): numscans = len(f) - elif isinstance(f, str): + elif isinstance(f, six.string_types): img = load(f) numscans = img.get_shape()[3] else: diff --git a/nipype/algorithms/rapidart.py b/nipype/algorithms/rapidart.py index 7b97352fdb..f304136d35 100644 --- a/nipype/algorithms/rapidart.py +++ b/nipype/algorithms/rapidart.py @@ -26,6 +26,7 @@ import numpy as np from scipy import signal import scipy.io as sio +from nipype.external import six from ..interfaces.base import (BaseInterface, traits, InputMultiPath, OutputMultiPath, TraitedSpec, File, @@ -279,7 +280,7 @@ def _get_output_filenames(self, motionfile, output_dir): output_dir: string output directory in which the files will be generated """ - if isinstance(motionfile, str): + if isinstance(motionfile, six.string_types): infile = motionfile elif isinstance(motionfile, list): infile = motionfile[0] @@ -350,7 +351,7 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None): cwd = os.getcwd() # read in functional image - if isinstance(imgfile, str): + if isinstance(imgfile, six.string_types): nim = load(imgfile) elif isinstance(imgfile, list): if len(imgfile) == 1: diff --git a/nipype/external/provcopy.py b/nipype/external/provcopy.py index 2f4900d1a9..59686f3b9b 100644 --- a/nipype/external/provcopy.py +++ b/nipype/external/provcopy.py @@ -17,6 +17,7 @@ import dateutil.parser import collections from collections import defaultdict +import six try: from rdflib.term import URIRef, BNode @@ -187,7 +188,7 @@ def _parse_xsd_dateTime(s): def _ensure_datetime(time): - if isinstance(time, basestring): + if isinstance(time, six.string_types): return _parse_xsd_dateTime(time) else: return time @@ -232,12 +233,12 @@ def parse_xsd_types(value, datatype): def _ensure_multiline_string_triple_quoted(s): - format_str = u'"""%s"""' if isinstance(s, basestring) and '\n' in s else u'"%s"' + format_str = u'"""%s"""' if isinstance(s, six.string_types) and '\n' in s else u'"%s"' return format_str % s def encoding_PROV_N_value(value): - if isinstance(value, basestring): + if isinstance(value, six.string_types): return _ensure_multiline_string_triple_quoted(value) elif isinstance(value, datetime.datetime): return value.isoformat() @@ -536,7 +537,7 @@ def _auto_literal_conversion(self, literal): if isinstance(literal, URIRef): return literal - if isinstance(literal, basestring): + if isinstance(literal, six.string_types): return unicode(literal) if isinstance(literal, Literal) and literal.has_no_langtag(): @@ -1568,7 +1569,7 @@ def _decode_JSON_container(self, jc): key=lambda tuple_rec: tuple_rec[0]) record_map = {} - _parse_attr_value = lambda value: record_map[value] if (isinstance(value, basestring) and value in record_map) else self._decode_json_representation(value) + _parse_attr_value = lambda value: record_map[value] if (isinstance(value, six.string_types) and value in record_map) else self._decode_json_representation(value) # Create all the records before setting their attributes for (record_type, identifier, content) in records: if record_type == PROV_REC_BUNDLE: diff --git a/nipype/external/six.py b/nipype/external/six.py new file mode 100644 index 0000000000..21b0e8032f --- /dev/null +++ b/nipype/external/six.py @@ -0,0 +1,762 @@ +"""Utilities for writing code that runs on Python 2 and 3""" + +# Copyright (c) 2010-2014 Benjamin Peterson +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import absolute_import + +import functools +import operator +import sys +import types + +__author__ = "Benjamin Peterson " +__version__ = "1.8.0" + + +# Useful for very coarse version differentiation. +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 + +if PY3: + string_types = str, + integer_types = int, + class_types = type, + text_type = str + binary_type = bytes + + MAXSIZE = sys.maxsize +else: + string_types = basestring, + integer_types = (int, long) + class_types = (type, types.ClassType) + text_type = unicode + binary_type = str + + if sys.platform.startswith("java"): + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + del X + + +def _add_doc(func, doc): + """Add documentation to a function.""" + func.__doc__ = doc + + +def _import_module(name): + """Import module, returning the module after the last dot.""" + __import__(name) + return sys.modules[name] + + +class _LazyDescr(object): + + def __init__(self, name): + self.name = name + + def __get__(self, obj, tp): + result = self._resolve() + setattr(obj, self.name, result) # Invokes __set__. + # This is a bit ugly, but it avoids running this again. + delattr(obj.__class__, self.name) + return result + + +class MovedModule(_LazyDescr): + + def __init__(self, name, old, new=None): + super(MovedModule, self).__init__(name) + if PY3: + if new is None: + new = name + self.mod = new + else: + self.mod = old + + def _resolve(self): + return _import_module(self.mod) + + def __getattr__(self, attr): + _module = self._resolve() + value = getattr(_module, attr) + setattr(self, attr, value) + return value + + +class _LazyModule(types.ModuleType): + + def __init__(self, name): + super(_LazyModule, self).__init__(name) + self.__doc__ = self.__class__.__doc__ + + def __dir__(self): + attrs = ["__doc__", "__name__"] + attrs += [attr.name for attr in self._moved_attributes] + return attrs + + # Subclasses should override this + _moved_attributes = [] + + +class MovedAttribute(_LazyDescr): + + def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): + super(MovedAttribute, self).__init__(name) + if PY3: + if new_mod is None: + new_mod = name + self.mod = new_mod + if new_attr is None: + if old_attr is None: + new_attr = name + else: + new_attr = old_attr + self.attr = new_attr + else: + self.mod = old_mod + if old_attr is None: + old_attr = name + self.attr = old_attr + + def _resolve(self): + module = _import_module(self.mod) + return getattr(module, self.attr) + + +class _SixMetaPathImporter(object): + """ + A meta path importer to import six.moves and its submodules. + + This class implements a PEP302 finder and loader. It should be compatible + with Python 2.5 and all existing versions of Python3 + """ + def __init__(self, six_module_name): + self.name = six_module_name + self.known_modules = {} + + def _add_module(self, mod, *fullnames): + for fullname in fullnames: + self.known_modules[self.name + "." + fullname] = mod + + def _get_module(self, fullname): + return self.known_modules[self.name + "." + fullname] + + def find_module(self, fullname, path=None): + if fullname in self.known_modules: + return self + return None + + def __get_module(self, fullname): + try: + return self.known_modules[fullname] + except KeyError: + raise ImportError("This loader does not know module " + fullname) + + def load_module(self, fullname): + try: + # in case of a reload + return sys.modules[fullname] + except KeyError: + pass + mod = self.__get_module(fullname) + if isinstance(mod, MovedModule): + mod = mod._resolve() + else: + mod.__loader__ = self + sys.modules[fullname] = mod + return mod + + def is_package(self, fullname): + """ + Return true, if the named module is a package. + + We need this method to get correct spec objects with + Python 3.4 (see PEP451) + """ + return hasattr(self.__get_module(fullname), "__path__") + + def get_code(self, fullname): + """Return None + + Required, if is_package is implemented""" + self.__get_module(fullname) # eventually raises ImportError + return None + get_source = get_code # same as get_code + +_importer = _SixMetaPathImporter(__name__) + + +class _MovedItems(_LazyModule): + """Lazy loading of moved objects""" + __path__ = [] # mark as package + + +_moved_attributes = [ + MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), + MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), + MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), + MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("intern", "__builtin__", "sys"), + MovedAttribute("map", "itertools", "builtins", "imap", "map"), + MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("reload_module", "__builtin__", "imp", "reload"), + MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), + MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserDict", "UserDict", "collections"), + MovedAttribute("UserList", "UserList", "collections"), + MovedAttribute("UserString", "UserString", "collections"), + MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), + MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), + + MovedModule("builtins", "__builtin__"), + MovedModule("configparser", "ConfigParser"), + MovedModule("copyreg", "copy_reg"), + MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), + MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), + MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), + MovedModule("http_cookies", "Cookie", "http.cookies"), + MovedModule("html_entities", "htmlentitydefs", "html.entities"), + MovedModule("html_parser", "HTMLParser", "html.parser"), + MovedModule("http_client", "httplib", "http.client"), + MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), + MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), + MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), + MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), + MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), + MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), + MovedModule("cPickle", "cPickle", "pickle"), + MovedModule("queue", "Queue"), + MovedModule("reprlib", "repr"), + MovedModule("socketserver", "SocketServer"), + MovedModule("_thread", "thread", "_thread"), + MovedModule("tkinter", "Tkinter"), + MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), + MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), + MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), + MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), + MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), + MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), + MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), + MovedModule("tkinter_colorchooser", "tkColorChooser", + "tkinter.colorchooser"), + MovedModule("tkinter_commondialog", "tkCommonDialog", + "tkinter.commondialog"), + MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), + MovedModule("tkinter_font", "tkFont", "tkinter.font"), + MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), + MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", + "tkinter.simpledialog"), + MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), + MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), + MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), + MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), + MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), + MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), + MovedModule("winreg", "_winreg"), +] +for attr in _moved_attributes: + setattr(_MovedItems, attr.name, attr) + if isinstance(attr, MovedModule): + _importer._add_module(attr, "moves." + attr.name) +del attr + +_MovedItems._moved_attributes = _moved_attributes + +moves = _MovedItems(__name__ + ".moves") +_importer._add_module(moves, "moves") + + +class Module_six_moves_urllib_parse(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_parse""" + + +_urllib_parse_moved_attributes = [ + MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("SplitResult", "urlparse", "urllib.parse"), + MovedAttribute("parse_qs", "urlparse", "urllib.parse"), + MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), + MovedAttribute("urldefrag", "urlparse", "urllib.parse"), + MovedAttribute("urljoin", "urlparse", "urllib.parse"), + MovedAttribute("urlparse", "urlparse", "urllib.parse"), + MovedAttribute("urlsplit", "urlparse", "urllib.parse"), + MovedAttribute("urlunparse", "urlparse", "urllib.parse"), + MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), + MovedAttribute("quote", "urllib", "urllib.parse"), + MovedAttribute("quote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote", "urllib", "urllib.parse"), + MovedAttribute("unquote_plus", "urllib", "urllib.parse"), + MovedAttribute("urlencode", "urllib", "urllib.parse"), + MovedAttribute("splitquery", "urllib", "urllib.parse"), + MovedAttribute("splittag", "urllib", "urllib.parse"), + MovedAttribute("splituser", "urllib", "urllib.parse"), + MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), + MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), + MovedAttribute("uses_params", "urlparse", "urllib.parse"), + MovedAttribute("uses_query", "urlparse", "urllib.parse"), + MovedAttribute("uses_relative", "urlparse", "urllib.parse"), +] +for attr in _urllib_parse_moved_attributes: + setattr(Module_six_moves_urllib_parse, attr.name, attr) +del attr + +Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes + +_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), + "moves.urllib_parse", "moves.urllib.parse") + + +class Module_six_moves_urllib_error(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_error""" + + +_urllib_error_moved_attributes = [ + MovedAttribute("URLError", "urllib2", "urllib.error"), + MovedAttribute("HTTPError", "urllib2", "urllib.error"), + MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), +] +for attr in _urllib_error_moved_attributes: + setattr(Module_six_moves_urllib_error, attr.name, attr) +del attr + +Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes + +_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), + "moves.urllib_error", "moves.urllib.error") + + +class Module_six_moves_urllib_request(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_request""" + + +_urllib_request_moved_attributes = [ + MovedAttribute("urlopen", "urllib2", "urllib.request"), + MovedAttribute("install_opener", "urllib2", "urllib.request"), + MovedAttribute("build_opener", "urllib2", "urllib.request"), + MovedAttribute("pathname2url", "urllib", "urllib.request"), + MovedAttribute("url2pathname", "urllib", "urllib.request"), + MovedAttribute("getproxies", "urllib", "urllib.request"), + MovedAttribute("Request", "urllib2", "urllib.request"), + MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), + MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), + MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), + MovedAttribute("BaseHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), + MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), + MovedAttribute("FileHandler", "urllib2", "urllib.request"), + MovedAttribute("FTPHandler", "urllib2", "urllib.request"), + MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), + MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), + MovedAttribute("urlretrieve", "urllib", "urllib.request"), + MovedAttribute("urlcleanup", "urllib", "urllib.request"), + MovedAttribute("URLopener", "urllib", "urllib.request"), + MovedAttribute("FancyURLopener", "urllib", "urllib.request"), + MovedAttribute("proxy_bypass", "urllib", "urllib.request"), +] +for attr in _urllib_request_moved_attributes: + setattr(Module_six_moves_urllib_request, attr.name, attr) +del attr + +Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes + +_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), + "moves.urllib_request", "moves.urllib.request") + + +class Module_six_moves_urllib_response(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_response""" + + +_urllib_response_moved_attributes = [ + MovedAttribute("addbase", "urllib", "urllib.response"), + MovedAttribute("addclosehook", "urllib", "urllib.response"), + MovedAttribute("addinfo", "urllib", "urllib.response"), + MovedAttribute("addinfourl", "urllib", "urllib.response"), +] +for attr in _urllib_response_moved_attributes: + setattr(Module_six_moves_urllib_response, attr.name, attr) +del attr + +Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes + +_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), + "moves.urllib_response", "moves.urllib.response") + + +class Module_six_moves_urllib_robotparser(_LazyModule): + """Lazy loading of moved objects in six.moves.urllib_robotparser""" + + +_urllib_robotparser_moved_attributes = [ + MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), +] +for attr in _urllib_robotparser_moved_attributes: + setattr(Module_six_moves_urllib_robotparser, attr.name, attr) +del attr + +Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes + +_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), + "moves.urllib_robotparser", "moves.urllib.robotparser") + + +class Module_six_moves_urllib(types.ModuleType): + """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" + __path__ = [] # mark as package + parse = _importer._get_module("moves.urllib_parse") + error = _importer._get_module("moves.urllib_error") + request = _importer._get_module("moves.urllib_request") + response = _importer._get_module("moves.urllib_response") + robotparser = _importer._get_module("moves.urllib_robotparser") + + def __dir__(self): + return ['parse', 'error', 'request', 'response', 'robotparser'] + +_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), + "moves.urllib") + + +def add_move(move): + """Add an item to six.moves.""" + setattr(_MovedItems, move.name, move) + + +def remove_move(name): + """Remove item from six.moves.""" + try: + delattr(_MovedItems, name) + except AttributeError: + try: + del moves.__dict__[name] + except KeyError: + raise AttributeError("no such move, %r" % (name,)) + + +if PY3: + _meth_func = "__func__" + _meth_self = "__self__" + + _func_closure = "__closure__" + _func_code = "__code__" + _func_defaults = "__defaults__" + _func_globals = "__globals__" +else: + _meth_func = "im_func" + _meth_self = "im_self" + + _func_closure = "func_closure" + _func_code = "func_code" + _func_defaults = "func_defaults" + _func_globals = "func_globals" + + +try: + advance_iterator = next +except NameError: + def advance_iterator(it): + return it.next() +next = advance_iterator + + +try: + callable = callable +except NameError: + def callable(obj): + return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + + +if PY3: + def get_unbound_function(unbound): + return unbound + + create_bound_method = types.MethodType + + Iterator = object +else: + def get_unbound_function(unbound): + return unbound.im_func + + def create_bound_method(func, obj): + return types.MethodType(func, obj, obj.__class__) + + class Iterator(object): + + def next(self): + return type(self).__next__(self) + + callable = callable +_add_doc(get_unbound_function, + """Get the function out of a possibly unbound function""") + + +get_method_function = operator.attrgetter(_meth_func) +get_method_self = operator.attrgetter(_meth_self) +get_function_closure = operator.attrgetter(_func_closure) +get_function_code = operator.attrgetter(_func_code) +get_function_defaults = operator.attrgetter(_func_defaults) +get_function_globals = operator.attrgetter(_func_globals) + + +if PY3: + def iterkeys(d, **kw): + return iter(d.keys(**kw)) + + def itervalues(d, **kw): + return iter(d.values(**kw)) + + def iteritems(d, **kw): + return iter(d.items(**kw)) + + def iterlists(d, **kw): + return iter(d.lists(**kw)) +else: + def iterkeys(d, **kw): + return iter(d.iterkeys(**kw)) + + def itervalues(d, **kw): + return iter(d.itervalues(**kw)) + + def iteritems(d, **kw): + return iter(d.iteritems(**kw)) + + def iterlists(d, **kw): + return iter(d.iterlists(**kw)) + +_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") +_add_doc(itervalues, "Return an iterator over the values of a dictionary.") +_add_doc(iteritems, + "Return an iterator over the (key, value) pairs of a dictionary.") +_add_doc(iterlists, + "Return an iterator over the (key, [values]) pairs of a dictionary.") + + +if PY3: + def b(s): + return s.encode("latin-1") + def u(s): + return s + unichr = chr + if sys.version_info[1] <= 1: + def int2byte(i): + return bytes((i,)) + else: + # This is about 2x faster than the implementation above on 3.2+ + int2byte = operator.methodcaller("to_bytes", 1, "big") + byte2int = operator.itemgetter(0) + indexbytes = operator.getitem + iterbytes = iter + import io + StringIO = io.StringIO + BytesIO = io.BytesIO +else: + def b(s): + return s + # Workaround for standalone backslash + def u(s): + return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") + unichr = unichr + int2byte = chr + def byte2int(bs): + return ord(bs[0]) + def indexbytes(buf, i): + return ord(buf[i]) + def iterbytes(buf): + return (ord(byte) for byte in buf) + import StringIO + StringIO = BytesIO = StringIO.StringIO +_add_doc(b, """Byte literal""") +_add_doc(u, """Text literal""") + + +if PY3: + exec_ = getattr(moves.builtins, "exec") + + + def reraise(tp, value, tb=None): + if value is None: + value = tp() + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + +else: + def exec_(_code_, _globs_=None, _locs_=None): + """Execute code in a namespace.""" + if _globs_ is None: + frame = sys._getframe(1) + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals + del frame + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") + + + exec_("""def reraise(tp, value, tb=None): + raise tp, value, tb +""") + + +print_ = getattr(moves.builtins, "print", None) +if print_ is None: + def print_(*args, **kwargs): + """The new-style print function for Python 2.4 and 2.5.""" + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + def write(data): + if not isinstance(data, basestring): + data = str(data) + # If the file has an encoding, encode unicode with it. + if (isinstance(fp, file) and + isinstance(data, unicode) and + fp.encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(fp.encoding, errors) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) + +_add_doc(reraise, """Reraise an exception.""") + +if sys.version_info[0:2] < (3, 4): + def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, + updated=functools.WRAPPER_UPDATES): + def wrapper(f): + f = functools.wraps(wrapped)(f) + f.__wrapped__ = wrapped + return f + return wrapper +else: + wraps = functools.wraps + +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(meta): + def __new__(cls, name, this_bases, d): + return meta(name, bases, d) + return type.__new__(metaclass, 'temporary_class', (), {}) + + +def add_metaclass(metaclass): + """Class decorator for creating a class with a metaclass.""" + def wrapper(cls): + orig_vars = cls.__dict__.copy() + slots = orig_vars.get('__slots__') + if slots is not None: + if isinstance(slots, str): + slots = [slots] + for slots_var in slots: + orig_vars.pop(slots_var) + orig_vars.pop('__dict__', None) + orig_vars.pop('__weakref__', None) + return metaclass(cls.__name__, cls.__bases__, orig_vars) + return wrapper + +# Complete the moves implementation. +# This code is at the end of this module to speed up module loading. +# Turn this module into a package. +__path__ = [] # required for PEP 302 and PEP 451 +__package__ = __name__ # see PEP 366 @ReservedAssignment +if globals().get("__spec__") is not None: + __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable +# Remove other six meta path importers, since they cause problems. This can +# happen if six is removed from sys.modules and then reloaded. (Setuptools does +# this for some reason.) +if sys.meta_path: + for i, importer in enumerate(sys.meta_path): + # Here's some real nastiness: Another "instance" of the six module might + # be floating around. Therefore, we can't use isinstance() to check for + # the six meta path importer, since the other six instance will have + # inserted an importer with different class. + if (type(importer).__name__ == "_SixMetaPathImporter" and + importer.name == __name__): + del sys.meta_path[i] + break + del i, importer +# Finally, add the importer to the meta path import hook. +sys.meta_path.append(_importer) diff --git a/nipype/fixes/numpy/testing/nosetester.py b/nipype/fixes/numpy/testing/nosetester.py index d6df51b0c7..735a5be749 100644 --- a/nipype/fixes/numpy/testing/nosetester.py +++ b/nipype/fixes/numpy/testing/nosetester.py @@ -6,6 +6,7 @@ """ import os import sys +from nipype.external import six def get_package_name(filepath): """ @@ -166,7 +167,7 @@ def _test_argv(self, label, verbose, extra_argv): ''' argv = [__file__, self.package_path, '-s'] if label and label != 'full': - if not isinstance(label, basestring): + if not isinstance(label, six.string_types): raise TypeError('Selection label should be a string') if label == 'fast': label = 'not slow' diff --git a/nipype/interfaces/base.py b/nipype/interfaces/base.py index c244998958..ef6f8fd1a1 100644 --- a/nipype/interfaces/base.py +++ b/nipype/interfaces/base.py @@ -24,6 +24,7 @@ from datetime import datetime as dt from dateutil.parser import parse as parseutc from warnings import warn +from nipype.external import six from .traits_extension import (traits, Undefined, TraitDictObject, @@ -541,7 +542,7 @@ def _get_sorteddict(self, object, dictwithhash=False, hash_method=None, out = tuple(out) else: if isdefined(object): - if (hash_files and isinstance(object, str) and + if (hash_files and isinstance(object, six.string_types) and os.path.isfile(object)): if hash_method is None: hash_method = config.get('execution', 'hash_method') @@ -984,7 +985,7 @@ def run(self, **inputs): else: inputs_str = '' - if len(e.args) == 1 and isinstance(e.args[0], str): + if len(e.args) == 1 and isinstance(e.args[0], six.string_types): e.args = (e.args[0] + " ".join([message, inputs_str]),) else: e.args += (message, ) diff --git a/nipype/interfaces/dcmstack.py b/nipype/interfaces/dcmstack.py index d6a4b13580..1223ec7623 100644 --- a/nipype/interfaces/dcmstack.py +++ b/nipype/interfaces/dcmstack.py @@ -23,6 +23,7 @@ import nibabel as nb from nipype.interfaces.traits_extension import isdefined, Undefined import imghdr +from nipype.external import six have_dcmstack = True try: @@ -109,7 +110,7 @@ class DcmStack(NiftiGeneratorBase): output_spec = DcmStackOutputSpec def _get_filelist(self, trait_input): - if isinstance(trait_input, str): + if isinstance(trait_input, six.string_types): if path.isdir(trait_input): return glob(path.join(trait_input, '*.dcm')) else: @@ -334,7 +335,7 @@ def _run_interface(self, runtime): ] if self.inputs.sort_order: sort_order = self.inputs.sort_order - if isinstance(sort_order, str): + if isinstance(sort_order, six.string_types): sort_order = [sort_order] nws.sort(key=make_key_func(sort_order)) if self.inputs.merge_dim == traits.Undefined: diff --git a/nipype/interfaces/io.py b/nipype/interfaces/io.py index 675c90e98d..dc694cd94b 100644 --- a/nipype/interfaces/io.py +++ b/nipype/interfaces/io.py @@ -30,6 +30,7 @@ import sqlite3 from nipype.utils.misc import human_order_sorted +from nipype.external import six try: import pyxnat @@ -520,7 +521,7 @@ def _list_outputs(self): for argnum, arglist in enumerate(args): maxlen = 1 for arg in arglist: - if isinstance(arg, str) and hasattr(self.inputs, arg): + if isinstance(arg, six.string_types) and hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): if (maxlen > 1) and (len(arg) != maxlen): @@ -531,7 +532,7 @@ def _list_outputs(self): for i in range(maxlen): argtuple = [] for arg in arglist: - if isinstance(arg, str) and hasattr(self.inputs, arg): + if isinstance(arg, six.string_types) and hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): argtuple.append(arg[i]) @@ -786,7 +787,7 @@ def _match_path(self, target_path): def _run_interface(self, runtime): #Prepare some of the inputs - if isinstance(self.inputs.root_paths, str): + if isinstance(self.inputs.root_paths, six.string_types): self.inputs.root_paths = [self.inputs.root_paths] self.match_regex = re.compile(self.inputs.match_regex) if self.inputs.max_depth is Undefined: @@ -1155,7 +1156,7 @@ def _list_outputs(self): for argnum, arglist in enumerate(args): maxlen = 1 for arg in arglist: - if isinstance(arg, str) and hasattr(self.inputs, arg): + if isinstance(arg, six.string_types) and hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): if (maxlen > 1) and (len(arg) != maxlen): @@ -1168,7 +1169,7 @@ def _list_outputs(self): for i in range(maxlen): argtuple = [] for arg in arglist: - if isinstance(arg, str) and \ + if isinstance(arg, six.string_types) and \ hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): @@ -1725,7 +1726,7 @@ def _list_outputs(self): for argnum, arglist in enumerate(args): maxlen = 1 for arg in arglist: - if isinstance(arg, str) and hasattr(self.inputs, arg): + if isinstance(arg, six.string_types) and hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): if (maxlen > 1) and (len(arg) != maxlen): @@ -1736,7 +1737,7 @@ def _list_outputs(self): for i in range(maxlen): argtuple = [] for arg in arglist: - if isinstance(arg, str) and hasattr(self.inputs, arg): + if isinstance(arg, six.string_types) and hasattr(self.inputs, arg): arg = getattr(self.inputs, arg) if isinstance(arg, list): argtuple.append(arg[i]) diff --git a/nipype/interfaces/mne/base.py b/nipype/interfaces/mne/base.py index 67beb888b2..609dcd2246 100644 --- a/nipype/interfaces/mne/base.py +++ b/nipype/interfaces/mne/base.py @@ -4,6 +4,7 @@ import glob from nipype.interfaces.freesurfer.base import FSCommand, FSTraitedSpec from nipype.utils.filemanip import list_to_filename +from nipype.external import six import logging logging.basicConfig() @@ -89,7 +90,7 @@ def _list_outputs(self): out_files = [] for value in value_list: out_files.append(op.abspath(value)) - elif isinstance(value_list, str): + elif isinstance(value_list, six.string_types): out_files = op.abspath(value_list) else: raise TypeError diff --git a/nipype/interfaces/nipy/model.py b/nipype/interfaces/nipy/model.py index 76b583b355..ebbe394fdc 100644 --- a/nipype/interfaces/nipy/model.py +++ b/nipype/interfaces/nipy/model.py @@ -3,6 +3,7 @@ import nibabel as nb import numpy as np +from nipype.external import six from ...utils.misc import package_check @@ -80,7 +81,7 @@ def _run_interface(self, runtime): session_info = self.inputs.session_info functional_runs = self.inputs.session_info[0]['scans'] - if isinstance(functional_runs, str): + if isinstance(functional_runs, six.string_types): functional_runs = [functional_runs] nii = nb.load(functional_runs[0]) data = nii.get_data() diff --git a/nipype/interfaces/slicer/generate_classes.py b/nipype/interfaces/slicer/generate_classes.py index 4affadafc5..013f31c75c 100644 --- a/nipype/interfaces/slicer/generate_classes.py +++ b/nipype/interfaces/slicer/generate_classes.py @@ -7,6 +7,7 @@ import subprocess import os from shutil import rmtree +from nipype.external import six import keyword python_keywords = keyword.kwlist # If c++ SEM module uses one of these key words as a command line parameter, we need to modify variable @@ -47,7 +48,7 @@ def add_class_to_package(class_codes, class_names, module_name, package_dir): def crawl_code_struct(code_struct, package_dir): subpackages = [] for k, v in code_struct.iteritems(): - if isinstance(v, str) or isinstance(v, unicode): + if isinstance(v, six.string_types) or isinstance(v, unicode): module_name = k.lower() class_name = k class_code = v @@ -57,7 +58,7 @@ def crawl_code_struct(code_struct, package_dir): l1 = {} l2 = {} for key in v.keys(): - if (isinstance(v[key], str) or isinstance(v[key], unicode)): + if (isinstance(v[key], six.string_types) or isinstance(v[key], unicode)): l1[key] = v[key] else: l2[key] = v[key] @@ -313,7 +314,7 @@ def grab_xml(module, launcher): def parse_params(params): list = [] for key, value in params.iteritems(): - if isinstance(value, str) or isinstance(value, unicode): + if isinstance(value, six.string_types) or isinstance(value, unicode): list.append('%s="%s"' % (key, value.replace('"', "'"))) else: list.append('%s=%s' % (key, value)) diff --git a/nipype/interfaces/spm/base.py b/nipype/interfaces/spm/base.py index c47abf0a6d..6d0ea0eb50 100644 --- a/nipype/interfaces/spm/base.py +++ b/nipype/interfaces/spm/base.py @@ -24,6 +24,7 @@ from nibabel import load import numpy as np from scipy.io import savemat +from nipype.external import six # Local imports from ..base import (BaseInterface, traits, isdefined, InputMultiPath, @@ -416,7 +417,7 @@ def _generate_job(self, prefix='', contents=None): if isinstance(val, np.ndarray): jobstring += self._generate_job(prefix=None, contents=val) - elif isinstance(val, str): + elif isinstance(val, six.string_types): jobstring += '\'%s\';...\n' % (val) else: jobstring += '%s;...\n' % str(val) @@ -431,7 +432,7 @@ def _generate_job(self, prefix='', contents=None): jobstring += self._generate_job(newprefix, val[field]) return jobstring - if isinstance(contents, str): + if isinstance(contents, six.string_types): jobstring += "%s = '%s';\n" % (prefix, contents) return jobstring jobstring += "%s = %s;\n" % (prefix, str(contents)) diff --git a/nipype/interfaces/spm/model.py b/nipype/interfaces/spm/model.py index 5b0528a084..eddf3ec47a 100644 --- a/nipype/interfaces/spm/model.py +++ b/nipype/interfaces/spm/model.py @@ -20,6 +20,7 @@ # Third-party imports import numpy as np import scipy.io as sio +from nipype.external import six # Local imports from nipype.interfaces.base import (Bunch, traits, TraitedSpec, File, Directory, @@ -196,7 +197,7 @@ def _format_arg(self, opt, spec, val): if opt == 'spm_mat_file': return np.array([str(val)], dtype=object) if opt == 'estimation_method': - if isinstance(val, str): + if isinstance(val, six.string_types): return {'%s' % val: 1} else: return val diff --git a/nipype/interfaces/utility.py b/nipype/interfaces/utility.py index 005eb4a501..210d74e134 100644 --- a/nipype/interfaces/utility.py +++ b/nipype/interfaces/utility.py @@ -5,6 +5,7 @@ from cPickle import dumps, loads import numpy as np import nibabel as nb +from nipype.external import six from nipype.utils.filemanip import (filename_to_list, copyfile, split_filename) from nipype.interfaces.base import (traits, TraitedSpec, DynamicTraitedSpec, File, @@ -386,7 +387,7 @@ def __init__(self, input_names, output_names, function=None, imports=None, raise Exception('Interface Function does not accept ' \ 'function objects defined interactively ' \ 'in a python session') - elif isinstance(function, str): + elif isinstance(function, six.string_types): self.inputs.function_str = dumps(function) else: raise Exception('Unknown type of function') @@ -404,7 +405,7 @@ def _set_function_string(self, obj, name, old, new): if name == 'function_str': if hasattr(new, '__call__'): function_source = getsource(new) - elif isinstance(new, str): + elif isinstance(new, six.string_types): function_source = dumps(new) self.inputs.trait_set(trait_change_notify=False, **{'%s' % name: function_source}) diff --git a/nipype/pipeline/engine.py b/nipype/pipeline/engine.py index 5e403ac22d..ea31ca8378 100644 --- a/nipype/pipeline/engine.py +++ b/nipype/pipeline/engine.py @@ -34,6 +34,7 @@ from tempfile import mkdtemp from warnings import warn from hashlib import sha1 +from nipype.external import six import numpy as np @@ -361,7 +362,7 @@ def connect(self, *args, **kwargs): # handles the case that source is specified # with a function sourcename = source[0] - elif isinstance(source, str): + elif isinstance(source, six.string_types): sourcename = source else: raise Exception(('Unknown source specification in ' @@ -382,7 +383,7 @@ def connect(self, *args, **kwargs): # turn functions into strings for srcnode, destnode, connects in connection_list: for idx, (src, dest) in enumerate(connects): - if isinstance(src, tuple) and not isinstance(src[1], str): + if isinstance(src, tuple) and not isinstance(src[1], six.string_types): function_source = getsource(src[1]) connects[idx] = ((src[0], function_source, src[2:]), dest) @@ -896,7 +897,7 @@ def _set_input(self, object, name, newvalue): def _set_node_input(self, node, param, source, sourceinfo): """Set inputs of a node given the edge connection""" - if isinstance(sourceinfo, str): + if isinstance(sourceinfo, six.string_types): val = source.get_output(sourceinfo) elif isinstance(sourceinfo, tuple): if callable(sourceinfo[1]): @@ -1841,7 +1842,7 @@ def __init__(self, interface, name, joinsource, joinfield=None, if not joinfield: # default is the interface fields joinfield = self._interface.inputs.copyable_trait_names() - elif isinstance(joinfield, str): + elif isinstance(joinfield, six.string_types): joinfield = [joinfield] self.joinfield = joinfield """the fields to join""" @@ -2047,7 +2048,7 @@ def __init__(self, interface, iterfield, name, serial=False, **kwargs): super(MapNode, self).__init__(interface, name, **kwargs) - if isinstance(iterfield, str): + if isinstance(iterfield, six.string_types): iterfield = [iterfield] self.iterfield = iterfield self._inputs = self._create_dynamic_traits(self._interface.inputs, diff --git a/nipype/pipeline/utils.py b/nipype/pipeline/utils.py index 21f7ef4036..b1889f0577 100644 --- a/nipype/pipeline/utils.py +++ b/nipype/pipeline/utils.py @@ -13,6 +13,7 @@ import numpy as np from nipype.utils.misc import package_check +from nipype.external import six package_check('networkx', '1.3') from socket import gethostname @@ -103,7 +104,7 @@ def modify_paths(object, relative=True, basedir=None): out = tuple(out) else: if isdefined(object): - if isinstance(object, str) and os.path.isfile(object): + if isinstance(object, six.string_types) and os.path.isfile(object): if relative: if config.getboolean('execution', 'use_relative_paths'): out = relpath(object, start=basedir) @@ -186,7 +187,7 @@ def _write_detailed_dot(graph, dotfilename): inports = [] for u, v, d in graph.in_edges_iter(nbunch=n, data=True): for cd in d['connect']: - if isinstance(cd[0], str): + if isinstance(cd[0], six.string_types): outport = cd[0] else: outport = cd[0][0] @@ -206,7 +207,7 @@ def _write_detailed_dot(graph, dotfilename): outports = [] for u, v, d in graph.out_edges_iter(nbunch=n, data=True): for cd in d['connect']: - if isinstance(cd[0], str): + if isinstance(cd[0], six.string_types): outport = cd[0] else: outport = cd[0][0] @@ -607,7 +608,7 @@ def generate_expanded_graph(graph_in): # the itersource is a (node name, fields) tuple src_name, src_fields = inode.itersource # convert a single field to a list - if isinstance(src_fields, str): + if isinstance(src_fields, six.string_types): src_fields = [src_fields] # find the unique iterable source node in the graph try: @@ -789,7 +790,7 @@ def _standardize_iterables(node): if node.synchronize: if len(iterables) == 2: first, last = iterables - if all((isinstance(item, str) and item in fields + if all((isinstance(item, six.string_types) and item in fields for item in first)): iterables = _transpose_iterables(first, last) @@ -961,7 +962,7 @@ def walk_outputs(object): if isdefined(val): out.extend(walk_outputs(val)) else: - if isdefined(object) and isinstance(object, basestring): + if isdefined(object) and isinstance(object, six.string_types): if os.path.islink(object) or os.path.isfile(object): out = [(filename, 'f') for filename in get_all_files(object)] elif os.path.isdir(object): diff --git a/nipype/testing/decorators.py b/nipype/testing/decorators.py index a2e7e581c3..2591b76ea1 100644 --- a/nipype/testing/decorators.py +++ b/nipype/testing/decorators.py @@ -5,6 +5,7 @@ """ from numpy.testing.decorators import * +from nipype.external import six from nibabel.data import DataError @@ -44,7 +45,7 @@ def make_label_dec(label, ds=None): >>> f.hard True """ - if isinstance(label,basestring): + if isinstance(label,six.string_types): labels = [label] else: labels = label diff --git a/nipype/utils/docparse.py b/nipype/utils/docparse.py index a380a8932d..2a60d257e1 100644 --- a/nipype/utils/docparse.py +++ b/nipype/utils/docparse.py @@ -16,6 +16,7 @@ import subprocess from nipype.interfaces.base import CommandLine from nipype.utils.misc import is_container +from nipype.external import six def grab_doc(cmd, trap_error=True): """Run cmd without args and grab documentation. @@ -277,7 +278,7 @@ def _parse_doc(doc, style=['--']): # individual flag/option. doclist = doc.split('\n') optmap = {} - if isinstance(style,str): + if isinstance(style,six.string_types): style = [style] for line in doclist: linelist = line.split() diff --git a/nipype/utils/provenance.py b/nipype/utils/provenance.py index a51173ba9c..10fb20552f 100644 --- a/nipype/utils/provenance.py +++ b/nipype/utils/provenance.py @@ -4,6 +4,7 @@ import pwd from socket import getfqdn from uuid import uuid1 +from nipype.external import six import numpy as np try: @@ -94,7 +95,7 @@ def _get_sorteddict(object, dictwithhash=False): if isinstance(object, tuple): out = tuple(out) else: - if isinstance(object, str) and os.path.isfile(object): + if isinstance(object, six.string_types) and os.path.isfile(object): hash = hash_infile(object) if dictwithhash: out = (object, hash) @@ -213,7 +214,7 @@ def prov_encode(graph, value, create_container=True): else: encoded_literal = safe_encode(value) attr = {pm.PROV['value']: encoded_literal} - if isinstance(value, basestring) and os.path.exists(value): + if isinstance(value, six.string_types) and os.path.exists(value): attr.update({pm.PROV['location']: encoded_literal}) if not os.path.isdir(value): sha512 = hash_infile(value, crypto=hashlib.sha512) diff --git a/tools/checkspecs.py b/tools/checkspecs.py index ec70f01a9e..6dd6b5133a 100644 --- a/tools/checkspecs.py +++ b/tools/checkspecs.py @@ -12,6 +12,7 @@ import tempfile import warnings +from nipype.external import six from nipype.interfaces.base import BaseInterface # Functions and classes @@ -215,7 +216,7 @@ def test_specs(self, uri): for key, value in sorted(trait.__dict__.items()): if key in in_built or key == 'desc': continue - if isinstance(value, basestring): + if isinstance(value, six.string_types): quote = "'" if "'" in value: quote = '"' @@ -257,7 +258,7 @@ def test_specs(self, uri): for key, value in sorted(trait.__dict__.items()): if key in in_built or key == 'desc': continue - if isinstance(value, basestring): + if isinstance(value, six.string_types): quote = "'" if "'" in value: quote = '"'