Changeset 328 for pyyaml/trunk/lib3/yaml

Show
Ignore:
Timestamp:
12/29/08 12:24:05 (3 years ago)
Author:
xi
Message:

Added basic support for Python 3 (Thanks idadesub(at)users(dot)sourceforge(dot)net).

Location:
pyyaml/trunk/lib3
Files:
13 modified
1 copied

Legend:

Unmodified
Added
Removed
  • pyyaml/trunk/lib3/yaml/__init__.py

    r314 r328  
    11 
    2 from error import * 
    3  
    4 from tokens import * 
    5 from events import * 
    6 from nodes import * 
    7  
    8 from loader import * 
    9 from dumper import * 
    10  
    11 __version__ = '3.07' 
    12  
    13 try: 
    14     from cyaml import * 
    15     __with_libyaml__ = True 
    16 except ImportError: 
    17     __with_libyaml__ = False 
     2__version__ = '3.08' 
     3__with_libyaml__ = False 
     4 
     5from .error import * 
     6 
     7from .tokens import * 
     8from .events import * 
     9from .nodes import * 
     10 
     11from .loader import * 
     12from .dumper import * 
     13 
     14import io 
    1815 
    1916def scan(stream, Loader=Loader): 
     
    9289    getvalue = None 
    9390    if stream is None: 
    94         try: 
    95             from cStringIO import StringIO 
    96         except ImportError: 
    97             from StringIO import StringIO 
    98         stream = StringIO() 
     91        stream = io.StringIO() 
    9992        getvalue = stream.getvalue 
    10093    dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, 
     
    116109    getvalue = None 
    117110    if stream is None: 
    118         try: 
    119             from cStringIO import StringIO 
    120         except ImportError: 
    121             from StringIO import StringIO 
    122         stream = StringIO() 
     111        stream = io.StringIO() 
    123112        getvalue = stream.getvalue 
    124113    dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, 
     
    152141    getvalue = None 
    153142    if stream is None: 
    154         try: 
    155             from cStringIO import StringIO 
    156         except ImportError: 
    157             from StringIO import StringIO 
    158         stream = StringIO() 
     143        stream = io.StringIO() 
    159144        getvalue = stream.getvalue 
    160145    dumper = Dumper(stream, default_style=default_style, 
     
    260245            cls.yaml_dumper.add_representer(cls, cls.to_yaml) 
    261246 
    262 class YAMLObject(object): 
     247class YAMLObject(metaclass=YAMLObjectMetaclass): 
    263248    """ 
    264249    An object that can dump itself to a YAML stream 
     
    266251    """ 
    267252 
    268     __metaclass__ = YAMLObjectMetaclass 
    269253    __slots__ = ()  # no direct instantiation, so allow immutable subclasses 
    270254 
     
    275259    yaml_flow_style = None 
    276260 
     261    @classmethod 
    277262    def from_yaml(cls, loader, node): 
    278263        """ 
     
    280265        """ 
    281266        return loader.construct_yaml_object(node, cls) 
    282     from_yaml = classmethod(from_yaml) 
    283  
     267 
     268    @classmethod 
    284269    def to_yaml(cls, dumper, data): 
    285270        """ 
     
    288273        return dumper.represent_yaml_object(cls.yaml_tag, data, cls, 
    289274                flow_style=cls.yaml_flow_style) 
    290     to_yaml = classmethod(to_yaml) 
    291  
     275 
  • pyyaml/trunk/lib3/yaml/composer.py

    r258 r328  
    22__all__ = ['Composer', 'ComposerError'] 
    33 
    4 from error import MarkedYAMLError 
    5 from events import * 
    6 from nodes import * 
     4from .error import MarkedYAMLError 
     5from .events import * 
     6from .nodes import * 
    77 
    88class ComposerError(MarkedYAMLError): 
    99    pass 
    1010 
    11 class Composer(object): 
     11class Composer: 
    1212 
    1313    def __init__(self): 
     
    6767            if anchor not in self.anchors: 
    6868                raise ComposerError(None, None, "found undefined alias %r" 
    69                         % anchor.encode('utf-8'), event.start_mark) 
     69                        % anchor, event.start_mark) 
    7070            return self.anchors[anchor] 
    7171        event = self.peek_event() 
     
    7474            if anchor in self.anchors: 
    7575                raise ComposerError("found duplicate anchor %r; first occurence" 
    76                         % anchor.encode('utf-8'), self.anchors[anchor].start_mark, 
     76                        % anchor, self.anchors[anchor].start_mark, 
    7777                        "second occurence", event.start_mark) 
    7878        self.descend_resolver(parent, index) 
     
    8989        event = self.get_event() 
    9090        tag = event.tag 
    91         if tag is None or tag == u'!': 
     91        if tag is None or tag == '!': 
    9292            tag = self.resolve(ScalarNode, event.value, event.implicit) 
    9393        node = ScalarNode(tag, event.value, 
     
    100100        start_event = self.get_event() 
    101101        tag = start_event.tag 
    102         if tag is None or tag == u'!': 
     102        if tag is None or tag == '!': 
    103103            tag = self.resolve(SequenceNode, None, start_event.implicit) 
    104104        node = SequenceNode(tag, [], 
     
    118118        start_event = self.get_event() 
    119119        tag = start_event.tag 
    120         if tag is None or tag == u'!': 
     120        if tag is None or tag == '!': 
    121121            tag = self.resolve(MappingNode, None, start_event.implicit) 
    122122        node = MappingNode(tag, [], 
  • pyyaml/trunk/lib3/yaml/constructor.py

    r303 r328  
    33    'ConstructorError'] 
    44 
    5 from error import * 
    6 from nodes import * 
    7  
    8 import datetime 
    9  
    10 try: 
    11     set 
    12 except NameError: 
    13     from sets import Set as set 
    14  
    15 import binascii, re, sys, types 
     5from .error import * 
     6from .nodes import * 
     7 
     8import collections, datetime, base64, binascii, re, sys, types 
    169 
    1710class ConstructorError(MarkedYAMLError): 
    1811    pass 
    1912 
    20 class BaseConstructor(object): 
     13class BaseConstructor: 
    2114 
    2215    yaml_constructors = {} 
     
    9689        if isinstance(data, types.GeneratorType): 
    9790            generator = data 
    98             data = generator.next() 
     91            data = next(generator) 
    9992            if self.deep_construct: 
    10093                for dummy in generator: 
     
    131124        for key_node, value_node in node.value: 
    132125            key = self.construct_object(key_node, deep=deep) 
    133             try: 
    134                 hash(key) 
    135             except TypeError, exc: 
     126            if not isinstance(key, collections.Hashable): 
    136127                raise ConstructorError("while constructing a mapping", node.start_mark, 
    137                         "found unacceptable key (%s)" % exc, key_node.start_mark) 
     128                        "found unhashable key", key_node.start_mark) 
    138129            value = self.construct_object(value_node, deep=deep) 
    139130            mapping[key] = value 
     
    152143        return pairs 
    153144 
     145    @classmethod 
    154146    def add_constructor(cls, tag, constructor): 
    155147        if not 'yaml_constructors' in cls.__dict__: 
    156148            cls.yaml_constructors = cls.yaml_constructors.copy() 
    157149        cls.yaml_constructors[tag] = constructor 
    158     add_constructor = classmethod(add_constructor) 
    159  
     150 
     151    @classmethod 
    160152    def add_multi_constructor(cls, tag_prefix, multi_constructor): 
    161153        if not 'yaml_multi_constructors' in cls.__dict__: 
    162154            cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy() 
    163155        cls.yaml_multi_constructors[tag_prefix] = multi_constructor 
    164     add_multi_constructor = classmethod(add_multi_constructor) 
    165156 
    166157class SafeConstructor(BaseConstructor): 
     
    169160        if isinstance(node, MappingNode): 
    170161            for key_node, value_node in node.value: 
    171                 if key_node.tag == u'tag:yaml.org,2002:value': 
     162                if key_node.tag == 'tag:yaml.org,2002:value': 
    172163                    return self.construct_scalar(value_node) 
    173         return BaseConstructor.construct_scalar(self, node) 
     164        return super().construct_scalar(node) 
    174165 
    175166    def flatten_mapping(self, node): 
     
    178169        while index < len(node.value): 
    179170            key_node, value_node = node.value[index] 
    180             if key_node.tag == u'tag:yaml.org,2002:merge': 
     171            if key_node.tag == 'tag:yaml.org,2002:merge': 
    181172                del node.value[index] 
    182173                if isinstance(value_node, MappingNode): 
     
    200191                            "expected a mapping or list of mappings for merging, but found %s" 
    201192                            % value_node.id, value_node.start_mark) 
    202             elif key_node.tag == u'tag:yaml.org,2002:value': 
    203                 key_node.tag = u'tag:yaml.org,2002:str' 
     193            elif key_node.tag == 'tag:yaml.org,2002:value': 
     194                key_node.tag = 'tag:yaml.org,2002:str' 
    204195                index += 1 
    205196            else: 
     
    211202        if isinstance(node, MappingNode): 
    212203            self.flatten_mapping(node) 
    213         return BaseConstructor.construct_mapping(self, node, deep=deep) 
     204        return super().construct_mapping(node, deep=deep) 
    214205 
    215206    def construct_yaml_null(self, node): 
     
    218209 
    219210    bool_values = { 
    220         u'yes':     True, 
    221         u'no':      False, 
    222         u'true':    True, 
    223         u'false':   False, 
    224         u'on':      True, 
    225         u'off':     False, 
     211        'yes':      True, 
     212        'no':       False, 
     213        'true':     True, 
     214        'false':    False, 
     215        'on':       True, 
     216        'off':      False, 
    226217    } 
    227218 
     
    231222 
    232223    def construct_yaml_int(self, node): 
    233         value = str(self.construct_scalar(node)) 
     224        value = self.construct_scalar(node) 
    234225        value = value.replace('_', '') 
    235226        sign = +1 
     
    264255 
    265256    def construct_yaml_float(self, node): 
    266         value = str(self.construct_scalar(node)) 
     257        value = self.construct_scalar(node) 
    267258        value = value.replace('_', '').lower() 
    268259        sign = +1 
     
    288279 
    289280    def construct_yaml_binary(self, node): 
    290         value = self.construct_scalar(node) 
    291281        try: 
    292             return str(value).decode('base64') 
    293         except (binascii.Error, UnicodeEncodeError), exc: 
    294             raise ConstructorError(None, None, 
    295                     "failed to decode base64 data: %s" % exc, node.start_mark)  
     282            value = self.construct_scalar(node).encode('ascii') 
     283        except UnicodeEncodeError as exc: 
     284            raise ConstructorError(None, None, 
     285                    "failed to convert base64 data into ascii: %s" % exc, 
     286                    node.start_mark) 
     287        try: 
     288            return base64.decodestring(value) 
     289        except binascii.Error as exc: 
     290            raise ConstructorError(None, None, 
     291                    "failed to decode base64 data: %s" % exc, node.start_mark) 
    296292 
    297293    timestamp_regexp = re.compile( 
    298             ur'''^(?P<year>[0-9][0-9][0-9][0-9]) 
     294            r'''^(?P<year>[0-9][0-9][0-9][0-9]) 
    299295                -(?P<month>[0-9][0-9]?) 
    300296                -(?P<day>[0-9][0-9]?) 
     
    387383 
    388384    def construct_yaml_str(self, node): 
    389         value = self.construct_scalar(node) 
    390         try: 
    391             return value.encode('ascii') 
    392         except UnicodeEncodeError: 
    393             return value 
     385        return self.construct_scalar(node) 
    394386 
    395387    def construct_yaml_seq(self, node): 
     
    416408    def construct_undefined(self, node): 
    417409        raise ConstructorError(None, None, 
    418                 "could not determine a constructor for the tag %r" % node.tag.encode('utf-8'), 
     410                "could not determine a constructor for the tag %r" % node.tag, 
    419411                node.start_mark) 
    420412 
    421413SafeConstructor.add_constructor( 
    422         u'tag:yaml.org,2002:null', 
     414        'tag:yaml.org,2002:null', 
    423415        SafeConstructor.construct_yaml_null) 
    424416 
    425417SafeConstructor.add_constructor( 
    426         u'tag:yaml.org,2002:bool', 
     418        'tag:yaml.org,2002:bool', 
    427419        SafeConstructor.construct_yaml_bool) 
    428420 
    429421SafeConstructor.add_constructor( 
    430         u'tag:yaml.org,2002:int', 
     422        'tag:yaml.org,2002:int', 
    431423        SafeConstructor.construct_yaml_int) 
    432424 
    433425SafeConstructor.add_constructor( 
    434         u'tag:yaml.org,2002:float', 
     426        'tag:yaml.org,2002:float', 
    435427        SafeConstructor.construct_yaml_float) 
    436428 
    437429SafeConstructor.add_constructor( 
    438         u'tag:yaml.org,2002:binary', 
     430        'tag:yaml.org,2002:binary', 
    439431        SafeConstructor.construct_yaml_binary) 
    440432 
    441433SafeConstructor.add_constructor( 
    442         u'tag:yaml.org,2002:timestamp', 
     434        'tag:yaml.org,2002:timestamp', 
    443435        SafeConstructor.construct_yaml_timestamp) 
    444436 
    445437SafeConstructor.add_constructor( 
    446         u'tag:yaml.org,2002:omap', 
     438        'tag:yaml.org,2002:omap', 
    447439        SafeConstructor.construct_yaml_omap) 
    448440 
    449441SafeConstructor.add_constructor( 
    450         u'tag:yaml.org,2002:pairs', 
     442        'tag:yaml.org,2002:pairs', 
    451443        SafeConstructor.construct_yaml_pairs) 
    452444 
    453445SafeConstructor.add_constructor( 
    454         u'tag:yaml.org,2002:set', 
     446        'tag:yaml.org,2002:set', 
    455447        SafeConstructor.construct_yaml_set) 
    456448 
    457449SafeConstructor.add_constructor( 
    458         u'tag:yaml.org,2002:str', 
     450        'tag:yaml.org,2002:str', 
    459451        SafeConstructor.construct_yaml_str) 
    460452 
    461453SafeConstructor.add_constructor( 
    462         u'tag:yaml.org,2002:seq', 
     454        'tag:yaml.org,2002:seq', 
    463455        SafeConstructor.construct_yaml_seq) 
    464456 
    465457SafeConstructor.add_constructor( 
    466         u'tag:yaml.org,2002:map', 
     458        'tag:yaml.org,2002:map', 
    467459        SafeConstructor.construct_yaml_map) 
    468460 
     
    473465 
    474466    def construct_python_str(self, node): 
    475         return self.construct_scalar(node).encode('utf-8') 
     467        return self.construct_scalar(node) 
    476468 
    477469    def construct_python_unicode(self, node): 
    478470        return self.construct_scalar(node) 
    479471 
     472    def construct_python_bytes(self, node): 
     473        try: 
     474            value = self.construct_scalar(node).encode('ascii') 
     475        except UnicodeEncodeError as exc: 
     476            raise ConstructorError(None, None, 
     477                    "failed to convert base64 data into ascii: %s" % exc, 
     478                    node.start_mark) 
     479        try: 
     480            return base64.decodestring(value) 
     481        except binascii.Error as exc: 
     482            raise ConstructorError(None, None, 
     483                    "failed to decode base64 data: %s" % exc, node.start_mark) 
     484 
    480485    def construct_python_long(self, node): 
    481         return long(self.construct_yaml_int(node)) 
     486        return self.construct_yaml_int(node) 
    482487 
    483488    def construct_python_complex(self, node): 
     
    493498        try: 
    494499            __import__(name) 
    495         except ImportError, exc: 
     500        except ImportError as exc: 
    496501            raise ConstructorError("while constructing a Python module", mark, 
    497                     "cannot find module %r (%s)" % (name.encode('utf-8'), exc), mark) 
     502                    "cannot find module %r (%s)" % (name, exc), mark) 
    498503        return sys.modules[name] 
    499504 
     
    502507            raise ConstructorError("while constructing a Python object", mark, 
    503508                    "expected non-empty name appended to the tag", mark) 
    504         if u'.' in name: 
    505             # Python 2.4 only 
    506             #module_name, object_name = name.rsplit('.', 1) 
    507             items = name.split('.') 
    508             object_name = items.pop() 
    509             module_name = '.'.join(items) 
     509        if '.' in name: 
     510            module_name, object_name = name.rsplit('.', 1) 
    510511        else: 
    511512            module_name = '__builtin__' 
     
    513514        try: 
    514515            __import__(module_name) 
    515         except ImportError, exc: 
     516        except ImportError as exc: 
    516517            raise ConstructorError("while constructing a Python object", mark, 
    517                     "cannot find module %r (%s)" % (module_name.encode('utf-8'), exc), mark) 
     518                    "cannot find module %r (%s)" % (module_name, exc), mark) 
    518519        module = sys.modules[module_name] 
    519520        if not hasattr(module, object_name): 
    520521            raise ConstructorError("while constructing a Python object", mark, 
    521                     "cannot find %r in the module %r" % (object_name.encode('utf-8'), 
    522                         module.__name__), mark) 
     522                    "cannot find %r in the module %r" 
     523                    % (object_name, module.__name__), mark) 
    523524        return getattr(module, object_name) 
    524525 
     
    527528        if value: 
    528529            raise ConstructorError("while constructing a Python name", node.start_mark, 
    529                     "expected the empty value, but found %r" % value.encode('utf-8'), 
    530                     node.start_mark) 
     530                    "expected the empty value, but found %r" % value, node.start_mark) 
    531531        return self.find_python_name(suffix, node.start_mark) 
    532532 
     
    535535        if value: 
    536536            raise ConstructorError("while constructing a Python module", node.start_mark, 
    537                     "expected the empty value, but found %r" % value.encode('utf-8'), 
    538                     node.start_mark) 
     537                    "expected the empty value, but found %r" % value, node.start_mark) 
    539538        return self.find_python_module(suffix, node.start_mark) 
    540  
    541     class classobj: pass 
    542539 
    543540    def make_python_instance(self, suffix, node, 
     
    548545            kwds = {} 
    549546        cls = self.find_python_name(suffix, node.start_mark) 
    550         if newobj and isinstance(cls, type(self.classobj))  \ 
    551                 and not args and not kwds: 
    552             instance = self.classobj() 
    553             instance.__class__ = cls 
    554             return instance 
    555         elif newobj and isinstance(cls, type): 
     547        if newobj and isinstance(cls, type): 
    556548            return cls.__new__(cls, *args, **kwds) 
    557549        else: 
     
    620612 
    621613Constructor.add_constructor( 
    622     u'tag:yaml.org,2002:python/none', 
     614    'tag:yaml.org,2002:python/none', 
    623615    Constructor.construct_yaml_null) 
    624616 
    625617Constructor.add_constructor( 
    626     u'tag:yaml.org,2002:python/bool', 
     618    'tag:yaml.org,2002:python/bool', 
    627619    Constructor.construct_yaml_bool) 
    628620 
    629621Constructor.add_constructor( 
    630     u'tag:yaml.org,2002:python/str', 
     622    'tag:yaml.org,2002:python/str', 
    631623    Constructor.construct_python_str) 
    632624 
    633625Constructor.add_constructor( 
    634     u'tag:yaml.org,2002:python/unicode', 
     626    'tag:yaml.org,2002:python/unicode', 
    635627    Constructor.construct_python_unicode) 
    636628 
    637629Constructor.add_constructor( 
    638     u'tag:yaml.org,2002:python/int', 
     630    'tag:yaml.org,2002:python/bytes', 
     631    Constructor.construct_python_bytes) 
     632 
     633Constructor.add_constructor( 
     634    'tag:yaml.org,2002:python/int', 
    639635    Constructor.construct_yaml_int) 
    640636 
    641637Constructor.add_constructor( 
    642     u'tag:yaml.org,2002:python/long', 
     638    'tag:yaml.org,2002:python/long', 
    643639    Constructor.construct_python_long) 
    644640 
    645641Constructor.add_constructor( 
    646     u'tag:yaml.org,2002:python/float', 
     642    'tag:yaml.org,2002:python/float', 
    647643    Constructor.construct_yaml_float) 
    648644 
    649645Constructor.add_constructor( 
    650     u'tag:yaml.org,2002:python/complex', 
     646    'tag:yaml.org,2002:python/complex', 
    651647    Constructor.construct_python_complex) 
    652648 
    653649Constructor.add_constructor( 
    654     u'tag:yaml.org,2002:python/list', 
     650    'tag:yaml.org,2002:python/list', 
    655651    Constructor.construct_yaml_seq) 
    656652 
    657653Constructor.add_constructor( 
    658     u'tag:yaml.org,2002:python/tuple', 
     654    'tag:yaml.org,2002:python/tuple', 
    659655    Constructor.construct_python_tuple) 
    660656 
    661657Constructor.add_constructor( 
    662     u'tag:yaml.org,2002:python/dict', 
     658    'tag:yaml.org,2002:python/dict', 
    663659    Constructor.construct_yaml_map) 
    664660 
    665661Constructor.add_multi_constructor( 
    666     u'tag:yaml.org,2002:python/name:', 
     662    'tag:yaml.org,2002:python/name:', 
    667663    Constructor.construct_python_name) 
    668664 
    669665Constructor.add_multi_constructor( 
    670     u'tag:yaml.org,2002:python/module:', 
     666    'tag:yaml.org,2002:python/module:', 
    671667    Constructor.construct_python_module) 
    672668 
    673669Constructor.add_multi_constructor( 
    674     u'tag:yaml.org,2002:python/object:', 
     670    'tag:yaml.org,2002:python/object:', 
    675671    Constructor.construct_python_object) 
    676672 
    677673Constructor.add_multi_constructor( 
    678     u'tag:yaml.org,2002:python/object/apply:', 
     674    'tag:yaml.org,2002:python/object/apply:', 
    679675    Constructor.construct_python_object_apply) 
    680676 
    681677Constructor.add_multi_constructor( 
    682     u'tag:yaml.org,2002:python/object/new:', 
     678    'tag:yaml.org,2002:python/object/new:', 
    683679    Constructor.construct_python_object_new) 
    684680 
  • pyyaml/trunk/lib3/yaml/dumper.py

    r307 r328  
    22__all__ = ['BaseDumper', 'SafeDumper', 'Dumper'] 
    33 
    4 from emitter import * 
    5 from serializer import * 
    6 from representer import * 
    7 from resolver import * 
     4from .emitter import * 
     5from .serializer import * 
     6from .representer import * 
     7from .resolver import * 
    88 
    99class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver): 
  • pyyaml/trunk/lib3/yaml/emitter.py

    r313 r328  
    99__all__ = ['Emitter', 'EmitterError'] 
    1010 
    11 from error import YAMLError 
    12 from events import * 
     11from .error import YAMLError 
     12from .events import * 
    1313 
    1414class EmitterError(YAMLError): 
    1515    pass 
    1616 
    17 class ScalarAnalysis(object): 
     17class ScalarAnalysis: 
    1818    def __init__(self, scalar, empty, multiline, 
    1919            allow_flow_plain, allow_block_plain, 
     
    2929        self.allow_block = allow_block 
    3030 
    31 class Emitter(object): 
     31class Emitter: 
    3232 
    3333    DEFAULT_TAG_PREFIXES = { 
    34         u'!' : u'!', 
    35         u'tag:yaml.org,2002:' : u'!!', 
     34        '!' : '!', 
     35        'tag:yaml.org,2002:' : '!!', 
    3636    } 
    3737 
     
    8989        if width and width > self.best_indent*2: 
    9090            self.best_width = width 
    91         self.best_line_break = u'\n' 
    92         if line_break in [u'\r', u'\n', u'\r\n']: 
     91        self.best_line_break = '\n' 
     92        if line_break in ['\r', '\n', '\r\n']: 
    9393            self.best_line_break = line_break 
    9494 
     
    155155    def expect_stream_start(self): 
    156156        if isinstance(self.event, StreamStartEvent): 
    157             if self.event.encoding: 
     157            if self.event.encoding and not hasattr(self.stream, 'encoding'): 
    158158                self.encoding = self.event.encoding 
    159159            self.write_stream_start() 
     
    174174        if isinstance(self.event, DocumentStartEvent): 
    175175            if (self.event.version or self.event.tags) and self.open_ended: 
    176                 self.write_indicator(u'...', True) 
     176                self.write_indicator('...', True) 
    177177                self.write_indent() 
    178178            if self.event.version: 
     
    194194            if not implicit: 
    195195                self.write_indent() 
    196                 self.write_indicator(u'---', True) 
     196                self.write_indicator('---', True) 
    197197                if self.canonical: 
    198198                    self.write_indent() 
     
    200200        elif isinstance(self.event, StreamEndEvent): 
    201201            if self.open_ended: 
    202                 self.write_indicator(u'...', True) 
     202                self.write_indicator('...', True) 
    203203                self.write_indent() 
    204204            self.write_stream_end() 
     
    212212            self.write_indent() 
    213213            if self.event.explicit: 
    214                 self.write_indicator(u'...', True) 
     214                self.write_indicator('...', True) 
    215215                self.write_indent() 
    216216            self.flush_stream() 
     
    235235            self.expect_alias() 
    236236        elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)): 
    237             self.process_anchor(u'&') 
     237            self.process_anchor('&') 
    238238            self.process_tag() 
    239239            if isinstance(self.event, ScalarEvent): 
     
    257257        if self.event.anchor is None: 
    258258            raise EmitterError("anchor is not specified for alias") 
    259         self.process_anchor(u'*') 
     259        self.process_anchor('*') 
    260260        self.state = self.states.pop() 
    261261 
     
    269269 
    270270    def expect_flow_sequence(self): 
    271         self.write_indicator(u'[', True, whitespace=True) 
     271        self.write_indicator('[', True, whitespace=True) 
    272272        self.flow_level += 1 
    273273        self.increase_indent(flow=True) 
     
    278278            self.indent = self.indents.pop() 
    279279            self.flow_level -= 1 
    280             self.write_indicator(u']', False) 
     280            self.write_indicator(']', False) 
    281281            self.state = self.states.pop() 
    282282        else: 
     
    291291            self.flow_level -= 1 
    292292            if self.canonical: 
    293                 self.write_indicator(u',', False) 
     293                self.write_indicator(',', False) 
    294294                self.write_indent() 
    295             self.write_indicator(u']', False) 
     295            self.write_indicator(']', False) 
    296296            self.state = self.states.pop() 
    297297        else: 
    298             self.write_indicator(u',', False) 
     298            self.write_indicator(',', False) 
    299299            if self.canonical or self.column > self.best_width: 
    300300                self.write_indent() 
     
    305305 
    306306    def expect_flow_mapping(self): 
    307         self.write_indicator(u'{', True, whitespace=True) 
     307        self.write_indicator('{', True, whitespace=True) 
    308308        self.flow_level += 1 
    309309        self.increase_indent(flow=True) 
     
    314314            self.indent = self.indents.pop() 
    315315            self.flow_level -= 1 
    316             self.write_indicator(u'}', False) 
     316            self.write_indicator('}', False) 
    317317            self.state = self.states.pop() 
    318318        else: 
     
    323323                self.expect_node(mapping=True, simple_key=True) 
    324324            else: 
    325                 self.write_indicator(u'?', True) 
     325                self.write_indicator('?', True) 
    326326                self.states.append(self.expect_flow_mapping_value) 
    327327                self.expect_node(mapping=True) 
     
    332332            self.flow_level -= 1 
    333333            if self.canonical: 
    334                 self.write_indicator(u',', False) 
     334                self.write_indicator(',', False) 
    335335                self.write_indent() 
    336             self.write_indicator(u'}', False) 
     336            self.write_indicator('}', False) 
    337337            self.state = self.states.pop() 
    338338        else: 
    339             self.write_indicator(u',', False) 
     339            self.write_indicator(',', False) 
    340340            if self.canonical or self.column > self.best_width: 
    341341                self.write_indent() 
     
    344344                self.expect_node(mapping=True, simple_key=True) 
    345345            else: 
    346                 self.write_indicator(u'?', True) 
     346                self.write_indicator('?', True) 
    347347                self.states.append(self.expect_flow_mapping_value) 
    348348                self.expect_node(mapping=True) 
    349349 
    350350    def expect_flow_mapping_simple_value(self): 
    351         self.write_indicator(u':', False) 
     351        self.write_indicator(':', False) 
    352352        self.states.append(self.expect_flow_mapping_key) 
    353353        self.expect_node(mapping=True) 
     
    356356        if self.canonical or self.column > self.best_width: 
    357357            self.write_indent() 
    358         self.write_indicator(u':', True) 
     358        self.write_indicator(':', True) 
    359359        self.states.append(self.expect_flow_mapping_key) 
    360360        self.expect_node(mapping=True) 
     
    376376        else: 
    377377            self.write_indent() 
    378             self.write_indicator(u'-', True, indention=True) 
     378            self.write_indicator('-', True, indention=True) 
    379379            self.states.append(self.expect_block_sequence_item) 
    380380            self.expect_node(sequence=True) 
     
    399399                self.expect_node(mapping=True, simple_key=True) 
    400400            else: 
    401                 self.write_indicator(u'?', True, indention=True) 
     401                self.write_indicator('?', True, indention=True) 
    402402                self.states.append(self.expect_block_mapping_value) 
    403403                self.expect_node(mapping=True) 
    404404 
    405405    def expect_block_mapping_simple_value(self): 
    406         self.write_indicator(u':', False) 
     406        self.write_indicator(':', False) 
    407407        self.states.append(self.expect_block_mapping_key) 
    408408        self.expect_node(mapping=True) 
     
    410410    def expect_block_mapping_value(self): 
    411411        self.write_indent() 
    412         self.write_indicator(u':', True, indention=True) 
     412        self.write_indicator(':', True, indention=True) 
    413413        self.states.append(self.expect_block_mapping_key) 
    414414        self.expect_node(mapping=True) 
     
    429429        event = self.events[0] 
    430430        return (isinstance(event, ScalarEvent) and event.anchor is None 
    431                 and event.tag is None and event.implicit and event.value == u'') 
     431                and event.tag is None and event.implicit and event.value == '') 
    432432 
    433433    def check_simple_key(self): 
     
    474474                return 
    475475            if self.event.implicit[0] and tag is None: 
    476                 tag = u'!' 
     476                tag = '!' 
    477477                self.prepared_tag = None 
    478478        else: 
     
    537537        if major != 1: 
    538538            raise EmitterError("unsupported YAML version: %d.%d" % (major, minor)) 
    539         return u'%d.%d' % (major, minor) 
     539        return '%d.%d' % (major, minor) 
    540540 
    541541    def prepare_tag_handle(self, handle): 
    542542        if not handle: 
    543543            raise EmitterError("tag handle must not be empty") 
    544         if handle[0] != u'!' or handle[-1] != u'!': 
    545             raise EmitterError("tag handle must start and end with '!': %r" 
    546                     % (handle.encode('utf-8'))) 
     544        if handle[0] != '!' or handle[-1] != '!': 
     545            raise EmitterError("tag handle must start and end with '!': %r" % handle) 
    547546        for ch in handle[1:-1]: 
    548             if not (u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'    \ 
    549                     or ch in u'-_'): 
     547            if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z'    \ 
     548                    or ch in '-_'): 
    550549                raise EmitterError("invalid character %r in the tag handle: %r" 
    551                         % (ch.encode('utf-8'), handle.encode('utf-8'))) 
     550                        % (ch, handle)) 
    552551        return handle 
    553552 
     
    557556        chunks = [] 
    558557        start = end = 0 
    559         if prefix[0] == u'!': 
     558        if prefix[0] == '!': 
    560559            end = 1 
    561560        while end < len(prefix): 
    562561            ch = prefix[end] 
    563             if u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z' \ 
    564                     or ch in u'-;/?!:@&=+$,_.~*\'()[]': 
     562            if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ 
     563                    or ch in '-;/?!:@&=+$,_.~*\'()[]': 
    565564                end += 1 
    566565            else: 
     
    570569                data = ch.encode('utf-8') 
    571570                for ch in data: 
    572                     chunks.append(u'%%%02X' % ord(ch)) 
     571                    chunks.append('%%%02X' % ord(ch)) 
    573572        if start < end: 
    574573            chunks.append(prefix[start:end]) 
    575         return u''.join(chunks) 
     574        return ''.join(chunks) 
    576575 
    577576    def prepare_tag(self, tag): 
    578577        if not tag: 
    579578            raise EmitterError("tag must not be empty") 
    580         if tag == u'!': 
     579        if tag == '!': 
    581580            return tag 
    582581        handle = None 
     
    584583        for prefix in self.tag_prefixes: 
    585584            if tag.startswith(prefix)   \ 
    586                     and (prefix == u'!' or len(prefix) < len(tag)): 
     585                    and (prefix == '!' or len(prefix) < len(tag)): 
    587586                handle = self.tag_prefixes[prefix] 
    588587                suffix = tag[len(prefix):] 
     
    591590        while end < len(suffix): 
    592591            ch = suffix[end] 
    593             if u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z' \ 
    594                     or ch in u'-;/?:@&=+$,_.~*\'()[]'   \ 
    595                     or (ch == u'!' and handle != u'!'): 
     592            if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ 
     593                    or ch in '-;/?:@&=+$,_.~*\'()[]'   \ 
     594                    or (ch == '!' and handle != '!'): 
    596595                end += 1 
    597596            else: 
     
    601600                data = ch.encode('utf-8') 
    602601                for ch in data: 
    603                     chunks.append(u'%%%02X' % ord(ch)) 
     602                    chunks.append('%%%02X' % ord(ch)) 
    604603        if start < end: 
    605604            chunks.append(suffix[start:end]) 
    606         suffix_text = u''.join(chunks) 
     605        suffix_text = ''.join(chunks) 
    607606        if handle: 
    608             return u'%s%s' % (handle, suffix_text) 
    609         else: 
    610             return u'!<%s>' % suffix_text 
     607            return '%s%s' % (handle, suffix_text) 
     608        else: 
     609            return '!<%s>' % suffix_text 
    611610 
    612611    def prepare_anchor(self, anchor): 
     
    614613            raise EmitterError("anchor must not be empty") 
    615614        for ch in anchor: 
    616             if not (u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'    \ 
    617                     or ch in u'-_'): 
     615            if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z'    \ 
     616                    or ch in '-_'): 
    618617                raise EmitterError("invalid character %r in the anchor: %r" 
    619                         % (ch.encode('utf-8'), anchor.encode('utf-8'))) 
     618                        % (ch, anchor)) 
    620619        return anchor 
    621620 
     
    644643 
    645644        # Check document indicators. 
    646         if scalar.startswith(u'---') or scalar.startswith(u'...'): 
     645        if scalar.startswith('---') or scalar.startswith('...'): 
    647646            block_indicators = True 
    648647            flow_indicators = True 
     
    653652        # Last character or followed by a whitespace. 
    654653        followed_by_whitespace = (len(scalar) == 1 or 
    655                 scalar[1] in u'\0 \t\r\n\x85\u2028\u2029') 
     654                scalar[1] in '\0 \t\r\n\x85\u2028\u2029') 
    656655 
    657656        # The previous character is a space. 
     
    668667            if index == 0: 
    669668                # Leading indicators are special characters. 
    670                 if ch in u'#,[]{}&*!|>\'\"%@`':  
     669                if ch in '#,[]{}&*!|>\'\"%@`':  
    671670                    flow_indicators = True 
    672671                    block_indicators = True 
    673                 if ch in u'?:': 
     672                if ch in '?:': 
    674673                    flow_indicators = True 
    675674                    if followed_by_whitespace: 
    676675                        block_indicators = True 
    677                 if ch == u'-' and followed_by_whitespace: 
     676                if ch == '-' and followed_by_whitespace: 
    678677                    flow_indicators = True 
    679678                    block_indicators = True 
    680679            else: 
    681680                # Some indicators cannot appear within a scalar as well. 
    682                 if ch in u',?[]{}': 
     681                if ch in ',?[]{}': 
    683682                    flow_indicators = True 
    684                 if ch == u':': 
     683                if ch == ':': 
    685684                    flow_indicators = True 
    686685                    if followed_by_whitespace: 
    687686                        block_indicators = True 
    688                 if ch == u'#' and preceeded_by_whitespace: 
     687                if ch == '#' and preceeded_by_whitespace: 
    689688                    flow_indicators = True 
    690689                    block_indicators = True 
    691690 
    692691            # Check for line breaks, special, and unicode characters. 
    693             if ch in u'\n\x85\u2028\u2029': 
     692            if ch in '\n\x85\u2028\u2029': 
    694693                line_breaks = True 
    695             if not (ch == u'\n' or u'\x20' <= ch <= u'\x7E'): 
    696                 if (ch == u'\x85' or u'\xA0' <= ch <= u'\uD7FF' 
    697                         or u'\uE000' <= ch <= u'\uFFFD') and ch != u'\uFEFF': 
     694            if not (ch == '\n' or '\x20' <= ch <= '\x7E'): 
     695                if (ch == '\x85' or '\xA0' <= ch <= '\uD7FF' 
     696                        or '\uE000' <= ch <= '\uFFFD') and ch != '\uFEFF': 
    698697                    unicode_characters = True 
    699698                    if not self.allow_unicode: 
     
    703702 
    704703            # Detect important whitespace combinations. 
    705             if ch == u' ': 
     704            if ch == ' ': 
    706705                if index == 0: 
    707706                    leading_space = True 
     
    712711                previous_space = True 
    713712                previous_break = False 
    714             elif ch in u'\n\x85\u2028\u2029': 
     713            elif ch in '\n\x85\u2028\u2029': 
    715714                if index == 0: 
    716715                    leading_break = True 
     
    727726            # Prepare for the next character. 
    728727            index += 1 
    729             preceeded_by_whitespace = (ch in u'\0 \t\r\n\x85\u2028\u2029') 
     728            preceeded_by_whitespace = (ch in '\0 \t\r\n\x85\u2028\u2029') 
    730729            followed_by_whitespace = (index+1 >= len(scalar) or 
    731                     scalar[index+1] in u'\0 \t\r\n\x85\u2028\u2029') 
     730                    scalar[index+1] in '\0 \t\r\n\x85\u2028\u2029') 
    732731 
    733732        # Let's decide what styles are allowed. 
     
    788787        # Write BOM if needed. 
    789788        if self.encoding and self.encoding.startswith('utf-16'): 
    790             self.stream.write(u'\xFF\xFE'.encode(self.encoding)) 
     789            self.stream.write('\xFF\xFE'.encode(self.encoding)) 
    791790 
    792791    def write_stream_end(self): 
     
    798797            data = indicator 
    799798        else: 
    800             data = u' '+indicator 
     799            data = ' '+indicator 
    801800        self.whitespace = whitespace 
    802801        self.indention = self.indention and indention 
     
    814813        if self.column < indent: 
    815814            self.whitespace = True 
    816             data = u' '*(indent-self.column) 
     815            data = ' '*(indent-self.column) 
    817816            self.column = indent 
    818817            if self.encoding: 
     
    832831 
    833832    def write_version_directive(self, version_text): 
    834         data = u'%%YAML %s' % version_text 
     833        data = '%%YAML %s' % version_text 
    835834        if self.encoding: 
    836835            data = data.encode(self.encoding) 
     
    839838 
    840839    def write_tag_directive(self, handle_text, prefix_text): 
    841         data = u'%%TAG %s %s' % (handle_text, prefix_text) 
     840        data = '%%TAG %s %s' % (handle_text, prefix_text) 
    842841        if self.encoding: 
    843842            data = data.encode(self.encoding) 
     
    848847 
    849848    def write_single_quoted(self, text, split=True): 
    850         self.write_indicator(u'\'', True) 
     849        self.write_indicator('\'', True) 
    851850        spaces = False 
    852851        breaks = False 
     
    857856                ch = text[end] 
    858857            if spaces: 
    859                 if ch is None or ch != u' ': 
     858                if ch is None or ch != ' ': 
    860859                    if start+1 == end and self.column > self.best_width and split   \ 
    861860                            and start != 0 and end != len(text): 
     
    869868                    start = end 
    870869            elif breaks: 
    871                 if ch is None or ch not in u'\n\x85\u2028\u2029': 
    872                     if text[start] == u'\n': 
     870                if ch is None or ch not in '\n\x85\u2028\u2029': 
     871                    if text[start] == '\n': 
    873872                        self.write_line_break() 
    874873                    for br in text[start:end]: 
    875                         if br == u'\n': 
     874                        if br == '\n': 
    876875                            self.write_line_break() 
    877876                        else: 
     
    880879                    start = end 
    881880            else: 
    882                 if ch is None or ch in u' \n\x85\u2028\u2029' or ch == u'\'': 
     881                if ch is None or ch in ' \n\x85\u2028\u2029' or ch == '\'': 
    883882                    if start < end: 
    884883                        data = text[start:end] 
     
    888887                        self.stream.write(data) 
    889888                        start = end 
    890             if ch == u'\'': 
    891                 data = u'\'\'' 
     889            if ch == '\'': 
     890                data = '\'\'' 
    892891                self.column += 2 
    893892                if self.encoding: 
     
    896895                start = end + 1 
    897896            if ch is not None: 
    898                 spaces = (ch == u' ') 
    899                 breaks = (ch in u'\n\x85\u2028\u2029') 
     897                spaces = (ch == ' ') 
     898                breaks = (ch in '\n\x85\u2028\u2029') 
    900899            end += 1 
    901         self.write_indicator(u'\'', False) 
     900        self.write_indicator('\'', False) 
    902901 
    903902    ESCAPE_REPLACEMENTS = { 
    904         u'\0':      u'0', 
    905         u'\x07':    u'a', 
    906         u'\x08':    u'b', 
    907         u'\x09':    u't', 
    908         u'\x0A':    u'n', 
    909         u'\x0B':    u'v', 
    910         u'\x0C':    u'f', 
    911         u'\x0D':    u'r', 
    912         u'\x1B':    u'e', 
    913         u'\"':      u'\"', 
    914         u'\\':      u'\\', 
    915         u'\x85':    u'N', 
    916         u'\xA0':    u'_', 
    917         u'\u2028':  u'L', 
    918         u'\u2029':  u'P', 
     903        '\0':       '0', 
     904        '\x07':     'a', 
     905        '\x08':     'b', 
     906        '\x09':     't', 
     907        '\x0A':     'n', 
     908        '\x0B':     'v', 
     909        '\x0C':     'f', 
     910        '\x0D':     'r', 
     911        '\x1B':     'e', 
     912        '\"':       '\"', 
     913        '\\':       '\\', 
     914        '\x85':     'N', 
     915        '\xA0':     '_', 
     916        '\u2028':   'L', 
     917        '\u2029':   'P', 
    919918    } 
    920919 
    921920    def write_double_quoted(self, text, split=True): 
    922         self.write_indicator(u'"', True) 
     921        self.write_indicator('"', True) 
    923922        start = end = 0 
    924923        while end <= len(text): 
     
    926925            if end < len(text): 
    927926                ch = text[end] 
    928             if ch is None or ch in u'"\\\x85\u2028\u2029\uFEFF' \ 
    929                     or not (u'\x20' <= ch <= u'\x7E' 
     927            if ch is None or ch in '"\\\x85\u2028\u2029\uFEFF' \ 
     928                    or not ('\x20' <= ch <= '\x7E' 
    930929                        or (self.allow_unicode 
    931                             and (u'\xA0' <= ch <= u'\uD7FF' 
    932                                 or u'\uE000' <= ch <= u'\uFFFD'))): 
     930                            and ('\xA0' <= ch <= '\uD7FF' 
     931                                or '\uE000' <= ch <= '\uFFFD'))): 
    933932                if start < end: 
    934933                    data = text[start:end] 
     
    940939                if ch is not None: 
    941940                    if ch in self.ESCAPE_REPLACEMENTS: 
    942                         data = u'\\'+self.ESCAPE_REPLACEMENTS[ch] 
    943                     elif ch <= u'\xFF': 
    944                         data = u'\\x%02X' % ord(ch) 
    945                     elif ch <= u'\uFFFF': 
    946                         data = u'\\u%04X' % ord(ch) 
     941                        data = '\\'+self.ESCAPE_REPLACEMENTS[ch] 
     942                    elif ch <= '\xFF': 
     943                        data = '\\x%02X' % ord(ch) 
     944                    elif ch <= '\uFFFF': 
     945                        data = '\\u%04X' % ord(ch) 
    947946                    else: 
    948                         data = u'\\U%08X' % ord(ch) 
     947                        data = '\\U%08X' % ord(ch) 
    949948                    self.column += len(data) 
    950949                    if self.encoding: 
     
    952951                    self.stream.write(data) 
    953952                    start = end+1 
    954             if 0 < end < len(text)-1 and (ch == u' ' or start >= end)   \ 
     953            if 0 < end < len(text)-1 and (ch == ' ' or start >= end)    \ 
    955954                    and self.column+(end-start) > self.best_width and split: 
    956                 data = text[start:end]+u'\\' 
     955                data = text[start:end]+'\\' 
    957956                if start < end: 
    958957                    start = end 
     
    964963                self.whitespace = False 
    965964                self.indention = False 
    966                 if text[start] == u' ': 
    967                     data = u'\\' 
     965                if text[start] == ' ': 
     966                    data = '\\' 
    968967                    self.column += len(data) 
    969968                    if self.encoding: 
     
    971970                    self.stream.write(data) 
    972971            end += 1 
    973         self.write_indicator(u'"', False) 
     972        self.write_indicator('"', False) 
    974973 
    975974    def determine_block_hints(self, text): 
    976         hints = u'' 
     975        hints = '' 
    977976        if text: 
    978             if text[0] in u' \n\x85\u2028\u2029': 
    979                 hints += unicode(self.best_indent) 
    980             if text[-1] not in u'\n\x85\u2028\u2029': 
    981                 hints += u'-' 
    982             elif len(text) == 1 or text[-2] in u'\n\x85\u2028\u2029': 
    983                 hints += u'+' 
     977            if text[0] in ' \n\x85\u2028\u2029': 
     978                hints += str(self.best_indent) 
     979            if text[-1] not in '\n\x85\u2028\u2029': 
     980                hints += '-' 
     981            elif len(text) == 1 or text[-2] in '\n\x85\u2028\u2029': 
     982                hints += '+' 
    984983        return hints 
    985984 
    986985    def write_folded(self, text): 
    987986        hints = self.determine_block_hints(text) 
    988         self.write_indicator(u'>'+hints, True) 
    989         if hints[-1:] == u'+': 
     987        self.write_indicator('>'+hints, True) 
     988        if hints[-1:] == '+': 
    990989            self.open_ended = True 
    991990        self.write_line_break() 
     
    999998                ch = text[end] 
    1000999            if breaks: 
    1001                 if ch is None or ch not in u'\n\x85\u2028\u2029': 
    1002                     if not leading_space and ch is not None and ch != u' '  \ 
    1003                             and text[start] == u'\n': 
     1000                if ch is None or ch not in '\n\x85\u2028\u2029': 
     1001                    if not leading_space and ch is not None and ch != ' '   \ 
     1002                            and text[start] == '\n': 
    10041003                        self.write_line_break() 
    1005                     leading_space = (ch == u' ') 
     1004                    leading_space = (ch == ' ') 
    10061005                    for br in text[start:end]: 
    1007                         if br == u'\n': 
     1006                        if br == '\n': 
    10081007                            self.write_line_break() 
    10091008                        else: 
     
    10131012                    start = end 
    10141013            elif spaces: 
    1015                 if ch != u' ': 
     1014                if ch != ' ': 
    10161015                    if start+1 == end and self.column > self.best_width: 
    10171016                        self.write_indent() 
     
    10241023                    start = end 
    10251024            else: 
    1026                 if ch is None or ch in u' \n\x85\u2028\u2029': 
     1025                if ch is None or ch in ' \n\x85\u2028\u2029': 
    10271026                    data = text[start:end] 
    10281027                    if self.encoding: 
     
    10331032                    start = end 
    10341033            if ch is not None: 
    1035                 breaks = (ch in u'\n\x85\u2028\u2029') 
    1036                 spaces = (ch == u' ') 
     1034                breaks = (ch in '\n\x85\u2028\u2029') 
     1035                spaces = (ch == ' ') 
    10371036            end += 1 
    10381037 
    10391038    def write_literal(self, text): 
    10401039        hints = self.determine_block_hints(text) 
    1041         self.write_indicator(u'|'+hints, True) 
    1042         if hints[-1:] == u'+': 
     1040        self.write_indicator('|'+hints, True) 
     1041        if hints[-1:] == '+': 
    10431042            self.open_ended = True 
    10441043        self.write_line_break() 
     
    10501049                ch = text[end] 
    10511050            if breaks: 
    1052                 if ch is None or ch not in u'\n\x85\u2028\u2029': 
     1051                if ch is None or ch not in '\n\x85\u2028\u2029': 
    10531052                    for br in text[start:end]: 
    1054                         if br == u'\n': 
     1053                        if br == '\n': 
    10551054                            self.write_line_break() 
    10561055                        else: 
     
    10601059                    start = end 
    10611060            else: 
    1062                 if ch is None or ch in u'\n\x85\u2028\u2029': 
     1061                if ch is None or ch in '\n\x85\u2028\u2029': 
    10631062                    data = text[start:end] 
    10641063                    if self.encoding: 
     
    10691068                    start = end 
    10701069            if ch is not None: 
    1071                 breaks = (ch in u'\n\x85\u2028\u2029') 
     1070                breaks = (ch in '\n\x85\u2028\u2029') 
    10721071            end += 1 
    10731072 
     
    10781077            return 
    10791078        if not self.whitespace: 
    1080             data = u' ' 
     1079            data = ' ' 
    10811080            self.column += len(data) 
    10821081            if self.encoding: 
     
    10931092                ch = text[end] 
    10941093            if spaces: 
    1095                 if ch != u' ': 
     1094                if ch != ' ': 
    10961095                    if start+1 == end and self.column > self.best_width and split: 
    10971096                        self.write_indent() 
     
    11061105                    start = end 
    11071106            elif breaks: 
    1108                 if ch not in u'\n\x85\u2028\u2029': 
    1109                     if text[start] == u'\n': 
     1107                if ch not in '\n\x85\u2028\u2029': 
     1108                    if text[start] == '\n': 
    11101109                        self.write_line_break() 
    11111110                    for br in text[start:end]: 
    1112                         if br == u'\n': 
     1111                        if br == '\n': 
    11131112                            self.write_line_break() 
    11141113                        else: 
     
    11191118                    start = end 
    11201119            else: 
    1121                 if ch is None or ch in u' \n\x85\u2028\u2029': 
     1120                if ch is None or ch in ' \n\x85\u2028\u2029': 
    11221121                    data = text[start:end] 
    11231122                    self.column += len(data) 
     
    11271126                    start = end 
    11281127            if ch is not None: 
    1129                 spaces = (ch == u' ') 
    1130                 breaks = (ch in u'\n\x85\u2028\u2029') 
     1128                spaces = (ch == ' ') 
     1129                breaks = (ch in '\n\x85\u2028\u2029') 
    11311130            end += 1 
    11321131 
  • pyyaml/trunk/lib3/yaml/error.py

    r222 r328  
    22__all__ = ['Mark', 'YAMLError', 'MarkedYAMLError'] 
    33 
    4 class Mark(object): 
     4class Mark: 
    55 
    66    def __init__(self, name, index, line, column, buffer, pointer): 
     
    1717        head = '' 
    1818        start = self.pointer 
    19         while start > 0 and self.buffer[start-1] not in u'\0\r\n\x85\u2028\u2029': 
     19        while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029': 
    2020            start -= 1 
    2121            if self.pointer-start > max_length/2-1: 
     
    2525        tail = '' 
    2626        end = self.pointer 
    27         while end < len(self.buffer) and self.buffer[end] not in u'\0\r\n\x85\u2028\u2029': 
     27        while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029': 
    2828            end += 1 
    2929            if end-self.pointer > max_length/2-1: 
     
    3131                end -= 5 
    3232                break 
    33         snippet = self.buffer[start:end].encode('utf-8') 
     33        snippet = self.buffer[start:end] 
    3434        return ' '*indent + head + snippet + tail + '\n'  \ 
    3535                + ' '*(indent+self.pointer-start+len(head)) + '^' 
  • pyyaml/trunk/lib3/yaml/loader.py

    r137 r328  
    22__all__ = ['BaseLoader', 'SafeLoader', 'Loader'] 
    33 
    4 from reader import * 
    5 from scanner import * 
    6 from parser import * 
    7 from composer import * 
    8 from constructor import * 
    9 from resolver import * 
     4from .reader import * 
     5from .scanner import * 
     6from .parser import * 
     7from .composer import * 
     8from .constructor import * 
     9from .resolver import * 
    1010 
    1111class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): 
  • pyyaml/trunk/lib3/yaml/parser.py

    r302 r328  
    6262__all__ = ['Parser', 'ParserError'] 
    6363 
    64 from error import MarkedYAMLError 
    65 from tokens import * 
    66 from events import * 
    67 from scanner import * 
     64from .error import MarkedYAMLError 
     65from .tokens import * 
     66from .events import * 
     67from .scanner import * 
    6868 
    6969class ParserError(MarkedYAMLError): 
    7070    pass 
    7171 
    72 class Parser(object): 
     72class Parser: 
    7373    # Since writing a recursive-descendant parser is a straightforward task, we 
    7474    # do not give many comments here. 
    7575 
    7676    DEFAULT_TAGS = { 
    77         u'!':   u'!', 
    78         u'!!':  u'tag:yaml.org,2002:', 
     77        '!':   '!', 
     78        '!!':  'tag:yaml.org,2002:', 
    7979    } 
    8080 
     
    215215        while self.check_token(DirectiveToken): 
    216216            token = self.get_token() 
    217             if token.name == u'YAML': 
     217            if token.name == 'YAML': 
    218218                if self.yaml_version is not None: 
    219219                    raise ParserError(None, None, 
     
    225225                            token.start_mark) 
    226226                self.yaml_version = token.value 
    227             elif token.name == u'TAG': 
     227            elif token.name == 'TAG': 
    228228                handle, prefix = token.value 
    229229                if handle in self.tag_handles: 
    230230                    raise ParserError(None, None, 
    231                             "duplicate tag handle %r" % handle.encode('utf-8'), 
     231                            "duplicate tag handle %r" % handle, 
    232232                            token.start_mark) 
    233233                self.tag_handles[handle] = prefix 
     
    299299                    if handle not in self.tag_handles: 
    300300                        raise ParserError("while parsing a node", start_mark, 
    301                                 "found undefined tag handle %r" % handle.encode('utf-8'), 
     301                                "found undefined tag handle %r" % handle, 
    302302                                tag_mark) 
    303303                    tag = self.tag_handles[handle]+suffix 
    304304                else: 
    305305                    tag = suffix 
    306             #if tag == u'!': 
     306            #if tag == '!': 
    307307            #    raise ParserError("while parsing a node", start_mark, 
    308308            #            "found non-specific tag '!'", tag_mark, 
     
    311311                start_mark = end_mark = self.peek_token().start_mark 
    312312            event = None 
    313             implicit = (tag is None or tag == u'!') 
     313            implicit = (tag is None or tag == '!') 
    314314            if indentless_sequence and self.check_token(BlockEntryToken): 
    315315                end_mark = self.peek_token().end_mark 
     
    321321                    token = self.get_token() 
    322322                    end_mark = token.end_mark 
    323                     if (token.plain and tag is None) or tag == u'!': 
     323                    if (token.plain and tag is None) or tag == '!': 
    324324                        implicit = (True, False) 
    325325                    elif tag is None: 
     
    353353                    # Empty scalars are allowed even if a tag or an anchor is 
    354354                    # specified. 
    355                     event = ScalarEvent(anchor, tag, (implicit, False), u'', 
     355                    event = ScalarEvent(anchor, tag, (implicit, False), '', 
    356356                            start_mark, end_mark) 
    357357                    self.state = self.states.pop() 
     
    581581 
    582582    def process_empty_scalar(self, mark): 
    583         return ScalarEvent(None, None, (True, False), u'', mark, mark) 
    584  
     583        return ScalarEvent(None, None, (True, False), '', mark, mark) 
     584 
  • pyyaml/trunk/lib3/yaml/reader.py

    r323 r328  
    1818__all__ = ['Reader', 'ReaderError'] 
    1919 
    20 from error import YAMLError, Mark 
     20from .error import YAMLError, Mark 
    2121 
    2222import codecs, re 
    23  
    24 # Unfortunately, codec functions in Python 2.3 does not support the `finish` 
    25 # arguments, so we have to write our own wrappers. 
    26  
    27 try: 
    28     codecs.utf_8_decode('', 'strict', False) 
    29     from codecs import utf_8_decode, utf_16_le_decode, utf_16_be_decode 
    30  
    31 except TypeError: 
    32  
    33     def utf_16_le_decode(data, errors, finish=False): 
    34         if not finish and len(data) % 2 == 1: 
    35             data = data[:-1] 
    36         return codecs.utf_16_le_decode(data, errors) 
    37  
    38     def utf_16_be_decode(data, errors, finish=False): 
    39         if not finish and len(data) % 2 == 1: 
    40             data = data[:-1] 
    41         return codecs.utf_16_be_decode(data, errors) 
    42  
    43     def utf_8_decode(data, errors, finish=False): 
    44         if not finish: 
    45             # We are trying to remove a possible incomplete multibyte character 
    46             # from the suffix of the data. 
    47             # The first byte of a multi-byte sequence is in the range 0xc0 to 0xfd. 
    48             # All further bytes are in the range 0x80 to 0xbf. 
    49             # UTF-8 encoded UCS characters may be up to six bytes long. 
    50             count = 0 
    51             while count < 5 and count < len(data)   \ 
    52                     and '\x80' <= data[-count-1] <= '\xBF': 
    53                 count -= 1 
    54             if count < 5 and count < len(data)  \ 
    55                     and '\xC0' <= data[-count-1] <= '\xFD': 
    56                 data = data[:-count-1] 
    57         return codecs.utf_8_decode(data, errors) 
    5823 
    5924class ReaderError(YAMLError): 
     
    6732 
    6833    def __str__(self): 
    69         if isinstance(self.character, str): 
     34        if isinstance(self.character, bytes): 
    7035            return "'%s' codec can't decode byte #x%02x: %s\n"  \ 
    7136                    "  in \"%s\", position %d"    \ 
     
    8045class Reader(object): 
    8146    # Reader: 
    82     # - determines the data encoding and converts it to unicode, 
     47    # - determines the data encoding and converts it to a unicode string, 
    8348    # - checks if characters are in allowed range, 
    8449    # - adds '\0' to the end. 
    8550 
    8651    # Reader accepts 
     52    #  - a `bytes` object, 
    8753    #  - a `str` object, 
    88     #  - a `unicode` object, 
    8954    #  - a file-like object with its `read` method returning `str`, 
    9055    #  - a file-like object with its `read` method returning `unicode`. 
     
    9762        self.stream_pointer = 0 
    9863        self.eof = True 
    99         self.buffer = u'' 
     64        self.buffer = '' 
    10065        self.pointer = 0 
    10166        self.raw_buffer = None 
     
    10570        self.line = 0 
    10671        self.column = 0 
    107         if isinstance(stream, unicode): 
     72        if isinstance(stream, str): 
    10873            self.name = "<unicode string>" 
    10974            self.check_printable(stream) 
    110             self.buffer = stream+u'\0' 
    111         elif isinstance(stream, str): 
    112             self.name = "<string>" 
     75            self.buffer = stream+'\0' 
     76        elif isinstance(stream, bytes): 
     77            self.name = "<byte string>" 
    11378            self.raw_buffer = stream 
    11479            self.determine_encoding() 
     
    11782            self.name = getattr(stream, 'name', "<file>") 
    11883            self.eof = False 
    119             self.raw_buffer = '' 
     84            self.raw_buffer = None 
    12085            self.determine_encoding() 
    12186 
     
    139104            self.pointer += 1 
    140105            self.index += 1 
    141             if ch in u'\n\x85\u2028\u2029'  \ 
    142                     or (ch == u'\r' and self.buffer[self.pointer] != u'\n'): 
     106            if ch in '\n\x85\u2028\u2029'  \ 
     107                    or (ch == '\r' and self.buffer[self.pointer] != '\n'): 
    143108                self.line += 1 
    144109                self.column = 0 
    145             elif ch != u'\uFEFF': 
     110            elif ch != '\uFEFF': 
    146111                self.column += 1 
    147112            length -= 1 
     
    156121 
    157122    def determine_encoding(self): 
    158         while not self.eof and len(self.raw_buffer) < 2: 
     123        while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2): 
    159124            self.update_raw() 
    160         if not isinstance(self.raw_buffer, unicode): 
     125        if isinstance(self.raw_buffer, bytes): 
    161126            if self.raw_buffer.startswith(codecs.BOM_UTF16_LE): 
    162                 self.raw_decode = utf_16_le_decode 
     127                self.raw_decode = codecs.utf_16_le_decode 
    163128                self.encoding = 'utf-16-le' 
    164129            elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE): 
    165                 self.raw_decode = utf_16_be_decode 
     130                self.raw_decode = codecs.utf_16_be_decode 
    166131                self.encoding = 'utf-16-be' 
    167132            else: 
    168                 self.raw_decode = utf_8_decode 
     133                self.raw_decode = codecs.utf_8_decode 
    169134                self.encoding = 'utf-8' 
    170135        self.update(1) 
    171136 
    172     NON_PRINTABLE = re.compile(u'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD]') 
     137    NON_PRINTABLE = re.compile('[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD]') 
    173138    def check_printable(self, data): 
    174139        match = self.NON_PRINTABLE.search(data) 
     
    191156                    data, converted = self.raw_decode(self.raw_buffer, 
    192157                            'strict', self.eof) 
    193                 except UnicodeDecodeError, exc: 
     158                except UnicodeDecodeError as exc: 
    194159                    character = exc.object[exc.start] 
    195160                    if self.stream is not None: 
     
    206171            self.raw_buffer = self.raw_buffer[converted:] 
    207172            if self.eof: 
    208                 self.buffer += u'\0' 
     173                self.buffer += '\0' 
    209174                self.raw_buffer = None 
    210175                break 
    211176 
    212     def update_raw(self, size=1024): 
     177    def update_raw(self, size=4096): 
    213178        data = self.stream.read(size) 
    214         if data: 
     179        if self.raw_buffer is None: 
     180            self.raw_buffer = data 
     181        else: 
    215182            self.raw_buffer += data 
    216             self.stream_pointer += len(data) 
    217         else: 
     183        self.stream_pointer += len(data) 
     184        if not data: 
    218185            self.eof = True 
    219186 
  • pyyaml/trunk/lib3/yaml/representer.py

    r248 r328  
    33    'RepresenterError'] 
    44 
    5 from error import * 
    6 from nodes import * 
    7  
    8 import datetime 
    9  
    10 try: 
    11     set 
    12 except NameError: 
    13     from sets import Set as set 
    14  
    15 import sys, copy_reg, types 
     5from .error import * 
     6from .nodes import * 
     7 
     8import datetime, sys, copyreg, types, base64 
    169 
    1710class RepresenterError(YAMLError): 
    1811    pass 
    1912 
    20 class BaseRepresenter(object): 
     13class BaseRepresenter: 
    2114 
    2215    yaml_representers = {} 
     
    3629        self.object_keeper = [] 
    3730        self.alias_key = None 
    38  
    39     def get_classobj_bases(self, cls): 
    40         bases = [cls] 
    41         for base in cls.__bases__: 
    42             bases.extend(self.get_classobj_bases(base)) 
    43         return bases 
    4431 
    4532    def represent_data(self, data): 
     
    5744            self.object_keeper.append(data) 
    5845        data_types = type(data).__mro__ 
    59         if type(data) is types.InstanceType: 
    60             data_types = self.get_classobj_bases(data.__class__)+list(data_types) 
    6146        if data_types[0] in self.yaml_representers: 
    6247            node = self.yaml_representers[data_types[0]](self, data) 
     
    7257                    node = self.yaml_representers[None](self, data) 
    7358                else: 
    74                     node = ScalarNode(None, unicode(data)) 
     59                    node = ScalarNode(None, str(data)) 
    7560        #if alias_key is not None: 
    7661        #    self.represented_objects[alias_key] = node 
    7762        return node 
    7863 
     64    @classmethod 
    7965    def add_representer(cls, data_type, representer): 
    8066        if not 'yaml_representers' in cls.__dict__: 
    8167            cls.yaml_representers = cls.yaml_representers.copy() 
    8268        cls.yaml_representers[data_type] = representer 
    83     add_representer = classmethod(add_representer) 
    84  
     69 
     70    @classmethod 
    8571    def add_multi_representer(cls, data_type, representer): 
    8672        if not 'yaml_multi_representers' in cls.__dict__: 
    8773            cls.yaml_multi_representers = cls.yaml_multi_representers.copy() 
    8874        cls.yaml_multi_representers[data_type] = representer 
    89     add_multi_representer = classmethod(add_multi_representer) 
    9075 
    9176    def represent_scalar(self, tag, value, style=None): 
     
    122107        best_style = True 
    123108        if hasattr(mapping, 'items'): 
    124             mapping = mapping.items() 
    125             mapping.sort() 
     109            mapping = list(mapping.items()) 
     110            try: 
     111                mapping = sorted(mapping) 
     112            except TypeError: 
     113                pass 
    126114        for item_key, item_value in mapping: 
    127115            node_key = self.represent_data(item_key) 
     
    147135        if data in [None, ()]: 
    148136            return True 
    149         if isinstance(data, (str, unicode, bool, int, float)): 
     137        if isinstance(data, (str, bytes, bool, int, float)): 
    150138            return True 
    151139 
    152140    def represent_none(self, data): 
    153         return self.represent_scalar(u'tag:yaml.org,2002:null', 
    154                 u'null') 
     141        return self.represent_scalar('tag:yaml.org,2002:null', 'null') 
    155142 
    156143    def represent_str(self, data): 
    157         tag = None 
    158         style = None 
    159         try: 
    160             data = unicode(data, 'ascii') 
    161             tag = u'tag:yaml.org,2002:str' 
    162         except UnicodeDecodeError: 
    163             try: 
    164                 data = unicode(data, 'utf-8') 
    165                 tag = u'tag:yaml.org,2002:str' 
    166             except UnicodeDecodeError: 
    167                 data = data.encode('base64') 
    168                 tag = u'tag:yaml.org,2002:binary' 
    169                 style = '|' 
    170         return self.represent_scalar(tag, data, style=style) 
    171  
    172     def represent_unicode(self, data): 
    173         return self.represent_scalar(u'tag:yaml.org,2002:str', data) 
     144        return self.represent_scalar('tag:yaml.org,2002:str', data) 
     145 
     146    def represent_binary(self, data): 
     147        data = base64.encodestring(data).decode('ascii') 
     148        return self.represent_scalar('tag:yaml.org,2002:binary', data, style='|') 
    174149 
    175150    def represent_bool(self, data): 
    176151        if data: 
    177             value = u'true' 
    178         else: 
    179             value = u'false' 
    180         return self.represent_scalar(u'tag:yaml.org,2002:bool', value) 
     152            value = 'true' 
     153        else: 
     154            value = 'false' 
     155        return self.represent_scalar('tag:yaml.org,2002:bool', value) 
    181156 
    182157    def represent_int(self, data): 
    183         return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data)) 
    184  
    185     def represent_long(self, data): 
    186         return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data)) 
     158        return self.represent_scalar('tag:yaml.org,2002:int', str(data)) 
    187159 
    188160    inf_value = 1e300 
     
    192164    def represent_float(self, data): 
    193165        if data != data or (data == 0.0 and data == 1.0): 
    194             value = u'.nan' 
     166            value = '.nan' 
    195167        elif data == self.inf_value: 
    196             value = u'.inf' 
     168            value = '.inf' 
    197169        elif data == -self.inf_value: 
    198             value = u'-.inf' 
    199         else: 
    200             value = unicode(repr(data)).lower() 
     170            value = '-.inf' 
     171        else: 
     172            value = repr(data).lower() 
    201173            # Note that in some cases `repr(data)` represents a float number 
    202174            # without the decimal parts.  For instance: 
     
    206178            # to the definition of the `!!float` tag.  We fix this by adding 
    207179            # '.0' before the 'e' symbol. 
    208             if u'.' not in value and u'e' in value: 
    209                 value = value.replace(u'e', u'.0e', 1) 
    210         return self.represent_scalar(u'tag:yaml.org,2002:float', value) 
     180            if '.' not in value and 'e' in value: 
     181                value = value.replace('e', '.0e', 1) 
     182        return self.represent_scalar('tag:yaml.org,2002:float', value) 
    211183 
    212184    def represent_list(self, data): 
     
    218190        #            break 
    219191        #if not pairs: 
    220             return self.represent_sequence(u'tag:yaml.org,2002:seq', data) 
     192            return self.represent_sequence('tag:yaml.org,2002:seq', data) 
    221193        #value = [] 
    222194        #for item_key, item_value in data: 
     
    226198 
    227199    def represent_dict(self, data): 
    228         return self.represent_mapping(u'tag:yaml.org,2002:map', data) 
     200        return self.represent_mapping('tag:yaml.org,2002:map', data) 
    229201 
    230202    def represent_set(self, data): 
     
    232204        for key in data: 
    233205            value[key] = None 
    234         return self.represent_mapping(u'tag:yaml.org,2002:set', value) 
     206        return self.represent_mapping('tag:yaml.org,2002:set', value) 
    235207 
    236208    def represent_date(self, data): 
    237         value = unicode(data.isoformat()) 
    238         return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value) 
     209        value = data.isoformat() 
     210        return self.represent_scalar('tag:yaml.org,2002:timestamp', value) 
    239211 
    240212    def represent_datetime(self, data): 
    241         value = unicode(data.isoformat(' ')) 
    242         return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value) 
     213        value = data.isoformat(' ') 
     214        return self.represent_scalar('tag:yaml.org,2002:timestamp', value) 
    243215 
    244216    def represent_yaml_object(self, tag, data, cls, flow_style=None): 
     
    258230        SafeRepresenter.represent_str) 
    259231 
    260 SafeRepresenter.add_representer(unicode, 
    261         SafeRepresenter.represent_unicode) 
     232SafeRepresenter.add_representer(bytes, 
     233        SafeRepresenter.represent_binary) 
    262234 
    263235SafeRepresenter.add_representer(bool, 
     
    267239        SafeRepresenter.represent_int) 
    268240 
    269 SafeRepresenter.add_representer(long, 
    270         SafeRepresenter.represent_long) 
    271  
    272241SafeRepresenter.add_representer(float, 
    273242        SafeRepresenter.represent_float) 
     
    287256SafeRepresenter.add_representer(datetime.date, 
    288257        SafeRepresenter.represent_date) 
     258 
    289259SafeRepresenter.add_representer(datetime.datetime, 
    290260        SafeRepresenter.represent_datetime) 
     
    295265class Representer(SafeRepresenter): 
    296266 
    297     def represent_str(self, data): 
    298         tag = None 
    299         style = None 
    300         try: 
    301             data = unicode(data, 'ascii') 
    302             tag = u'tag:yaml.org,2002:str' 
    303         except UnicodeDecodeError: 
    304             try: 
    305                 data = unicode(data, 'utf-8') 
    306                 tag = u'tag:yaml.org,2002:python/str' 
    307             except UnicodeDecodeError: 
    308                 data = data.encode('base64') 
    309                 tag = u'tag:yaml.org,2002:binary' 
    310                 style = '|' 
    311         return self.represent_scalar(tag, data, style=style) 
    312  
    313     def represent_unicode(self, data): 
    314         tag = None 
    315         try: 
    316             data.encode('ascii') 
    317             tag = u'tag:yaml.org,2002:python/unicode' 
    318         except UnicodeEncodeError: 
    319             tag = u'tag:yaml.org,2002:str' 
    320         return self.represent_scalar(tag, data) 
    321  
    322     def represent_long(self, data): 
    323         tag = u'tag:yaml.org,2002:int' 
    324         if int(data) is not data: 
    325             tag = u'tag:yaml.org,2002:python/long' 
    326         return self.represent_scalar(tag, unicode(data)) 
    327  
    328267    def represent_complex(self, data): 
    329268        if data.imag == 0.0: 
    330             data = u'%r' % data.real 
     269            data = '%r' % data.real 
    331270        elif data.real == 0.0: 
    332             data = u'%rj' % data.imag 
     271            data = '%rj' % data.imag 
    333272        elif data.imag > 0: 
    334             data = u'%r+%rj' % (data.real, data.imag) 
    335         else: 
    336             data = u'%r%rj' % (data.real, data.imag) 
    337         return self.represent_scalar(u'tag:yaml.org,2002:python/complex', data) 
     273            data = '%r+%rj' % (data.real, data.imag) 
     274        else: 
     275            data = '%r%rj' % (data.real, data.imag) 
     276        return self.represent_scalar('tag:yaml.org,2002:python/complex', data) 
    338277 
    339278    def represent_tuple(self, data): 
    340         return self.represent_sequence(u'tag:yaml.org,2002:python/tuple', data) 
     279        return self.represent_sequence('tag:yaml.org,2002:python/tuple', data) 
    341280 
    342281    def represent_name(self, data): 
    343         name = u'%s.%s' % (data.__module__, data.__name__) 
    344         return self.represent_scalar(u'tag:yaml.org,2002:python/name:'+name, u'') 
     282        name = '%s.%s' % (data.__module__, data.__name__) 
     283        return self.represent_scalar('tag:yaml.org,2002:python/name:'+name, '') 
    345284 
    346285    def represent_module(self, data): 
    347286        return self.represent_scalar( 
    348                 u'tag:yaml.org,2002:python/module:'+data.__name__, u'') 
    349  
    350     def represent_instance(self, data): 
    351         # For instances of classic classes, we use __getinitargs__ and 
    352         # __getstate__ to serialize the data. 
    353  
    354         # If data.__getinitargs__ exists, the object must be reconstructed by 
    355         # calling cls(**args), where args is a tuple returned by 
    356         # __getinitargs__. Otherwise, the cls.__init__ method should never be 
    357         # called and the class instance is created by instantiating a trivial 
    358         # class and assigning to the instance's __class__ variable. 
    359  
    360         # If data.__getstate__ exists, it returns the state of the object. 
    361         # Otherwise, the state of the object is data.__dict__. 
    362  
    363         # We produce either a !!python/object or !!python/object/new node. 
    364         # If data.__getinitargs__ does not exist and state is a dictionary, we 
    365         # produce a !!python/object node . Otherwise we produce a 
    366         # !!python/object/new node. 
    367  
    368         cls = data.__class__ 
    369         class_name = u'%s.%s' % (cls.__module__, cls.__name__) 
    370         args = None 
    371         state = None 
    372         if hasattr(data, '__getinitargs__'): 
    373             args = list(data.__getinitargs__()) 
    374         if hasattr(data, '__getstate__'): 
    375             state = data.__getstate__() 
    376         else: 
    377             state = data.__dict__ 
    378         if args is None and isinstance(state, dict): 
    379             return self.represent_mapping( 
    380                     u'tag:yaml.org,2002:python/object:'+class_name, state) 
    381         if isinstance(state, dict) and not state: 
    382             return self.represent_sequence( 
    383                     u'tag:yaml.org,2002:python/object/new:'+class_name, args) 
    384         value = {} 
    385         if args: 
    386             value['args'] = args 
    387         value['state'] = state 
    388         return self.represent_mapping( 
    389                 u'tag:yaml.org,2002:python/object/new:'+class_name, value) 
     287                'tag:yaml.org,2002:python/module:'+data.__name__, '') 
    390288 
    391289    def represent_object(self, data): 
     
    407305 
    408306        cls = type(data) 
    409         if cls in copy_reg.dispatch_table: 
    410             reduce = copy_reg.dispatch_table[cls](data) 
     307        if cls in copyreg.dispatch_table: 
     308            reduce = copyreg.dispatch_table[cls](data) 
    411309        elif hasattr(data, '__reduce_ex__'): 
    412310            reduce = data.__reduce_ex__(2) 
     
    427325            function = args[0] 
    428326            args = args[1:] 
    429             tag = u'tag:yaml.org,2002:python/object/new:' 
     327            tag = 'tag:yaml.org,2002:python/object/new:' 
    430328            newobj = True 
    431329        else: 
    432             tag = u'tag:yaml.org,2002:python/object/apply:' 
     330            tag = 'tag:yaml.org,2002:python/object/apply:' 
    433331            newobj = False 
    434         function_name = u'%s.%s' % (function.__module__, function.__name__) 
     332        function_name = '%s.%s' % (function.__module__, function.__name__) 
    435333        if not args and not listitems and not dictitems \ 
    436334                and isinstance(state, dict) and newobj: 
    437335            return self.represent_mapping( 
    438                     u'tag:yaml.org,2002:python/object:'+function_name, state) 
     336                    'tag:yaml.org,2002:python/object:'+function_name, state) 
    439337        if not listitems and not dictitems  \ 
    440338                and isinstance(state, dict) and not state: 
     
    451349        return self.represent_mapping(tag+function_name, value) 
    452350 
    453 Representer.add_representer(str, 
    454         Representer.represent_str) 
    455  
    456 Representer.add_representer(unicode, 
    457         Representer.represent_unicode) 
    458  
    459 Representer.add_representer(long, 
    460         Representer.represent_long) 
    461  
    462351Representer.add_representer(complex, 
    463352        Representer.represent_complex) 
     
    469358        Representer.represent_name) 
    470359 
    471 Representer.add_representer(types.ClassType, 
    472         Representer.represent_name) 
    473  
    474360Representer.add_representer(types.FunctionType, 
    475361        Representer.represent_name) 
     
    481367        Representer.represent_module) 
    482368 
    483 Representer.add_multi_representer(types.InstanceType, 
    484         Representer.represent_instance) 
    485  
    486369Representer.add_multi_representer(object, 
    487370        Representer.represent_object) 
  • pyyaml/trunk/lib3/yaml/resolver.py

    r260 r328  
    22__all__ = ['BaseResolver', 'Resolver'] 
    33 
    4 from error import * 
    5 from nodes import * 
     4from .error import * 
     5from .nodes import * 
    66 
    77import re 
     
    1010    pass 
    1111 
    12 class BaseResolver(object): 
    13  
    14     DEFAULT_SCALAR_TAG = u'tag:yaml.org,2002:str' 
    15     DEFAULT_SEQUENCE_TAG = u'tag:yaml.org,2002:seq' 
    16     DEFAULT_MAPPING_TAG = u'tag:yaml.org,2002:map' 
     12class BaseResolver: 
     13 
     14    DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str' 
     15    DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq' 
     16    DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map' 
    1717 
    1818    yaml_implicit_resolvers = {} 
     
    2323        self.resolver_prefix_paths = [] 
    2424 
     25    @classmethod 
    2526    def add_implicit_resolver(cls, tag, regexp, first): 
    2627        if not 'yaml_implicit_resolvers' in cls.__dict__: 
     
    3031        for ch in first: 
    3132            cls.yaml_implicit_resolvers.setdefault(ch, []).append((tag, regexp)) 
    32     add_implicit_resolver = classmethod(add_implicit_resolver) 
    33  
     33 
     34    @classmethod 
    3435    def add_path_resolver(cls, tag, path, kind=None): 
    3536        # Note: `add_path_resolver` is experimental.  The API could be changed. 
     
    6768                node_check = MappingNode 
    6869            elif node_check not in [ScalarNode, SequenceNode, MappingNode]  \ 
    69                     and not isinstance(node_check, basestring) \ 
     70                    and not isinstance(node_check, str) \ 
    7071                    and node_check is not None: 
    7172                raise ResolverError("Invalid node checker: %s" % node_check) 
    72             if not isinstance(index_check, (basestring, int))   \ 
     73            if not isinstance(index_check, (str, int))  \ 
    7374                    and index_check is not None: 
    7475                raise ResolverError("Invalid index checker: %s" % index_check) 
     
    8485            raise ResolverError("Invalid node kind: %s" % kind) 
    8586        cls.yaml_path_resolvers[tuple(new_path), kind] = tag 
    86     add_path_resolver = classmethod(add_path_resolver) 
    8787 
    8888    def descend_resolver(self, current_node, current_index): 
     
    118118            current_node, current_index): 
    119119        node_check, index_check = path[depth-1] 
    120         if isinstance(node_check, basestring): 
     120        if isinstance(node_check, str): 
    121121            if current_node.tag != node_check: 
    122122                return 
     
    129129                and current_index is None: 
    130130            return 
    131         if isinstance(index_check, basestring): 
     131        if isinstance(index_check, str): 
    132132            if not (isinstance(current_index, ScalarNode) 
    133133                    and index_check == current_index.value): 
     
    140140    def resolve(self, kind, value, implicit): 
    141141        if kind is ScalarNode and implicit[0]: 
    142             if value == u'': 
    143                 resolvers = self.yaml_implicit_resolvers.get(u'', []) 
     142            if value == '': 
     143                resolvers = self.yaml_implicit_resolvers.get('', []) 
    144144            else: 
    145145                resolvers = self.yaml_implicit_resolvers.get(value[0], []) 
     
    166166 
    167167Resolver.add_implicit_resolver( 
    168         u'tag:yaml.org,2002:bool', 
    169         re.compile(ur'''^(?:yes|Yes|YES|no|No|NO 
     168        'tag:yaml.org,2002:bool', 
     169        re.compile(r'''^(?:yes|Yes|YES|no|No|NO 
    170170                    |true|True|TRUE|false|False|FALSE 
    171171                    |on|On|ON|off|Off|OFF)$''', re.X), 
    172         list(u'yYnNtTfFoO')) 
    173  
    174 Resolver.add_implicit_resolver( 
    175         u'tag:yaml.org,2002:float', 
    176         re.compile(ur'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? 
     172        list('yYnNtTfFoO')) 
     173 
     174Resolver.add_implicit_resolver( 
     175        'tag:yaml.org,2002:float', 
     176        re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? 
    177177                    |\.[0-9_]+(?:[eE][-+][0-9]+)? 
    178178                    |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]* 
    179179                    |[-+]?\.(?:inf|Inf|INF) 
    180180                    |\.(?:nan|NaN|NAN))$''', re.X), 
    181         list(u'-+0123456789.')) 
    182  
    183 Resolver.add_implicit_resolver( 
    184         u'tag:yaml.org,2002:int', 
    185         re.compile(ur'''^(?:[-+]?0b[0-1_]+ 
     181        list('-+0123456789.')) 
     182 
     183Resolver.add_implicit_resolver( 
     184        'tag:yaml.org,2002:int', 
     185        re.compile(r'''^(?:[-+]?0b[0-1_]+ 
    186186                    |[-+]?0[0-7_]+ 
    187187                    |[-+]?(?:0|[1-9][0-9_]*) 
    188188                    |[-+]?0x[0-9a-fA-F_]+ 
    189189                    |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), 
    190         list(u'-+0123456789')) 
    191  
    192 Resolver.add_implicit_resolver( 
    193         u'tag:yaml.org,2002:merge', 
    194         re.compile(ur'^(?:<<)$'), 
     190        list('-+0123456789')) 
     191 
     192Resolver.add_implicit_resolver( 
     193        'tag:yaml.org,2002:merge', 
     194        re.compile(r'^(?:<<)$'), 
    195195        ['<']) 
    196196 
    197197Resolver.add_implicit_resolver( 
    198         u'tag:yaml.org,2002:null', 
    199         re.compile(ur'''^(?: ~ 
     198        'tag:yaml.org,2002:null', 
     199        re.compile(r'''^(?: ~ 
    200200                    |null|Null|NULL 
    201201                    | )$''', re.X), 
    202         [u'~', u'n', u'N', u'']) 
    203  
    204 Resolver.add_implicit_resolver( 
    205         u'tag:yaml.org,2002:timestamp', 
    206         re.compile(ur'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] 
     202        ['~', 'n', 'N', '']) 
     203 
     204Resolver.add_implicit_resolver( 
     205        'tag:yaml.org,2002:timestamp', 
     206        re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] 
    207207                    |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? 
    208208                     (?:[Tt]|[ \t]+)[0-9][0-9]? 
    209209                     :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)? 
    210210                     (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), 
    211         list(u'0123456789')) 
    212  
    213 Resolver.add_implicit_resolver( 
    214         u'tag:yaml.org,2002:value', 
    215         re.compile(ur'^(?:=)$'), 
     211        list('0123456789')) 
     212 
     213Resolver.add_implicit_resolver( 
     214        'tag:yaml.org,2002:value', 
     215        re.compile(r'^(?:=)$'), 
    216216        ['=']) 
    217217 
     
    219219# because plain scalars cannot start with '!', '&', or '*'. 
    220220Resolver.add_implicit_resolver( 
    221         u'tag:yaml.org,2002:yaml', 
    222         re.compile(ur'^(?:!|&|\*)$'), 
    223         list(u'!&*')) 
    224  
     221        'tag:yaml.org,2002:yaml', 
     222        re.compile(r'^(?:!|&|\*)$'), 
     223        list('!&*')) 
     224 
  • pyyaml/trunk/lib3/yaml/scanner.py

    r222 r328  
    2727__all__ = ['Scanner', 'ScannerError'] 
    2828 
    29 from error import MarkedYAMLError 
    30 from tokens import * 
     29from .error import MarkedYAMLError 
     30from .tokens import * 
    3131 
    3232class ScannerError(MarkedYAMLError): 
    3333    pass 
    3434 
    35 class SimpleKey(object): 
     35class SimpleKey: 
    3636    # See below simple keys treatment. 
    3737 
     
    4444        self.mark = mark 
    4545 
    46 class Scanner(object): 
     46class Scanner: 
    4747 
    4848    def __init__(self): 
     
    167167 
    168168        # Is it the end of stream? 
    169         if ch == u'\0': 
     169        if ch == '\0': 
    170170            return self.fetch_stream_end() 
    171171 
    172172        # Is it a directive? 
    173         if ch == u'%' and self.check_directive(): 
     173        if ch == '%' and self.check_directive(): 
    174174            return self.fetch_directive() 
    175175 
    176176        # Is it the document start? 
    177         if ch == u'-' and self.check_document_start(): 
     177        if ch == '-' and self.check_document_start(): 
    178178            return self.fetch_document_start() 
    179179 
    180180        # Is it the document end? 
    181         if ch == u'.' and self.check_document_end(): 
     181        if ch == '.' and self.check_document_end(): 
    182182            return self.fetch_document_end() 
    183183 
    184184        # TODO: support for BOM within a stream. 
    185         #if ch == u'\uFEFF': 
     185        #if ch == '\uFEFF': 
    186186        #    return self.fetch_bom()    <-- issue BOMToken 
    187187 
     
    189189 
    190190        # Is it the flow sequence start indicator? 
    191         if ch == u'[': 
     191        if ch == '[': 
    192192            return self.fetch_flow_sequence_start() 
    193193 
    194194        # Is it the flow mapping start indicator? 
    195         if ch == u'{': 
     195        if ch == '{': 
    196196            return self.fetch_flow_mapping_start() 
    197197 
    198198        # Is it the flow sequence end indicator? 
    199         if ch == u']': 
     199        if ch == ']': 
    200200            return self.fetch_flow_sequence_end() 
    201201 
    202202        # Is it the flow mapping end indicator? 
    203         if ch == u'}': 
     203        if ch == '}': 
    204204            return self.fetch_flow_mapping_end() 
    205205 
    206206        # Is it the flow entry indicator? 
    207         if ch == u',': 
     207        if ch == ',': 
    208208            return self.fetch_flow_entry() 
    209209 
    210210        # Is it the block entry indicator? 
    211         if ch == u'-' and self.check_block_entry(): 
     211        if ch == '-' and self.check_block_entry(): 
    212212            return self.fetch_block_entry() 
    213213 
    214214        # Is it the key indicator? 
    215         if ch == u'?' and self.check_key(): 
     215        if ch == '?' and self.check_key(): 
    216216            return self.fetch_key() 
    217217 
    218218        # Is it the value indicator? 
    219         if ch == u':' and self.check_value(): 
     219        if ch == ':' and self.check_value(): 
    220220            return self.fetch_value() 
    221221 
    222222        # Is it an alias? 
    223         if ch == u'*': 
     223        if ch == '*': 
    224224            return self.fetch_alias() 
    225225 
    226226        # Is it an anchor? 
    227         if ch == u'&': 
     227        if ch == '&': 
    228228            return self.fetch_anchor() 
    229229 
    230230        # Is it a tag? 
    231         if ch == u'!': 
     231        if ch == '!': 
    232232            return self.fetch_tag() 
    233233 
    234234        # Is it a literal scalar? 
    235         if ch == u'|' and not self.flow_level: 
     235        if ch == '|' and not self.flow_level: 
    236236            return self.fetch_literal() 
    237237 
    238238        # Is it a folded scalar? 
    239         if ch == u'>' and not self.flow_level: 
     239        if ch == '>' and not self.flow_level: 
    240240            return self.fetch_folded() 
    241241 
    242242        # Is it a single quoted scalar? 
    243         if ch == u'\'': 
     243        if ch == '\'': 
    244244            return self.fetch_single() 
    245245 
    246246        # Is it a double quoted scalar? 
    247         if ch == u'\"': 
     247        if ch == '\"': 
    248248            return self.fetch_double() 
    249249 
     
    254254        # No? It's an error. Let's produce a nice error message. 
    255255        raise ScannerError("while scanning for the next token", None, 
    256                 "found character %r that cannot start any token" 
    257                 % ch.encode('utf-8'), self.get_mark()) 
     256                "found character %r that cannot start any token" % ch, 
     257                self.get_mark()) 
    258258 
    259259    # Simple keys treatment. 
     
    281281        # Disabling this procedure will allow simple keys of any length and 
    282282        # height (may cause problems if indentation is broken though). 
    283         for level in self.possible_simple_keys.keys(): 
     283        for level in list(self.possible_simple_keys): 
    284284            key = self.possible_simple_keys[level] 
    285285            if key.line != self.line  \ 
     
    692692        # DOCUMENT-START:   ^ '---' (' '|'\n') 
    693693        if self.column == 0: 
    694             if self.prefix(3) == u'---'  \ 
    695                     and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': 
     694            if self.prefix(3) == '---'  \ 
     695                    and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': 
    696696                return True 
    697697 
     
    700700        # DOCUMENT-END:     ^ '...' (' '|'\n') 
    701701        if self.column == 0: 
    702             if self.prefix(3) == u'...'  \ 
    703                     and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': 
     702            if self.prefix(3) == '...'  \ 
     703                    and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': 
    704704                return True 
    705705 
     
    707707 
    708708        # BLOCK-ENTRY:      '-' (' '|'\n') 
    709         return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029' 
     709        return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' 
    710710 
    711711    def check_key(self): 
     
    717717        # KEY(block context):   '?' (' '|'\n') 
    718718        else: 
    719             return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029' 
     719            return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' 
    720720 
    721721    def check_value(self): 
     
    727727        # VALUE(block context): ':' (' '|'\n') 
    728728        else: 
    729             return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029' 
     729            return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' 
    730730 
    731731    def check_plain(self): 
     
    744744        # independent. 
    745745        ch = self.peek() 
    746         return ch not in u'\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`'  \ 
    747                 or (self.peek(1) not in u'\0 \t\r\n\x85\u2028\u2029' 
    748                         and (ch == u'-' or (not self.flow_level and ch in u'?:'))) 
     746        return ch not in '\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`'  \ 
     747                or (self.peek(1) not in '\0 \t\r\n\x85\u2028\u2029' 
     748                        and (ch == '-' or (not self.flow_level and ch in '?:'))) 
    749749 
    750750    # Scanners. 
     
    770770        # Scanners for block, flow, and plain scalars need to be modified. 
    771771 
    772         if self.index == 0 and self.peek() == u'\uFEFF': 
     772        if self.index == 0 and self.peek() == '\uFEFF': 
    773773            self.forward() 
    774774        found = False 
    775775        while not found: 
    776             while self.peek() == u' ': 
     776            while self.peek() == ' ': 
    777777                self.forward() 
    778             if self.peek() == u'#': 
    779                 while self.peek() not in u'\0\r\n\x85\u2028\u2029': 
     778            if self.peek() == '#': 
     779                while self.peek() not in '\0\r\n\x85\u2028\u2029': 
    780780                    self.forward() 
    781781            if self.scan_line_break(): 
     
    791791        name = self.scan_directive_name(start_mark) 
    792792        value = None 
    793         if name == u'YAML': 
     793        if name == 'YAML': 
    794794            value = self.scan_yaml_directive_value(start_mark) 
    795795            end_mark = self.get_mark() 
    796         elif name == u'TAG': 
     796        elif name == 'TAG': 
    797797            value = self.scan_tag_directive_value(start_mark) 
    798798            end_mark = self.get_mark() 
    799799        else: 
    800800            end_mark = self.get_mark() 
    801             while self.peek() not in u'\0\r\n\x85\u2028\u2029': 
     801            while self.peek() not in '\0\r\n\x85\u2028\u2029': 
    802802                self.forward() 
    803803        self.scan_directive_ignored_line(start_mark) 
     
    808808        length = 0 
    809809        ch = self.peek(length) 
    810         while u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'  \ 
    811                 or ch in u'-_': 
     810        while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z'  \ 
     811                or ch in '-_': 
    812812            length += 1 
    813813            ch = self.peek(length) 
     
    815815            raise ScannerError("while scanning a directive", start_mark, 
    816816                    "expected alphabetic or numeric character, but found %r" 
    817                     % ch.encode('utf-8'), self.get_mark()) 
     817                    % ch, self.get_mark()) 
    818818        value = self.prefix(length) 
    819819        self.forward(length) 
    820820        ch = self.peek() 
    821         if ch not in u'\0 \r\n\x85\u2028\u2029': 
     821        if ch not in '\0 \r\n\x85\u2028\u2029': 
    822822            raise ScannerError("while scanning a directive", start_mark, 
    823823                    "expected alphabetic or numeric character, but found %r" 
    824                     % ch.encode('utf-8'), self.get_mark()) 
     824                    % ch, self.get_mark()) 
    825825        return value 
    826826 
    827827    def scan_yaml_directive_value(self, start_mark): 
    828828        # See the specification for details. 
    829         while self.peek() == u' ': 
     829        while self.peek() == ' ': 
    830830            self.forward() 
    831831        major = self.scan_yaml_directive_number(start_mark) 
    832832        if self.peek() != '.': 
    833833            raise ScannerError("while scanning a directive", start_mark, 
    834                     "expected a digit or '.', but found %r" 
    835                     % self.peek().encode('utf-8'), 
     834                    "expected a digit or '.', but found %r" % self.peek(), 
    836835                    self.get_mark()) 
    837836        self.forward() 
    838837        minor = self.scan_yaml_directive_number(start_mark) 
    839         if self.peek() not in u'\0 \r\n\x85\u2028\u2029': 
     838        if self.peek() not in '\0 \r\n\x85\u2028\u2029': 
    840839            raise ScannerError("while scanning a directive", start_mark, 
    841                     "expected a digit or ' ', but found %r" 
    842                     % self.peek().encode('utf-8'), 
     840                    "expected a digit or ' ', but found %r" % self.peek(), 
    843841                    self.get_mark()) 
    844842        return (major, minor) 
     
    847845        # See the specification for details. 
    848846        ch = self.peek() 
    849         if not (u'0' <= ch <= '9'): 
     847        if not ('0' <= ch <= '9'): 
    850848            raise ScannerError("while scanning a directive", start_mark, 
    851                     "expected a digit, but found %r" % ch.encode('utf-8'), 
    852                     self.get_mark()) 
     849                    "expected a digit, but found %r" % ch, self.get_mark()) 
    853850        length = 0 
    854         while u'0' <= self.peek(length) <= u'9': 
     851        while '0' <= self.peek(length) <= '9': 
    855852            length += 1 
    856853        value = int(self.prefix(length)) 
     
    860857    def scan_tag_directive_value(self, start_mark): 
    861858        # See the specification for details. 
    862         while self.peek() == u' ': 
     859        while self.peek() == ' ': 
    863860            self.forward() 
    864861        handle = self.scan_tag_directive_handle(start_mark) 
    865         while self.peek() == u' ': 
     862        while self.peek() == ' ': 
    866863            self.forward() 
    867864        prefix = self.scan_tag_directive_prefix(start_mark) 
     
    872869        value = self.scan_tag_handle('directive', start_mark) 
    873870        ch = self.peek() 
    874         if ch != u' ': 
     871        if ch != ' ': 
    875872            raise ScannerError("while scanning a directive", start_mark, 
    876                     "expected ' ', but found %r" % ch.encode('utf-8'), 
    877                     self.get_mark()) 
     873                    "expected ' ', but found %r" % ch, self.get_mark()) 
    878874        return value 
    879875 
     
    882878        value = self.scan_tag_uri('directive', start_mark) 
    883879        ch = self.peek() 
    884         if ch not in u'\0 \r\n\x85\u2028\u2029': 
     880        if ch not in '\0 \r\n\x85\u2028\u2029': 
    885881            raise ScannerError("while scanning a directive", start_mark, 
    886                     "expected ' ', but found %r" % ch.encode('utf-8'), 
    887                     self.get_mark()) 
     882                    "expected ' ', but found %r" % ch, self.get_mark()) 
    888883        return value 
    889884 
    890885    def scan_directive_ignored_line(self, start_mark): 
    891886        # See the specification for details. 
    892         while self.peek() == u' ': 
     887        while self.peek() == ' ': 
    893888            self.forward() 
    894         if self.peek() == u'#': 
    895             while self.peek() not in u'\0\r\n\x85\u2028\u2029': 
     889        if self.peek() == '#': 
     890            while self.peek() not in '\0\r\n\x85\u2028\u2029': 
    896891                self.forward() 
    897892        ch = self.peek() 
    898         if ch not in u'\0\r\n\x85\u2028\u2029': 
     893        if ch not in '\0\r\n\x85\u2028\u2029': 
    899894            raise ScannerError("while scanning a directive", start_mark, 
    900895                    "expected a comment or a line break, but found %r" 
    901                         % ch.encode('utf-8'), self.get_mark()) 
     896                        % ch, self.get_mark()) 
    902897        self.scan_line_break() 
    903898 
     
    920915        length = 0 
    921916        ch = self.peek(length) 
    922         while u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'  \ 
    923                 or ch in u'-_': 
     917        while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z'  \ 
     918                or ch in '-_': 
    924919            length += 1 
    925920            ch = self.peek(length) 
     
    927922            raise ScannerError("while scanning an %s" % name, start_mark, 
    928923                    "expected alphabetic or numeric character, but found %r" 
    929                     % ch.encode('utf-8'), self.get_mark()) 
     924                    % ch, self.get_mark()) 
    930925        value = self.prefix(length) 
    931926        self.forward(length) 
    932927        ch = self.peek() 
    933         if ch not in u'\0 \t\r\n\x85\u2028\u2029?:,]}%@`': 
     928        if ch not in '\0 \t\r\n\x85\u2028\u2029?:,]}%@`': 
    934929            raise ScannerError("while scanning an %s" % name, start_mark, 
    935930                    "expected alphabetic or numeric character, but found %r" 
    936                     % ch.encode('utf-8'), self.get_mark()) 
     931                    % ch, self.get_mark()) 
    937932        end_mark = self.get_mark() 
    938933        return TokenClass(value, start_mark, end_mark) 
     
    942937        start_mark = self.get_mark() 
    943938        ch = self.peek(1) 
    944         if ch == u'<': 
     939        if ch == '<': 
    945940            handle = None 
    946941            self.forward(2) 
    947942            suffix = self.scan_tag_uri('tag', start_mark) 
    948             if self.peek() != u'>': 
     943            if self.peek() != '>': 
    949944                raise ScannerError("while parsing a tag", start_mark, 
    950                         "expected '>', but found %r" % self.peek().encode('utf-8'), 
     945                        "expected '>', but found %r" % self.peek(), 
    951946                        self.get_mark()) 
    952947            self.forward() 
    953         elif ch in u'\0 \t\r\n\x85\u2028\u2029': 
     948        elif ch in '\0 \t\r\n\x85\u2028\u2029': 
    954949            handle = None 
    955             suffix = u'!' 
     950            suffix = '!' 
    956951            self.forward() 
    957952        else: 
    958953            length = 1 
    959954            use_handle = False 
    960             while ch not in u'\0 \r\n\x85\u2028\u2029': 
    961                 if ch == u'!': 
     955            while ch not in '\0 \r\n\x85\u2028\u2029': 
     956                if ch == '!': 
    962957                    use_handle = True 
    963958                    break 
    964959                length += 1 
    965960                ch = self.peek(length) 
    966             handle = u'!' 
     961            handle = '!' 
    967962            if use_handle: 
    968963                handle = self.scan_tag_handle('tag', start_mark) 
    969964            else: 
    970                 handle = u'!' 
     965                handle = '!' 
    971966                self.forward() 
    972967            suffix = self.scan_tag_uri('tag', start_mark) 
    973968        ch = self.peek() 
    974         if ch not in u'\0 \r\n\x85\u2028\u2029': 
     969        if ch not in '\0 \r\n\x85\u2028\u2029': 
    975970            raise ScannerError("while scanning a tag", start_mark, 
    976                     "expected ' ', but found %r" % ch.encode('utf-8'), 
    977                     self.get_mark()) 
     971                    "expected ' ', but found %r" % ch, self.get_mark()) 
    978972        value = (handle, suffix) 
    979973        end_mark = self.get_mark() 
     
    10061000            indent = min_indent+increment-1 
    10071001            breaks, end_mark = self.scan_block_scalar_breaks(indent) 
    1008         line_break = u'' 
     1002        line_break = '' 
    10091003 
    10101004        # Scan the inner part of the block scalar. 
    1011         while self.column == indent and self.peek() != u'\0': 
     1005        while self.column == indent and self.peek() != '\0': 
    10121006            chunks.extend(breaks) 
    1013             leading_non_space = self.peek() not in u' \t' 
     1007            leading_non_space = self.peek() not in ' \t' 
    10141008            length = 0 
    1015             while self.peek(length) not in u'\0\r\n\x85\u2028\u2029': 
     1009            while self.peek(length) not in '\0\r\n\x85\u2028\u2029': 
    10161010                length += 1 
    10171011            chunks.append(self.prefix(length)) 
     
    10191013            line_break = self.scan_line_break() 
    10201014            breaks, end_mark = self.scan_block_scalar_breaks(indent) 
    1021             if self.column == indent and self.peek() != u'\0': 
     1015            if self.column == indent and self.peek() != '\0': 
    10221016 
    10231017                # Unfortunately, folding rules are ambiguous. 
     
    10251019                # This is the folding according to the specification: 
    10261020                 
    1027                 if folded and line_break == u'\n'   \ 
    1028                         and leading_non_space and self.peek() not in u' \t': 
     1021                if folded and line_break == '\n'    \ 
     1022                        and leading_non_space and self.peek() not in ' \t': 
    10291023                    if not breaks: 
    1030                         chunks.append(u' ') 
     1024                        chunks.append(' ') 
    10311025                else: 
    10321026                    chunks.append(line_break) 
     
    10351029                # examples): 
    10361030                # 
    1037                 #if folded and line_break == u'\n': 
     1031                #if folded and line_break == '\n': 
    10381032                #    if not breaks: 
    10391033                #        if self.peek() not in ' \t': 
    1040                 #            chunks.append(u' ') 
     1034                #            chunks.append(' ') 
    10411035                #        else: 
    10421036                #            chunks.append(line_break) 
     
    10531047 
    10541048        # We are done. 
    1055         return ScalarToken(u''.join(chunks), False, start_mark, end_mark, 
     1049        return ScalarToken(''.join(chunks), False, start_mark, end_mark, 
    10561050                style) 
    10571051 
     
    10611055        increment = None 
    10621056        ch = self.peek() 
    1063         if ch in u'+-': 
     1057        if ch in '+-': 
    10641058            if ch == '+': 
    10651059                chomping = True 
     
    10681062            self.forward() 
    10691063            ch = self.peek() 
    1070             if ch in u'0123456789': 
     1064            if ch in '0123456789': 
    10711065                increment = int(ch) 
    10721066                if increment == 0: 
     
    10751069                            self.get_mark()) 
    10761070                self.forward() 
    1077         elif ch in u'0123456789': 
     1071        elif ch in '0123456789': 
    10781072            increment = int(ch) 
    10791073            if increment == 0: 
     
    10831077            self.forward() 
    10841078            ch = self.peek() 
    1085             if ch in u'+-': 
     1079            if ch in '+-': 
    10861080                if ch == '+': 
    10871081                    chomping = True 
     
    10901084                self.forward() 
    10911085        ch = self.peek() 
    1092         if ch not in u'\0 \r\n\x85\u2028\u2029': 
     1086        if ch not in '\0 \r\n\x85\u2028\u2029': 
    10931087            raise ScannerError("while scanning a block scalar", start_mark, 
    10941088                    "expected chomping or indentation indicators, but found %r" 
    1095                         % ch.encode('utf-8'), self.get_mark()) 
     1089                    % ch, self.get_mark()) 
    10961090        return chomping, increment 
    10971091 
    10981092    def scan_block_scalar_ignored_line(self, start_mark): 
    10991093        # See the specification for details. 
    1100         while self.peek() == u' ': 
     1094        while self.peek() == ' ': 
    11011095            self.forward() 
    1102         if self.peek() == u'#': 
    1103             while self.peek() not in u'\0\r\n\x85\u2028\u2029': 
     1096        if self.peek() == '#': 
     1097            while self.peek() not in '\0\r\n\x85\u2028\u2029': 
    11041098                self.forward() 
    11051099        ch = self.peek() 
    1106         if ch not in u'\0\r\n\x85\u2028\u2029': 
     1100        if ch not in '\0\r\n\x85\u2028\u2029': 
    11071101            raise ScannerError("while scanning a block scalar", start_mark, 
    1108                     "expected a comment or a line break, but found %r" 
    1109                         % ch.encode('utf-8'), self.get_mark()) 
     1102                    "expected a comment or a line break, but found %r" % ch, 
     1103                    self.get_mark()) 
    11101104        self.scan_line_break() 
    11111105 
     
    11151109        max_indent = 0 
    11161110        end_mark = self.get_mark() 
    1117         while self.peek() in u' \r\n\x85\u2028\u2029': 
    1118             if self.peek() != u' ': 
     1111        while self.peek() in ' \r\n\x85\u2028\u2029': 
     1112            if self.peek() != ' ': 
    11191113                chunks.append(self.scan_line_break()) 
    11201114                end_mark = self.get_mark() 
     
    11291123        chunks = [] 
    11301124        end_mark = self.get_mark() 
    1131         while self.column < indent and self.peek() == u' ': 
     1125        while self.column < indent and self.peek() == ' ': 
    11321126            self.forward() 
    1133         while self.peek() in u'\r\n\x85\u2028\u2029': 
     1127        while self.peek() in '\r\n\x85\u2028\u2029': 
    11341128            chunks.append(self.scan_line_break()) 
    11351129            end_mark = self.get_mark() 
    1136             while self.column < indent and self.peek() == u' ': 
     1130            while self.column < indent and self.peek() == ' ': 
    11371131                self.forward() 
    11381132        return chunks, end_mark 
     
    11591153        self.forward() 
    11601154        end_mark = self.get_mark() 
    1161         return ScalarToken(u''.join(chunks), False, start_mark, end_mark, 
     1155        return ScalarToken(''.join(chunks), False, start_mark, end_mark, 
    11621156                style) 
    11631157 
    11641158    ESCAPE_REPLACEMENTS = { 
    1165         u'0':   u'\0', 
    1166         u'a':   u'\x07', 
    1167         u'b':   u'\x08', 
    1168         u't':   u'\x09', 
    1169         u'\t':  u'\x09', 
    1170         u'n':   u'\x0A', 
    1171         u'v':   u'\x0B', 
    1172         u'f':   u'\x0C', 
    1173         u'r':   u'\x0D', 
    1174         u'e':   u'\x1B', 
    1175         u' ':   u'\x20', 
    1176         u'\"':  u'\"', 
    1177         u'\\':  u'\\', 
    1178         u'N':   u'\x85', 
    1179         u'_':   u'\xA0', 
    1180         u'L':   u'\u2028', 
    1181         u'P':   u'\u2029', 
     1159        '0':    '\0', 
     1160        'a':    '\x07', 
     1161        'b':    '\x08', 
     1162        't':    '\x09', 
     1163        '\t':   '\x09', 
     1164        'n':    '\x0A', 
     1165        'v':    '\x0B', 
     1166        'f':    '\x0C', 
     1167        'r':    '\x0D', 
     1168        'e':    '\x1B', 
     1169        ' ':    '\x20', 
     1170        '\"':   '\"', 
     1171        '\\':   '\\', 
     1172        'N':    '\x85', 
     1173        '_':    '\xA0', 
     1174        'L':    '\u2028', 
     1175        'P':    '\u2029', 
    11821176    } 
    11831177 
    11841178    ESCAPE_CODES = { 
    1185         u'x':   2, 
    1186         u'u':   4, 
    1187         u'U':   8, 
     1179        'x':    2, 
     1180        'u':    4, 
     1181        'U':    8, 
    11881182    } 
    11891183 
     
    11931187        while True: 
    11941188            length = 0 
    1195             while self.peek(length) not in u'\'\"\\\0 \t\r\n\x85\u2028\u2029': 
     1189            while self.peek(length) not in '\'\"\\\0 \t\r\n\x85\u2028\u2029': 
    11961190                length += 1 
    11971191            if length: 
     
    11991193                self.forward(length) 
    12001194            ch = self.peek() 
    1201             if not double and ch == u'\'' and self.peek(1) == u'\'': 
    1202                 chunks.append(u'\'') 
     1195            if not double and ch == '\'' and self.peek(1) == '\'': 
     1196                chunks.append('\'') 
    12031197                self.forward(2) 
    1204             elif (double and ch == u'\'') or (not double and ch in u'\"\\'): 
     1198            elif (double and ch == '\'') or (not double and ch in '\"\\'): 
    12051199                chunks.append(ch) 
    12061200                self.forward() 
    1207             elif double and ch == u'\\': 
     1201            elif double and ch == '\\': 
    12081202                self.forward() 
    12091203                ch = self.peek() 
     
    12151209                    self.forward() 
    12161210                    for k in range(length): 
    1217                         if self.peek(k) not in u'0123456789ABCDEFabcdef': 
     1211                        if self.peek(k) not in '0123456789ABCDEFabcdef': 
    12181212                            raise ScannerError("while scanning a double-quoted scalar", start_mark, 
    12191213                                    "expected escape sequence of %d hexdecimal numbers, but found %r" % 
    1220                                         (length, self.peek(k).encode('utf-8')), self.get_mark()) 
     1214                                        (length, self.peek(k)), self.get_mark()) 
    12211215                    code = int(self.prefix(length), 16) 
    1222                     chunks.append(unichr(code)) 
     1216                    chunks.append(chr(code)) 
    12231217                    self.forward(length) 
    1224                 elif ch in u'\r\n\x85\u2028\u2029': 
     1218                elif ch in '\r\n\x85\u2028\u2029': 
    12251219                    self.scan_line_break() 
    12261220                    chunks.extend(self.scan_flow_scalar_breaks(double, start_mark)) 
    12271221                else: 
    12281222                    raise ScannerError("while scanning a double-quoted scalar", start_mark, 
    1229                             "found unknown escape character %r" % ch.encode('utf-8'), self.get_mark()) 
     1223                            "found unknown escape character %r" % ch, self.get_mark()) 
    12301224            else: 
    12311225                return chunks 
     
    12351229        chunks = [] 
    12361230        length = 0 
    1237         while self.peek(length) in u' \t': 
     1231        while self.peek(length) in ' \t': 
    12381232            length += 1 
    12391233        whitespaces = self.prefix(length) 
    12401234        self.forward(length) 
    12411235        ch = self.peek() 
    1242         if ch == u'\0': 
     1236        if ch == '\0': 
    12431237            raise ScannerError("while scanning a quoted scalar", start_mark, 
    12441238                    "found unexpected end of stream", self.get_mark()) 
    1245         elif ch in u'\r\n\x85\u2028\u2029': 
     1239        elif ch in '\r\n\x85\u2028\u2029': 
    12461240            line_break = self.scan_line_break() 
    12471241            breaks = self.scan_flow_scalar_breaks(double, start_mark) 
    1248             if line_break != u'\n': 
     1242            if line_break != '\n': 
    12491243                chunks.append(line_break) 
    12501244            elif not breaks: 
    1251                 chunks.append(u' ') 
     1245                chunks.append(' ') 
    12521246            chunks.extend(breaks) 
    12531247        else: 
     
    12621256            # separators. 
    12631257            prefix = self.prefix(3) 
    1264             if (prefix == u'---' or prefix == u'...')   \ 
    1265                     and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': 
     1258            if (prefix == '---' or prefix == '...')   \ 
     1259                    and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': 
    12661260                raise ScannerError("while scanning a quoted scalar", start_mark, 
    12671261                        "found unexpected document separator", self.get_mark()) 
    1268             while self.peek() in u' \t': 
     1262            while self.peek() in ' \t': 
    12691263                self.forward() 
    1270             if self.peek() in u'\r\n\x85\u2028\u2029': 
     1264            if self.peek() in '\r\n\x85\u2028\u2029': 
    12711265                chunks.append(self.scan_line_break()) 
    12721266            else: 
     
    12901284        while True: 
    12911285            length = 0 
    1292             if self.peek() == u'#': 
     1286            if self.peek() == '#': 
    12931287                break 
    12941288            while True: 
    12951289                ch = self.peek(length) 
    1296                 if ch in u'\0 \t\r\n\x85\u2028\u2029'   \ 
    1297                         or (not self.flow_level and ch == u':' and 
    1298                                 self.peek(length+1) in u'\0 \t\r\n\x85\u2028\u2029') \ 
    1299                         or (self.flow_level and ch in u',:?[]{}'): 
     1290                if ch in '\0 \t\r\n\x85\u2028\u2029'    \ 
     1291                        or (not self.flow_level and ch == ':' and 
     1292                                self.peek(length+1) in '\0 \t\r\n\x85\u2028\u2029') \ 
     1293                        or (self.flow_level and ch in ',:?[]{}'): 
    13001294                    break 
    13011295                length += 1 
    13021296            # It's not clear what we should do with ':' in the flow context. 
    1303             if (self.flow_level and ch == u':' 
    1304                     and self.peek(length+1) not in u'\0 \t\r\n\x85\u2028\u2029,[]{}'): 
     1297            if (self.flow_level and ch == ':' 
     1298                    and self.peek(length+1) not in '\0 \t\r\n\x85\u2028\u2029,[]{}'): 
    13051299                self.forward(length) 
    13061300                raise ScannerError("while scanning a plain scalar", start_mark, 
     
    13151309            end_mark = self.get_mark() 
    13161310            spaces = self.scan_plain_spaces(indent, start_mark) 
    1317             if not spaces or self.peek() == u'#' \ 
     1311            if not spaces or self.peek() == '#' \ 
    13181312                    or (not self.flow_level and self.column < indent): 
    13191313                break 
    1320         return ScalarToken(u''.join(chunks), True, start_mark, end_mark) 
     1314        return ScalarToken(''.join(chunks), True, start_mark, end_mark) 
    13211315 
    13221316    def scan_plain_spaces(self, indent, start_mark): 
     
    13261320        chunks = [] 
    13271321        length = 0 
    1328         while self.peek(length) in u' ': 
     1322        while self.peek(length) in ' ': 
    13291323            length += 1 
    13301324        whitespaces = self.prefix(length) 
    13311325        self.forward(length) 
    13321326        ch = self.peek() 
    1333         if ch in u'\r\n\x85\u2028\u2029': 
     1327        if ch in '\r\n\x85\u2028\u2029': 
    13341328            line_break = self.scan_line_break() 
    13351329            self.allow_simple_key = True 
    13361330            prefix = self.prefix(3) 
    1337             if (prefix == u'---' or prefix == u'...')   \ 
    1338                     and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': 
     1331            if (prefix == '---' or prefix == '...')   \ 
     1332                    and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': 
    13391333                return 
    13401334            breaks = [] 
    1341             while self.peek() in u' \r\n\x85\u2028\u2029': 
     1335            while self.peek() in ' \r\n\x85\u2028\u2029': 
    13421336                if self.peek() == ' ': 
    13431337                    self.forward() 
     
    13451339                    breaks.append(self.scan_line_break()) 
    13461340                    prefix = self.prefix(3) 
    1347                     if (prefix == u'---' or prefix == u'...')   \ 
    1348                             and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': 
     1341                    if (prefix == '---' or prefix == '...')   \ 
     1342                            and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': 
    13491343                        return 
    1350             if line_break != u'\n': 
     1344            if line_break != '\n': 
    13511345                chunks.append(line_break) 
    13521346            elif not breaks: 
    1353                 chunks.append(u' ') 
     1347                chunks.append(' ') 
    13541348            chunks.extend(breaks) 
    13551349        elif whitespaces: 
     
    13621356        # tag handles. I have allowed it anyway. 
    13631357        ch = self.peek() 
    1364         if ch != u'!': 
     1358        if ch != '!': 
    13651359            raise ScannerError("while scanning a %s" % name, start_mark, 
    1366                     "expected '!', but found %r" % ch.encode('utf-8'), 
    1367                     self.get_mark()) 
     1360                    "expected '!', but found %r" % ch, self.get_mark()) 
    13681361        length = 1 
    13691362        ch = self.peek(length) 
    1370         if ch != u' ': 
    1371             while u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'  \ 
    1372                     or ch in u'-_': 
     1363        if ch != ' ': 
     1364            while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z'  \ 
     1365                    or ch in '-_': 
    13731366                length += 1 
    13741367                ch = self.peek(length) 
    1375             if ch != u'!': 
     1368            if ch != '!': 
    13761369                self.forward(length) 
    13771370                raise ScannerError("while scanning a %s" % name, start_mark, 
    1378                         "expected '!', but found %r" % ch.encode('utf-8'), 
    1379                         self.get_mark()) 
     1371                        "expected '!', but found %r" % ch, self.get_mark()) 
    13801372            length += 1 
    13811373        value = self.prefix(length) 
     
    13891381        length = 0 
    13901382        ch = self.peek(length) 
    1391         while u'0' <= ch <= u'9' or u'A' <= ch <= 'Z' or u'a' <= ch <= 'z'  \ 
    1392                 or ch in u'-;/?:@&=+$,_.!~*\'()[]%': 
    1393             if ch == u'%': 
     1383        while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z'  \ 
     1384                or ch in '-;/?:@&=+$,_.!~*\'()[]%': 
     1385            if ch == '%': 
    13941386                chunks.append(self.prefix(length)) 
    13951387                self.forward(length) 
     
    14051397        if not chunks: 
    14061398            raise ScannerError("while parsing a %s" % name, start_mark, 
    1407                     "expected URI, but found %r" % ch.encode('utf-8'), 
    1408                     self.get_mark()) 
    1409         return u''.join(chunks) 
     1399                    "expected URI, but found %r" % ch, self.get_mark()) 
     1400        return ''.join(chunks) 
    14101401 
    14111402    def scan_uri_escapes(self, name, start_mark): 
    14121403        # See the specification for details. 
    1413         bytes = [] 
     1404        codes = [] 
    14141405        mark = self.get_mark() 
    1415         while self.peek() == u'%': 
     1406        while self.peek() == '%': 
    14161407            self.forward() 
    14171408            for k in range(2): 
    1418                 if self.peek(k) not in u'0123456789ABCDEFabcdef': 
     1409                if self.peek(k) not in '0123456789ABCDEFabcdef': 
    14191410                    raise ScannerError("while scanning a %s" % name, start_mark, 
    1420                             "expected URI escape sequence of 2 hexdecimal numbers, but found %r" % 
    1421                                 (self.peek(k).encode('utf-8')), self.get_mark()) 
    1422             bytes.append(chr(int(self.prefix(2), 16))) 
     1411                            "expected URI escape sequence of 2 hexdecimal numbers, but found %r" 
     1412                            % self.peek(k), self.get_mark()) 
     1413            codes.append(int(self.prefix(2), 16)) 
    14231414            self.forward(2) 
    14241415        try: 
    1425             value = unicode(''.join(bytes), 'utf-8') 
    1426         except UnicodeDecodeError, exc: 
     1416            value = bytes(codes).decode('utf-8') 
     1417        except UnicodeDecodeError as exc: 
    14271418            raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark) 
    14281419        return value 
     
    14381429        #   default     :   '' 
    14391430        ch = self.peek() 
    1440         if ch in u'\r\n\x85': 
    1441             if self.prefix(2) == u'\r\n': 
     1431        if ch in '\r\n\x85': 
     1432            if self.prefix(2) == '\r\n': 
    14421433                self.forward(2) 
    14431434            else: 
    14441435                self.forward() 
    1445             return u'\n' 
    1446         elif ch in u'\u2028\u2029': 
     1436            return '\n' 
     1437        elif ch in '\u2028\u2029': 
    14471438            self.forward() 
    14481439            return ch 
    1449         return u'' 
     1440        return '' 
    14501441 
    14511442#try: 
  • pyyaml/trunk/lib3/yaml/serializer.py

    r222 r328  
    22__all__ = ['Serializer', 'SerializerError'] 
    33 
    4 from error import YAMLError 
    5 from events import * 
    6 from nodes import * 
     4from .error import YAMLError 
     5from .events import * 
     6from .nodes import * 
    77 
    88class SerializerError(YAMLError): 
    99    pass 
    1010 
    11 class Serializer(object): 
     11class Serializer: 
    1212 
    13     ANCHOR_TEMPLATE = u'id%03d' 
     13    ANCHOR_TEMPLATE = 'id%03d' 
    1414 
    1515    def __init__(self, encoding=None,