##// END OF EJS Templates
Replace references to unicode and basestring
Thomas Kluyver -
Show More
@@ -40,6 +40,7 b' from IPython.utils.traitlets import ('
40 from IPython.utils.importstring import import_item
40 from IPython.utils.importstring import import_item
41 from IPython.utils.text import indent, wrap_paragraphs, dedent
41 from IPython.utils.text import indent, wrap_paragraphs, dedent
42 from IPython.utils import py3compat
42 from IPython.utils import py3compat
43 from IPython.utils.py3compat import string_types
43
44
44 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
45 # function for re-wrapping a helpstring
46 # function for re-wrapping a helpstring
@@ -155,7 +156,7 b' class Application(SingletonConfigurable):'
155 help="Set the log level by value or name.")
156 help="Set the log level by value or name.")
156 def _log_level_changed(self, name, old, new):
157 def _log_level_changed(self, name, old, new):
157 """Adjust the log level when log_level is set."""
158 """Adjust the log level when log_level is set."""
158 if isinstance(new, basestring):
159 if isinstance(new, string_types):
159 new = getattr(logging, new)
160 new = getattr(logging, new)
160 self.log_level = new
161 self.log_level = new
161 self.log.setLevel(new)
162 self.log.setLevel(new)
@@ -218,7 +219,7 b' class Application(SingletonConfigurable):'
218 for key,value in new.iteritems():
219 for key,value in new.iteritems():
219 assert len(value) == 2, "Bad flag: %r:%s"%(key,value)
220 assert len(value) == 2, "Bad flag: %r:%s"%(key,value)
220 assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value)
221 assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value)
221 assert isinstance(value[1], basestring), "Bad flag: %r:%s"%(key,value)
222 assert isinstance(value[1], string_types), "Bad flag: %r:%s"%(key,value)
222
223
223
224
224 # subcommands for launching other applications
225 # subcommands for launching other applications
@@ -400,7 +401,7 b' class Application(SingletonConfigurable):'
400 """Initialize a subcommand with argv."""
401 """Initialize a subcommand with argv."""
401 subapp,help = self.subcommands.get(subc)
402 subapp,help = self.subcommands.get(subc)
402
403
403 if isinstance(subapp, basestring):
404 if isinstance(subapp, string_types):
404 subapp = import_item(subapp)
405 subapp = import_item(subapp)
405
406
406 # clear existing instances
407 # clear existing instances
@@ -32,7 +32,7 b' import sys'
32 from IPython.utils.path import filefind, get_ipython_dir
32 from IPython.utils.path import filefind, get_ipython_dir
33 from IPython.utils import py3compat, warn
33 from IPython.utils import py3compat, warn
34 from IPython.utils.encoding import DEFAULT_ENCODING
34 from IPython.utils.encoding import DEFAULT_ENCODING
35 from IPython.utils.py3compat import builtin_mod
35 from IPython.utils.py3compat import builtin_mod, unicode_type
36 from IPython.utils.traitlets import HasTraits, List, Any, TraitError
36 from IPython.utils.traitlets import HasTraits, List, Any, TraitError
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
@@ -567,7 +567,7 b' class KeyValueConfigLoader(CommandLineConfigLoader):'
567 if enc is None:
567 if enc is None:
568 enc = DEFAULT_ENCODING
568 enc = DEFAULT_ENCODING
569 for arg in argv:
569 for arg in argv:
570 if not isinstance(arg, unicode):
570 if not isinstance(arg, unicode_type):
571 # only decode if not already decoded
571 # only decode if not already decoded
572 arg = arg.decode(enc)
572 arg = arg.decode(enc)
573 uargv.append(arg)
573 uargv.append(arg)
@@ -757,9 +757,9 b' class KVArgParseConfigLoader(ArgParseConfigLoader):'
757 else:
757 else:
758 nargs = None
758 nargs = None
759 if len(key) is 1:
759 if len(key) is 1:
760 paa('-'+key, '--'+key, type=unicode, dest=value, nargs=nargs)
760 paa('-'+key, '--'+key, type=unicode_type, dest=value, nargs=nargs)
761 else:
761 else:
762 paa('--'+key, type=unicode, dest=value, nargs=nargs)
762 paa('--'+key, type=unicode_type, dest=value, nargs=nargs)
763 for key, (value, help) in flags.iteritems():
763 for key, (value, help) in flags.iteritems():
764 if key in self.aliases:
764 if key in self.aliases:
765 #
765 #
@@ -27,6 +27,7 b' import sys'
27 from IPython.config.configurable import Configurable
27 from IPython.config.configurable import Configurable
28 from IPython.core.error import UsageError
28 from IPython.core.error import UsageError
29
29
30 from IPython.utils.py3compat import string_types
30 from IPython.utils.traitlets import List, Instance
31 from IPython.utils.traitlets import List, Instance
31 from IPython.utils.warn import error
32 from IPython.utils.warn import error
32
33
@@ -131,7 +132,7 b' class Alias(object):'
131 raise InvalidAliasError("The name %s can't be aliased "
132 raise InvalidAliasError("The name %s can't be aliased "
132 "because it is another magic command." % self.name)
133 "because it is another magic command." % self.name)
133
134
134 if not (isinstance(self.cmd, basestring)):
135 if not (isinstance(self.cmd, string_types)):
135 raise InvalidAliasError("An alias command must be a string, "
136 raise InvalidAliasError("An alias command must be a string, "
136 "got: %r" % self.cmd)
137 "got: %r" % self.cmd)
137
138
@@ -82,7 +82,7 b' from IPython.utils import generics'
82 from IPython.utils import io
82 from IPython.utils import io
83 from IPython.utils.dir2 import dir2
83 from IPython.utils.dir2 import dir2
84 from IPython.utils.process import arg_split
84 from IPython.utils.process import arg_split
85 from IPython.utils.py3compat import builtin_mod
85 from IPython.utils.py3compat import builtin_mod, string_types
86 from IPython.utils.traitlets import CBool, Enum
86 from IPython.utils.traitlets import CBool, Enum
87
87
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
@@ -423,7 +423,7 b' def get__all__entries(obj):'
423 except:
423 except:
424 return []
424 return []
425
425
426 return [w for w in words if isinstance(w, basestring)]
426 return [w for w in words if isinstance(w, string_types)]
427
427
428
428
429 class IPCompleter(Completer):
429 class IPCompleter(Completer):
@@ -31,6 +31,7 b' from zipimport import zipimporter'
31 from IPython.core.completer import expand_user, compress_user
31 from IPython.core.completer import expand_user, compress_user
32 from IPython.core.error import TryNext
32 from IPython.core.error import TryNext
33 from IPython.utils._process_common import arg_split
33 from IPython.utils._process_common import arg_split
34 from IPython.utils.py3compat import string_types
34
35
35 # FIXME: this should be pulled in with the right call via the component system
36 # FIXME: this should be pulled in with the right call via the component system
36 from IPython import get_ipython
37 from IPython import get_ipython
@@ -189,7 +190,7 b' def quick_completer(cmd, completions):'
189 [d:\ipython]|3> foo ba
190 [d:\ipython]|3> foo ba
190 """
191 """
191
192
192 if isinstance(completions, basestring):
193 if isinstance(completions, string_types):
193 completions = completions.split()
194 completions = completions.split()
194
195
195 def do_complete(self, event):
196 def do_complete(self, event):
@@ -22,7 +22,8 b' from __future__ import print_function'
22 import os
22 import os
23 import struct
23 import struct
24
24
25 from IPython.utils.py3compat import string_types, cast_bytes_py2, cast_unicode
25 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
26 unicode_type)
26
27
27 from .displaypub import publish_display_data
28 from .displaypub import publish_display_data
28
29
@@ -300,7 +301,7 b' class DisplayObject(object):'
300
301
301 self.data = data
302 self.data = data
302 self.url = url
303 self.url = url
303 self.filename = None if filename is None else unicode(filename)
304 self.filename = None if filename is None else unicode_type(filename)
304
305
305 self.reload()
306 self.reload()
306
307
@@ -444,11 +445,11 b' class Javascript(DisplayObject):'
444 The full URLs of the css files should be given. A single css URL
445 The full URLs of the css files should be given. A single css URL
445 can also be given as a string.
446 can also be given as a string.
446 """
447 """
447 if isinstance(lib, basestring):
448 if isinstance(lib, string_types):
448 lib = [lib]
449 lib = [lib]
449 elif lib is None:
450 elif lib is None:
450 lib = []
451 lib = []
451 if isinstance(css, basestring):
452 if isinstance(css, string_types):
452 css = [css]
453 css = [css]
453 elif css is None:
454 elif css is None:
454 css = []
455 css = []
@@ -590,7 +591,7 b' class Image(DisplayObject):'
590 if data[:2] == _JPEG:
591 if data[:2] == _JPEG:
591 format = 'jpeg'
592 format = 'jpeg'
592
593
593 self.format = unicode(format).lower()
594 self.format = unicode_type(format).lower()
594 self.embed = embed if embed is not None else (url is None)
595 self.embed = embed if embed is not None else (url is None)
595
596
596 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
597 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
@@ -654,7 +655,7 b' class Image(DisplayObject):'
654 return self._data_and_metadata()
655 return self._data_and_metadata()
655
656
656 def _find_ext(self, s):
657 def _find_ext(self, s):
657 return unicode(s.split('.')[-1].lower())
658 return unicode_type(s.split('.')[-1].lower())
658
659
659
660
660 def clear_output(wait=False):
661 def clear_output(wait=False):
@@ -31,6 +31,7 b' from __future__ import print_function'
31
31
32 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
33 from IPython.utils import io
33 from IPython.utils import io
34 from IPython.utils.py3compat import string_types
34 from IPython.utils.traitlets import List
35 from IPython.utils.traitlets import List
35
36
36 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
@@ -58,7 +59,7 b' class DisplayPublisher(Configurable):'
58 Any metadata for the data.
59 Any metadata for the data.
59 """
60 """
60
61
61 if not isinstance(source, basestring):
62 if not isinstance(source, string_types):
62 raise TypeError('source must be a str, got: %r' % source)
63 raise TypeError('source must be a str, got: %r' % source)
63 if not isinstance(data, dict):
64 if not isinstance(data, dict):
64 raise TypeError('data must be a dict, got: %r' % data)
65 raise TypeError('data must be a dict, got: %r' % data)
@@ -68,7 +68,7 b' from IPython.utils.ipstruct import Struct'
68 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
68 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
69 from IPython.utils.pickleshare import PickleShareDB
69 from IPython.utils.pickleshare import PickleShareDB
70 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
71 from IPython.utils.py3compat import builtin_mod
71 from IPython.utils.py3compat import builtin_mod, unicode_type, string_types
72 from IPython.utils.strdispatch import StrDispatch
72 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.syspathcontext import prepended_to_syspath
73 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.text import (format_screen, LSString, SList,
74 from IPython.utils.text import (format_screen, LSString, SList,
@@ -1294,8 +1294,8 b' class InteractiveShell(SingletonConfigurable):'
1294 # We need a dict of name/value pairs to do namespace updates.
1294 # We need a dict of name/value pairs to do namespace updates.
1295 if isinstance(variables, dict):
1295 if isinstance(variables, dict):
1296 vdict = variables
1296 vdict = variables
1297 elif isinstance(variables, (basestring, list, tuple)):
1297 elif isinstance(variables, string_types+(list, tuple)):
1298 if isinstance(variables, basestring):
1298 if isinstance(variables, string_types):
1299 vlist = variables.split()
1299 vlist = variables.split()
1300 else:
1300 else:
1301 vlist = variables
1301 vlist = variables
@@ -1589,14 +1589,14 b' class InteractiveShell(SingletonConfigurable):'
1589 msg = "CustomTB must return list of strings, not %r" % stb
1589 msg = "CustomTB must return list of strings, not %r" % stb
1590 if stb is None:
1590 if stb is None:
1591 return []
1591 return []
1592 elif isinstance(stb, basestring):
1592 elif isinstance(stb, string_types):
1593 return [stb]
1593 return [stb]
1594 elif not isinstance(stb, list):
1594 elif not isinstance(stb, list):
1595 raise TypeError(msg)
1595 raise TypeError(msg)
1596 # it's a list
1596 # it's a list
1597 for line in stb:
1597 for line in stb:
1598 # check every element
1598 # check every element
1599 if not isinstance(line, basestring):
1599 if not isinstance(line, string_types):
1600 raise TypeError(msg)
1600 raise TypeError(msg)
1601 return stb
1601 return stb
1602
1602
@@ -2200,7 +2200,7 b' class InteractiveShell(SingletonConfigurable):'
2200
2200
2201 from IPython.core import macro
2201 from IPython.core import macro
2202
2202
2203 if isinstance(themacro, basestring):
2203 if isinstance(themacro, string_types):
2204 themacro = macro.Macro(themacro)
2204 themacro = macro.Macro(themacro)
2205 if not isinstance(themacro, macro.Macro):
2205 if not isinstance(themacro, macro.Macro):
2206 raise ValueError('A macro must be a string or a Macro instance.')
2206 raise ValueError('A macro must be a string or a Macro instance.')
@@ -2383,7 +2383,7 b' class InteractiveShell(SingletonConfigurable):'
2383 exc_info = {
2383 exc_info = {
2384 u'status' : 'error',
2384 u'status' : 'error',
2385 u'traceback' : stb,
2385 u'traceback' : stb,
2386 u'ename' : unicode(etype.__name__),
2386 u'ename' : unicode_type(etype.__name__),
2387 u'evalue' : py3compat.safe_unicode(evalue),
2387 u'evalue' : py3compat.safe_unicode(evalue),
2388 }
2388 }
2389
2389
@@ -3113,7 +3113,7 b' class InteractiveShell(SingletonConfigurable):'
3113 except Exception:
3113 except Exception:
3114 raise ValueError(("'%s' was not found in history, as a file, url, "
3114 raise ValueError(("'%s' was not found in history, as a file, url, "
3115 "nor in the user namespace.") % target)
3115 "nor in the user namespace.") % target)
3116 if isinstance(codeobj, basestring):
3116 if isinstance(codeobj, string_types):
3117 return codeobj
3117 return codeobj
3118 elif isinstance(codeobj, Macro):
3118 elif isinstance(codeobj, Macro):
3119 return codeobj.value
3119 return codeobj.value
@@ -52,6 +52,6 b' class Macro(object):'
52 def __add__(self, other):
52 def __add__(self, other):
53 if isinstance(other, Macro):
53 if isinstance(other, Macro):
54 return Macro(self.value + other.value)
54 return Macro(self.value + other.value)
55 elif isinstance(other, basestring):
55 elif isinstance(other, py3compat.string_types):
56 return Macro(self.value + other)
56 return Macro(self.value + other)
57 raise TypeError
57 raise TypeError
@@ -30,6 +30,7 b' from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2'
30 from IPython.external.decorator import decorator
30 from IPython.external.decorator import decorator
31 from IPython.utils.ipstruct import Struct
31 from IPython.utils.ipstruct import Struct
32 from IPython.utils.process import arg_split
32 from IPython.utils.process import arg_split
33 from IPython.utils.py3compat import string_types
33 from IPython.utils.text import dedent
34 from IPython.utils.text import dedent
34 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
35 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
35 from IPython.utils.warn import error
36 from IPython.utils.warn import error
@@ -197,7 +198,7 b' def _method_magic_marker(magic_kind):'
197 name = func.func_name
198 name = func.func_name
198 retval = decorator(call, func)
199 retval = decorator(call, func)
199 record_magic(magics, magic_kind, name, name)
200 record_magic(magics, magic_kind, name, name)
200 elif isinstance(arg, basestring):
201 elif isinstance(arg, string_types):
201 # Decorator called with arguments (@foo('bar'))
202 # Decorator called with arguments (@foo('bar'))
202 name = arg
203 name = arg
203 def mark(func, *a, **kw):
204 def mark(func, *a, **kw):
@@ -242,7 +243,7 b' def _function_magic_marker(magic_kind):'
242 name = func.func_name
243 name = func.func_name
243 ip.register_magic_function(func, magic_kind, name)
244 ip.register_magic_function(func, magic_kind, name)
244 retval = decorator(call, func)
245 retval = decorator(call, func)
245 elif isinstance(arg, basestring):
246 elif isinstance(arg, string_types):
246 # Decorator called with arguments (@foo('bar'))
247 # Decorator called with arguments (@foo('bar'))
247 name = arg
248 name = arg
248 def mark(func, *a, **kw):
249 def mark(func, *a, **kw):
@@ -533,7 +534,7 b' class Magics(Configurable):'
533 tab = self.magics[mtype] = {}
534 tab = self.magics[mtype] = {}
534 cls_tab = class_magics[mtype]
535 cls_tab = class_magics[mtype]
535 for magic_name, meth_name in cls_tab.iteritems():
536 for magic_name, meth_name in cls_tab.iteritems():
536 if isinstance(meth_name, basestring):
537 if isinstance(meth_name, string_types):
537 # it's a method name, grab it
538 # it's a method name, grab it
538 tab[magic_name] = getattr(self, meth_name)
539 tab[magic_name] = getattr(self, meth_name)
539 else:
540 else:
@@ -29,6 +29,7 b' from IPython.core.magic import Magics, magics_class, line_magic'
29 from IPython.core.oinspect import find_file, find_source_lines
29 from IPython.core.oinspect import find_file, find_source_lines
30 from IPython.testing.skipdoctest import skip_doctest
30 from IPython.testing.skipdoctest import skip_doctest
31 from IPython.utils import py3compat
31 from IPython.utils import py3compat
32 from IPython.utils.py3compat import string_types
32 from IPython.utils.contexts import preserve_keys
33 from IPython.utils.contexts import preserve_keys
33 from IPython.utils.path import get_py_filename, unquote_filename
34 from IPython.utils.path import get_py_filename, unquote_filename
34 from IPython.utils.warn import warn, error
35 from IPython.utils.warn import warn, error
@@ -396,7 +397,7 b' class CodeMagics(Magics):'
396
397
397 #print '*** args',args,'type',type(args) # dbg
398 #print '*** args',args,'type',type(args) # dbg
398 data = eval(args, shell.user_ns)
399 data = eval(args, shell.user_ns)
399 if not isinstance(data, basestring):
400 if not isinstance(data, string_types):
400 raise DataIsObject
401 raise DataIsObject
401
402
402 except (NameError,SyntaxError):
403 except (NameError,SyntaxError):
@@ -26,6 +26,7 b' from IPython.testing.skipdoctest import skip_doctest'
26 from IPython.utils.encoding import DEFAULT_ENCODING
26 from IPython.utils.encoding import DEFAULT_ENCODING
27 from IPython.utils.openpy import read_py_file
27 from IPython.utils.openpy import read_py_file
28 from IPython.utils.path import get_py_filename
28 from IPython.utils.path import get_py_filename
29 from IPython.utils.py3compat import unicode_type
29
30
30 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
31 # Magic implementation classes
32 # Magic implementation classes
@@ -462,7 +463,7 b' class NamespaceMagics(Magics):'
462 try:
463 try:
463 vstr = str(var)
464 vstr = str(var)
464 except UnicodeEncodeError:
465 except UnicodeEncodeError:
465 vstr = unicode(var).encode(DEFAULT_ENCODING,
466 vstr = unicode_type(var).encode(DEFAULT_ENCODING,
466 'backslashreplace')
467 'backslashreplace')
467 except:
468 except:
468 vstr = "<object with id %d (str() failed)>" % id(var)
469 vstr = "<object with id %d (str() failed)>" % id(var)
@@ -40,7 +40,7 b' from IPython.utils.dir2 import safe_hasattr'
40 from IPython.utils.text import indent
40 from IPython.utils.text import indent
41 from IPython.utils.wildcard import list_namespace
41 from IPython.utils.wildcard import list_namespace
42 from IPython.utils.coloransi import *
42 from IPython.utils.coloransi import *
43 from IPython.utils.py3compat import cast_unicode
43 from IPython.utils.py3compat import cast_unicode, string_types
44
44
45 #****************************************************************************
45 #****************************************************************************
46 # Builtin color schemes
46 # Builtin color schemes
@@ -130,7 +130,7 b' def getdoc(obj):'
130 pass
130 pass
131 else:
131 else:
132 # if we get extra info, we add it to the normal docstring.
132 # if we get extra info, we add it to the normal docstring.
133 if isinstance(ds, basestring):
133 if isinstance(ds, string_types):
134 return inspect.cleandoc(ds)
134 return inspect.cleandoc(ds)
135
135
136 try:
136 try:
@@ -98,7 +98,7 b' class LazyEvaluate(object):'
98 return str(self())
98 return str(self())
99
99
100 def __unicode__(self):
100 def __unicode__(self):
101 return unicode(self())
101 return py3compat.unicode_type(self())
102
102
103 def __format__(self, format_spec):
103 def __format__(self, format_spec):
104 return format(self(), format_spec)
104 return format(self(), format_spec)
@@ -18,6 +18,7 b' from IPython.core import completer'
18 from IPython.external.decorators import knownfailureif
18 from IPython.external.decorators import knownfailureif
19 from IPython.utils.tempdir import TemporaryDirectory
19 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.generics import complete_object
20 from IPython.utils.generics import complete_object
21 from IPython.utils.py3compat import string_types, unicode_type
21
22
22 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
23 # Test functions
24 # Test functions
@@ -83,7 +84,7 b' def test_line_split():'
83 check_line_split(sp, t)
84 check_line_split(sp, t)
84 # Ensure splitting works OK with unicode by re-running the tests with
85 # Ensure splitting works OK with unicode by re-running the tests with
85 # all inputs turned into unicode
86 # all inputs turned into unicode
86 check_line_split(sp, [ map(unicode, p) for p in t] )
87 check_line_split(sp, [ map(unicode_type, p) for p in t] )
87
88
88
89
89 def test_custom_completion_error():
90 def test_custom_completion_error():
@@ -104,13 +105,13 b' def test_unicode_completions():'
104 # Some strings that trigger different types of completion. Check them both
105 # Some strings that trigger different types of completion. Check them both
105 # in str and unicode forms
106 # in str and unicode forms
106 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
107 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
107 for t in s + map(unicode, s):
108 for t in s + map(unicode_type, s):
108 # We don't need to check exact completion values (they may change
109 # We don't need to check exact completion values (they may change
109 # depending on the state of the namespace, but at least no exceptions
110 # depending on the state of the namespace, but at least no exceptions
110 # should be thrown and the return value should be a pair of text, list
111 # should be thrown and the return value should be a pair of text, list
111 # values.
112 # values.
112 text, matches = ip.complete(t)
113 text, matches = ip.complete(t)
113 nt.assert_true(isinstance(text, basestring))
114 nt.assert_true(isinstance(text, string_types))
114 nt.assert_true(isinstance(matches, list))
115 nt.assert_true(isinstance(matches, list))
115
116
116
117
@@ -29,6 +29,7 b' from IPython.core import inputsplitter as isp'
29 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
29 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
30 from IPython.testing import tools as tt
30 from IPython.testing import tools as tt
31 from IPython.utils import py3compat
31 from IPython.utils import py3compat
32 from IPython.utils.py3compat import string_types
32
33
33 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
34 # Semi-complete examples (also used as tests)
35 # Semi-complete examples (also used as tests)
@@ -113,7 +114,7 b' def test_remove_comments():'
113
114
114 def test_get_input_encoding():
115 def test_get_input_encoding():
115 encoding = isp.get_input_encoding()
116 encoding = isp.get_input_encoding()
116 nt.assert_true(isinstance(encoding, basestring))
117 nt.assert_true(isinstance(encoding, string_types))
117 # simple-minded check that at least encoding a simple string works with the
118 # simple-minded check that at least encoding a simple string works with the
118 # encoding we got.
119 # encoding we got.
119 nt.assert_equal(u'test'.encode(encoding), b'test')
120 nt.assert_equal(u'test'.encode(encoding), b'test')
@@ -37,6 +37,7 b' import nose.tools as nt'
37 from IPython.testing.decorators import skipif, skip_win32, onlyif_unicode_paths
37 from IPython.testing.decorators import skipif, skip_win32, onlyif_unicode_paths
38 from IPython.testing import tools as tt
38 from IPython.testing import tools as tt
39 from IPython.utils import io
39 from IPython.utils import io
40 from IPython.utils.py3compat import unicode_type
40
41
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42 # Globals
43 # Globals
@@ -140,7 +141,7 b' class InteractiveShellTestCase(unittest.TestCase):'
140 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
141 assert isinstance(ip.user_ns['byte_str'], str) # string literals are byte strings by default
141 ip.run_cell('from __future__ import unicode_literals')
142 ip.run_cell('from __future__ import unicode_literals')
142 ip.run_cell(u'unicode_str = "a"')
143 ip.run_cell(u'unicode_str = "a"')
143 assert isinstance(ip.user_ns['unicode_str'], unicode) # strings literals are now unicode
144 assert isinstance(ip.user_ns['unicode_str'], unicode_type) # strings literals are now unicode
144 finally:
145 finally:
145 # Reset compiler flags so we don't mess up other tests.
146 # Reset compiler flags so we don't mess up other tests.
146 ip.compile.reset_compiler_flags()
147 ip.compile.reset_compiler_flags()
@@ -9,6 +9,7 b' from IPython.testing import tools as tt, decorators as dec'
9 from IPython.core.prompts import PromptManager, LazyEvaluate
9 from IPython.core.prompts import PromptManager, LazyEvaluate
10 from IPython.testing.globalipapp import get_ipython
10 from IPython.testing.globalipapp import get_ipython
11 from IPython.utils.tempdir import TemporaryDirectory
11 from IPython.utils.tempdir import TemporaryDirectory
12 from IPython.utils.py3compat import unicode_type
12
13
13 ip = get_ipython()
14 ip = get_ipython()
14
15
@@ -77,7 +78,7 b' class PromptTests(unittest.TestCase):'
77 u = u'ΓΌnicΓΈdΓ©'
78 u = u'ΓΌnicΓΈdΓ©'
78 lz = LazyEvaluate(lambda : u)
79 lz = LazyEvaluate(lambda : u)
79 # str(lz) would fail
80 # str(lz) would fail
80 self.assertEqual(unicode(lz), u)
81 self.assertEqual(unicode_type(lz), u)
81 self.assertEqual(format(lz), u)
82 self.assertEqual(format(lz), u)
82
83
83 def test_lazy_eval_nonascii_bytes(self):
84 def test_lazy_eval_nonascii_bytes(self):
@@ -93,7 +94,7 b' class PromptTests(unittest.TestCase):'
93 lz = LazyEvaluate(lambda : f)
94 lz = LazyEvaluate(lambda : f)
94
95
95 self.assertEqual(str(lz), str(f))
96 self.assertEqual(str(lz), str(f))
96 self.assertEqual(unicode(lz), unicode(f))
97 self.assertEqual(unicode_type(lz), unicode_type(f))
97 self.assertEqual(format(lz), str(f))
98 self.assertEqual(format(lz), str(f))
98 self.assertEqual(format(lz, '.1'), '0.5')
99 self.assertEqual(format(lz, '.1'), '0.5')
99
100
@@ -943,7 +943,7 b' class VerboseTB(TBTools):'
943 ColorsNormal, py3compat.cast_unicode(evalue_str))]
943 ColorsNormal, py3compat.cast_unicode(evalue_str))]
944 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
944 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
945 try:
945 try:
946 names = [w for w in dir(evalue) if isinstance(w, basestring)]
946 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
947 except:
947 except:
948 # Every now and then, an object with funny inernals blows up
948 # Every now and then, an object with funny inernals blows up
949 # when dir() is called on it. We do the best we can to report
949 # when dir() is called on it. We do the best we can to report
@@ -30,6 +30,7 b' from IPython.core.error import UsageError'
30 from IPython.core.magic import Magics, magics_class, line_magic
30 from IPython.core.magic import Magics, magics_class, line_magic
31 from IPython.testing.skipdoctest import skip_doctest
31 from IPython.testing.skipdoctest import skip_doctest
32 from IPython.utils.traitlets import Bool
32 from IPython.utils.traitlets import Bool
33 from IPython.utils.py3compat import string_types
33
34
34 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
35 # Functions and classes
36 # Functions and classes
@@ -193,7 +194,7 b' class StoreMagics(Magics):'
193 obj.__class__.__name__, fnam))
194 obj.__class__.__name__, fnam))
194
195
195
196
196 if not isinstance (obj, basestring):
197 if not isinstance (obj, string_types):
197 from pprint import pprint
198 from pprint import pprint
198 pprint(obj, fil)
199 pprint(obj, fil)
199 else:
200 else:
@@ -27,6 +27,7 b' maintained here for backwards compatablitiy with old SymPy versions.'
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28
28
29 from IPython.lib.latextools import latex_to_png
29 from IPython.lib.latextools import latex_to_png
30 from IPython.utils.py3compat import string_types
30
31
31 try:
32 try:
32 from sympy import pretty, latex
33 from sympy import pretty, latex
@@ -85,7 +86,7 b' def can_print_latex(o):'
85 if isinstance(o, (list, tuple, set, frozenset)):
86 if isinstance(o, (list, tuple, set, frozenset)):
86 return all(can_print_latex(i) for i in o)
87 return all(can_print_latex(i) for i in o)
87 elif isinstance(o, dict):
88 elif isinstance(o, dict):
88 return all((isinstance(i, basestring) or can_print_latex(i)) and can_print_latex(o[i]) for i in o)
89 return all((isinstance(i, string_types) or can_print_latex(i)) and can_print_latex(o[i]) for i in o)
89 elif isinstance(o,(sympy.Basic, sympy.matrices.Matrix, int, long, float)):
90 elif isinstance(o,(sympy.Basic, sympy.matrices.Matrix, int, long, float)):
90 return True
91 return True
91 return False
92 return False
@@ -145,8 +145,11 b' class TIMEOUT(ExceptionPexpect):'
145
145
146 PY3 = (sys.version_info[0] >= 3)
146 PY3 = (sys.version_info[0] >= 3)
147
147
148 unicode_type = str if PY3 else unicode
149 basestring_type = str if PY3 else basestring
150
148 def _cast_bytes(s, enc):
151 def _cast_bytes(s, enc):
149 if isinstance(s, unicode):
152 if isinstance(s, unicode_type):
150 return s.encode(enc)
153 return s.encode(enc)
151 return s
154 return s
152
155
@@ -249,16 +252,16 b' def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None'
249 while 1:
252 while 1:
250 try:
253 try:
251 index = child.expect (patterns)
254 index = child.expect (patterns)
252 if isinstance(child.after, basestring):
255 if isinstance(child.after, basestring_type):
253 child_result_list.append(child.before + child.after)
256 child_result_list.append(child.before + child.after)
254 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
257 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
255 child_result_list.append(child.before)
258 child_result_list.append(child.before)
256 if isinstance(responses[index], basestring):
259 if isinstance(responses[index], basestring_type):
257 child.send(responses[index])
260 child.send(responses[index])
258 elif type(responses[index]) is types.FunctionType:
261 elif type(responses[index]) is types.FunctionType:
259 callback_result = responses[index](locals())
262 callback_result = responses[index](locals())
260 sys.stdout.flush()
263 sys.stdout.flush()
261 if isinstance(callback_result, basestring):
264 if isinstance(callback_result, basestring_type):
262 child.send(callback_result)
265 child.send(callback_result)
263 elif callback_result:
266 elif callback_result:
264 break
267 break
@@ -1255,7 +1258,7 b' class spawnb(object):'
1255 compile_flags = compile_flags | re.IGNORECASE
1258 compile_flags = compile_flags | re.IGNORECASE
1256 compiled_pattern_list = []
1259 compiled_pattern_list = []
1257 for p in patterns:
1260 for p in patterns:
1258 if isinstance(p, (bytes, unicode)):
1261 if isinstance(p, (bytes, unicode_type)):
1259 p = self._cast_buffer_type(p)
1262 p = self._cast_buffer_type(p)
1260 compiled_pattern_list.append(re.compile(p, compile_flags))
1263 compiled_pattern_list.append(re.compile(p, compile_flags))
1261 elif p is EOF:
1264 elif p is EOF:
@@ -1272,7 +1275,7 b' class spawnb(object):'
1272
1275
1273 def _prepare_regex_pattern(self, p):
1276 def _prepare_regex_pattern(self, p):
1274 "Recompile unicode regexes as bytes regexes. Overridden in subclass."
1277 "Recompile unicode regexes as bytes regexes. Overridden in subclass."
1275 if isinstance(p.pattern, unicode):
1278 if isinstance(p.pattern, unicode_type):
1276 p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE)
1279 p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE)
1277 return p
1280 return p
1278
1281
@@ -1384,7 +1387,7 b' class spawnb(object):'
1384 This method is also useful when you don't want to have to worry about
1387 This method is also useful when you don't want to have to worry about
1385 escaping regular expression characters that you want to match."""
1388 escaping regular expression characters that you want to match."""
1386
1389
1387 if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF):
1390 if isinstance(pattern_list, (bytes, unicode_type)) or pattern_list in (TIMEOUT, EOF):
1388 pattern_list = [pattern_list]
1391 pattern_list = [pattern_list]
1389 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1392 return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize)
1390
1393
@@ -1608,7 +1611,7 b' class spawn(spawnb):'
1608 """This is the main class interface for Pexpect. Use this class to start
1611 """This is the main class interface for Pexpect. Use this class to start
1609 and control child applications."""
1612 and control child applications."""
1610
1613
1611 _buffer_type = unicode
1614 _buffer_type = unicode_type
1612 def _cast_buffer_type(self, s):
1615 def _cast_buffer_type(self, s):
1613 return _cast_unicode(s, self.encoding)
1616 return _cast_unicode(s, self.encoding)
1614 _empty_buffer = u''
1617 _empty_buffer = u''
@@ -34,6 +34,7 b' except ImportError:'
34
34
35 from IPython.config import Application
35 from IPython.config import Application
36 from IPython.utils.path import filefind
36 from IPython.utils.path import filefind
37 from IPython.utils.py3compat import string_types
37
38
38 # UF_HIDDEN is a stat flag not defined in the stat module.
39 # UF_HIDDEN is a stat flag not defined in the stat module.
39 # It is used by BSD to indicate hidden files.
40 # It is used by BSD to indicate hidden files.
@@ -307,7 +308,7 b' class FileFindHandler(web.StaticFileHandler):'
307 _static_paths = {}
308 _static_paths = {}
308
309
309 def initialize(self, path, default_filename=None):
310 def initialize(self, path, default_filename=None):
310 if isinstance(path, basestring):
311 if isinstance(path, string_types):
311 path = [path]
312 path = [path]
312
313
313 self.root = tuple(
314 self.root = tuple(
@@ -22,6 +22,7 b' import sqlite3'
22 from tornado import web
22 from tornado import web
23
23
24 from IPython.config.configurable import LoggingConfigurable
24 from IPython.config.configurable import LoggingConfigurable
25 from IPython.utils.py3compat import unicode_type
25
26
26 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
27 # Classes
28 # Classes
@@ -66,7 +67,7 b' class SessionManager(LoggingConfigurable):'
66
67
67 def new_session_id(self):
68 def new_session_id(self):
68 "Create a uuid for a new session"
69 "Create a uuid for a new session"
69 return unicode(uuid.uuid4())
70 return unicode_type(uuid.uuid4())
70
71
71 def create_session(self, name=None, path=None, kernel_id=None, ws_url=None):
72 def create_session(self, name=None, path=None, kernel_id=None, ws_url=None):
72 """Creates a session and returns its model"""
73 """Creates a session and returns its model"""
@@ -31,6 +31,7 b' from .channelsabc import ('
31 ShellChannelABC, IOPubChannelABC,
31 ShellChannelABC, IOPubChannelABC,
32 HBChannelABC, StdInChannelABC,
32 HBChannelABC, StdInChannelABC,
33 )
33 )
34 from IPython.utils.py3compat import string_types
34
35
35 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
36 # Constants and exceptions
37 # Constants and exceptions
@@ -53,7 +54,7 b' def validate_string_list(lst):'
53 if not isinstance(lst, list):
54 if not isinstance(lst, list):
54 raise ValueError('input %r must be a list' % lst)
55 raise ValueError('input %r must be a list' % lst)
55 for x in lst:
56 for x in lst:
56 if not isinstance(x, basestring):
57 if not isinstance(x, string_types):
57 raise ValueError('element %r in list must be a string' % x)
58 raise ValueError('element %r in list must be a string' % x)
58
59
59
60
@@ -62,9 +63,9 b' def validate_string_dict(dct):'
62
63
63 Raises ValueError if not."""
64 Raises ValueError if not."""
64 for k,v in dct.iteritems():
65 for k,v in dct.iteritems():
65 if not isinstance(k, basestring):
66 if not isinstance(k, string_types):
66 raise ValueError('key %r in dict must be a string' % k)
67 raise ValueError('key %r in dict must be a string' % k)
67 if not isinstance(v, basestring):
68 if not isinstance(v, string_types):
68 raise ValueError('value %r in dict must be a string' % v)
69 raise ValueError('value %r in dict must be a string' % v)
69
70
70
71
@@ -264,7 +265,7 b' class ShellChannel(ZMQSocketChannel):'
264
265
265
266
266 # Don't waste network traffic if inputs are invalid
267 # Don't waste network traffic if inputs are invalid
267 if not isinstance(code, basestring):
268 if not isinstance(code, string_types):
268 raise ValueError('code %r must be a string' % code)
269 raise ValueError('code %r must be a string' % code)
269 validate_string_list(user_variables)
270 validate_string_list(user_variables)
270 validate_string_dict(user_expressions)
271 validate_string_dict(user_expressions)
@@ -38,7 +38,8 b' from IPython.config import Configurable'
38 from IPython.core.profiledir import ProfileDir
38 from IPython.core.profiledir import ProfileDir
39 from IPython.utils.localinterfaces import localhost
39 from IPython.utils.localinterfaces import localhost
40 from IPython.utils.path import filefind, get_ipython_dir
40 from IPython.utils.path import filefind, get_ipython_dir
41 from IPython.utils.py3compat import str_to_bytes, bytes_to_str, cast_bytes_py2
41 from IPython.utils.py3compat import (str_to_bytes, bytes_to_str, cast_bytes_py2,
42 string_types)
42 from IPython.utils.traitlets import (
43 from IPython.utils.traitlets import (
43 Bool, Integer, Unicode, CaselessStrEnum,
44 Bool, Integer, Unicode, CaselessStrEnum,
44 )
45 )
@@ -347,7 +348,7 b' def tunnel_to_kernel(connection_info, sshserver, sshkey=None):'
347 (shell, iopub, stdin, hb) : ints
348 (shell, iopub, stdin, hb) : ints
348 The four ports on localhost that have been forwarded to the kernel.
349 The four ports on localhost that have been forwarded to the kernel.
349 """
350 """
350 if isinstance(connection_info, basestring):
351 if isinstance(connection_info, string_types):
351 # it's a path, unpack it
352 # it's a path, unpack it
352 with open(connection_info) as f:
353 with open(connection_info) as f:
353 connection_info = json.loads(f.read())
354 connection_info = json.loads(f.read())
@@ -28,6 +28,7 b' from IPython.utils.importstring import import_item'
28 from IPython.utils.traitlets import (
28 from IPython.utils.traitlets import (
29 Instance, Dict, Unicode, Any, DottedObjectName
29 Instance, Dict, Unicode, Any, DottedObjectName
30 )
30 )
31 from IPython.utils.py3compat import unicode_type
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
33 # Classes
34 # Classes
@@ -102,7 +103,7 b' class MultiKernelManager(LoggingConfigurable):'
102 km.start_kernel(stdout=PIPE, stderr=PIPE)
103 km.start_kernel(stdout=PIPE, stderr=PIPE)
103
104
104 """
105 """
105 kernel_id = kwargs.pop('kernel_id', unicode(uuid.uuid4()))
106 kernel_id = kwargs.pop('kernel_id', unicode_type(uuid.uuid4()))
106 if kernel_id in self:
107 if kernel_id in self:
107 raise DuplicateKernelError('Kernel already exists: %s' % kernel_id)
108 raise DuplicateKernelError('Kernel already exists: %s' % kernel_id)
108 # kernel_manager_factory is the constructor for the KernelManager
109 # kernel_manager_factory is the constructor for the KernelManager
@@ -18,6 +18,7 b' from IPython.kernel import KernelManager'
18 from IPython.utils.traitlets import (
18 from IPython.utils.traitlets import (
19 HasTraits, TraitError, Bool, Unicode, Dict, Integer, List, Enum, Any,
19 HasTraits, TraitError, Bool, Unicode, Dict, Integer, List, Enum, Any,
20 )
20 )
21 from IPython.utils.py3compat import string_types
21
22
22 from .utils import TIMEOUT, start_global_kernel, flush_channels, execute
23 from .utils import TIMEOUT, start_global_kernel, flush_channels, execute
23
24
@@ -155,7 +156,7 b' class KernelInfoReply(Reference):'
155
156
156 def _ipython_version_changed(self, name, old, new):
157 def _ipython_version_changed(self, name, old, new):
157 for v in new:
158 for v in new:
158 assert isinstance(v, int) or isinstance(v, basestring), \
159 assert isinstance(v, int) or isinstance(v, string_types), \
159 'expected int or string as version component, got {0!r}'.format(v)
160 'expected int or string as version component, got {0!r}'.format(v)
160
161
161
162
@@ -183,7 +184,7 b' class DisplayData(Reference):'
183 def _data_changed(self, name, old, new):
184 def _data_changed(self, name, old, new):
184 for k,v in new.iteritems():
185 for k,v in new.iteritems():
185 assert mime_pat.match(k)
186 assert mime_pat.match(k)
186 nt.assert_is_instance(v, basestring)
187 nt.assert_is_instance(v, string_types)
187
188
188
189
189 class PyOut(Reference):
190 class PyOut(Reference):
@@ -192,7 +193,7 b' class PyOut(Reference):'
192 def _data_changed(self, name, old, new):
193 def _data_changed(self, name, old, new):
193 for k,v in new.iteritems():
194 for k,v in new.iteritems():
194 assert mime_pat.match(k)
195 assert mime_pat.match(k)
195 nt.assert_is_instance(v, basestring)
196 nt.assert_is_instance(v, string_types)
196
197
197
198
198 references = {
199 references = {
@@ -19,6 +19,7 b' import zmq'
19 from .session import extract_header
19 from .session import extract_header
20
20
21 from IPython.utils import py3compat
21 from IPython.utils import py3compat
22 from IPython.utils.py3compat import unicode_type
22
23
23 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
24 # Globals
25 # Globals
@@ -180,7 +181,7 b' class OutStream(object):'
180 raise ValueError('I/O operation on closed file')
181 raise ValueError('I/O operation on closed file')
181 else:
182 else:
182 # Make sure that we're handling unicode
183 # Make sure that we're handling unicode
183 if not isinstance(string, unicode):
184 if not isinstance(string, unicode_type):
184 string = string.decode(self.encoding, 'replace')
185 string = string.decode(self.encoding, 'replace')
185
186
186 is_child = (self._check_mp_mode() == CHILD)
187 is_child = (self._check_mp_mode() == CHILD)
@@ -28,7 +28,7 b' from IPython.config.configurable import Configurable'
28 from IPython.core.error import StdinNotImplementedError
28 from IPython.core.error import StdinNotImplementedError
29 from IPython.core import release
29 from IPython.core import release
30 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31 from IPython.utils.py3compat import builtin_mod
31 from IPython.utils.py3compat import builtin_mod, unicode_type, string_types
32 from IPython.utils.jsonutil import json_clean
32 from IPython.utils.jsonutil import json_clean
33 from IPython.utils.traitlets import (
33 from IPython.utils.traitlets import (
34 Any, Instance, Float, Dict, List, Set, Integer, Unicode,
34 Any, Instance, Float, Dict, List, Set, Integer, Unicode,
@@ -89,7 +89,7 b' class Kernel(Configurable):'
89 ident = Unicode()
89 ident = Unicode()
90
90
91 def _ident_default(self):
91 def _ident_default(self):
92 return unicode(uuid.uuid4())
92 return unicode_type(uuid.uuid4())
93
93
94
94
95 # Private interface
95 # Private interface
@@ -649,7 +649,7 b' class Kernel(Configurable):'
649 def abort_request(self, stream, ident, parent):
649 def abort_request(self, stream, ident, parent):
650 """abort a specifig msg by id"""
650 """abort a specifig msg by id"""
651 msg_ids = parent['content'].get('msg_ids', None)
651 msg_ids = parent['content'].get('msg_ids', None)
652 if isinstance(msg_ids, basestring):
652 if isinstance(msg_ids, string_types):
653 msg_ids = [msg_ids]
653 msg_ids = [msg_ids]
654 if not msg_ids:
654 if not msg_ids:
655 self.abort_queues()
655 self.abort_queues()
@@ -49,7 +49,7 b' from IPython.config.configurable import Configurable, LoggingConfigurable'
49 from IPython.utils import io
49 from IPython.utils import io
50 from IPython.utils.importstring import import_item
50 from IPython.utils.importstring import import_item
51 from IPython.utils.jsonutil import extract_dates, squash_dates, date_default
51 from IPython.utils.jsonutil import extract_dates, squash_dates, date_default
52 from IPython.utils.py3compat import str_to_bytes, str_to_unicode
52 from IPython.utils.py3compat import str_to_bytes, str_to_unicode, unicode_type
53 from IPython.utils.traitlets import (CBytes, Unicode, Bool, Any, Instance, Set,
53 from IPython.utils.traitlets import (CBytes, Unicode, Bool, Any, Instance, Set,
54 DottedObjectName, CUnicode, Dict, Integer,
54 DottedObjectName, CUnicode, Dict, Integer,
55 TraitError,
55 TraitError,
@@ -65,12 +65,12 b' def squash_unicode(obj):'
65 if isinstance(obj,dict):
65 if isinstance(obj,dict):
66 for key in obj.keys():
66 for key in obj.keys():
67 obj[key] = squash_unicode(obj[key])
67 obj[key] = squash_unicode(obj[key])
68 if isinstance(key, unicode):
68 if isinstance(key, unicode_type):
69 obj[squash_unicode(key)] = obj.pop(key)
69 obj[squash_unicode(key)] = obj.pop(key)
70 elif isinstance(obj, list):
70 elif isinstance(obj, list):
71 for i,v in enumerate(obj):
71 for i,v in enumerate(obj):
72 obj[i] = squash_unicode(v)
72 obj[i] = squash_unicode(v)
73 elif isinstance(obj, unicode):
73 elif isinstance(obj, unicode_type):
74 obj = obj.encode('utf8')
74 obj = obj.encode('utf8')
75 return obj
75 return obj
76
76
@@ -288,7 +288,7 b' class Session(Configurable):'
288 session = CUnicode(u'', config=True,
288 session = CUnicode(u'', config=True,
289 help="""The UUID identifying this session.""")
289 help="""The UUID identifying this session.""")
290 def _session_default(self):
290 def _session_default(self):
291 u = unicode(uuid.uuid4())
291 u = unicode_type(uuid.uuid4())
292 self.bsession = u.encode('ascii')
292 self.bsession = u.encode('ascii')
293 return u
293 return u
294
294
@@ -538,7 +538,7 b' class Session(Configurable):'
538 elif isinstance(content, bytes):
538 elif isinstance(content, bytes):
539 # content is already packed, as in a relayed message
539 # content is already packed, as in a relayed message
540 pass
540 pass
541 elif isinstance(content, unicode):
541 elif isinstance(content, unicode_type):
542 # should be bytes, but JSON often spits out unicode
542 # should be bytes, but JSON often spits out unicode
543 content = content.encode('utf8')
543 content = content.encode('utf8')
544 else:
544 else:
@@ -24,6 +24,7 b' import nose.tools as nt'
24
24
25 from IPython.kernel import BlockingKernelClient
25 from IPython.kernel import BlockingKernelClient
26 from IPython.utils import path, py3compat
26 from IPython.utils import path, py3compat
27 from IPython.utils.py3compat import unicode_type
27
28
28 #-------------------------------------------------------------------------------
29 #-------------------------------------------------------------------------------
29 # Tests
30 # Tests
@@ -183,7 +184,7 b' def test_embed_kernel_reentrant():'
183 msg = client.get_shell_msg(block=True, timeout=TIMEOUT)
184 msg = client.get_shell_msg(block=True, timeout=TIMEOUT)
184 content = msg['content']
185 content = msg['content']
185 nt.assert_true(content['found'])
186 nt.assert_true(content['found'])
186 nt.assert_equal(content['string_form'], unicode(i))
187 nt.assert_equal(content['string_form'], unicode_type(i))
187
188
188 # exit from embed_kernel
189 # exit from embed_kernel
189 client.execute("get_ipython().exit_now = True")
190 client.execute("get_ipython().exit_now = True")
@@ -44,6 +44,7 b' from IPython.utils import openpy'
44 from IPython.utils.jsonutil import json_clean, encode_images
44 from IPython.utils.jsonutil import json_clean, encode_images
45 from IPython.utils.process import arg_split
45 from IPython.utils.process import arg_split
46 from IPython.utils import py3compat
46 from IPython.utils import py3compat
47 from IPython.utils.py3compat import unicode_type
47 from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes, Any
48 from IPython.utils.traitlets import Instance, Type, Dict, CBool, CBytes, Any
48 from IPython.utils.warn import error
49 from IPython.utils.warn import error
49 from IPython.kernel.zmq.displayhook import ZMQShellDisplayHook
50 from IPython.kernel.zmq.displayhook import ZMQShellDisplayHook
@@ -555,7 +556,7 b' class ZMQInteractiveShell(InteractiveShell):'
555
556
556 exc_content = {
557 exc_content = {
557 u'traceback' : stb,
558 u'traceback' : stb,
558 u'ename' : unicode(etype.__name__),
559 u'ename' : unicode_type(etype.__name__),
559 u'evalue' : py3compat.safe_unicode(evalue),
560 u'evalue' : py3compat.safe_unicode(evalue),
560 }
561 }
561
562
@@ -37,6 +37,7 b' import threading'
37 from IPython import get_ipython
37 from IPython import get_ipython
38 from IPython.core.ultratb import AutoFormattedTB
38 from IPython.core.ultratb import AutoFormattedTB
39 from IPython.utils.warn import error
39 from IPython.utils.warn import error
40 from IPython.utils.py3compat import string_types
40
41
41
42
42 class BackgroundJobManager(object):
43 class BackgroundJobManager(object):
@@ -171,7 +172,7 b' class BackgroundJobManager(object):'
171 if callable(func_or_exp):
172 if callable(func_or_exp):
172 kw = kwargs.get('kw',{})
173 kw = kwargs.get('kw',{})
173 job = BackgroundJobFunc(func_or_exp,*args,**kw)
174 job = BackgroundJobFunc(func_or_exp,*args,**kw)
174 elif isinstance(func_or_exp, basestring):
175 elif isinstance(func_or_exp, string_types):
175 if not args:
176 if not args:
176 frame = sys._getframe(1)
177 frame = sys._getframe(1)
177 glob, loc = frame.f_globals, frame.f_locals
178 glob, loc = frame.f_globals, frame.f_locals
@@ -199,7 +199,7 b' class InteractiveRunner(object):'
199
199
200 # if the source is a string, chop it up in lines so we can iterate
200 # if the source is a string, chop it up in lines so we can iterate
201 # over it just as if it were an open file.
201 # over it just as if it were an open file.
202 if isinstance(source, basestring):
202 if isinstance(source, py3compat.string_types):
203 source = source.splitlines(True)
203 source = source.splitlines(True)
204
204
205 if self.echo:
205 if self.echo:
@@ -17,6 +17,7 b' from functools import wraps'
17
17
18 from IPython.nbformat.v3.nbbase import NotebookNode
18 from IPython.nbformat.v3.nbbase import NotebookNode
19 from IPython.config import Config
19 from IPython.config import Config
20 from IPython.utils.py3compat import string_types
20
21
21 from .exporter import Exporter
22 from .exporter import Exporter
22 from .templateexporter import TemplateExporter
23 from .templateexporter import TemplateExporter
@@ -116,7 +117,7 b' def export(exporter, nb, **kw):'
116 #Try to convert the notebook using the appropriate conversion function.
117 #Try to convert the notebook using the appropriate conversion function.
117 if isinstance(nb, NotebookNode):
118 if isinstance(nb, NotebookNode):
118 output, resources = exporter_instance.from_notebook_node(nb, resources)
119 output, resources = exporter_instance.from_notebook_node(nb, resources)
119 elif isinstance(nb, basestring):
120 elif isinstance(nb, string_types):
120 output, resources = exporter_instance.from_filename(nb, resources)
121 output, resources = exporter_instance.from_filename(nb, resources)
121 else:
122 else:
122 output, resources = exporter_instance.from_file(nb, resources)
123 output, resources = exporter_instance.from_file(nb, resources)
@@ -22,6 +22,8 b' from __future__ import print_function'
22 from xml.etree import ElementTree as ET
22 from xml.etree import ElementTree as ET
23 import re
23 import re
24
24
25 from IPython.utils.py3compat import unicode_type
26
25 from IPython.nbformat.v3 import (
27 from IPython.nbformat.v3 import (
26 NotebookNode,
28 NotebookNode,
27 new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
29 new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
@@ -106,7 +108,7 b' def reads(s, format, **kwargs):'
106 nb : NotebookNode
108 nb : NotebookNode
107 The notebook that was read.
109 The notebook that was read.
108 """
110 """
109 format = unicode(format)
111 format = unicode_type(format)
110 if format == u'json' or format == u'ipynb':
112 if format == u'json' or format == u'ipynb':
111 return reads_json(s, **kwargs)
113 return reads_json(s, **kwargs)
112 elif format == u'py':
114 elif format == u'py':
@@ -132,7 +134,7 b' def writes(nb, format, **kwargs):'
132 s : unicode
134 s : unicode
133 The notebook string.
135 The notebook string.
134 """
136 """
135 format = unicode(format)
137 format = unicode_type(format)
136 if format == u'json' or format == u'ipynb':
138 if format == u'json' or format == u'ipynb':
137 return writes_json(nb, **kwargs)
139 return writes_json(nb, **kwargs)
138 elif format == u'py':
140 elif format == u'py':
@@ -20,6 +20,7 b' import pprint'
20 import uuid
20 import uuid
21
21
22 from IPython.utils.ipstruct import Struct
22 from IPython.utils.ipstruct import Struct
23 from IPython.utils.py3compat import unicode_type
23
24
24 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
25 # Code
26 # Code
@@ -46,7 +47,7 b' def new_code_cell(code=None, prompt_number=None):'
46 cell = NotebookNode()
47 cell = NotebookNode()
47 cell.cell_type = u'code'
48 cell.cell_type = u'code'
48 if code is not None:
49 if code is not None:
49 cell.code = unicode(code)
50 cell.code = unicode_type(code)
50 if prompt_number is not None:
51 if prompt_number is not None:
51 cell.prompt_number = int(prompt_number)
52 cell.prompt_number = int(prompt_number)
52 return cell
53 return cell
@@ -56,7 +57,7 b' def new_text_cell(text=None):'
56 """Create a new text cell."""
57 """Create a new text cell."""
57 cell = NotebookNode()
58 cell = NotebookNode()
58 if text is not None:
59 if text is not None:
59 cell.text = unicode(text)
60 cell.text = unicode_type(text)
60 cell.cell_type = u'text'
61 cell.cell_type = u'text'
61 return cell
62 return cell
62
63
@@ -25,6 +25,7 b' import pprint'
25 import uuid
25 import uuid
26
26
27 from IPython.utils.ipstruct import Struct
27 from IPython.utils.ipstruct import Struct
28 from IPython.utils.py3compat import unicode_type
28
29
29 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
30 # Code
31 # Code
@@ -53,25 +54,25 b' def new_output(output_type=None, output_text=None, output_png=None,'
53 """Create a new code cell with input and output"""
54 """Create a new code cell with input and output"""
54 output = NotebookNode()
55 output = NotebookNode()
55 if output_type is not None:
56 if output_type is not None:
56 output.output_type = unicode(output_type)
57 output.output_type = unicode_type(output_type)
57
58
58 if output_type != 'pyerr':
59 if output_type != 'pyerr':
59 if output_text is not None:
60 if output_text is not None:
60 output.text = unicode(output_text)
61 output.text = unicode_type(output_text)
61 if output_png is not None:
62 if output_png is not None:
62 output.png = bytes(output_png)
63 output.png = bytes(output_png)
63 if output_jpeg is not None:
64 if output_jpeg is not None:
64 output.jpeg = bytes(output_jpeg)
65 output.jpeg = bytes(output_jpeg)
65 if output_html is not None:
66 if output_html is not None:
66 output.html = unicode(output_html)
67 output.html = unicode_type(output_html)
67 if output_svg is not None:
68 if output_svg is not None:
68 output.svg = unicode(output_svg)
69 output.svg = unicode_type(output_svg)
69 if output_latex is not None:
70 if output_latex is not None:
70 output.latex = unicode(output_latex)
71 output.latex = unicode_type(output_latex)
71 if output_json is not None:
72 if output_json is not None:
72 output.json = unicode(output_json)
73 output.json = unicode_type(output_json)
73 if output_javascript is not None:
74 if output_javascript is not None:
74 output.javascript = unicode(output_javascript)
75 output.javascript = unicode_type(output_javascript)
75
76
76 if output_type == u'pyout':
77 if output_type == u'pyout':
77 if prompt_number is not None:
78 if prompt_number is not None:
@@ -79,11 +80,11 b' def new_output(output_type=None, output_text=None, output_png=None,'
79
80
80 if output_type == u'pyerr':
81 if output_type == u'pyerr':
81 if etype is not None:
82 if etype is not None:
82 output.etype = unicode(etype)
83 output.etype = unicode_type(etype)
83 if evalue is not None:
84 if evalue is not None:
84 output.evalue = unicode(evalue)
85 output.evalue = unicode_type(evalue)
85 if traceback is not None:
86 if traceback is not None:
86 output.traceback = [unicode(frame) for frame in list(traceback)]
87 output.traceback = [unicode_type(frame) for frame in list(traceback)]
87
88
88 return output
89 return output
89
90
@@ -94,9 +95,9 b' def new_code_cell(input=None, prompt_number=None, outputs=None,'
94 cell = NotebookNode()
95 cell = NotebookNode()
95 cell.cell_type = u'code'
96 cell.cell_type = u'code'
96 if language is not None:
97 if language is not None:
97 cell.language = unicode(language)
98 cell.language = unicode_type(language)
98 if input is not None:
99 if input is not None:
99 cell.input = unicode(input)
100 cell.input = unicode_type(input)
100 if prompt_number is not None:
101 if prompt_number is not None:
101 cell.prompt_number = int(prompt_number)
102 cell.prompt_number = int(prompt_number)
102 if outputs is None:
103 if outputs is None:
@@ -112,9 +113,9 b' def new_text_cell(cell_type, source=None, rendered=None):'
112 """Create a new text cell."""
113 """Create a new text cell."""
113 cell = NotebookNode()
114 cell = NotebookNode()
114 if source is not None:
115 if source is not None:
115 cell.source = unicode(source)
116 cell.source = unicode_type(source)
116 if rendered is not None:
117 if rendered is not None:
117 cell.rendered = unicode(rendered)
118 cell.rendered = unicode_type(rendered)
118 cell.cell_type = cell_type
119 cell.cell_type = cell_type
119 return cell
120 return cell
120
121
@@ -123,7 +124,7 b' def new_worksheet(name=None, cells=None):'
123 """Create a worksheet by name with with a list of cells."""
124 """Create a worksheet by name with with a list of cells."""
124 ws = NotebookNode()
125 ws = NotebookNode()
125 if name is not None:
126 if name is not None:
126 ws.name = unicode(name)
127 ws.name = unicode_type(name)
127 if cells is None:
128 if cells is None:
128 ws.cells = []
129 ws.cells = []
129 else:
130 else:
@@ -151,29 +152,29 b' def new_metadata(name=None, authors=None, license=None, created=None,'
151 """Create a new metadata node."""
152 """Create a new metadata node."""
152 metadata = NotebookNode()
153 metadata = NotebookNode()
153 if name is not None:
154 if name is not None:
154 metadata.name = unicode(name)
155 metadata.name = unicode_type(name)
155 if authors is not None:
156 if authors is not None:
156 metadata.authors = list(authors)
157 metadata.authors = list(authors)
157 if created is not None:
158 if created is not None:
158 metadata.created = unicode(created)
159 metadata.created = unicode_type(created)
159 if modified is not None:
160 if modified is not None:
160 metadata.modified = unicode(modified)
161 metadata.modified = unicode_type(modified)
161 if license is not None:
162 if license is not None:
162 metadata.license = unicode(license)
163 metadata.license = unicode_type(license)
163 if gistid is not None:
164 if gistid is not None:
164 metadata.gistid = unicode(gistid)
165 metadata.gistid = unicode_type(gistid)
165 return metadata
166 return metadata
166
167
167 def new_author(name=None, email=None, affiliation=None, url=None):
168 def new_author(name=None, email=None, affiliation=None, url=None):
168 """Create a new author."""
169 """Create a new author."""
169 author = NotebookNode()
170 author = NotebookNode()
170 if name is not None:
171 if name is not None:
171 author.name = unicode(name)
172 author.name = unicode_type(name)
172 if email is not None:
173 if email is not None:
173 author.email = unicode(email)
174 author.email = unicode_type(email)
174 if affiliation is not None:
175 if affiliation is not None:
175 author.affiliation = unicode(affiliation)
176 author.affiliation = unicode_type(affiliation)
176 if url is not None:
177 if url is not None:
177 author.url = unicode(url)
178 author.url = unicode_type(url)
178 return author
179 return author
179
180
@@ -17,6 +17,7 b' Authors:'
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import re
19 import re
20 from IPython.utils.py3compat import unicode_type
20 from .rwbase import NotebookReader, NotebookWriter
21 from .rwbase import NotebookReader, NotebookWriter
21 from .nbbase import new_code_cell, new_text_cell, new_worksheet, new_notebook
22 from .nbbase import new_code_cell, new_text_cell, new_worksheet, new_notebook
22
23
@@ -136,7 +137,7 b' class PyWriter(NotebookWriter):'
136 lines.extend([u'# ' + line for line in input.splitlines()])
137 lines.extend([u'# ' + line for line in input.splitlines()])
137 lines.append(u'')
138 lines.append(u'')
138 lines.append('')
139 lines.append('')
139 return unicode('\n'.join(lines))
140 return unicode_type('\n'.join(lines))
140
141
141
142
142 _reader = PyReader()
143 _reader = PyReader()
@@ -20,6 +20,7 b' from base64 import encodestring, decodestring'
20 import warnings
20 import warnings
21 from xml.etree import ElementTree as ET
21 from xml.etree import ElementTree as ET
22
22
23 from IPython.utils.py3compat import unicode_type
23 from .rwbase import NotebookReader, NotebookWriter
24 from .rwbase import NotebookReader, NotebookWriter
24 from .nbbase import (
25 from .nbbase import (
25 new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output,
26 new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output,
@@ -71,7 +72,7 b' def _get_int(e, tag):'
71 def _set_int(nbnode, attr, parent, tag):
72 def _set_int(nbnode, attr, parent, tag):
72 if attr in nbnode:
73 if attr in nbnode:
73 e = ET.SubElement(parent, tag)
74 e = ET.SubElement(parent, tag)
74 e.text = unicode(nbnode[attr])
75 e.text = unicode_type(nbnode[attr])
75
76
76
77
77 def _get_bool(e, tag):
78 def _get_bool(e, tag):
@@ -19,7 +19,7 b' Authors:'
19 from base64 import encodestring, decodestring
19 from base64 import encodestring, decodestring
20 import pprint
20 import pprint
21
21
22 from IPython.utils.py3compat import str_to_bytes
22 from IPython.utils.py3compat import str_to_bytes, unicode_type, string_types
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Code
25 # Code
@@ -83,17 +83,17 b' def split_lines(nb):'
83 for ws in nb.worksheets:
83 for ws in nb.worksheets:
84 for cell in ws.cells:
84 for cell in ws.cells:
85 if cell.cell_type == 'code':
85 if cell.cell_type == 'code':
86 if 'input' in cell and isinstance(cell.input, basestring):
86 if 'input' in cell and isinstance(cell.input, string_types):
87 cell.input = cell.input.splitlines()
87 cell.input = cell.input.splitlines()
88 for output in cell.outputs:
88 for output in cell.outputs:
89 for key in _multiline_outputs:
89 for key in _multiline_outputs:
90 item = output.get(key, None)
90 item = output.get(key, None)
91 if isinstance(item, basestring):
91 if isinstance(item, string_types):
92 output[key] = item.splitlines()
92 output[key] = item.splitlines()
93 else: # text cell
93 else: # text cell
94 for key in ['source', 'rendered']:
94 for key in ['source', 'rendered']:
95 item = cell.get(key, None)
95 item = cell.get(key, None)
96 if isinstance(item, basestring):
96 if isinstance(item, string_types):
97 cell[key] = item.splitlines()
97 cell[key] = item.splitlines()
98 return nb
98 return nb
99
99
@@ -110,11 +110,11 b' def base64_decode(nb):'
110 if cell.cell_type == 'code':
110 if cell.cell_type == 'code':
111 for output in cell.outputs:
111 for output in cell.outputs:
112 if 'png' in output:
112 if 'png' in output:
113 if isinstance(output.png, unicode):
113 if isinstance(output.png, unicode_type):
114 output.png = output.png.encode('ascii')
114 output.png = output.png.encode('ascii')
115 output.png = decodestring(output.png)
115 output.png = decodestring(output.png)
116 if 'jpeg' in output:
116 if 'jpeg' in output:
117 if isinstance(output.jpeg, unicode):
117 if isinstance(output.jpeg, unicode_type):
118 output.jpeg = output.jpeg.encode('ascii')
118 output.jpeg = output.jpeg.encode('ascii')
119 output.jpeg = decodestring(output.jpeg)
119 output.jpeg = decodestring(output.jpeg)
120 return nb
120 return nb
@@ -25,7 +25,7 b' import pprint'
25 import uuid
25 import uuid
26
26
27 from IPython.utils.ipstruct import Struct
27 from IPython.utils.ipstruct import Struct
28 from IPython.utils.py3compat import cast_unicode
28 from IPython.utils.py3compat import cast_unicode, unicode_type
29
29
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31 # Code
31 # Code
@@ -58,7 +58,7 b' def new_output(output_type=None, output_text=None, output_png=None,'
58 """Create a new code cell with input and output"""
58 """Create a new code cell with input and output"""
59 output = NotebookNode()
59 output = NotebookNode()
60 if output_type is not None:
60 if output_type is not None:
61 output.output_type = unicode(output_type)
61 output.output_type = unicode_type(output_type)
62
62
63 if metadata is None:
63 if metadata is None:
64 metadata = {}
64 metadata = {}
@@ -20,8 +20,7 b' from base64 import encodestring, decodestring'
20 import pprint
20 import pprint
21
21
22 from IPython.utils import py3compat
22 from IPython.utils import py3compat
23
23 from IPython.utils.py3compat import str_to_bytes, unicode_type, string_types
24 str_to_bytes = py3compat.str_to_bytes
25
24
26 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
27 # Code
26 # Code
@@ -103,17 +102,17 b' def split_lines(nb):'
103 for ws in nb.worksheets:
102 for ws in nb.worksheets:
104 for cell in ws.cells:
103 for cell in ws.cells:
105 if cell.cell_type == 'code':
104 if cell.cell_type == 'code':
106 if 'input' in cell and isinstance(cell.input, basestring):
105 if 'input' in cell and isinstance(cell.input, string_types):
107 cell.input = cell.input.splitlines(True)
106 cell.input = cell.input.splitlines(True)
108 for output in cell.outputs:
107 for output in cell.outputs:
109 for key in _multiline_outputs:
108 for key in _multiline_outputs:
110 item = output.get(key, None)
109 item = output.get(key, None)
111 if isinstance(item, basestring):
110 if isinstance(item, string_types):
112 output[key] = item.splitlines(True)
111 output[key] = item.splitlines(True)
113 else: # text, heading cell
112 else: # text, heading cell
114 for key in ['source', 'rendered']:
113 for key in ['source', 'rendered']:
115 item = cell.get(key, None)
114 item = cell.get(key, None)
116 if isinstance(item, basestring):
115 if isinstance(item, string_types):
117 cell[key] = item.splitlines(True)
116 cell[key] = item.splitlines(True)
118 return nb
117 return nb
119
118
@@ -130,11 +129,11 b' def base64_decode(nb):'
130 if cell.cell_type == 'code':
129 if cell.cell_type == 'code':
131 for output in cell.outputs:
130 for output in cell.outputs:
132 if 'png' in output:
131 if 'png' in output:
133 if isinstance(output.png, unicode):
132 if isinstance(output.png, unicode_type):
134 output.png = output.png.encode('ascii')
133 output.png = output.png.encode('ascii')
135 output.png = decodestring(output.png)
134 output.png = decodestring(output.png)
136 if 'jpeg' in output:
135 if 'jpeg' in output:
137 if isinstance(output.jpeg, unicode):
136 if isinstance(output.jpeg, unicode_type):
138 output.jpeg = output.jpeg.encode('ascii')
137 output.jpeg = output.jpeg.encode('ascii')
139 output.jpeg = decodestring(output.jpeg)
138 output.jpeg = decodestring(output.jpeg)
140 return nb
139 return nb
@@ -168,7 +167,7 b' class NotebookReader(object):'
168 def read(self, fp, **kwargs):
167 def read(self, fp, **kwargs):
169 """Read a notebook from a file like object"""
168 """Read a notebook from a file like object"""
170 nbs = fp.read()
169 nbs = fp.read()
171 if not py3compat.PY3 and not isinstance(nbs, unicode):
170 if not py3compat.PY3 and not isinstance(nbs, unicode_type):
172 nbs = py3compat.str_to_unicode(nbs)
171 nbs = py3compat.str_to_unicode(nbs)
173 return self.reads(nbs, **kwargs)
172 return self.reads(nbs, **kwargs)
174
173
@@ -183,7 +182,7 b' class NotebookWriter(object):'
183 def write(self, nb, fp, **kwargs):
182 def write(self, nb, fp, **kwargs):
184 """Write a notebook to a file like object"""
183 """Write a notebook to a file like object"""
185 nbs = self.writes(nb,**kwargs)
184 nbs = self.writes(nb,**kwargs)
186 if not py3compat.PY3 and not isinstance(nbs, unicode):
185 if not py3compat.PY3 and not isinstance(nbs, unicode_type):
187 # this branch is likely only taken for JSON on Python 2
186 # this branch is likely only taken for JSON on Python 2
188 nbs = py3compat.str_to_unicode(nbs)
187 nbs = py3compat.str_to_unicode(nbs)
189 return fp.write(nbs)
188 return fp.write(nbs)
@@ -2,6 +2,7 b' import pprint'
2 from base64 import decodestring
2 from base64 import decodestring
3 from unittest import TestCase
3 from unittest import TestCase
4
4
5 from IPython.utils.py3compat import unicode_type
5 from ..nbjson import reads, writes
6 from ..nbjson import reads, writes
6 from .. import nbjson
7 from .. import nbjson
7 from .nbexamples import nb0
8 from .nbexamples import nb0
@@ -42,7 +43,7 b' class TestJSON(formattest.NBFormatTest, TestCase):'
42 if 'png' in output:
43 if 'png' in output:
43 found_png = True
44 found_png = True
44 pngdata = output['png']
45 pngdata = output['png']
45 self.assertEqual(type(pngdata), unicode)
46 self.assertEqual(type(pngdata), unicode_type)
46 # test that it is valid b64 data
47 # test that it is valid b64 data
47 b64bytes = pngdata.encode('ascii')
48 b64bytes = pngdata.encode('ascii')
48 raw_bytes = decodestring(b64bytes)
49 raw_bytes = decodestring(b64bytes)
@@ -60,7 +61,7 b' class TestJSON(formattest.NBFormatTest, TestCase):'
60 if 'jpeg' in output:
61 if 'jpeg' in output:
61 found_jpeg = True
62 found_jpeg = True
62 jpegdata = output['jpeg']
63 jpegdata = output['jpeg']
63 self.assertEqual(type(jpegdata), unicode)
64 self.assertEqual(type(jpegdata), unicode_type)
64 # test that it is valid b64 data
65 # test that it is valid b64 data
65 b64bytes = jpegdata.encode('ascii')
66 b64bytes = jpegdata.encode('ascii')
66 raw_bytes = decodestring(b64bytes)
67 raw_bytes = decodestring(b64bytes)
@@ -2,6 +2,8 b''
2
2
3 from unittest import TestCase
3 from unittest import TestCase
4
4
5 from IPython.utils.py3compat import string_types
6
5 from . import formattest
7 from . import formattest
6
8
7 from .. import nbpy
9 from .. import nbpy
@@ -31,7 +33,7 b' class TestPy(formattest.NBFormatTest, TestCase):'
31 for a,b in zip(da, db):
33 for a,b in zip(da, db):
32 self.assertSubset(a,b)
34 self.assertSubset(a,b)
33 else:
35 else:
34 if isinstance(da, basestring) and isinstance(db, basestring):
36 if isinstance(da, string_types) and isinstance(db, string_types):
35 # pyfile is not sensitive to preserving leading/trailing
37 # pyfile is not sensitive to preserving leading/trailing
36 # newlines in blocks through roundtrip
38 # newlines in blocks through roundtrip
37 da = da.strip('\n')
39 da = da.strip('\n')
@@ -20,8 +20,6 b' Authors:'
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from __future__ import with_statement
24
25 import os
23 import os
26 import logging
24 import logging
27 import re
25 import re
@@ -38,8 +36,9 b' from IPython.core.application import ('
38 base_flags as base_ip_flags
36 base_flags as base_ip_flags
39 )
37 )
40 from IPython.utils.path import expand_path
38 from IPython.utils.path import expand_path
39 from IPython.utils.py3compat import unicode_type
41
40
42 from IPython.utils.traitlets import Unicode, Bool, Instance, Dict, List
41 from IPython.utils.traitlets import Unicode, Bool, Instance, Dict
43
42
44 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
45 # Module errors
44 # Module errors
@@ -110,7 +109,7 b' class BaseParallelApplication(BaseIPythonApplication):'
110 help='Set the working dir for the process.'
109 help='Set the working dir for the process.'
111 )
110 )
112 def _work_dir_changed(self, name, old, new):
111 def _work_dir_changed(self, name, old, new):
113 self.work_dir = unicode(expand_path(new))
112 self.work_dir = unicode_type(expand_path(new))
114
113
115 log_to_file = Bool(config=True,
114 log_to_file = Bool(config=True,
116 help="whether to log to a file")
115 help="whether to log to a file")
@@ -157,7 +156,7 b' class BaseParallelApplication(BaseIPythonApplication):'
157
156
158 def to_work_dir(self):
157 def to_work_dir(self):
159 wd = self.work_dir
158 wd = self.work_dir
160 if unicode(wd) != os.getcwdu():
159 if unicode_type(wd) != os.getcwdu():
161 os.chdir(wd)
160 os.chdir(wd)
162 self.log.info("Changing to working dir: %s" % wd)
161 self.log.info("Changing to working dir: %s" % wd)
163 # This is the working dir by now.
162 # This is the working dir by now.
@@ -38,6 +38,7 b' from IPython.core.application import BaseIPythonApplication'
38 from IPython.core.profiledir import ProfileDir
38 from IPython.core.profiledir import ProfileDir
39 from IPython.utils.daemonize import daemonize
39 from IPython.utils.daemonize import daemonize
40 from IPython.utils.importstring import import_item
40 from IPython.utils.importstring import import_item
41 from IPython.utils.py3compat import string_types
41 from IPython.utils.sysinfo import num_cpus
42 from IPython.utils.sysinfo import num_cpus
42 from IPython.utils.traitlets import (Integer, Unicode, Bool, CFloat, Dict, List, Any,
43 from IPython.utils.traitlets import (Integer, Unicode, Bool, CFloat, Dict, List, Any,
43 DottedObjectName)
44 DottedObjectName)
@@ -258,7 +259,7 b' class IPClusterEngines(BaseParallelApplication):'
258
259
259 engine_launcher = Any(config=True, help="Deprecated, use engine_launcher_class")
260 engine_launcher = Any(config=True, help="Deprecated, use engine_launcher_class")
260 def _engine_launcher_changed(self, name, old, new):
261 def _engine_launcher_changed(self, name, old, new):
261 if isinstance(new, basestring):
262 if isinstance(new, string_types):
262 self.log.warn("WARNING: %s.engine_launcher is deprecated as of 0.12,"
263 self.log.warn("WARNING: %s.engine_launcher is deprecated as of 0.12,"
263 " use engine_launcher_class" % self.__class__.__name__)
264 " use engine_launcher_class" % self.__class__.__name__)
264 self.engine_launcher_class = new
265 self.engine_launcher_class = new
@@ -462,7 +463,7 b' class IPClusterStart(IPClusterEngines):'
462
463
463 controller_launcher = Any(config=True, help="Deprecated, use controller_launcher_class")
464 controller_launcher = Any(config=True, help="Deprecated, use controller_launcher_class")
464 def _controller_launcher_changed(self, name, old, new):
465 def _controller_launcher_changed(self, name, old, new):
465 if isinstance(new, basestring):
466 if isinstance(new, string_types):
466 # old 0.11-style config
467 # old 0.11-style config
467 self.log.warn("WARNING: %s.controller_launcher is deprecated as of 0.12,"
468 self.log.warn("WARNING: %s.controller_launcher is deprecated as of 0.12,"
468 " use controller_launcher_class" % self.__class__.__name__)
469 " use controller_launcher_class" % self.__class__.__name__)
@@ -24,6 +24,8 b' import zmq'
24
24
25 from threading import Thread
25 from threading import Thread
26
26
27 from IPython.utils.py3compat import unicode_type
28
27 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
28 # Code
30 # Code
29 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
@@ -39,7 +41,7 b' class ForwarderThread(Thread):'
39 """Loop through lines in self.fd, and send them over self.sock."""
41 """Loop through lines in self.fd, and send them over self.sock."""
40 line = self.fd.readline()
42 line = self.fd.readline()
41 # allow for files opened in unicode mode
43 # allow for files opened in unicode mode
42 if isinstance(line, unicode):
44 if isinstance(line, unicode_type):
43 send = self.sock.send_unicode
45 send = self.sock.send_unicode
44 else:
46 else:
45 send = self.sock.send
47 send = self.sock.send
@@ -26,6 +26,7 b' from zmq import MessageTracker'
26 from IPython.core.display import clear_output, display, display_pretty
26 from IPython.core.display import clear_output, display, display_pretty
27 from IPython.external.decorator import decorator
27 from IPython.external.decorator import decorator
28 from IPython.parallel import error
28 from IPython.parallel import error
29 from IPython.utils.py3compat import string_types
29
30
30 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
31 # Functions
32 # Functions
@@ -61,7 +62,7 b' class AsyncResult(object):'
61 _single_result = False
62 _single_result = False
62
63
63 def __init__(self, client, msg_ids, fname='unknown', targets=None, tracker=None):
64 def __init__(self, client, msg_ids, fname='unknown', targets=None, tracker=None):
64 if isinstance(msg_ids, basestring):
65 if isinstance(msg_ids, string_types):
65 # always a list
66 # always a list
66 msg_ids = [msg_ids]
67 msg_ids = [msg_ids]
67 self._single_result = True
68 self._single_result = True
@@ -254,7 +255,7 b' class AsyncResult(object):'
254 elif isinstance(key, slice):
255 elif isinstance(key, slice):
255 self._check_ready()
256 self._check_ready()
256 return error.collect_exceptions(self._result[key], self._fname)
257 return error.collect_exceptions(self._result[key], self._fname)
257 elif isinstance(key, basestring):
258 elif isinstance(key, string_types):
258 # metadata proxy *does not* require that results are done
259 # metadata proxy *does not* require that results are done
259 self.wait(0)
260 self.wait(0)
260 values = [ md[key] for md in self._metadata ]
261 values = [ md[key] for md in self._metadata ]
@@ -40,7 +40,7 b' from IPython.utils.coloransi import TermColors'
40 from IPython.utils.jsonutil import rekey
40 from IPython.utils.jsonutil import rekey
41 from IPython.utils.localinterfaces import localhost, is_local_ip
41 from IPython.utils.localinterfaces import localhost, is_local_ip
42 from IPython.utils.path import get_ipython_dir
42 from IPython.utils.path import get_ipython_dir
43 from IPython.utils.py3compat import cast_bytes
43 from IPython.utils.py3compat import cast_bytes, string_types
44 from IPython.utils.traitlets import (HasTraits, Integer, Instance, Unicode,
44 from IPython.utils.traitlets import (HasTraits, Integer, Instance, Unicode,
45 Dict, List, Bool, Set, Any)
45 Dict, List, Bool, Set, Any)
46 from IPython.external.decorator import decorator
46 from IPython.external.decorator import decorator
@@ -573,7 +573,7 b' class Client(HasTraits):'
573
573
574 if targets is None:
574 if targets is None:
575 targets = self._ids
575 targets = self._ids
576 elif isinstance(targets, basestring):
576 elif isinstance(targets, string_types):
577 if targets.lower() == 'all':
577 if targets.lower() == 'all':
578 targets = self._ids
578 targets = self._ids
579 else:
579 else:
@@ -1067,7 +1067,7 b' class Client(HasTraits):'
1067 if jobs is None:
1067 if jobs is None:
1068 theids = self.outstanding
1068 theids = self.outstanding
1069 else:
1069 else:
1070 if isinstance(jobs, (int, basestring, AsyncResult)):
1070 if isinstance(jobs, string_types + (int, AsyncResult)):
1071 jobs = [jobs]
1071 jobs = [jobs]
1072 theids = set()
1072 theids = set()
1073 for job in jobs:
1073 for job in jobs:
@@ -1135,9 +1135,9 b' class Client(HasTraits):'
1135 targets = self._build_targets(targets)[0]
1135 targets = self._build_targets(targets)[0]
1136
1136
1137 msg_ids = []
1137 msg_ids = []
1138 if isinstance(jobs, (basestring,AsyncResult)):
1138 if isinstance(jobs, string_types + (AsyncResult,)):
1139 jobs = [jobs]
1139 jobs = [jobs]
1140 bad_ids = filter(lambda obj: not isinstance(obj, (basestring, AsyncResult)), jobs)
1140 bad_ids = filter(lambda obj: not isinstance(obj, string_types + (AsyncResult,)), jobs)
1141 if bad_ids:
1141 if bad_ids:
1142 raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0])
1142 raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0])
1143 for j in jobs:
1143 for j in jobs:
@@ -1288,7 +1288,7 b' class Client(HasTraits):'
1288 metadata = metadata if metadata is not None else {}
1288 metadata = metadata if metadata is not None else {}
1289
1289
1290 # validate arguments
1290 # validate arguments
1291 if not isinstance(code, basestring):
1291 if not isinstance(code, string_types):
1292 raise TypeError("code must be text, not %s" % type(code))
1292 raise TypeError("code must be text, not %s" % type(code))
1293 if not isinstance(metadata, dict):
1293 if not isinstance(metadata, dict):
1294 raise TypeError("metadata must be dict, not %s" % type(metadata))
1294 raise TypeError("metadata must be dict, not %s" % type(metadata))
@@ -1416,7 +1416,7 b' class Client(HasTraits):'
1416 for id in indices_or_msg_ids:
1416 for id in indices_or_msg_ids:
1417 if isinstance(id, int):
1417 if isinstance(id, int):
1418 id = self.history[id]
1418 id = self.history[id]
1419 if not isinstance(id, basestring):
1419 if not isinstance(id, string_types):
1420 raise TypeError("indices must be str or int, not %r"%id)
1420 raise TypeError("indices must be str or int, not %r"%id)
1421 theids.append(id)
1421 theids.append(id)
1422
1422
@@ -1471,7 +1471,7 b' class Client(HasTraits):'
1471 for id in indices_or_msg_ids:
1471 for id in indices_or_msg_ids:
1472 if isinstance(id, int):
1472 if isinstance(id, int):
1473 id = self.history[id]
1473 id = self.history[id]
1474 if not isinstance(id, basestring):
1474 if not isinstance(id, string_types):
1475 raise TypeError("indices must be str or int, not %r"%id)
1475 raise TypeError("indices must be str or int, not %r"%id)
1476 theids.append(id)
1476 theids.append(id)
1477
1477
@@ -1528,7 +1528,7 b' class Client(HasTraits):'
1528 for msg_id in msg_ids:
1528 for msg_id in msg_ids:
1529 if isinstance(msg_id, int):
1529 if isinstance(msg_id, int):
1530 msg_id = self.history[msg_id]
1530 msg_id = self.history[msg_id]
1531 if not isinstance(msg_id, basestring):
1531 if not isinstance(msg_id, string_types):
1532 raise TypeError("msg_ids must be str, not %r"%msg_id)
1532 raise TypeError("msg_ids must be str, not %r"%msg_id)
1533 theids.append(msg_id)
1533 theids.append(msg_id)
1534
1534
@@ -1653,9 +1653,9 b' class Client(HasTraits):'
1653 if not jobs:
1653 if not jobs:
1654 return []
1654 return []
1655 msg_ids = []
1655 msg_ids = []
1656 if isinstance(jobs, (basestring,AsyncResult)):
1656 if isinstance(jobs, string_types + (AsyncResult,)):
1657 jobs = [jobs]
1657 jobs = [jobs]
1658 bad_ids = filter(lambda obj: not isinstance(obj, (basestring, AsyncResult)), jobs)
1658 bad_ids = filter(lambda obj: not isinstance(obj, string_types + (AsyncResult)), jobs)
1659 if bad_ids:
1659 if bad_ids:
1660 raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0])
1660 raise TypeError("Invalid msg_id type %r, expected str or AsyncResult"%bad_ids[0])
1661 for j in jobs:
1661 for j in jobs:
@@ -1827,7 +1827,7 b' class Client(HasTraits):'
1827 The subset of keys to be returned. The default is to fetch everything but buffers.
1827 The subset of keys to be returned. The default is to fetch everything but buffers.
1828 'msg_id' will *always* be included.
1828 'msg_id' will *always* be included.
1829 """
1829 """
1830 if isinstance(keys, basestring):
1830 if isinstance(keys, string_types):
1831 keys = [keys]
1831 keys = [keys]
1832 content = dict(query=query, keys=keys)
1832 content = dict(query=query, keys=keys)
1833 self.session.send(self._query_socket, "db_request", content=content)
1833 self.session.send(self._query_socket, "db_request", content=content)
@@ -32,6 +32,7 b' from IPython.external.decorator import decorator'
32
32
33 from IPython.parallel import util
33 from IPython.parallel import util
34 from IPython.parallel.controller.dependency import Dependency, dependent
34 from IPython.parallel.controller.dependency import Dependency, dependent
35 from IPython.utils.py3compat import string_types
35
36
36 from . import map as Map
37 from . import map as Map
37 from .asyncresult import AsyncResult, AsyncMapResult
38 from .asyncresult import AsyncResult, AsyncMapResult
@@ -719,11 +720,11 b' class DirectView(View):'
719 block = block if block is not None else self.block
720 block = block if block is not None else self.block
720 targets = targets if targets is not None else self.targets
721 targets = targets if targets is not None else self.targets
721 applier = self.apply_sync if block else self.apply_async
722 applier = self.apply_sync if block else self.apply_async
722 if isinstance(names, basestring):
723 if isinstance(names, string_types):
723 pass
724 pass
724 elif isinstance(names, (list,tuple,set)):
725 elif isinstance(names, (list,tuple,set)):
725 for key in names:
726 for key in names:
726 if not isinstance(key, basestring):
727 if not isinstance(key, string_types):
727 raise TypeError("keys must be str, not type %r"%type(key))
728 raise TypeError("keys must be str, not type %r"%type(key))
728 else:
729 else:
729 raise TypeError("names must be strs, not %r"%names)
730 raise TypeError("names must be strs, not %r"%names)
@@ -871,11 +872,11 b' class LoadBalancedView(View):'
871
872
872 For use in `set_flags`.
873 For use in `set_flags`.
873 """
874 """
874 if dep is None or isinstance(dep, (basestring, AsyncResult, Dependency)):
875 if dep is None or isinstance(dep, string_types + (AsyncResult, Dependency)):
875 return True
876 return True
876 elif isinstance(dep, (list,set, tuple)):
877 elif isinstance(dep, (list,set, tuple)):
877 for d in dep:
878 for d in dep:
878 if not isinstance(d, (basestring, AsyncResult)):
879 if not isinstance(d, string_types + (AsyncResult,)):
879 return False
880 return False
880 elif isinstance(dep, dict):
881 elif isinstance(dep, dict):
881 if set(dep.keys()) != set(Dependency().as_dict().keys()):
882 if set(dep.keys()) != set(Dependency().as_dict().keys()):
@@ -883,7 +884,7 b' class LoadBalancedView(View):'
883 if not isinstance(dep['msg_ids'], list):
884 if not isinstance(dep['msg_ids'], list):
884 return False
885 return False
885 for d in dep['msg_ids']:
886 for d in dep['msg_ids']:
886 if not isinstance(d, basestring):
887 if not isinstance(d, string_types):
887 return False
888 return False
888 else:
889 else:
889 return False
890 return False
@@ -17,6 +17,7 b' from IPython.parallel.client.asyncresult import AsyncResult'
17 from IPython.parallel.error import UnmetDependency
17 from IPython.parallel.error import UnmetDependency
18 from IPython.parallel.util import interactive
18 from IPython.parallel.util import interactive
19 from IPython.utils import py3compat
19 from IPython.utils import py3compat
20 from IPython.utils.py3compat import string_types
20 from IPython.utils.pickleutil import can, uncan
21 from IPython.utils.pickleutil import can, uncan
21
22
22 class depend(object):
23 class depend(object):
@@ -117,7 +118,7 b' def require(*objects, **mapping):'
117 if isinstance(obj, ModuleType):
118 if isinstance(obj, ModuleType):
118 obj = obj.__name__
119 obj = obj.__name__
119
120
120 if isinstance(obj, basestring):
121 if isinstance(obj, string_types):
121 names.append(obj)
122 names.append(obj)
122 elif hasattr(obj, '__name__'):
123 elif hasattr(obj, '__name__'):
123 mapping[obj.__name__] = obj
124 mapping[obj.__name__] = obj
@@ -165,10 +166,10 b' class Dependency(set):'
165 ids = []
166 ids = []
166
167
167 # extract ids from various sources:
168 # extract ids from various sources:
168 if isinstance(dependencies, (basestring, AsyncResult)):
169 if isinstance(dependencies, string_types + (AsyncResult,)):
169 dependencies = [dependencies]
170 dependencies = [dependencies]
170 for d in dependencies:
171 for d in dependencies:
171 if isinstance(d, basestring):
172 if isinstance(d, string_types):
172 ids.append(d)
173 ids.append(d)
173 elif isinstance(d, AsyncResult):
174 elif isinstance(d, AsyncResult):
174 ids.extend(d.msg_ids)
175 ids.extend(d.msg_ids)
@@ -31,7 +31,7 b' from zmq.eventloop.zmqstream import ZMQStream'
31 # internal:
31 # internal:
32 from IPython.utils.importstring import import_item
32 from IPython.utils.importstring import import_item
33 from IPython.utils.localinterfaces import localhost
33 from IPython.utils.localinterfaces import localhost
34 from IPython.utils.py3compat import cast_bytes
34 from IPython.utils.py3compat import cast_bytes, unicode_type
35 from IPython.utils.traitlets import (
35 from IPython.utils.traitlets import (
36 HasTraits, Instance, Integer, Unicode, Dict, Set, Tuple, CBytes, DottedObjectName
36 HasTraits, Instance, Integer, Unicode, Dict, Set, Tuple, CBytes, DottedObjectName
37 )
37 )
@@ -471,13 +471,13 b' class Hub(SessionFactory):'
471 # default to all
471 # default to all
472 return self.ids
472 return self.ids
473
473
474 if isinstance(targets, (int,str,unicode)):
474 if isinstance(targets, (int,str,unicode_type)):
475 # only one target specified
475 # only one target specified
476 targets = [targets]
476 targets = [targets]
477 _targets = []
477 _targets = []
478 for t in targets:
478 for t in targets:
479 # map raw identities to ids
479 # map raw identities to ids
480 if isinstance(t, (str,unicode)):
480 if isinstance(t, (str,unicode_type)):
481 t = self.by_ident.get(cast_bytes(t), t)
481 t = self.by_ident.get(cast_bytes(t), t)
482 _targets.append(t)
482 _targets.append(t)
483 targets = _targets
483 targets = _targets
@@ -17,6 +17,8 b' from __future__ import print_function'
17 import sys
17 import sys
18 import traceback
18 import traceback
19
19
20 from IPython.utils.py3compat import unicode_type
21
20 __docformat__ = "restructuredtext en"
22 __docformat__ = "restructuredtext en"
21
23
22 # Tell nose to skip this module
24 # Tell nose to skip this module
@@ -236,8 +238,8 b' def wrap_exception(engine_info={}):'
236 exc_content = {
238 exc_content = {
237 'status' : 'error',
239 'status' : 'error',
238 'traceback' : stb,
240 'traceback' : stb,
239 'ename' : unicode(etype.__name__),
241 'ename' : unicode_type(etype.__name__),
240 'evalue' : unicode(evalue),
242 'evalue' : unicode_type(evalue),
241 'engine_info' : engine_info
243 'engine_info' : engine_info
242 }
244 }
243 return exc_content
245 return exc_content
@@ -34,6 +34,7 b' from IPython.config import Config'
34 from IPython.parallel.apps import launcher
34 from IPython.parallel.apps import launcher
35
35
36 from IPython.testing import decorators as dec
36 from IPython.testing import decorators as dec
37 from IPython.utils.py3compat import string_types
37
38
38
39
39 #-------------------------------------------------------------------------------
40 #-------------------------------------------------------------------------------
@@ -79,7 +80,7 b' class LauncherTest:'
79 def test_args(self):
80 def test_args(self):
80 launcher = self.build_launcher()
81 launcher = self.build_launcher()
81 for arg in launcher.args:
82 for arg in launcher.args:
82 self.assertTrue(isinstance(arg, basestring), str(arg))
83 self.assertTrue(isinstance(arg, string_types), str(arg))
83
84
84 class BatchTest:
85 class BatchTest:
85 """Tests for batch-system launchers (LSF, SGE, PBS)"""
86 """Tests for batch-system launchers (LSF, SGE, PBS)"""
@@ -28,6 +28,7 b' from nose.plugins.attrib import attr'
28
28
29 from IPython.testing import decorators as dec
29 from IPython.testing import decorators as dec
30 from IPython.utils.io import capture_output
30 from IPython.utils.io import capture_output
31 from IPython.utils.py3compat import unicode_type
31
32
32 from IPython import parallel as pmod
33 from IPython import parallel as pmod
33 from IPython.parallel import error
34 from IPython.parallel import error
@@ -450,7 +451,7 b' class TestView(ClusterTestCase):'
450
451
451 @interactive
452 @interactive
452 def check_unicode(a, check):
453 def check_unicode(a, check):
453 assert isinstance(a, unicode), "%r is not unicode"%a
454 assert isinstance(a, unicode_type), "%r is not unicode"%a
454 assert isinstance(check, bytes), "%r is not bytes"%check
455 assert isinstance(check, bytes), "%r is not bytes"%check
455 assert a.encode('utf8') == check, "%s != %s"%(a,check)
456 assert a.encode('utf8') == check, "%s != %s"%(a,check)
456
457
@@ -590,7 +591,7 b' class TestView(ClusterTestCase):'
590 view.execute("from IPython.core.display import *")
591 view.execute("from IPython.core.display import *")
591 ar = view.execute("[ display(i) for i in range(5) ]", block=True)
592 ar = view.execute("[ display(i) for i in range(5) ]", block=True)
592
593
593 expected = [ {u'text/plain' : unicode(j)} for j in range(5) ]
594 expected = [ {u'text/plain' : unicode_type(j)} for j in range(5) ]
594 for outputs in ar.outputs:
595 for outputs in ar.outputs:
595 mimes = [ out['data'] for out in outputs ]
596 mimes = [ out['data'] for out in outputs ]
596 self.assertEqual(mimes, expected)
597 self.assertEqual(mimes, expected)
@@ -606,7 +607,7 b' class TestView(ClusterTestCase):'
606
607
607 ar = view.apply_async(publish)
608 ar = view.apply_async(publish)
608 ar.get(5)
609 ar.get(5)
609 expected = [ {u'text/plain' : unicode(j)} for j in range(5) ]
610 expected = [ {u'text/plain' : unicode_type(j)} for j in range(5) ]
610 for outputs in ar.outputs:
611 for outputs in ar.outputs:
611 mimes = [ out['data'] for out in outputs ]
612 mimes = [ out['data'] for out in outputs ]
612 self.assertEqual(mimes, expected)
613 self.assertEqual(mimes, expected)
@@ -44,6 +44,7 b' from IPython.external.decorator import decorator'
44 # IPython imports
44 # IPython imports
45 from IPython.config.application import Application
45 from IPython.config.application import Application
46 from IPython.utils.localinterfaces import localhost, is_public_ip, public_ips
46 from IPython.utils.localinterfaces import localhost, is_public_ip, public_ips
47 from IPython.utils.py3compat import string_types
47 from IPython.kernel.zmq.log import EnginePUBHandler
48 from IPython.kernel.zmq.log import EnginePUBHandler
48 from IPython.kernel.zmq.serialize import (
49 from IPython.kernel.zmq.serialize import (
49 unserialize_object, serialize_object, pack_apply_message, unpack_apply_message
50 unserialize_object, serialize_object, pack_apply_message, unpack_apply_message
@@ -130,7 +131,7 b' def is_url(url):'
130
131
131 def validate_url(url):
132 def validate_url(url):
132 """validate a url for zeromq"""
133 """validate a url for zeromq"""
133 if not isinstance(url, basestring):
134 if not isinstance(url, string_types):
134 raise TypeError("url must be a string, not %r"%type(url))
135 raise TypeError("url must be a string, not %r"%type(url))
135 url = url.lower()
136 url = url.lower()
136
137
@@ -163,7 +164,7 b' def validate_url(url):'
163
164
164 def validate_url_container(container):
165 def validate_url_container(container):
165 """validate a potentially nested collection of urls."""
166 """validate a potentially nested collection of urls."""
166 if isinstance(container, basestring):
167 if isinstance(container, string_types):
167 url = container
168 url = container
168 return validate_url(url)
169 return validate_url(url)
169 elif isinstance(container, dict):
170 elif isinstance(container, dict):
@@ -11,6 +11,9 b' import re'
11 # System library imports
11 # System library imports
12 from IPython.external.qt import QtGui
12 from IPython.external.qt import QtGui
13
13
14 # Local imports
15 from IPython.utils.py3compat import string_types
16
14 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
15 # Constants and datatypes
18 # Constants and datatypes
16 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
@@ -318,7 +321,7 b' class QtAnsiCodeProcessor(AnsiCodeProcessor):'
318 color += 8
321 color += 8
319
322
320 constructor = self.color_map.get(color, None)
323 constructor = self.color_map.get(color, None)
321 if isinstance(constructor, basestring):
324 if isinstance(constructor, string_types):
322 # If this is an X11 color name, we just hope there is a close SVG
325 # If this is an X11 color name, we just hope there is a close SVG
323 # color name. We could use QColor's static method
326 # color name. We could use QColor's static method
324 # 'setAllowX11ColorNames()', but this is global and only available
327 # 'setAllowX11ColorNames()', but this is global and only available
@@ -2,6 +2,7 b''
2 from IPython.external.qt import QtGui
2 from IPython.external.qt import QtGui
3
3
4 # Local imports
4 # Local imports
5 from IPython.utils.py3compat import unicode_type
5 from IPython.utils.traitlets import Bool
6 from IPython.utils.traitlets import Bool
6 from .console_widget import ConsoleWidget
7 from .console_widget import ConsoleWidget
7
8
@@ -285,7 +286,7 b' class HistoryConsoleWidget(ConsoleWidget):'
285 if index in self._history_edits:
286 if index in self._history_edits:
286 return self._history_edits[index]
287 return self._history_edits[index]
287 elif index == len(self._history):
288 elif index == len(self._history):
288 return unicode()
289 return unicode_type()
289 return self._history[index]
290 return self._history[index]
290
291
291 def _set_history(self, history):
292 def _set_history(self, history):
@@ -5,6 +5,8 b' from pygments.lexer import RegexLexer, _TokenType, Text, Error'
5 from pygments.lexers import PythonLexer
5 from pygments.lexers import PythonLexer
6 from pygments.styles import get_style_by_name
6 from pygments.styles import get_style_by_name
7
7
8 # Local imports
9 from IPython.utils.py3compat import string_types
8
10
9 def get_tokens_unprocessed(self, text, stack=('root',)):
11 def get_tokens_unprocessed(self, text, stack=('root',)):
10 """ Split ``text`` into (tokentype, text) pairs.
12 """ Split ``text`` into (tokentype, text) pairs.
@@ -129,7 +131,7 b' class PygmentsHighlighter(QtGui.QSyntaxHighlighter):'
129 def set_style(self, style):
131 def set_style(self, style):
130 """ Sets the style to the specified Pygments style.
132 """ Sets the style to the specified Pygments style.
131 """
133 """
132 if isinstance(style, basestring):
134 if isinstance(style, string_types):
133 style = get_style_by_name(style)
135 style = get_style_by_name(style)
134 self._style = style
136 self._style = style
135 self._clear_caches()
137 self._clear_caches()
@@ -4,6 +4,8 b''
4 # System library imports.
4 # System library imports.
5 from IPython.external.qt import QtCore, QtGui, QtSvg
5 from IPython.external.qt import QtCore, QtGui, QtSvg
6
6
7 # Our own imports
8 from IPython.utils.py3compat import unicode_type
7
9
8 def save_svg(string, parent=None):
10 def save_svg(string, parent=None):
9 """ Prompts the user to save an SVG document to disk.
11 """ Prompts the user to save an SVG document to disk.
@@ -21,7 +23,7 b' def save_svg(string, parent=None):'
21 The name of the file to which the document was saved, or None if the save
23 The name of the file to which the document was saved, or None if the save
22 was cancelled.
24 was cancelled.
23 """
25 """
24 if isinstance(string, unicode):
26 if isinstance(string, unicode_type):
25 string = string.encode('utf-8')
27 string = string.encode('utf-8')
26
28
27 dialog = QtGui.QFileDialog(parent, 'Save SVG Document')
29 dialog = QtGui.QFileDialog(parent, 'Save SVG Document')
@@ -30,7 +32,7 b' def save_svg(string, parent=None):'
30 dialog.setNameFilter('SVG document (*.svg)')
32 dialog.setNameFilter('SVG document (*.svg)')
31 if dialog.exec_():
33 if dialog.exec_():
32 filename = dialog.selectedFiles()[0]
34 filename = dialog.selectedFiles()[0]
33 f = open(filename, 'w')
35 f = open(filename, 'wb')
34 try:
36 try:
35 f.write(string)
37 f.write(string)
36 finally:
38 finally:
@@ -46,7 +48,7 b' def svg_to_clipboard(string):'
46 string : basestring
48 string : basestring
47 A Python string containing a SVG document.
49 A Python string containing a SVG document.
48 """
50 """
49 if isinstance(string, unicode):
51 if isinstance(string, unicode_type):
50 string = string.encode('utf-8')
52 string = string.encode('utf-8')
51
53
52 mime_data = QtCore.QMimeData()
54 mime_data = QtCore.QMimeData()
@@ -74,7 +76,7 b' def svg_to_image(string, size=None):'
74 --------
76 --------
75 A QImage of format QImage.Format_ARGB32.
77 A QImage of format QImage.Format_ARGB32.
76 """
78 """
77 if isinstance(string, unicode):
79 if isinstance(string, unicode_type):
78 string = string.encode('utf-8')
80 string = string.encode('utf-8')
79
81
80 renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string))
82 renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string))
@@ -28,6 +28,7 b' from Queue import Empty'
28 from IPython.core import page
28 from IPython.core import page
29 from IPython.utils.warn import warn, error
29 from IPython.utils.warn import warn, error
30 from IPython.utils import io
30 from IPython.utils import io
31 from IPython.utils.py3compat import string_types
31 from IPython.utils.traitlets import List, Enum, Any, Instance, Unicode, Float
32 from IPython.utils.traitlets import List, Enum, Any, Instance, Unicode, Float
32 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
33 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
33
34
@@ -387,7 +388,7 b' class ZMQTerminalInteractiveShell(TerminalInteractiveShell):'
387 if display_banner is None:
388 if display_banner is None:
388 display_banner = self.display_banner
389 display_banner = self.display_banner
389
390
390 if isinstance(display_banner, basestring):
391 if isinstance(display_banner, string_types):
391 self.show_banner(display_banner)
392 self.show_banner(display_banner)
392 elif display_banner:
393 elif display_banner:
393 self.show_banner()
394 self.show_banner()
@@ -105,7 +105,7 b' class TerminalMagics(Magics):'
105 # Sanity checks
105 # Sanity checks
106 if b is None:
106 if b is None:
107 raise UsageError('No previous pasted block available')
107 raise UsageError('No previous pasted block available')
108 if not isinstance(b, basestring):
108 if not isinstance(b, py3compat.string_types):
109 raise UsageError(
109 raise UsageError(
110 "Variable 'pasted_block' is not a string, can't execute")
110 "Variable 'pasted_block' is not a string, can't execute")
111
111
@@ -473,7 +473,7 b' class TerminalInteractiveShell(InteractiveShell):'
473 if display_banner is None:
473 if display_banner is None:
474 display_banner = self.display_banner
474 display_banner = self.display_banner
475
475
476 if isinstance(display_banner, basestring):
476 if isinstance(display_banner, py3compat.string_types):
477 self.show_banner(display_banner)
477 self.show_banner(display_banner)
478 elif display_banner:
478 elif display_banner:
479 self.show_banner()
479 self.show_banner()
@@ -64,6 +64,7 b' from IPython.external.decorators import *'
64
64
65 # For onlyif_cmd_exists decorator
65 # For onlyif_cmd_exists decorator
66 from IPython.utils.process import is_cmd_found
66 from IPython.utils.process import is_cmd_found
67 from IPython.utils.py3compat import string_types
67
68
68 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
69 # Classes and functions
70 # Classes and functions
@@ -141,7 +142,7 b' def make_label_dec(label,ds=None):'
141 True
142 True
142 """
143 """
143
144
144 if isinstance(label,basestring):
145 if isinstance(label, string_types):
145 labels = [label]
146 labels = [label]
146 else:
147 else:
147 labels = label
148 labels = label
@@ -16,6 +16,9 b' from __future__ import print_function'
16 import os, sys, threading
16 import os, sys, threading
17 import ctypes, msvcrt
17 import ctypes, msvcrt
18
18
19 # local imports
20 from .py3compat import unicode_type
21
19 # Win32 API types needed for the API calls
22 # Win32 API types needed for the API calls
20 from ctypes import POINTER
23 from ctypes import POINTER
21 from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
24 from ctypes.wintypes import HANDLE, HLOCAL, LPVOID, WORD, DWORD, BOOL, \
@@ -12,6 +12,8 b''
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 from .py3compat import string_types
16
15 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
16 # Code
18 # Code
17 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
@@ -79,5 +81,5 b' def dir2(obj):'
79 # filter out non-string attributes which may be stuffed by dir() calls
81 # filter out non-string attributes which may be stuffed by dir() calls
80 # and poor coding in third-party modules
82 # and poor coding in third-party modules
81
83
82 words = [w for w in words if isinstance(w, basestring)]
84 words = [w for w in words if isinstance(w, string_types)]
83 return sorted(words)
85 return sorted(words)
@@ -19,6 +19,7 b' import sys'
19 import tempfile
19 import tempfile
20 from StringIO import StringIO
20 from StringIO import StringIO
21 from .capture import CapturedIO, capture_output
21 from .capture import CapturedIO, capture_output
22 from .py3compat import string_types
22
23
23 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
24 # Code
25 # Code
@@ -57,7 +58,7 b' class IOStream:'
57 file=sys.stderr)
58 file=sys.stderr)
58
59
59 def writelines(self, lines):
60 def writelines(self, lines):
60 if isinstance(lines, basestring):
61 if isinstance(lines, string_types):
61 lines = [lines]
62 lines = [lines]
62 for line in lines:
63 for line in lines:
63 self.write(line)
64 self.write(line)
@@ -24,6 +24,7 b' except ImportError:'
24 from base64 import encodestring as encodebytes
24 from base64 import encodestring as encodebytes
25
25
26 from IPython.utils import py3compat
26 from IPython.utils import py3compat
27 from IPython.utils.py3compat import string_types, unicode_type
27 from IPython.utils.encoding import DEFAULT_ENCODING
28 from IPython.utils.encoding import DEFAULT_ENCODING
28 next_attr_name = '__next__' if py3compat.PY3 else 'next'
29 next_attr_name = '__next__' if py3compat.PY3 else 'next'
29
30
@@ -43,7 +44,7 b' def rekey(dikt):'
43 """Rekey a dict that has been forced to use str keys where there should be
44 """Rekey a dict that has been forced to use str keys where there should be
44 ints by json."""
45 ints by json."""
45 for k in dikt.iterkeys():
46 for k in dikt.iterkeys():
46 if isinstance(k, basestring):
47 if isinstance(k, string_types):
47 ik=fk=None
48 ik=fk=None
48 try:
49 try:
49 ik = int(k)
50 ik = int(k)
@@ -70,7 +71,7 b' def extract_dates(obj):'
70 obj[k] = extract_dates(v)
71 obj[k] = extract_dates(v)
71 elif isinstance(obj, (list, tuple)):
72 elif isinstance(obj, (list, tuple)):
72 obj = [ extract_dates(o) for o in obj ]
73 obj = [ extract_dates(o) for o in obj ]
73 elif isinstance(obj, basestring):
74 elif isinstance(obj, string_types):
74 m = ISO8601_PAT.match(obj)
75 m = ISO8601_PAT.match(obj)
75 if m:
76 if m:
76 # FIXME: add actual timezone support
77 # FIXME: add actual timezone support
@@ -183,7 +184,7 b' def json_clean(obj):'
183 """
184 """
184 # types that are 'atomic' and ok in json as-is. bool doesn't need to be
185 # types that are 'atomic' and ok in json as-is. bool doesn't need to be
185 # listed explicitly because bools pass as int instances
186 # listed explicitly because bools pass as int instances
186 atomic_ok = (unicode, int, types.NoneType)
187 atomic_ok = (unicode_type, int, types.NoneType)
187
188
188 # containers that we need to convert into lists
189 # containers that we need to convert into lists
189 container_to_list = (tuple, set, types.GeneratorType)
190 container_to_list = (tuple, set, types.GeneratorType)
@@ -11,8 +11,10 b' from io import TextIOWrapper, BytesIO'
11 import os.path
11 import os.path
12 import re
12 import re
13
13
14 cookie_re = re.compile(ur"coding[:=]\s*([-\w.]+)", re.UNICODE)
14 from .py3compat import unicode_type
15 cookie_comment_re = re.compile(ur"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE)
15
16 cookie_re = re.compile(r"coding[:=]\s*([-\w.]+)", re.UNICODE)
17 cookie_comment_re = re.compile(r"^\s*#.*coding[:=]\s*([-\w.]+)", re.UNICODE)
16
18
17 try:
19 try:
18 # Available in Python 3
20 # Available in Python 3
@@ -128,7 +130,7 b" def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True):"
128 txt can be either a bytes buffer or a string containing the source
130 txt can be either a bytes buffer or a string containing the source
129 code.
131 code.
130 """
132 """
131 if isinstance(txt, unicode):
133 if isinstance(txt, unicode_type):
132 return txt
134 return txt
133 if isinstance(txt, bytes):
135 if isinstance(txt, bytes):
134 buffer = BytesIO(txt)
136 buffer = BytesIO(txt)
@@ -162,7 +162,7 b' def filefind(filename, path_dirs=None):'
162
162
163 if path_dirs is None:
163 if path_dirs is None:
164 path_dirs = ("",)
164 path_dirs = ("",)
165 elif isinstance(path_dirs, basestring):
165 elif isinstance(path_dirs, py3compat.string_types):
166 path_dirs = (path_dirs,)
166 path_dirs = (path_dirs,)
167
167
168 for path in path_dirs:
168 for path in path_dirs:
@@ -28,6 +28,7 b' except ImportError:'
28 from . import codeutil # This registers a hook when it's imported
28 from . import codeutil # This registers a hook when it's imported
29 from . import py3compat
29 from . import py3compat
30 from .importstring import import_item
30 from .importstring import import_item
31 from .py3compat import string_types
31
32
32 from IPython.config import Application
33 from IPython.config import Application
33
34
@@ -85,7 +86,7 b' class CannedObject(object):'
85 class Reference(CannedObject):
86 class Reference(CannedObject):
86 """object for wrapping a remote reference by name."""
87 """object for wrapping a remote reference by name."""
87 def __init__(self, name):
88 def __init__(self, name):
88 if not isinstance(name, basestring):
89 if not isinstance(name, string_types):
89 raise TypeError("illegal name: %r"%name)
90 raise TypeError("illegal name: %r"%name)
90 self.name = name
91 self.name = name
91 self.buffers = []
92 self.buffers = []
@@ -216,7 +217,7 b' def _import_mapping(mapping, original=None):'
216 log = _logger()
217 log = _logger()
217 log.debug("Importing canning map")
218 log.debug("Importing canning map")
218 for key,value in mapping.items():
219 for key,value in mapping.items():
219 if isinstance(key, basestring):
220 if isinstance(key, string_types):
220 try:
221 try:
221 cls = import_item(key)
222 cls = import_item(key)
222 except Exception:
223 except Exception:
@@ -246,7 +247,7 b' def can(obj):'
246 import_needed = False
247 import_needed = False
247
248
248 for cls,canner in can_map.iteritems():
249 for cls,canner in can_map.iteritems():
249 if isinstance(cls, basestring):
250 if isinstance(cls, string_types):
250 import_needed = True
251 import_needed = True
251 break
252 break
252 elif istype(obj, cls):
253 elif istype(obj, cls):
@@ -291,7 +292,7 b' def uncan(obj, g=None):'
291
292
292 import_needed = False
293 import_needed = False
293 for cls,uncanner in uncan_map.iteritems():
294 for cls,uncanner in uncan_map.iteritems():
294 if isinstance(cls, basestring):
295 if isinstance(cls, string_types):
295 import_needed = True
296 import_needed = True
296 break
297 break
297 elif isinstance(obj, cls):
298 elif isinstance(obj, cls):
@@ -34,7 +34,7 b' def cast_bytes(s, encoding=None):'
34 def _modify_str_or_docstring(str_change_func):
34 def _modify_str_or_docstring(str_change_func):
35 @functools.wraps(str_change_func)
35 @functools.wraps(str_change_func)
36 def wrapper(func_or_str):
36 def wrapper(func_or_str):
37 if isinstance(func_or_str, basestring):
37 if isinstance(func_or_str, string_types):
38 func = None
38 func = None
39 doc = func_or_str
39 doc = func_or_str
40 else:
40 else:
@@ -54,7 +54,7 b' def safe_unicode(e):'
54 safe to call unicode() on.
54 safe to call unicode() on.
55 """
55 """
56 try:
56 try:
57 return unicode(e)
57 return unicode_type(e)
58 except UnicodeError:
58 except UnicodeError:
59 pass
59 pass
60
60
@@ -177,7 +177,7 b' class SList(list):'
177 except IndexError:
177 except IndexError:
178 return ""
178 return ""
179
179
180 if isinstance(pattern, basestring):
180 if isinstance(pattern, py3compat.string_types):
181 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
181 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
182 else:
182 else:
183 pred = pattern
183 pred = pattern
@@ -321,7 +321,7 b' def list_strings(arg):'
321 Out[9]: ['A', 'list', 'of', 'strings']
321 Out[9]: ['A', 'list', 'of', 'strings']
322 """
322 """
323
323
324 if isinstance(arg,basestring): return [arg]
324 if isinstance(arg, py3compat.string_types): return [arg]
325 else: return arg
325 else: return arg
326
326
327
327
@@ -94,7 +94,7 b' def class_of ( object ):'
94 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
94 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
95 'a PlotValue').
95 'a PlotValue').
96 """
96 """
97 if isinstance( object, basestring ):
97 if isinstance( object, py3compat.string_types ):
98 return add_article( object )
98 return add_article( object )
99
99
100 return add_article( object.__class__.__name__ )
100 return add_article( object.__class__.__name__ )
@@ -680,7 +680,7 b' class Type(ClassBasedTraitType):'
680 elif klass is None:
680 elif klass is None:
681 klass = default_value
681 klass = default_value
682
682
683 if not (inspect.isclass(klass) or isinstance(klass, basestring)):
683 if not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)):
684 raise TraitError("A Type trait must specify a class.")
684 raise TraitError("A Type trait must specify a class.")
685
685
686 self.klass = klass
686 self.klass = klass
@@ -701,7 +701,7 b' class Type(ClassBasedTraitType):'
701
701
702 def info(self):
702 def info(self):
703 """ Returns a description of the trait."""
703 """ Returns a description of the trait."""
704 if isinstance(self.klass, basestring):
704 if isinstance(self.klass, py3compat.string_types):
705 klass = self.klass
705 klass = self.klass
706 else:
706 else:
707 klass = self.klass.__name__
707 klass = self.klass.__name__
@@ -715,9 +715,9 b' class Type(ClassBasedTraitType):'
715 super(Type, self).instance_init(obj)
715 super(Type, self).instance_init(obj)
716
716
717 def _resolve_classes(self):
717 def _resolve_classes(self):
718 if isinstance(self.klass, basestring):
718 if isinstance(self.klass, py3compat.string_types):
719 self.klass = import_item(self.klass)
719 self.klass = import_item(self.klass)
720 if isinstance(self.default_value, basestring):
720 if isinstance(self.default_value, py3compat.string_types):
721 self.default_value = import_item(self.default_value)
721 self.default_value = import_item(self.default_value)
722
722
723 def get_default_value(self):
723 def get_default_value(self):
@@ -772,7 +772,7 b' class Instance(ClassBasedTraitType):'
772
772
773 self._allow_none = allow_none
773 self._allow_none = allow_none
774
774
775 if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, basestring))):
775 if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types))):
776 raise TraitError('The klass argument must be a class'
776 raise TraitError('The klass argument must be a class'
777 ' you gave: %r' % klass)
777 ' you gave: %r' % klass)
778 self.klass = klass
778 self.klass = klass
@@ -809,7 +809,7 b' class Instance(ClassBasedTraitType):'
809 self.error(obj, value)
809 self.error(obj, value)
810
810
811 def info(self):
811 def info(self):
812 if isinstance(self.klass, basestring):
812 if isinstance(self.klass, py3compat.string_types):
813 klass = self.klass
813 klass = self.klass
814 else:
814 else:
815 klass = self.klass.__name__
815 klass = self.klass.__name__
@@ -824,7 +824,7 b' class Instance(ClassBasedTraitType):'
824 super(Instance, self).instance_init(obj)
824 super(Instance, self).instance_init(obj)
825
825
826 def _resolve_classes(self):
826 def _resolve_classes(self):
827 if isinstance(self.klass, basestring):
827 if isinstance(self.klass, py3compat.string_types):
828 self.klass = import_item(self.klass)
828 self.klass = import_item(self.klass)
829
829
830 def get_default_value(self):
830 def get_default_value(self):
@@ -1022,10 +1022,10 b' class Unicode(TraitType):'
1022 info_text = 'a unicode string'
1022 info_text = 'a unicode string'
1023
1023
1024 def validate(self, obj, value):
1024 def validate(self, obj, value):
1025 if isinstance(value, unicode):
1025 if isinstance(value, py3compat.unicode_type):
1026 return value
1026 return value
1027 if isinstance(value, bytes):
1027 if isinstance(value, bytes):
1028 return unicode(value)
1028 return py3compat.unicode_type(value)
1029 self.error(obj, value)
1029 self.error(obj, value)
1030
1030
1031
1031
@@ -1034,7 +1034,7 b' class CUnicode(Unicode):'
1034
1034
1035 def validate(self, obj, value):
1035 def validate(self, obj, value):
1036 try:
1036 try:
1037 return unicode(value)
1037 return py3compat.unicode_type(value)
1038 except:
1038 except:
1039 self.error(obj, value)
1039 self.error(obj, value)
1040
1040
@@ -1131,7 +1131,7 b' class CaselessStrEnum(Enum):'
1131 if self._allow_none:
1131 if self._allow_none:
1132 return value
1132 return value
1133
1133
1134 if not isinstance(value, basestring):
1134 if not isinstance(value, py3compat.string_types):
1135 self.error(obj, value)
1135 self.error(obj, value)
1136
1136
1137 for v in self.values:
1137 for v in self.values:
@@ -1418,7 +1418,7 b' class TCPAddress(TraitType):'
1418 def validate(self, obj, value):
1418 def validate(self, obj, value):
1419 if isinstance(value, tuple):
1419 if isinstance(value, tuple):
1420 if len(value) == 2:
1420 if len(value) == 2:
1421 if isinstance(value[0], basestring) and isinstance(value[1], int):
1421 if isinstance(value[0], py3compat.string_types) and isinstance(value[1], int):
1422 port = value[1]
1422 port = value[1]
1423 if port >= 0 and port <= 65535:
1423 if port >= 0 and port <= 65535:
1424 return value
1424 return value
@@ -26,7 +26,7 b' else:'
26 lines = linecache.getlines(filename, module_globals=module_globals)
26 lines = linecache.getlines(filename, module_globals=module_globals)
27
27
28 # The bits we cache ourselves can be unicode.
28 # The bits we cache ourselves can be unicode.
29 if (not lines) or isinstance(lines[0], unicode):
29 if (not lines) or isinstance(lines[0], py3compat.unicode_type):
30 return lines
30 return lines
31
31
32 readline = openpy._list_readline(lines)
32 readline = openpy._list_readline(lines)
General Comments 0
You need to be logged in to leave comments. Login now