提交 feabe7f9 authored 作者: David Warde-Farley's avatar David Warde-Farley 提交者: Arnaud Bergeron

Use six.string_types instead of basestring

上级 2108b783
......@@ -17,6 +17,7 @@ import numpy
import theano
from theano import gof
from theano.compat import get_unbound_function
from theano.compat.six import string_types
from theano.compat.six.moves import StringIO, xrange
from theano.gof import (FunctionGraph, graph, utils, link,
ops_with_inner_function)
......@@ -66,7 +67,7 @@ AddConfigVar('DebugMode.warn_input_not_reused',
def is_valid_check_preallocated_output_param(param):
if not isinstance(param, basestring):
if not isinstance(param, string_types):
return False
valid = ["initial", "previous", "c_contiguous", "f_contiguous",
"strided", "wrong_size", "ALL", ""]
......
......@@ -6,6 +6,7 @@ import logging
import traceback as tb
import re
from theano.compat.six import string_types
from theano.compile.io import In
from theano.compile.function_module import orig_function
from theano.compile.pfunc import pfunc
......@@ -40,7 +41,7 @@ def function_dump(filename, inputs, outputs=None, mode=None, updates=None,
calling set_value(...) on them before calling `function_dump`.
"""
assert isinstance(filename, basestring)
assert isinstance(filename, string_types)
d = dict(inputs=inputs, outputs=outputs, mode=mode, updates=updates,
givens=givens, no_default_updates=no_default_updates,
accept_inplace=accept_inplace, name=name,
......@@ -212,7 +213,7 @@ def function(inputs, outputs=None, mode=None, updates=None, givens=None,
output_items = outputs.items()
for item_pair in output_items:
assert isinstance(item_pair[0], basestring)
assert isinstance(item_pair[0], string_types)
output_items_sorted = sorted(output_items)
......
......@@ -1565,7 +1565,7 @@ def convert_function_input(input):
orig = input
if not input:
raise TypeError("Nonsensical input specification: %s" % input)
if isinstance(input[0], basestring):
if isinstance(input[0], string_types):
name = input[0]
input = input[1:]
else:
......
......@@ -3,6 +3,8 @@
from theano import gof
from .sharedvalue import SharedVariable
from theano.compat.six import string_types
import logging
_logger = logging.getLogger("theano.compile.io")
......@@ -71,7 +73,7 @@ class SymbolicInput(object):
else:
self.name = name
if self.name is not None and not isinstance(self.name, basestring):
if self.name is not None and not isinstance(self.name, string_types):
raise TypeError("name must be a string! (got: %s)" % self.name)
self.update = update
if (mutable is not None):
......@@ -106,7 +108,7 @@ class SymbolicInputKit(object):
"""
def __init__(self, name):
if not isinstance(name, basestring):
if not isinstance(name, string_types):
raise TypeError('naem must be a string (got: %s)' % name)
self.name = name
self.sinputs = []
......
......@@ -10,6 +10,7 @@ from theano import gof
import theano.gof.vm
from theano.configparser import config, AddConfigVar, StrParam
from theano.compile.ops import _output_guard
from theano.compat.six import string_types
_logger = logging.getLogger('theano.compile.mode')
......@@ -271,10 +272,10 @@ class Mode(object):
linker, optimizer = state
self.provided_linker = linker
self.provided_optimizer = optimizer
if isinstance(linker, basestring) or linker is None:
if isinstance(linker, string_types) or linker is None:
linker = predefined_linkers[linker]
self.linker = linker
if isinstance(optimizer, basestring) or optimizer is None:
if isinstance(optimizer, string_types) or optimizer is None:
optimizer = predefined_optimizers[optimizer]
if isinstance(optimizer, gof.Query):
self.provided_optimizer = optimizer
......@@ -297,9 +298,9 @@ class Mode(object):
optimizer = property(__get_optimizer)
def get_linker_optimizer(self, linker, optimizer):
if isinstance(linker, basestring) or linker is None:
if isinstance(linker, string_types) or linker is None:
linker = predefined_linkers[linker]
if isinstance(optimizer, basestring) or optimizer is None:
if isinstance(optimizer, string_types) or optimizer is None:
optimizer = predefined_optimizers[optimizer]
return (linker, optimizer)
......@@ -341,7 +342,7 @@ def get_mode(orig_string):
string = config.mode
else:
string = orig_string
if not isinstance(string, basestring):
if not isinstance(string, string_types):
return string # it is hopefully already a mode...
global instanciated_default_mode
......
......@@ -7,6 +7,7 @@ import warnings
import theano
from theano.gof.link import WrapLinker
from theano.compat.six import string_types
from theano.compile.mode import (Mode, register_mode,
predefined_modes, predefined_linkers,
predefined_optimizers)
......@@ -192,7 +193,7 @@ class ProfileMode(Mode):
self.provided_linker = linker
self.provided_optimizer = optimizer
if isinstance(linker, basestring) or linker is None:
if isinstance(linker, string_types) or linker is None:
linker = predefined_linkers[linker]
if not config.ProfileMode.profile_memory:
......@@ -202,7 +203,7 @@ class ProfileMode(Mode):
linker = WrapLinker([linker], p_thunk)
self.linker = linker
if isinstance(optimizer, basestring) or optimizer is None:
if isinstance(optimizer, string_types) or optimizer is None:
optimizer = predefined_optimizers[optimizer]
self._optimizer = optimizer
......
......@@ -14,6 +14,7 @@ from theano.compat.six import StringIO
import theano
from theano.compat import configparser as ConfigParser
from theano.compat.six import string_types
import collections
_logger = logging.getLogger('theano.configparser')
......@@ -337,7 +338,7 @@ class EnumStr(ConfigParam):
# All options should be strings
for val in self.all:
if not isinstance(val, basestring):
if not isinstance(val, string_types):
raise ValueError('Valid values for an EnumStr parameter '
'should be strings', val, type(val))
......
......@@ -12,6 +12,7 @@ from itertools import izip
import numpy
from theano.compat import PY3
from theano.compat.six import string_types
from theano.compat.six.moves import StringIO, xrange
from theano.gof.utils import MethodNotDefined
......@@ -702,7 +703,7 @@ class CLinker(link.Linker):
pass
else:
# The following will be executed if the "try" block succeeds
assert isinstance(c_support_code_apply[-1], basestring), (
assert isinstance(c_support_code_apply[-1], string_types), (
str(node.op) +
" didn't return a string for c_support_code_apply")
......@@ -711,13 +712,13 @@ class CLinker(link.Linker):
except utils.MethodNotDefined:
pass
else:
assert isinstance(c_init_code_apply[-1], basestring), (
assert isinstance(c_init_code_apply[-1], string_types), (
str(node.op) +
" didn't return a string for c_init_code_apply")
try:
struct_init = op.c_init_code_struct(node, name, sub_struct)
assert isinstance(struct_init, basestring), (
assert isinstance(struct_init, string_types), (
str(node.op) +
" didn't return a string for c_init_code_struct")
except utils.MethodNotDefined:
......@@ -725,7 +726,7 @@ class CLinker(link.Linker):
try:
struct_support = op.c_support_code_struct(node, name)
assert isinstance(struct_support, basestring), (
assert isinstance(struct_support, string_types), (
str(node.op) +
" didn't return a string for c_support_code_struct")
except utils.MethodNotDefined:
......@@ -733,7 +734,7 @@ class CLinker(link.Linker):
try:
struct_cleanup = op.c_cleanup_code_struct(node, name)
assert isinstance(struct_cleanup, basestring), (
assert isinstance(struct_cleanup, string_types), (
str(node.op) +
" didn't return a string for c_cleanup_code_struct")
except utils.MethodNotDefined:
......@@ -744,7 +745,7 @@ class CLinker(link.Linker):
behavior = op.c_code(node, name, isyms, osyms, sub)
except utils.MethodNotDefined:
raise NotImplementedError("%s cannot produce C code" % op)
assert isinstance(behavior, basestring), (
assert isinstance(behavior, string_types), (
str(node.op) + " didn't return a string for c_code")
# To help understand what is following. It help read the c code.
# This prevent different op that generate the same c code
......
......@@ -25,7 +25,7 @@ import numpy.distutils # TODO: TensorType should handle this
import theano
from theano.compat import PY3, decode, decode_iter
from theano.compat.six import b, BytesIO, StringIO
from theano.compat.six import b, BytesIO, StringIO, string_types
from theano.gof.utils import flatten
from theano.configparser import config
from theano.gof.cc import hash_from_code
......@@ -396,7 +396,7 @@ def get_module_hash(src_code, key):
# This should be the C++ compilation command line parameters or the
# libraries to link against.
to_hash += list(key_element)
elif isinstance(key_element, basestring):
elif isinstance(key_element, string_types):
if key_element.startswith('md5:'):
# This is the md5 hash of the config options. We can stop
# here.
......@@ -429,7 +429,7 @@ def get_safe_part(key):
# Find the md5 hash part.
c_link_key = key[1]
for key_element in c_link_key[1:]:
if (isinstance(key_element, basestring)
if (isinstance(key_element, string_types)
and key_element.startswith('md5:')):
md5 = key_element[4:]
break
......
......@@ -14,6 +14,7 @@ import textwrap
import numpy
import theano
from theano.compat.six import string_types
from theano.configparser import config, AddConfigVar, ConfigParam, StrParam
from theano.gof.utils import flatten
from theano.misc.windows import output_subprocess_Popen
......@@ -289,7 +290,7 @@ def cleanup():
# force the removing of key
have_npy_abi_version = False
break
elif isinstance(obj, basestring):
elif isinstance(obj, string_types):
if obj.startswith('NPY_ABI_VERSION=0x'):
have_npy_abi_version = True
elif obj.startswith('c_compiler_str='):
......
......@@ -13,10 +13,10 @@ from collections import deque
from copy import copy
from itertools import count
import theano
import warnings
from theano.gof import utils
from theano.compat.six import string_types
from theano.misc.ordered_set import OrderedSet
# Lazy imports to avoid circular dependencies.
......@@ -340,7 +340,7 @@ class Variable(Node):
if index is not None and not isinstance(index, int):
raise TypeError("index must be an int", index)
self.index = index
if name is not None and not isinstance(name, basestring):
if name is not None and not isinstance(name, string_types):
raise TypeError("name must be a string", name)
self.name = name
self.auto_name = 'auto_' + str(next(self.__count__))
......
......@@ -17,6 +17,7 @@ import numpy
import theano
from theano import config
from theano.compat.six import string_types
from theano.compat.six.moves import reduce
from theano.gof import graph, op, utils, unify, toolbox
from theano.gof.fg import InconsistencyError
......@@ -1255,7 +1256,7 @@ class PatternSub(LocalOptimizer):
allow_multiple_clients))
else:
return retry_with_equiv()
elif isinstance(pattern, basestring):
elif isinstance(pattern, string_types):
v = unify.Var(pattern)
if u[v] is not v and u[v] is not expr:
return retry_with_equiv()
......@@ -1286,7 +1287,7 @@ class PatternSub(LocalOptimizer):
if isinstance(pattern, (list, tuple)):
args = [build(p, u) for p in pattern[1:]]
return pattern[0](*args)
elif isinstance(pattern, basestring):
elif isinstance(pattern, string_types):
return u[unify.Var(pattern)]
elif isinstance(pattern, (int, float)):
return pattern
......
from __future__ import print_function
from theano.compat.six.moves import reduce
from theano.compat.six import string_types
if 0:
class _EquilibriumOptimizer(NavigatorOptimizer):
......@@ -66,7 +67,7 @@ if 0:
_nodes = nodes
nodes = reduce(list.__iadd__,
[reduce(list.__iadd__,
[[n for n, i in out.clients if not isinstance(n, basestring)] for out in node.outputs],
[[n for n, i in out.clients if not isinstance(n, string_types)] for out in node.outputs],
[]) for node in nodes],
[])
candidates = tracks
......@@ -123,7 +124,7 @@ if 0:
# for candidate in candidates:
# if candidate.current.inputs is not None:
# for in1, in2 in zip(candidate.current.inputs, node.inputs):
# if isinstance(in1, basestring):
# if isinstance(in1, string_types):
# candidate.match[in1] = in2
# for client in node.clients:
......
......@@ -5,6 +5,7 @@ import numpy
import theano
import theano.gof.op as op
from theano.compat.six import string_types
from theano.compat.six.moves import xrange
from theano.gof.type import Type, Generic
from theano.gof.graph import Apply, Variable
......@@ -39,7 +40,7 @@ class MyType(Type):
def filter(self, x, strict=False, allow_downcast=None):
# Dummy filter: we want this type to represent strings that
# start with `self.thingy`.
if not isinstance(x, basestring):
if not isinstance(x, string_types):
raise TypeError("Invalid type")
if not x.startswith(self.thingy):
raise ValueError("Invalid value")
......
"""WRITEME Defines the `Type` class."""
from theano.compat import PY3
from theano.compat.six import string_types
from theano.gof import utils
from theano.gof.utils import MethodNotDefined, object2
......@@ -540,10 +541,10 @@ class CDataType(Type):
function must have a `void` return and take a
single pointer argument.
"""
assert isinstance(ctype, basestring)
assert isinstance(ctype, string_types)
self.ctype = ctype
if freefunc is not None:
assert isinstance(freefunc, basestring)
assert isinstance(freefunc, string_types)
self.freefunc = freefunc
def __eq__(self, other):
......
......@@ -3,6 +3,8 @@ from collections import MutableSet
from theano.compat import OrderedDict
import types
from theano.compat.six import string_types
def check_deterministic(iterable):
# Most places where OrderedSet is used, theano interprets any exception
......@@ -13,7 +15,7 @@ def check_deterministic(iterable):
# theano to use exceptions correctly, so that this can be a TypeError.
if iterable is not None:
assert isinstance(iterable, (
list, tuple, OrderedSet, types.GeneratorType, basestring))
list, tuple, OrderedSet, types.GeneratorType, string_types))
# Copyright (C) 2009 Raymond Hettinger
# Permission is hereby granted, free of charge, to any person obtaining a
......
......@@ -23,6 +23,7 @@ TheanoElementwiseKernel.
import numpy
import theano
from theano.compat.six import string_types
from theano.compat.six.moves import xrange
from theano.gof import Op, Apply, local_optimizer, EquilibriumDB
from theano.sandbox.cuda import GpuElemwise, CudaNdarrayType, GpuOp
......@@ -64,7 +65,7 @@ class TheanoElementwiseKernel(pycuda.elementwise.ElementwiseKernel):
name="kernel", keep=False, options=None, **kwargs):
if options is None:
options = []
if isinstance(arguments, basestring):
if isinstance(arguments, string_types):
arguments = [theano_parse_c_arg(arg)
for arg in arguments.split(",")]
pycuda.elementwise.ElementwiseKernel.__init__(self, arguments,
......
......@@ -13,6 +13,7 @@ import hashlib
import numpy as np
import collections
from theano.compat.six import string_types
try:
import pydot as pd
......@@ -345,7 +346,7 @@ class PatternPrinter:
def __init__(self, *patterns):
self.patterns = []
for pattern in patterns:
if isinstance(pattern, basestring):
if isinstance(pattern, string_types):
self.patterns.append((pattern, ()))
else:
self.patterns.append((pattern[0], pattern[1:]))
......
......@@ -12,6 +12,7 @@ from theano.tensor.basic import Alloc, Join, Split
from theano.gof import HideC
from theano.gof.utils import MethodNotDefined
from theano.compat import PY3
from theano.compat.six import string_types
try:
import pygpu
......@@ -65,7 +66,7 @@ class Kernel(object):
@staticmethod
def get_flags(*types):
def get_dtype(t):
if isinstance(t, (str, unicode)):
if isinstance(t, string_types):
return numpy.dtype(t)
elif isinstance(t, Type):
return t.dtype
......
......@@ -4,6 +4,7 @@ import theano
import theano.tensor as T
import collections
from theano.compat.six import string_types
#import klass
......@@ -133,7 +134,7 @@ def compile(smod, initial_values=None):
elif issymbolicmodule(val):
for s in modwalker(val.__dict__, [v for k, v in sym_items(val)]):
yield s
elif isinstance(val, (basestring, int, float)):
elif isinstance(val, (string_types, int, float)):
pass
elif isinstance(val, theano.Variable):
pass
......@@ -184,7 +185,7 @@ def compile(smod, initial_values=None):
reflected[thing] = cmod
for key, val in sym_items(thing):
setattr(CMod, key, reflect(val))
elif isinstance(thing, (basestring, int, float)):
elif isinstance(thing, (string_types, int, float)):
reflected[thing] = thing
elif isinstance(thing, theano.Variable):
if thing.owner is None:
......
......@@ -72,6 +72,7 @@ from theano.compat import OrderedDict
from theano.tensor import TensorType
from theano.tensor.opt import Shape_i
from theano.gradient import grad_undefined, DisconnectedType, NullType
from theano.compat.six import string_types
from theano.compile.profiling import ScanProfileStats
from theano.scan_module import scan_utils
......@@ -745,9 +746,9 @@ class Scan(PureOp):
wrapped_outputs += self.outputs[slices:]
profile = None
if (theano.config.profile or
(isinstance(self.profile, (basestring, bool, int))
(isinstance(self.profile, (string_types, bool, int))
and self.profile)):
if isinstance(self.profile, basestring):
if isinstance(self.profile, string_types):
profile = ScanProfileStats(name=self.profile)
else:
profile = ScanProfileStats(name=self.name)
......
......@@ -21,6 +21,7 @@ from itertools import izip
import numpy
import theano
from theano.compat.six import string_types
from theano.compile.pfunc import rebuild_collect_shared
from theano import gof, compat
from theano import tensor, scalar
......@@ -367,7 +368,7 @@ def isNaN_or_Inf_or_None(x):
try:
isNaN = numpy.isnan(x)
isInf = numpy.isinf(x)
isStr = isinstance(x, basestring)
isStr = isinstance(x, string_types)
except Exception:
isNaN = False
isInf = False
......@@ -380,7 +381,7 @@ def isNaN_or_Inf_or_None(x):
except Exception:
isNaN = False
isInf = False
if isinstance(x, gof.Constant) and isinstance(x.data, basestring):
if isinstance(x, gof.Constant) and isinstance(x.data, string_types):
isStr = True
else:
isStr = False
......
......@@ -7,6 +7,7 @@ except ImportError:
import theano
from theano import gof
from theano.compat.six import string_types
def _is_sparse(x):
......@@ -61,7 +62,7 @@ class SparseType(gof.Type):
raise NotImplementedError('unsupported dtype "%s" not in list' %
dtype, list(self.dtype_set))
assert isinstance(format, basestring)
assert isinstance(format, string_types)
if format in self.format_cls:
self.format = format
else:
......
......@@ -12,6 +12,7 @@ from theano.compat.six.moves import reduce
from theano import tensor
from theano.tensor import opt
from theano import gof
from theano.compat.six import string_types
from theano.compile import optdb
......@@ -144,7 +145,7 @@ class RandomFunction(gof.Op):
def __setstate__(self, state):
self.state = state
fn, outtype, inplace, ndim_added = state
if isinstance(fn, basestring):
if isinstance(fn, string_types):
self.fn = getattr(numpy.random.RandomState, fn)
else:
self.fn = fn
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论