##// END OF EJS Templates
Merge branch 'traitlets-str' into traitlets-str-merge...
Thomas Kluyver -
r4073:83ed9bae merge
parent child Browse files
Show More
@@ -28,7 +28,7 b' from IPython.config.configurable import ('
28 28 )
29 29
30 30 from IPython.utils.traitlets import (
31 Int, Float, Str
31 Int, Float, Unicode
32 32 )
33 33
34 34 from IPython.config.loader import Config
@@ -42,7 +42,7 b' from IPython.config.loader import Config'
42 42 class MyConfigurable(Configurable):
43 43 a = Int(1, config=True, help="The integer a.")
44 44 b = Float(1.0, config=True, help="The integer b.")
45 c = Str('no config')
45 c = Unicode('no config')
46 46
47 47
48 48 mc_help=u"""MyConfigurable options
@@ -56,11 +56,11 b' MyConfigurable.b : Float'
56 56
57 57 class Foo(Configurable):
58 58 a = Int(0, config=True, help="The integer a.")
59 b = Str('nope', config=True)
59 b = Unicode('nope', config=True)
60 60
61 61
62 62 class Bar(Foo):
63 b = Str('gotit', config=False, help="The string b.")
63 b = Unicode('gotit', config=False, help="The string b.")
64 64 c = Float(config=True, help="The string c.")
65 65
66 66
@@ -28,7 +28,7 b' from StringIO import StringIO'
28 28 # Our own imports
29 29 from IPython.config.configurable import Configurable
30 30 from IPython.lib import pretty
31 from IPython.utils.traitlets import Bool, Dict, Int, Str, CStr
31 from IPython.utils.traitlets import Bool, Dict, Int, Unicode, CUnicode, ObjectName
32 32
33 33
34 34 #-----------------------------------------------------------------------------
@@ -191,11 +191,11 b' class BaseFormatter(Configurable):'
191 191 returned and this format type is not used.
192 192 """
193 193
194 format_type = Str('text/plain')
194 format_type = Unicode('text/plain')
195 195
196 196 enabled = Bool(True, config=True)
197 197
198 print_method = Str('__repr__')
198 print_method = ObjectName('__repr__')
199 199
200 200 # The singleton printers.
201 201 # Maps the IDs of the builtin singleton objects to the format functions.
@@ -337,14 +337,14 b' class PlainTextFormatter(BaseFormatter):'
337 337 """
338 338
339 339 # The format type of data returned.
340 format_type = Str('text/plain')
340 format_type = Unicode('text/plain')
341 341
342 342 # This subclass ignores this attribute as it always need to return
343 343 # something.
344 344 enabled = Bool(True, config=False)
345 345
346 346 # Look for a _repr_pretty_ methods to use for pretty printing.
347 print_method = Str('_repr_pretty_')
347 print_method = ObjectName('_repr_pretty_')
348 348
349 349 # Whether to pretty-print or not.
350 350 pprint = Bool(True, config=True)
@@ -356,12 +356,12 b' class PlainTextFormatter(BaseFormatter):'
356 356 max_width = Int(79, config=True)
357 357
358 358 # The newline character.
359 newline = Str('\n', config=True)
359 newline = Unicode('\n', config=True)
360 360
361 361 # format-string for pprinting floats
362 float_format = Str('%r')
362 float_format = Unicode('%r')
363 363 # setter for float precision, either int or direct format-string
364 float_precision = CStr('', config=True)
364 float_precision = CUnicode('', config=True)
365 365
366 366 def _float_precision_changed(self, name, old, new):
367 367 """float_precision changed, set float_format accordingly.
@@ -454,9 +454,9 b' class HTMLFormatter(BaseFormatter):'
454 454 could be injected into an existing DOM. It should *not* include the
455 455 ```<html>`` or ```<body>`` tags.
456 456 """
457 format_type = Str('text/html')
457 format_type = Unicode('text/html')
458 458
459 print_method = Str('_repr_html_')
459 print_method = ObjectName('_repr_html_')
460 460
461 461
462 462 class SVGFormatter(BaseFormatter):
@@ -471,9 +471,9 b' class SVGFormatter(BaseFormatter):'
471 471 ```<svg>``` tags, that could be injected into an existing DOM. It should
472 472 *not* include the ```<html>`` or ```<body>`` tags.
473 473 """
474 format_type = Str('image/svg+xml')
474 format_type = Unicode('image/svg+xml')
475 475
476 print_method = Str('_repr_svg_')
476 print_method = ObjectName('_repr_svg_')
477 477
478 478
479 479 class PNGFormatter(BaseFormatter):
@@ -487,9 +487,9 b' class PNGFormatter(BaseFormatter):'
487 487 The return value of this formatter should be raw PNG data, *not*
488 488 base64 encoded.
489 489 """
490 format_type = Str('image/png')
490 format_type = Unicode('image/png')
491 491
492 print_method = Str('_repr_png_')
492 print_method = ObjectName('_repr_png_')
493 493
494 494
495 495 class LatexFormatter(BaseFormatter):
@@ -503,9 +503,9 b' class LatexFormatter(BaseFormatter):'
503 503 The return value of this formatter should be a valid LaTeX equation,
504 504 enclosed in either ```$``` or ```$$```.
505 505 """
506 format_type = Str('text/latex')
506 format_type = Unicode('text/latex')
507 507
508 print_method = Str('_repr_latex_')
508 print_method = ObjectName('_repr_latex_')
509 509
510 510
511 511 class JSONFormatter(BaseFormatter):
@@ -518,9 +518,9 b' class JSONFormatter(BaseFormatter):'
518 518
519 519 The return value of this formatter should be a valid JSON string.
520 520 """
521 format_type = Str('application/json')
521 format_type = Unicode('application/json')
522 522
523 print_method = Str('_repr_json_')
523 print_method = ObjectName('_repr_json_')
524 524
525 525
526 526 class JavascriptFormatter(BaseFormatter):
@@ -534,9 +534,9 b' class JavascriptFormatter(BaseFormatter):'
534 534 The return value of this formatter should be valid Javascript code and
535 535 should *not* be enclosed in ```<script>``` tags.
536 536 """
537 format_type = Str('application/javascript')
537 format_type = Unicode('application/javascript')
538 538
539 print_method = Str('_repr_javascript_')
539 print_method = ObjectName('_repr_javascript_')
540 540
541 541 FormatterABC.register(BaseFormatter)
542 542 FormatterABC.register(PlainTextFormatter)
@@ -70,7 +70,7 b' from IPython.utils.process import system, getoutput'
70 70 from IPython.utils.strdispatch import StrDispatch
71 71 from IPython.utils.syspathcontext import prepended_to_syspath
72 72 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
73 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 from IPython.utils.traitlets import (Int, CBool, CaselessStrEnum, Enum,
74 74 List, Unicode, Instance, Type)
75 75 from IPython.utils.warn import warn, error, fatal
76 76 import IPython.core.hooks
@@ -122,16 +122,16 b' def get_default_colors():'
122 122 return 'Linux'
123 123
124 124
125 class SeparateStr(Str):
126 """A Str subclass to validate separate_in, separate_out, etc.
125 class SeparateUnicode(Unicode):
126 """A Unicode subclass to validate separate_in, separate_out, etc.
127 127
128 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
129 129 """
130 130
131 131 def validate(self, obj, value):
132 132 if value == '0': value = ''
133 133 value = value.replace('\\n','\n')
134 return super(SeparateStr, self).validate(obj, value)
134 return super(SeparateUnicode, self).validate(obj, value)
135 135
136 136
137 137 class ReadlineNoRecord(object):
@@ -294,9 +294,9 b' class InteractiveShell(SingletonConfigurable, Magic):'
294 294 """
295 295 )
296 296
297 prompt_in1 = Str('In [\\#]: ', config=True)
298 prompt_in2 = Str(' .\\D.: ', config=True)
299 prompt_out = Str('Out[\\#]: ', config=True)
297 prompt_in1 = Unicode('In [\\#]: ', config=True)
298 prompt_in2 = Unicode(' .\\D.: ', config=True)
299 prompt_out = Unicode('Out[\\#]: ', config=True)
300 300 prompts_pad_left = CBool(True, config=True)
301 301 quiet = CBool(False, config=True)
302 302
@@ -307,7 +307,7 b' class InteractiveShell(SingletonConfigurable, Magic):'
307 307 readline_use = CBool(True, config=True)
308 308 readline_merge_completions = CBool(True, config=True)
309 309 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
310 readline_remove_delims = Str('-/~', config=True)
310 readline_remove_delims = Unicode('-/~', config=True)
311 311 # don't use \M- bindings by default, because they
312 312 # conflict with 8-bit encodings. See gh-58,gh-88
313 313 readline_parse_and_bind = List([
@@ -327,9 +327,9 b' class InteractiveShell(SingletonConfigurable, Magic):'
327 327
328 328 # TODO: this part of prompt management should be moved to the frontends.
329 329 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
330 separate_in = SeparateStr('\n', config=True)
331 separate_out = SeparateStr('', config=True)
332 separate_out2 = SeparateStr('', config=True)
330 separate_in = SeparateUnicode('\n', config=True)
331 separate_out = SeparateUnicode('', config=True)
332 separate_out2 = SeparateUnicode('', config=True)
333 333 wildcards_case_sensitive = CBool(True, config=True)
334 334 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
335 335 default_value='Context', config=True)
@@ -1670,7 +1670,8 b' class InteractiveShell(SingletonConfigurable, Magic):'
1670 1670 # Remove some chars from the delimiters list. If we encounter
1671 1671 # unicode chars, discard them.
1672 1672 delims = readline.get_completer_delims().encode("ascii", "ignore")
1673 delims = delims.translate(None, self.readline_remove_delims)
1673 for d in self.readline_remove_delims:
1674 delims = delims.replace(d, "")
1674 1675 delims = delims.replace(ESC_MAGIC, '')
1675 1676 readline.set_completer_delims(delims)
1676 1677 # otherwise we end up with a monster history after a while:
@@ -3472,25 +3472,25 b' Defaulting color scheme to \'NoColor\'"""'
3472 3472 In [1]: from math import pi
3473 3473
3474 3474 In [2]: %precision 3
3475 Out[2]: '%.3f'
3475 Out[2]: u'%.3f'
3476 3476
3477 3477 In [3]: pi
3478 3478 Out[3]: 3.142
3479 3479
3480 3480 In [4]: %precision %i
3481 Out[4]: '%i'
3481 Out[4]: u'%i'
3482 3482
3483 3483 In [5]: pi
3484 3484 Out[5]: 3
3485 3485
3486 3486 In [6]: %precision %e
3487 Out[6]: '%e'
3487 Out[6]: u'%e'
3488 3488
3489 3489 In [7]: pi**10
3490 3490 Out[7]: 9.364805e+04
3491 3491
3492 3492 In [8]: %precision
3493 Out[8]: '%r'
3493 Out[8]: u'%r'
3494 3494
3495 3495 In [9]: pi**10
3496 3496 Out[9]: 93648.047476082982
@@ -36,7 +36,7 b' from IPython.core.macro import Macro'
36 36 from IPython.core.splitinput import split_user_input
37 37 from IPython.core import page
38 38
39 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 from IPython.utils.traitlets import List, Int, Any, Unicode, CBool, Bool, Instance
40 40 from IPython.utils.text import make_quoted_expr
41 41 from IPython.utils.autoattr import auto_attr
42 42
@@ -756,7 +756,7 b' class AutocallChecker(PrefilterChecker):'
756 756
757 757 class PrefilterHandler(Configurable):
758 758
759 handler_name = Str('normal')
759 handler_name = Unicode('normal')
760 760 esc_strings = List([])
761 761 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
762 762 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
@@ -797,7 +797,7 b' class PrefilterHandler(Configurable):'
797 797
798 798 class AliasHandler(PrefilterHandler):
799 799
800 handler_name = Str('alias')
800 handler_name = Unicode('alias')
801 801
802 802 def handle(self, line_info):
803 803 """Handle alias input lines. """
@@ -812,7 +812,7 b' class AliasHandler(PrefilterHandler):'
812 812
813 813 class ShellEscapeHandler(PrefilterHandler):
814 814
815 handler_name = Str('shell')
815 handler_name = Unicode('shell')
816 816 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
817 817
818 818 def handle(self, line_info):
@@ -839,7 +839,7 b' class ShellEscapeHandler(PrefilterHandler):'
839 839
840 840
841 841 class MacroHandler(PrefilterHandler):
842 handler_name = Str("macro")
842 handler_name = Unicode("macro")
843 843
844 844 def handle(self, line_info):
845 845 obj = self.shell.user_ns.get(line_info.ifun)
@@ -850,7 +850,7 b' class MacroHandler(PrefilterHandler):'
850 850
851 851 class MagicHandler(PrefilterHandler):
852 852
853 handler_name = Str('magic')
853 handler_name = Unicode('magic')
854 854 esc_strings = List([ESC_MAGIC])
855 855
856 856 def handle(self, line_info):
@@ -864,7 +864,7 b' class MagicHandler(PrefilterHandler):'
864 864
865 865 class AutoHandler(PrefilterHandler):
866 866
867 handler_name = Str('auto')
867 handler_name = Unicode('auto')
868 868 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
869 869
870 870 def handle(self, line_info):
@@ -924,7 +924,7 b' class AutoHandler(PrefilterHandler):'
924 924
925 925 class HelpHandler(PrefilterHandler):
926 926
927 handler_name = Str('help')
927 handler_name = Unicode('help')
928 928 esc_strings = List([ESC_HELP])
929 929
930 930 def handle(self, line_info):
@@ -962,7 +962,7 b' class HelpHandler(PrefilterHandler):'
962 962
963 963 class EmacsHandler(PrefilterHandler):
964 964
965 handler_name = Str('emacs')
965 handler_name = Unicode('emacs')
966 966 esc_strings = List([])
967 967
968 968 def handle(self, line_info):
@@ -448,15 +448,15 b' def doctest_precision():'
448 448 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
449 449
450 450 In [2]: %precision 5
451 Out[2]: '%.5f'
451 Out[2]: u'%.5f'
452 452
453 453 In [3]: f.float_format
454 Out[3]: '%.5f'
454 Out[3]: u'%.5f'
455 455
456 456 In [4]: %precision %e
457 Out[4]: '%e'
457 Out[4]: u'%e'
458 458
459 459 In [5]: f(3.1415927)
460 Out[5]: '3.141593e+00'
460 Out[5]: u'3.141593e+00'
461 461 """
462 462
@@ -21,7 +21,7 b' from IPython.external.qt import QtCore, QtGui'
21 21 from IPython.core.inputsplitter import IPythonInputSplitter, \
22 22 transform_ipy_prompt
23 23 from IPython.core.usage import default_gui_banner
24 from IPython.utils.traitlets import Bool, Str, Unicode
24 from IPython.utils.traitlets import Bool, Unicode
25 25 from frontend_widget import FrontendWidget
26 26 import styles
27 27
@@ -82,8 +82,7 b' class IPythonWidget(FrontendWidget):'
82 82 3. IPython: .error, .in-prompt, .out-prompt, etc
83 83 """)
84 84
85
86 syntax_style = Str(config=True,
85 syntax_style = Unicode(config=True,
87 86 help="""
88 87 If not empty, use this Pygments style for syntax highlighting.
89 88 Otherwise, the style sheet is queried for Pygments style
@@ -91,11 +90,11 b' class IPythonWidget(FrontendWidget):'
91 90 """)
92 91
93 92 # Prompts.
94 in_prompt = Str(default_in_prompt, config=True)
95 out_prompt = Str(default_out_prompt, config=True)
96 input_sep = Str(default_input_sep, config=True)
97 output_sep = Str(default_output_sep, config=True)
98 output_sep2 = Str(default_output_sep2, config=True)
93 in_prompt = Unicode(default_in_prompt, config=True)
94 out_prompt = Unicode(default_out_prompt, config=True)
95 input_sep = Unicode(default_input_sep, config=True)
96 output_sep = Unicode(default_output_sep, config=True)
97 output_sep2 = Unicode(default_output_sep2, config=True)
99 98
100 99 # FrontendWidget protected class variables.
101 100 _input_splitter_class = IPythonInputSplitter
@@ -33,7 +33,7 b' from IPython.core import ultratb'
33 33 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
34 34 from IPython.frontend.terminal.ipapp import load_default_config
35 35
36 from IPython.utils.traitlets import Bool, Str, CBool, Unicode
36 from IPython.utils.traitlets import Bool, CBool, Unicode
37 37 from IPython.utils.io import ask_yes_no
38 38
39 39
@@ -31,7 +31,7 b' from IPython.utils.terminal import toggle_set_term_title, set_term_title'
31 31 from IPython.utils.process import abbrev_cwd
32 32 from IPython.utils.warn import warn
33 33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool, Unicode
34 from IPython.utils.traitlets import Int, CBool, Unicode
35 35
36 36 #-----------------------------------------------------------------------------
37 37 # Utilities
@@ -37,7 +37,8 b' from IPython.core.application import BaseIPythonApplication'
37 37 from IPython.core.profiledir import ProfileDir
38 38 from IPython.utils.daemonize import daemonize
39 39 from IPython.utils.importstring import import_item
40 from IPython.utils.traitlets import Int, Unicode, Bool, CFloat, Dict, List
40 from IPython.utils.traitlets import (Int, Unicode, Bool, CFloat, Dict, List,
41 DottedObjectName)
41 42
42 43 from IPython.parallel.apps.baseapp import (
43 44 BaseParallelApplication,
@@ -198,7 +199,7 b' class IPClusterEngines(BaseParallelApplication):'
198 199 n = Int(2, config=True,
199 200 help="The number of engines to start.")
200 201
201 engine_launcher_class = Unicode('LocalEngineSetLauncher',
202 engine_launcher_class = DottedObjectName('LocalEngineSetLauncher',
202 203 config=True,
203 204 help="The class for launching a set of Engines."
204 205 )
@@ -330,7 +331,7 b' class IPClusterStart(IPClusterEngines):'
330 331 delay = CFloat(1., config=True,
331 332 help="delay (in s) between starting the controller and the engines")
332 333
333 controller_launcher_class = Unicode('LocalControllerLauncher',
334 controller_launcher_class = DottedObjectName('LocalControllerLauncher',
334 335 config=True,
335 336 help="The class for launching a Controller."
336 337 )
@@ -341,6 +341,8 b' class Client(HasTraits):'
341 341 if os.path.isfile(exec_key):
342 342 extra_args['keyfile'] = exec_key
343 343 else:
344 if isinstance(exec_key, unicode):
345 exec_key = exec_key.encode('ascii')
344 346 extra_args['key'] = exec_key
345 347 self.session = Session(**extra_args)
346 348
@@ -30,7 +30,7 b' from zmq.eventloop.zmqstream import ZMQStream'
30 30 # internal:
31 31 from IPython.utils.importstring import import_item
32 32 from IPython.utils.traitlets import (
33 HasTraits, Instance, Int, Unicode, Dict, Set, Tuple, CStr
33 HasTraits, Instance, Int, Unicode, Dict, Set, Tuple, Bytes, DottedObjectName
34 34 )
35 35
36 36 from IPython.parallel import error, util
@@ -111,10 +111,10 b' class EngineConnector(HasTraits):'
111 111 heartbeat (str): identity of heartbeat XREQ socket
112 112 """
113 113 id=Int(0)
114 queue=CStr()
115 control=CStr()
116 registration=CStr()
117 heartbeat=CStr()
114 queue=Bytes()
115 control=Bytes()
116 registration=Bytes()
117 heartbeat=Bytes()
118 118 pending=Set()
119 119
120 120 class HubFactory(RegistrationFactory):
@@ -179,8 +179,8 b' class HubFactory(RegistrationFactory):'
179 179
180 180 monitor_url = Unicode('')
181 181
182 db_class = Unicode('IPython.parallel.controller.dictdb.DictDB', config=True,
183 help="""The class to use for the DB backend""")
182 db_class = DottedObjectName('IPython.parallel.controller.dictdb.DictDB',
183 config=True, help="""The class to use for the DB backend""")
184 184
185 185 # not configurable
186 186 db = Instance('IPython.parallel.controller.dictdb.BaseDB')
@@ -39,7 +39,7 b' from zmq.eventloop import ioloop, zmqstream'
39 39 # local imports
40 40 from IPython.external.decorator import decorator
41 41 from IPython.config.loader import Config
42 from IPython.utils.traitlets import Instance, Dict, List, Set, Int, Str, Enum
42 from IPython.utils.traitlets import Instance, Dict, List, Set, Int, Enum
43 43
44 44 from IPython.parallel import error
45 45 from IPython.parallel.factory import SessionFactory
@@ -22,12 +22,14 b' Authors:'
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 24
25 import sys
25 26 from unittest import TestCase
26 27
27 28 from IPython.utils.traitlets import (
28 HasTraits, MetaHasTraits, TraitType, Any, CStr,
29 Int, Long, Float, Complex, Str, Unicode, TraitError,
30 Undefined, Type, This, Instance, TCPAddress, List, Tuple
29 HasTraits, MetaHasTraits, TraitType, Any, CBytes,
30 Int, Long, Float, Complex, Bytes, Unicode, TraitError,
31 Undefined, Type, This, Instance, TCPAddress, List, Tuple,
32 ObjectName, DottedObjectName
31 33 )
32 34
33 35
@@ -700,13 +702,13 b' class TestComplex(TraitTestBase):'
700 702 _bad_values = [10L, -10L, u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
701 703
702 704
703 class StringTrait(HasTraits):
705 class BytesTrait(HasTraits):
704 706
705 value = Str('string')
707 value = Bytes('string')
706 708
707 class TestString(TraitTestBase):
709 class TestBytes(TraitTestBase):
708 710
709 obj = StringTrait()
711 obj = BytesTrait()
710 712
711 713 _default_value = 'string'
712 714 _good_values = ['10', '-10', '10L',
@@ -725,11 +727,42 b' class TestUnicode(TraitTestBase):'
725 727
726 728 _default_value = u'unicode'
727 729 _good_values = ['10', '-10', '10L', '-10L', '10.1',
728 '-10.1', '', u'', 'string', u'string', ]
730 '-10.1', '', u'', 'string', u'string', u"€"]
729 731 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j,
730 732 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
731 733
732 734
735 class ObjectNameTrait(HasTraits):
736 value = ObjectName("abc")
737
738 class TestObjectName(TraitTestBase):
739 obj = ObjectNameTrait()
740
741 _default_value = "abc"
742 _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"]
743 _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
744 object(), object]
745 if sys.version_info[0] < 3:
746 _bad_values.append(u"ΓΎ")
747 else:
748 _good_values.append(u"ΓΎ") # ΓΎ=1 is valid in Python 3 (PEP 3131).
749
750
751 class DottedObjectNameTrait(HasTraits):
752 value = DottedObjectName("a.b")
753
754 class TestDottedObjectName(TraitTestBase):
755 obj = DottedObjectNameTrait()
756
757 _default_value = "a.b"
758 _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"]
759 _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc."]
760 if sys.version_info[0] < 3:
761 _bad_values.append(u"t.ΓΎ")
762 else:
763 _good_values.append(u"t.ΓΎ")
764
765
733 766 class TCPAddressTrait(HasTraits):
734 767
735 768 value = TCPAddress()
@@ -781,7 +814,7 b' class TestTupleTrait(TraitTestBase):'
781 814 def test_invalid_args(self):
782 815 self.assertRaises(TypeError, Tuple, 5)
783 816 self.assertRaises(TypeError, Tuple, default_value='hello')
784 t = Tuple(Int, CStr, default_value=(1,5))
817 t = Tuple(Int, CBytes, default_value=(1,5))
785 818
786 819 class LooseTupleTrait(HasTraits):
787 820
@@ -798,12 +831,12 b' class TestLooseTupleTrait(TraitTestBase):'
798 831 def test_invalid_args(self):
799 832 self.assertRaises(TypeError, Tuple, 5)
800 833 self.assertRaises(TypeError, Tuple, default_value='hello')
801 t = Tuple(Int, CStr, default_value=(1,5))
834 t = Tuple(Int, CBytes, default_value=(1,5))
802 835
803 836
804 837 class MultiTupleTrait(HasTraits):
805 838
806 value = Tuple(Int, Str, default_value=[99,'bottles'])
839 value = Tuple(Int, Bytes, default_value=[99,'bottles'])
807 840
808 841 class TestMultiTuple(TraitTestBase):
809 842
@@ -50,6 +50,7 b' Authors:'
50 50
51 51
52 52 import inspect
53 import re
53 54 import sys
54 55 import types
55 56 from types import (
@@ -951,30 +952,29 b' class CComplex(Complex):'
951 952 except:
952 953 self.error(obj, value)
953 954
954
955 class Str(TraitType):
955 # We should always be explicit about whether we're using bytes or unicode, both
956 # for Python 3 conversion and for reliable unicode behaviour on Python 2. So
957 # we don't have a Str type.
958 class Bytes(TraitType):
956 959 """A trait for strings."""
957 960
958 961 default_value = ''
959 962 info_text = 'a string'
960 963
961 964 def validate(self, obj, value):
962 if isinstance(value, str):
965 if isinstance(value, bytes):
963 966 return value
964 967 self.error(obj, value)
965 968
966 969
967 class CStr(Str):
970 class CBytes(Bytes):
968 971 """A casting version of the string trait."""
969 972
970 973 def validate(self, obj, value):
971 974 try:
972 return str(value)
975 return bytes(value)
973 976 except:
974 try:
975 return unicode(value)
976 except:
977 self.error(obj, value)
977 self.error(obj, value)
978 978
979 979
980 980 class Unicode(TraitType):
@@ -986,7 +986,7 b' class Unicode(TraitType):'
986 986 def validate(self, obj, value):
987 987 if isinstance(value, unicode):
988 988 return value
989 if isinstance(value, str):
989 if isinstance(value, bytes):
990 990 return unicode(value)
991 991 self.error(obj, value)
992 992
@@ -999,6 +999,50 b' class CUnicode(Unicode):'
999 999 return unicode(value)
1000 1000 except:
1001 1001 self.error(obj, value)
1002
1003
1004 class ObjectName(TraitType):
1005 """A string holding a valid object name in this version of Python.
1006
1007 This does not check that the name exists in any scope."""
1008 info_text = "a valid object identifier in Python"
1009
1010 if sys.version_info[0] < 3:
1011 # Python 2:
1012 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
1013 def isidentifier(self, s):
1014 return bool(self._name_re.match(s))
1015
1016 def coerce_str(self, obj, value):
1017 "In Python 2, coerce ascii-only unicode to str"
1018 if isinstance(value, unicode):
1019 try:
1020 return str(value)
1021 except UnicodeEncodeError:
1022 self.error(obj, value)
1023 return value
1024
1025 else:
1026 # Python 3:
1027 isidentifier = staticmethod(lambda s: s.isidentifier())
1028 coerce_str = staticmethod(lambda _,s: s)
1029
1030 def validate(self, obj, value):
1031 value = self.coerce_str(obj, value)
1032
1033 if isinstance(value, str) and self.isidentifier(value):
1034 return value
1035 self.error(obj, value)
1036
1037 class DottedObjectName(ObjectName):
1038 """A string holding a valid dotted object name in Python, such as A.b3._c"""
1039 def validate(self, obj, value):
1040 value = self.coerce_str(obj, value)
1041
1042 if isinstance(value, str) and all(self.isidentifier(x) \
1043 for x in value.split('.')):
1044 return value
1045 self.error(obj, value)
1002 1046
1003 1047
1004 1048 class Bool(TraitType):
@@ -30,7 +30,8 b' from IPython.core.application import ('
30 30 )
31 31 from IPython.utils import io
32 32 from IPython.utils.localinterfaces import LOCALHOST
33 from IPython.utils.traitlets import Any, Instance, Dict, Unicode, Int, Bool
33 from IPython.utils.traitlets import (Any, Instance, Dict, Unicode, Int, Bool,
34 DottedObjectName)
34 35 from IPython.utils.importstring import import_item
35 36 # local imports
36 37 from IPython.zmq.heartbeat import Heartbeat
@@ -75,7 +76,7 b' class KernelApp(BaseIPythonApplication):'
75 76 flags = Dict(kernel_flags)
76 77 classes = [Session]
77 78 # the kernel class, as an importstring
78 kernel_class = Unicode('IPython.zmq.pykernel.Kernel')
79 kernel_class = DottedObjectName('IPython.zmq.pykernel.Kernel')
79 80 kernel = Any()
80 81 poller = Any() # don't restrict this even though current pollers are all Threads
81 82 heartbeat = Instance(Heartbeat)
@@ -93,10 +94,10 b' class KernelApp(BaseIPythonApplication):'
93 94 # streams, etc.
94 95 no_stdout = Bool(False, config=True, help="redirect stdout to the null device")
95 96 no_stderr = Bool(False, config=True, help="redirect stderr to the null device")
96 outstream_class = Unicode('IPython.zmq.iostream.OutStream', config=True,
97 help="The importstring for the OutStream factory")
98 displayhook_class = Unicode('IPython.zmq.displayhook.ZMQDisplayHook', config=True,
99 help="The importstring for the DisplayHook factory")
97 outstream_class = DottedObjectName('IPython.zmq.iostream.OutStream',
98 config=True, help="The importstring for the OutStream factory")
99 displayhook_class = DottedObjectName('IPython.zmq.displayhook.ZMQDisplayHook',
100 config=True, help="The importstring for the DisplayHook factory")
100 101
101 102 # polling
102 103 parent = Int(0, config=True,
@@ -47,7 +47,8 b' from zmq.eventloop.zmqstream import ZMQStream'
47 47 from IPython.config.configurable import Configurable, LoggingConfigurable
48 48 from IPython.utils.importstring import import_item
49 49 from IPython.utils.jsonutil import extract_dates, squash_dates, date_default
50 from IPython.utils.traitlets import CStr, Unicode, Bool, Any, Instance, Set
50 from IPython.utils.traitlets import (Bytes, Unicode, Bool, Any, Instance, Set,
51 DottedObjectName)
51 52
52 53 #-----------------------------------------------------------------------------
53 54 # utility functions
@@ -211,7 +212,7 b' class Session(Configurable):'
211 212
212 213 debug=Bool(False, config=True, help="""Debug output in the Session""")
213 214
214 packer = Unicode('json',config=True,
215 packer = DottedObjectName('json',config=True,
215 216 help="""The name of the packer for serializing messages.
216 217 Should be one of 'json', 'pickle', or an import name
217 218 for a custom callable serializer.""")
@@ -225,7 +226,7 b' class Session(Configurable):'
225 226 else:
226 227 self.pack = import_item(str(new))
227 228
228 unpacker = Unicode('json', config=True,
229 unpacker = DottedObjectName('json', config=True,
229 230 help="""The name of the unpacker for unserializing messages.
230 231 Only used with custom functions for `packer`.""")
231 232 def _unpacker_changed(self, name, old, new):
@@ -238,7 +239,7 b' class Session(Configurable):'
238 239 else:
239 240 self.unpack = import_item(str(new))
240 241
241 session = CStr('', config=True,
242 session = Bytes(b'', config=True,
242 243 help="""The UUID identifying this session.""")
243 244 def _session_default(self):
244 245 return bytes(uuid.uuid4())
@@ -247,7 +248,7 b' class Session(Configurable):'
247 248 help="""Username for the Session. Default is your system username.""")
248 249
249 250 # message signature related traits:
250 key = CStr('', config=True,
251 key = Bytes(b'', config=True,
251 252 help="""execution key, for extra authentication.""")
252 253 def _key_changed(self, name, old, new):
253 254 if new:
@@ -126,7 +126,7 b' subclass::'
126 126
127 127 # Sample component that can be configured.
128 128 from IPython.config.configurable import Configurable
129 from IPython.utils.traitlets import Int, Float, Str, Bool
129 from IPython.utils.traitlets import Int, Float, Unicode, Bool
130 130
131 131 class MyClass(Configurable):
132 132 name = Unicode(u'defaultname', config=True)
@@ -150,8 +150,8 b' After this configuration file is loaded, the values set in it will override'
150 150 the class defaults anytime a :class:`MyClass` is created. Furthermore,
151 151 these attributes will be type checked and validated anytime they are set.
152 152 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
153 which provides the :class:`Str`, :class:`Int` and :class:`Float` types. In
154 addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
153 which provides the :class:`Unicode`, :class:`Int` and :class:`Float` types.
154 In addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
155 155 traitlets for a number of other types.
156 156
157 157 .. note::
@@ -237,14 +237,14 b' Sometimes, your classes will have an inheritance hierarchy that you want'
237 237 to be reflected in the configuration system. Here is a simple example::
238 238
239 239 from IPython.config.configurable import Configurable
240 from IPython.utils.traitlets import Int, Float, Str, Bool
240 from IPython.utils.traitlets import Int, Float, Unicode, Bool
241 241
242 242 class Foo(Configurable):
243 name = Str('fooname', config=True)
243 name = Unicode(u'fooname', config=True)
244 244 value = Float(100.0, config=True)
245 245
246 246 class Bar(Foo):
247 name = Str('barname', config=True)
247 name = Unicode(u'barname', config=True)
248 248 othervalue = Int(0, config=True)
249 249
250 250 Now, we can create a configuration file to configure instances of :class:`Foo`
@@ -253,7 +253,7 b' and :class:`Bar`::'
253 253 # config file
254 254 c = get_config()
255 255
256 c.Foo.name = 'bestname'
256 c.Foo.name = u'bestname'
257 257 c.Bar.othervalue = 10
258 258
259 259 This class hierarchy and configuration file accomplishes the following:
@@ -460,7 +460,7 b' Here are the main requirements we wanted our configuration system to have:'
460 460 hierarchical data structures, namely regular attribute access
461 461 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
462 462 import configuration attributes from one configuration file to another.
463 Forth, even though Python is dynamically typed, it does have types that can
463 Fourth, even though Python is dynamically typed, it does have types that can
464 464 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
465 465 while a ``'1'`` is a string.
466 466
General Comments 0
You need to be logged in to leave comments. Login now