[pypy-commit] pypy default: pep8/cleanup
pjenvey
noreply at buildbot.pypy.org
Sat Jan 25 01:55:57 CET 2014
Author: Philip Jenvey <pjenvey at underboss.org>
Branch:
Changeset: r68923:2f70add7ec6d
Date: 2014-01-24 16:17 -0800
http://bitbucket.org/pypy/pypy/changeset/2f70add7ec6d/
Log: pep8/cleanup
diff --git a/pypy/interpreter/baseobjspace.py b/pypy/interpreter/baseobjspace.py
--- a/pypy/interpreter/baseobjspace.py
+++ b/pypy/interpreter/baseobjspace.py
@@ -232,9 +232,8 @@
raise operationerrfmt(space.w_TypeError, msg, w_result)
def ord(self, space):
- typename = space.type(self).getname(space)
- msg = "ord() expected string of length 1, but %s found"
- raise operationerrfmt(space.w_TypeError, msg, typename)
+ msg = "ord() expected string of length 1, but %T found"
+ raise operationerrfmt(space.w_TypeError, msg, self)
def __spacebind__(self, space):
return self
diff --git a/pypy/objspace/std/bytearrayobject.py b/pypy/objspace/std/bytearrayobject.py
--- a/pypy/objspace/std/bytearrayobject.py
+++ b/pypy/objspace/std/bytearrayobject.py
@@ -1,20 +1,21 @@
"""The builtin bytearray implementation"""
+from rpython.rlib.objectmodel import (
+ import_from_mixin, newlist_hint, resizelist_hint)
+from rpython.rlib.rstring import StringBuilder
+
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.buffer import RWBuffer
from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
+from pypy.interpreter.gateway import WrappedDefault, interp2app, unwrap_spec
from pypy.interpreter.signature import Signature
from pypy.objspace.std.sliceobject import W_SliceObject
from pypy.objspace.std.stdtypedef import StdTypeDef
from pypy.objspace.std.stringmethods import StringMethods
from pypy.objspace.std.util import get_positive_index
-from rpython.rlib.objectmodel import newlist_hint, resizelist_hint, import_from_mixin
-from rpython.rlib.rstring import StringBuilder
+NON_HEX_MSG = "non-hexadecimal number found in fromhex() arg at position %d"
-def _make_data(s):
- return [s[i] for i in range(len(s))]
class W_BytearrayObject(W_Root):
import_from_mixin(StringMethods)
@@ -23,7 +24,7 @@
w_self.data = data
def __repr__(w_self):
- """ representation for debugging purposes """
+ """representation for debugging purposes"""
return "%s(%s)" % (w_self.__class__.__name__, ''.join(w_self.data))
def _new(self, value):
@@ -127,11 +128,6 @@
@staticmethod
def descr_fromhex(space, w_bytearraytype, w_hexstring):
- "bytearray.fromhex(string) -> bytearray\n"
- "\n"
- "Create a bytearray object from a string of hexadecimal numbers.\n"
- "Spaces between two numbers are accepted.\n"
- "Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')."
hexstring = space.str_w(w_hexstring)
hexstring = hexstring.lower()
data = []
@@ -143,18 +139,15 @@
i += 1
if i >= length:
break
- if i+1 == length:
- raise OperationError(space.w_ValueError, space.wrap(
- "non-hexadecimal number found in fromhex() arg at position %d" % i))
+ if i + 1 == length:
+ raise operationerrfmt(space.w_ValueError, NON_HEX_MSG, i)
top = _hex_digit_to_int(hexstring[i])
if top == -1:
- raise OperationError(space.w_ValueError, space.wrap(
- "non-hexadecimal number found in fromhex() arg at position %d" % i))
+ raise operationerrfmt(space.w_ValueError, NON_HEX_MSG, i)
bot = _hex_digit_to_int(hexstring[i+1])
if bot == -1:
- raise OperationError(space.w_ValueError, space.wrap(
- "non-hexadecimal number found in fromhex() arg at position %d" % (i+1,)))
+ raise operationerrfmt(space.w_ValueError, NON_HEX_MSG, i + 1)
data.append(chr(top*16 + bot))
# in CPython bytearray.fromhex is a staticmethod, so
@@ -178,23 +171,25 @@
from pypy.objspace.std.unicodeobject import (
_get_encoding_and_errors, encode_object
)
- encoding, errors = _get_encoding_and_errors(space, w_encoding, w_errors)
+ encoding, errors = _get_encoding_and_errors(space, w_encoding,
+ w_errors)
- # if w_source is an integer this correctly raises a TypeError
- # the CPython error message is: "encoding or errors without a string argument"
- # ours is: "expected unicode, got int object"
+ # if w_source is an integer this correctly raises a
+ # TypeError the CPython error message is: "encoding or
+ # errors without a string argument" ours is: "expected
+ # unicode, got int object"
w_source = encode_object(space, w_source, encoding, errors)
# Is it an int?
try:
count = space.int_w(w_source)
- except OperationError, e:
+ except OperationError as e:
if not e.match(space, space.w_TypeError):
raise
else:
if count < 0:
- raise OperationError(space.w_ValueError,
- space.wrap("bytearray negative count"))
+ raise operationerrfmt(space.w_ValueError,
+ "bytearray negative count")
self.data = ['\0'] * count
return
@@ -224,8 +219,8 @@
elif not '\x20' <= c < '\x7f':
n = ord(c)
buf.append('\\x')
- buf.append("0123456789abcdef"[n>>4])
- buf.append("0123456789abcdef"[n&0xF])
+ buf.append("0123456789abcdef"[n >> 4])
+ buf.append("0123456789abcdef"[n & 0xF])
else:
buf.append(c)
@@ -238,51 +233,57 @@
def descr_eq(self, space, w_other):
try:
- return space.newbool(self._val(space) == self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) == self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_ne(self, space, w_other):
try:
- return space.newbool(self._val(space) != self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) != self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_lt(self, space, w_other):
try:
- return space.newbool(self._val(space) < self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) < self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_le(self, space, w_other):
try:
- return space.newbool(self._val(space) <= self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) <= self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_gt(self, space, w_other):
try:
- return space.newbool(self._val(space) > self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) > self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_ge(self, space, w_other):
try:
- return space.newbool(self._val(space) >= self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) >= self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_buffer(self, space):
return BytearrayBuffer(self.data)
@@ -297,7 +298,7 @@
def descr_inplace_mul(self, space, w_times):
try:
times = space.getindex_w(w_times, space.w_OverflowError)
- except OperationError, e:
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
@@ -312,12 +313,13 @@
_setitem_slice_helper(space, self.data, start, step,
slicelength, sequence2, empty_elem='\x00')
else:
- idx = space.getindex_w(w_index, space.w_IndexError, "bytearray index")
+ idx = space.getindex_w(w_index, space.w_IndexError,
+ "bytearray index")
try:
self.data[idx] = getbytevalue(space, w_other)
except IndexError:
- raise OperationError(space.w_IndexError,
- space.wrap("bytearray index out of range"))
+ raise operationerrfmt(space.w_IndexError,
+ "bytearray index out of range")
def descr_delitem(self, space, w_idx):
if isinstance(w_idx, W_SliceObject):
@@ -325,12 +327,13 @@
len(self.data))
_delitem_slice_helper(space, self.data, start, step, slicelength)
else:
- idx = space.getindex_w(w_idx, space.w_IndexError, "bytearray index")
+ idx = space.getindex_w(w_idx, space.w_IndexError,
+ "bytearray index")
try:
del self.data[idx]
except IndexError:
- raise OperationError(space.w_IndexError,
- space.wrap("bytearray deletion index out of range"))
+ raise operationerrfmt(space.w_IndexError,
+ "bytearray deletion index out of range")
def descr_append(self, space, w_item):
self.data.append(getbytevalue(space, w_item))
@@ -357,10 +360,9 @@
result = self.data.pop(index)
except IndexError:
if not self.data:
- raise OperationError(space.w_IndexError, space.wrap(
- "pop from empty bytearray"))
- raise OperationError(space.w_IndexError, space.wrap(
- "pop index out of range"))
+ raise operationerrfmt(space.w_IndexError,
+ "pop from empty bytearray")
+ raise operationerrfmt(space.w_IndexError, "pop index out of range")
return space.wrap(ord(result))
def descr_remove(self, space, w_char):
@@ -368,27 +370,33 @@
try:
self.data.remove(chr(char))
except ValueError:
- raise OperationError(space.w_ValueError, space.wrap(
- "value not found in bytearray"))
+ raise operationerrfmt(space.w_ValueError,
+ "value not found in bytearray")
def descr_reverse(self, space):
self.data.reverse()
+
+def _make_data(s):
+ return [s[i] for i in range(len(s))]
+
+
def getbytevalue(space, w_value):
if space.isinstance_w(w_value, space.w_str):
string = space.str_w(w_value)
if len(string) != 1:
- raise OperationError(space.w_ValueError, space.wrap(
- "string must be of size 1"))
+ raise operationerrfmt(space.w_ValueError,
+ "string must be of size 1")
return string[0]
value = space.getindex_w(w_value, None)
if not 0 <= value < 256:
# this includes the OverflowError in case the long is too large
- raise OperationError(space.w_ValueError, space.wrap(
- "byte must be in range(0, 256)"))
+ raise operationerrfmt(space.w_ValueError,
+ "byte must be in range(0, 256)")
return chr(value)
+
def new_bytearray(space, w_bytearraytype, data):
w_obj = space.allocate_instance(W_BytearrayObject, w_bytearraytype)
W_BytearrayObject.__init__(w_obj, data)
@@ -399,7 +407,7 @@
# String-like argument
try:
string = space.bufferstr_new_w(w_source)
- except OperationError, e:
+ except OperationError as e:
if not e.match(space, space.w_TypeError):
raise
else:
@@ -413,7 +421,7 @@
while True:
try:
w_item = space.next(w_iter)
- except OperationError, e:
+ except OperationError as e:
if not e.match(space, space.w_StopIteration):
raise
break
@@ -424,6 +432,7 @@
resizelist_hint(data, extended)
return data
+
def _hex_digit_to_int(d):
val = ord(d)
if 47 < val < 58:
@@ -560,12 +569,12 @@
def decode():
"""B.decode(encoding=None, errors='strict') -> unicode
- Decode B using the codec registered for encoding. encoding defaults
- to the default encoding. errors may be given to set a different error
- handling scheme. Default is 'strict' meaning that encoding errors raise
- a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
- as well as any other name registered with codecs.register_error that is
- able to handle UnicodeDecodeErrors.
+ Decode B using the codec registered for encoding. encoding defaults to
+ the default encoding. errors may be given to set a different error
+ handling scheme. Default is 'strict' meaning that encoding errors
+ raise a UnicodeDecodeError. Other possible values are 'ignore' and
+ 'replace' as well as any other name registered with
+ codecs.register_error that is able to handle UnicodeDecodeErrors.
"""
def endswith():
@@ -602,7 +611,7 @@
"""
def fromhex():
- """bytearray.fromhex(string) -> bytearray (static method)
+ r"""bytearray.fromhex(string) -> bytearray (static method)
Create a bytearray object from a string of hexadecimal numbers.
Spaces between two numbers are accepted.
@@ -1024,9 +1033,10 @@
_space_chars = ''.join([chr(c) for c in [9, 10, 11, 12, 13, 32]])
-#XXX share the code again with the stuff in listobject.py
+
+# XXX share the code again with the stuff in listobject.py
def _delitem_slice_helper(space, items, start, step, slicelength):
- if slicelength==0:
+ if slicelength == 0:
return
if step < 0:
@@ -1056,6 +1066,7 @@
assert start >= 0 # annotator hint
del items[start:]
+
def _setitem_slice_helper(space, items, start, step, slicelength, sequence2,
empty_elem):
assert slicelength >= 0
diff --git a/pypy/objspace/std/bytesobject.py b/pypy/objspace/std/bytesobject.py
--- a/pypy/objspace/std/bytesobject.py
+++ b/pypy/objspace/std/bytesobject.py
@@ -1,19 +1,23 @@
"""The builtin str implementation"""
+from rpython.rlib.jit import we_are_jitted
+from rpython.rlib.objectmodel import (
+ compute_hash, compute_unique_id, import_from_mixin)
+from rpython.rlib.rstring import StringBuilder, replace
+
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.buffer import StringBuffer
from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault, interpindirect2app
+from pypy.interpreter.gateway import (
+ WrappedDefault, interp2app, interpindirect2app, unwrap_spec)
from pypy.objspace.std import newformat
from pypy.objspace.std.basestringtype import basestring_typedef
from pypy.objspace.std.formatting import mod_format
from pypy.objspace.std.stdtypedef import StdTypeDef
from pypy.objspace.std.stringmethods import StringMethods
-from pypy.objspace.std.unicodeobject import (unicode_from_string,
- decode_object, unicode_from_encoded_object, _get_encoding_and_errors)
-from rpython.rlib.jit import we_are_jitted
-from rpython.rlib.objectmodel import compute_hash, compute_unique_id, import_from_mixin
-from rpython.rlib.rstring import StringBuilder, replace
+from pypy.objspace.std.unicodeobject import (
+ _get_encoding_and_errors, decode_object, unicode_from_encoded_object,
+ unicode_from_string)
class W_AbstractBytesObject(W_Root):
@@ -184,8 +188,8 @@
def descr_format(self, space, __args__):
"""S.format(*args, **kwargs) -> string
- Return a formatted version of S, using substitutions from args and kwargs.
- The substitutions are identified by braces ('{' and '}').
+ Return a formatted version of S, using substitutions from args and
+ kwargs. The substitutions are identified by braces ('{' and '}').
"""
def descr_index(self, space, w_sub, w_start=None, w_end=None):
@@ -319,8 +323,8 @@
"""S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return
- the part before it, the separator itself, and the part after it. If the
- separator is not found, return two empty strings and S.
+ the part before it, the separator itself, and the part after it. If
+ the separator is not found, return two empty strings and S.
"""
@unwrap_spec(maxsplit=int)
@@ -432,7 +436,7 @@
self._value = str
def __repr__(self):
- """ representation for debugging purposes """
+ """representation for debugging purposes"""
return "%s(%r)" % (self.__class__.__name__, self._value)
def unwrap(self, space):
@@ -521,7 +525,7 @@
return space.newlist_bytes(lst)
@staticmethod
- @unwrap_spec(w_object = WrappedDefault(""))
+ @unwrap_spec(w_object=WrappedDefault(""))
def descr_new(space, w_stringtype, w_object):
# NB. the default value of w_object is really a *wrapped* empty string:
# there is gateway magic at work
@@ -624,7 +628,8 @@
_StringMethods_descr_add = descr_add
def descr_add(self, space, w_other):
if space.isinstance_w(w_other, space.w_unicode):
- self_as_unicode = unicode_from_encoded_object(space, self, None, None)
+ self_as_unicode = unicode_from_encoded_object(space, self, None,
+ None)
return space.add(self_as_unicode, w_other)
elif space.isinstance_w(w_other, space.w_bytearray):
# XXX: eliminate double-copy
@@ -635,7 +640,7 @@
from pypy.objspace.std.strbufobject import W_StringBufferObject
try:
other = self._op_val(space, w_other)
- except OperationError, e:
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
@@ -648,24 +653,32 @@
_StringMethods__startswith = _startswith
def _startswith(self, space, value, w_prefix, start, end):
if space.isinstance_w(w_prefix, space.w_unicode):
- self_as_unicode = unicode_from_encoded_object(space, self, None, None)
- return self_as_unicode._startswith(space, self_as_unicode._value, w_prefix, start, end)
- return self._StringMethods__startswith(space, value, w_prefix, start, end)
+ self_as_unicode = unicode_from_encoded_object(space, self, None,
+ None)
+ return self_as_unicode._startswith(space, self_as_unicode._value,
+ w_prefix, start, end)
+ return self._StringMethods__startswith(space, value, w_prefix, start,
+ end)
_StringMethods__endswith = _endswith
def _endswith(self, space, value, w_suffix, start, end):
if space.isinstance_w(w_suffix, space.w_unicode):
- self_as_unicode = unicode_from_encoded_object(space, self, None, None)
- return self_as_unicode._endswith(space, self_as_unicode._value, w_suffix, start, end)
- return self._StringMethods__endswith(space, value, w_suffix, start, end)
+ self_as_unicode = unicode_from_encoded_object(space, self, None,
+ None)
+ return self_as_unicode._endswith(space, self_as_unicode._value,
+ w_suffix, start, end)
+ return self._StringMethods__endswith(space, value, w_suffix, start,
+ end)
_StringMethods_descr_contains = descr_contains
def descr_contains(self, space, w_sub):
if space.isinstance_w(w_sub, space.w_unicode):
from pypy.objspace.std.unicodeobject import W_UnicodeObject
assert isinstance(w_sub, W_UnicodeObject)
- self_as_unicode = unicode_from_encoded_object(space, self, None, None)
- return space.newbool(self_as_unicode._value.find(w_sub._value) >= 0)
+ self_as_unicode = unicode_from_encoded_object(space, self, None,
+ None)
+ return space.newbool(
+ self_as_unicode._value.find(w_sub._value) >= 0)
return self._StringMethods_descr_contains(space, w_sub)
_StringMethods_descr_replace = descr_replace
@@ -685,8 +698,8 @@
try:
res = replace(input, sub, by, count)
except OverflowError:
- raise OperationError(space.w_OverflowError,
- space.wrap("replace string is too long"))
+ raise operationerrfmt(space.w_OverflowError,
+ "replace string is too long")
return self_as_uni._new(res)
return self._StringMethods_descr_replace(space, w_old, w_new, count)
@@ -751,6 +764,7 @@
return W_BytesObject.EMPTY
return W_BytesObject(s)
+
def wrapchar(space, c):
if space.config.objspace.std.withprebuiltchar and not we_are_jitted():
return W_BytesObject.PREBUILT[ord(c)]
@@ -830,7 +844,8 @@
__format__ = interpindirect2app(W_BytesObject.descr__format__),
__mod__ = interpindirect2app(W_BytesObject.descr_mod),
__buffer__ = interpindirect2app(W_AbstractBytesObject.descr_buffer),
- __getnewargs__ = interpindirect2app(W_AbstractBytesObject.descr_getnewargs),
+ __getnewargs__ = interpindirect2app(
+ W_AbstractBytesObject.descr_getnewargs),
_formatter_parser = interp2app(W_BytesObject.descr_formatter_parser),
_formatter_field_name_split =
interp2app(W_BytesObject.descr_formatter_field_name_split),
@@ -865,8 +880,8 @@
buf.append_slice(s, startslice, i)
startslice = i + 1
buf.append('\\x')
- buf.append("0123456789abcdef"[n>>4])
- buf.append("0123456789abcdef"[n&0xF])
+ buf.append("0123456789abcdef"[n >> 4])
+ buf.append("0123456789abcdef"[n & 0xF])
if use_bs_char:
if i != startslice:
diff --git a/pypy/objspace/std/listobject.py b/pypy/objspace/std/listobject.py
--- a/pypy/objspace/std/listobject.py
+++ b/pypy/objspace/std/listobject.py
@@ -162,9 +162,9 @@
return self
@staticmethod
- def newlist_bytes(space, list_s):
+ def newlist_bytes(space, list_b):
strategy = space.fromcache(BytesListStrategy)
- storage = strategy.erase(list_s)
+ storage = strategy.erase(list_b)
return W_ListObject.from_storage_and_strategy(space, storage, strategy)
@staticmethod
diff --git a/pypy/objspace/std/stringmethods.py b/pypy/objspace/std/stringmethods.py
--- a/pypy/objspace/std/stringmethods.py
+++ b/pypy/objspace/std/stringmethods.py
@@ -1,18 +1,22 @@
-from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.gateway import unwrap_spec, WrappedDefault
-from pypy.objspace.std import slicetype
-from pypy.objspace.std.sliceobject import W_SliceObject, normalize_simple_slice
+"""Functionality shared between bytes/bytearray/unicode"""
+
from rpython.rlib import jit
from rpython.rlib.objectmodel import specialize
from rpython.rlib.rarithmetic import ovfcheck
-from rpython.rlib.rstring import split, rsplit, replace, startswith, endswith
+from rpython.rlib.rstring import endswith, replace, rsplit, split, startswith
+
+from pypy.interpreter.error import OperationError, operationerrfmt
+from pypy.interpreter.gateway import WrappedDefault, unwrap_spec
+from pypy.objspace.std import slicetype
+from pypy.objspace.std.sliceobject import W_SliceObject, normalize_simple_slice
class StringMethods(object):
def _sliced(self, space, s, start, stop, orig_obj):
assert start >= 0
assert stop >= 0
- #if start == 0 and stop == len(s) and space.is_w(space.type(orig_obj), space.w_str):
+ #if start == 0 and stop == len(s) and space.is_w(space.type(orig_obj),
+ # space.w_str):
# return orig_obj
return self._new(s[start:stop])
@@ -21,7 +25,7 @@
value = self._val(space)
lenself = len(value)
start, end = slicetype.unwrap_start_stop(
- space, lenself, w_start, w_end, upper_bound=upper_bound)
+ space, lenself, w_start, w_end, upper_bound=upper_bound)
return (value, start, end)
def descr_len(self, space):
@@ -36,12 +40,14 @@
space.isinstance_w(w_sub, space.w_int)):
char = space.int_w(w_sub)
return _descr_contains_bytearray(self.data, space, char)
- return space.newbool(self._val(space).find(self._op_val(space, w_sub)) >= 0)
+ value = self._val(space)
+ other = self._op_val(space, w_sub)
+ return space.newbool(value.find(other) >= 0)
def descr_add(self, space, w_other):
try:
other = self._op_val(space, w_other)
- except OperationError, e:
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
@@ -50,7 +56,7 @@
def descr_mul(self, space, w_times):
try:
times = space.getindex_w(w_times, space.w_OverflowError)
- except OperationError, e:
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
@@ -82,12 +88,11 @@
if index < 0:
index += selflen
if index < 0 or index >= selflen:
- raise OperationError(space.w_IndexError,
- space.wrap("string index out of range"))
+ raise operationerrfmt(space.w_IndexError,
+ "string index out of range")
from pypy.objspace.std.bytearrayobject import W_BytearrayObject
if isinstance(self, W_BytearrayObject):
return space.wrap(ord(selfvalue[index]))
- #return wrapchar(space, selfvalue[index])
return self._new(selfvalue[index])
def descr_getslice(self, space, w_start, w_stop):
@@ -115,35 +120,39 @@
value = self._val(space)
fillchar = self._op_val(space, w_fillchar)
if len(fillchar) != 1:
- raise OperationError(space.w_TypeError,
- space.wrap("center() argument 2 must be a single character"))
+ raise operationerrfmt(space.w_TypeError,
+ "center() argument 2 must be a single "
+ "character")
d = width - len(value)
- if d>0:
+ if d > 0:
offset = d//2 + (d & width & 1)
fillchar = fillchar[0] # annotator hint: it's a single character
- u_centered = offset * fillchar + value + (d - offset) * fillchar
+ centered = offset * fillchar + value + (d - offset) * fillchar
else:
- u_centered = value
+ centered = value
- return self._new(u_centered)
+ return self._new(centered)
def descr_count(self, space, w_sub, w_start=None, w_end=None):
value, start, end = self._convert_idx_params(space, w_start, w_end)
- return space.newint(value.count(self._op_val(space, w_sub), start, end))
+ return space.newint(value.count(self._op_val(space, w_sub), start,
+ end))
def descr_decode(self, space, w_encoding=None, w_errors=None):
- from pypy.objspace.std.unicodeobject import _get_encoding_and_errors, \
- unicode_from_string, decode_object
- encoding, errors = _get_encoding_and_errors(space, w_encoding, w_errors)
+ from pypy.objspace.std.unicodeobject import (
+ _get_encoding_and_errors, decode_object, unicode_from_string)
+ encoding, errors = _get_encoding_and_errors(space, w_encoding,
+ w_errors)
if encoding is None and errors is None:
return unicode_from_string(space, self)
return decode_object(space, self, encoding, errors)
def descr_encode(self, space, w_encoding=None, w_errors=None):
- from pypy.objspace.std.unicodeobject import _get_encoding_and_errors, \
- encode_object
- encoding, errors = _get_encoding_and_errors(space, w_encoding, w_errors)
+ from pypy.objspace.std.unicodeobject import (
+ _get_encoding_and_errors, encode_object)
+ encoding, errors = _get_encoding_and_errors(space, w_encoding,
+ w_errors)
return encode_object(space, self, encoding, errors)
@unwrap_spec(tabsize=int)
@@ -156,18 +165,19 @@
try:
ovfcheck(len(splitted) * tabsize)
except OverflowError:
- raise OperationError(space.w_OverflowError,
- space.wrap("new string is too long"))
+ raise operationerrfmt(space.w_OverflowError,
+ "new string is too long")
expanded = oldtoken = splitted.pop(0)
for token in splitted:
- expanded += self._chr(' ') * self._tabindent(oldtoken, tabsize) + token
+ expanded += self._chr(' ') * self._tabindent(oldtoken,
+ tabsize) + token
oldtoken = token
return self._new(expanded)
def _tabindent(self, token, tabsize):
- "calculates distance behind the token to the next tabstop"
+ """calculates distance behind the token to the next tabstop"""
distance = tabsize
if token:
@@ -203,8 +213,8 @@
(value, start, end) = self._convert_idx_params(space, w_start, w_end)
res = value.find(self._op_val(space, w_sub), start, end)
if res < 0:
- raise OperationError(space.w_ValueError,
- space.wrap("substring not found in string.index"))
+ raise operationerrfmt(space.w_ValueError,
+ "substring not found in string.index")
return space.wrap(res)
@@ -212,8 +222,8 @@
(value, start, end) = self._convert_idx_params(space, w_start, w_end)
res = value.rfind(self._op_val(space, w_sub), start, end)
if res < 0:
- raise OperationError(space.w_ValueError,
- space.wrap("substring not found in string.rindex"))
+ raise operationerrfmt(space.w_ValueError,
+ "substring not found in string.rindex")
return space.wrap(res)
@@ -349,8 +359,7 @@
if check_item == 1:
raise operationerrfmt(
space.w_TypeError,
- "sequence item %d: expected string, %s "
- "found", i, space.type(w_s).getname(space))
+ "sequence item %d: expected string, %T found", i, w_s)
elif check_item == 2:
return self._join_autoconvert(space, list_w)
prealloc_size += len(self._op_val(space, w_s))
@@ -370,9 +379,9 @@
value = self._val(space)
fillchar = self._op_val(space, w_fillchar)
if len(fillchar) != 1:
- raise OperationError(space.w_TypeError,
- space.wrap("ljust() argument 2 must be a single character"))
-
+ raise operationerrfmt(space.w_TypeError,
+ "ljust() argument 2 must be a single "
+ "character")
d = width - len(value)
if d > 0:
fillchar = fillchar[0] # annotator hint: it's a single character
@@ -385,9 +394,9 @@
value = self._val(space)
fillchar = self._op_val(space, w_fillchar)
if len(fillchar) != 1:
- raise OperationError(space.w_TypeError,
- space.wrap("rjust() argument 2 must be a single character"))
-
+ raise operationerrfmt(space.w_TypeError,
+ "rjust() argument 2 must be a single "
+ "character")
d = width - len(value)
if d > 0:
fillchar = fillchar[0] # annotator hint: it's a single character
@@ -406,8 +415,7 @@
value = self._val(space)
sub = self._op_val(space, w_sub)
if not sub:
- raise OperationError(space.w_ValueError,
- space.wrap("empty separator"))
+ raise operationerrfmt(space.w_ValueError, "empty separator")
pos = value.find(sub)
if pos == -1:
from pypy.objspace.std.bytearrayobject import W_BytearrayObject
@@ -426,8 +434,7 @@
value = self._val(space)
sub = self._op_val(space, w_sub)
if not sub:
- raise OperationError(space.w_ValueError,
- space.wrap("empty separator"))
+ raise operationerrfmt(space.w_ValueError, "empty separator")
pos = value.rfind(sub)
if pos == -1:
from pypy.objspace.std.bytearrayobject import W_BytearrayObject
@@ -450,8 +457,8 @@
try:
res = replace(input, sub, by, count)
except OverflowError:
- raise OperationError(space.w_OverflowError,
- space.wrap("replace string is too long"))
+ raise operationerrfmt(space.w_OverflowError,
+ "replace string is too long")
return self._new(res)
@unwrap_spec(maxsplit=int)
@@ -466,7 +473,7 @@
by = self._op_val(space, w_sep)
bylen = len(by)
if bylen == 0:
- raise OperationError(space.w_ValueError, space.wrap("empty separator"))
+ raise operationerrfmt(space.w_ValueError, "empty separator")
res = split(value, by, maxsplit)
return self._newlist_unwrapped(space, res)
@@ -481,7 +488,7 @@
by = self._op_val(space, w_sep)
bylen = len(by)
if bylen == 0:
- raise OperationError(space.w_ValueError, space.wrap("empty separator"))
+ raise operationerrfmt(space.w_ValueError, "empty separator")
res = rsplit(value, by, maxsplit)
return self._newlist_unwrapped(space, res)
@@ -515,21 +522,22 @@
if self._startswith(space, value, w_prefix, start, end):
return space.w_True
return space.w_False
- return space.newbool(self._startswith(space, value, w_prefix, start, end))
+ return space.newbool(self._startswith(space, value, w_prefix, start,
+ end))
def _startswith(self, space, value, w_prefix, start, end):
return startswith(value, self._op_val(space, w_prefix), start, end)
def descr_endswith(self, space, w_suffix, w_start=None, w_end=None):
- (value, start, end) = self._convert_idx_params(space, w_start,
- w_end, True)
-
+ (value, start, end) = self._convert_idx_params(space, w_start, w_end,
+ True)
if space.isinstance_w(w_suffix, space.w_tuple):
for w_suffix in space.fixedview(w_suffix):
if self._endswith(space, value, w_suffix, start, end):
return space.w_True
return space.w_False
- return space.newbool(self._endswith(space, value, w_suffix, start, end))
+ return space.newbool(self._endswith(space, value, w_suffix, start,
+ end))
def _endswith(self, space, value, w_prefix, start, end):
return endswith(value, self._op_val(space, w_prefix), start, end)
@@ -537,18 +545,17 @@
def _strip(self, space, w_chars, left, right):
"internal function called by str_xstrip methods"
value = self._val(space)
- u_chars = self._op_val(space, w_chars)
+ chars = self._op_val(space, w_chars)
lpos = 0
rpos = len(value)
if left:
- #print "while %d < %d and -%s- in -%s-:"%(lpos, rpos, value[lpos],w_chars)
- while lpos < rpos and value[lpos] in u_chars:
+ while lpos < rpos and value[lpos] in chars:
lpos += 1
if right:
- while rpos > lpos and value[rpos - 1] in u_chars:
+ while rpos > lpos and value[rpos - 1] in chars:
rpos -= 1
assert rpos >= lpos # annotator hint, don't remove
@@ -562,13 +569,12 @@
rpos = len(value)
if left:
- #print "while %d < %d and -%s- in -%s-:"%(lpos, rpos, value[lpos],w_chars)
while lpos < rpos and self._isspace(value[lpos]):
- lpos += 1
+ lpos += 1
if right:
while rpos > lpos and self._isspace(value[rpos - 1]):
- rpos -= 1
+ rpos -= 1
assert rpos >= lpos # annotator hint, don't remove
return self._sliced(space, value, lpos, rpos, self)
@@ -629,9 +635,9 @@
else:
table = self._op_val(space, w_table)
if len(table) != 256:
- raise OperationError(
+ raise operationerrfmt(
space.w_ValueError,
- space.wrap("translation table must be 256 characters long"))
+ "translation table must be 256 characters long")
string = self._val(space)
deletechars = self._op_val(space, w_deletechars)
@@ -685,13 +691,14 @@
def _descr_contains_bytearray(data, space, char):
if not 0 <= char < 256:
- raise OperationError(space.w_ValueError,
- space.wrap("byte must be in range(0, 256)"))
+ raise operationerrfmt(space.w_ValueError,
+ "byte must be in range(0, 256)")
for c in data:
if ord(c) == char:
return space.w_True
return space.w_False
+
@specialize.argtype(0)
def _descr_getslice_slowpath(selfvalue, start, step, sl):
return [selfvalue[start + i*step] for i in range(sl)]
diff --git a/pypy/objspace/std/unicodeobject.py b/pypy/objspace/std/unicodeobject.py
--- a/pypy/objspace/std/unicodeobject.py
+++ b/pypy/objspace/std/unicodeobject.py
@@ -1,19 +1,22 @@
"""The builtin unicode implementation"""
+from rpython.rlib.objectmodel import (
+ compute_hash, compute_unique_id, import_from_mixin)
+from rpython.rlib.rstring import UnicodeBuilder
+from rpython.rlib.runicode import (
+ make_unicode_escape_function, str_decode_ascii, str_decode_utf_8,
+ unicode_encode_ascii, unicode_encode_utf_8)
+
from pypy.interpreter import unicodehelper
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
+from pypy.interpreter.gateway import WrappedDefault, interp2app, unwrap_spec
from pypy.module.unicodedata import unicodedb
from pypy.objspace.std import newformat
from pypy.objspace.std.basestringtype import basestring_typedef
from pypy.objspace.std.formatting import mod_format
from pypy.objspace.std.stdtypedef import StdTypeDef
from pypy.objspace.std.stringmethods import StringMethods
-from rpython.rlib.objectmodel import compute_hash, compute_unique_id, import_from_mixin
-from rpython.rlib.rstring import UnicodeBuilder
-from rpython.rlib.runicode import (str_decode_utf_8, str_decode_ascii,
- unicode_encode_utf_8, unicode_encode_ascii, make_unicode_escape_function)
__all__ = ['W_UnicodeObject', 'wrapunicode', 'plain_str2unicode',
'encode_object', 'decode_object', 'unicode_from_object',
@@ -29,7 +32,7 @@
w_self._value = unistr
def __repr__(w_self):
- """ representation for debugging purposes """
+ """representation for debugging purposes"""
return "%s(%r)" % (w_self.__class__.__name__, w_self._value)
def unwrap(w_self, space):
@@ -90,7 +93,8 @@
return w_other._value
if space.isinstance_w(w_other, space.w_str):
return unicode_from_string(space, w_other)._value
- return unicode_from_encoded_object(space, w_other, None, "strict")._value
+ return unicode_from_encoded_object(
+ space, w_other, None, "strict")._value
def _chr(self, char):
assert len(char) == 1
@@ -144,14 +148,15 @@
return space.newlist_unicode(lst)
@staticmethod
- @unwrap_spec(w_string = WrappedDefault(""))
+ @unwrap_spec(w_string=WrappedDefault(""))
def descr_new(space, w_unicodetype, w_string, w_encoding=None,
w_errors=None):
# NB. the default value of w_obj is really a *wrapped* empty string:
# there is gateway magic at work
w_obj = w_string
- encoding, errors = _get_encoding_and_errors(space, w_encoding, w_errors)
+ encoding, errors = _get_encoding_and_errors(space, w_encoding,
+ w_errors)
# convoluted logic for the case when unicode subclass has a __unicode__
# method, we need to call this method
is_precisely_unicode = space.is_w(space.type(w_obj), space.w_unicode)
@@ -159,8 +164,8 @@
(space.isinstance_w(w_obj, space.w_unicode) and
space.findattr(w_obj, space.wrap('__unicode__')) is None)):
if encoding is not None or errors is not None:
- raise OperationError(space.w_TypeError, space.wrap(
- 'decoding Unicode is not supported'))
+ raise operationerrfmt(space.w_TypeError,
+ "decoding Unicode is not supported")
if (is_precisely_unicode and
space.is_w(w_unicodetype, space.w_unicode)):
return w_obj
@@ -194,8 +199,8 @@
def descr_eq(self, space, w_other):
try:
- return space.newbool(self._val(space) == self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) == self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
if (e.match(space, space.w_UnicodeDecodeError) or
@@ -206,11 +211,12 @@
space.warn(space.wrap(msg), space.w_UnicodeWarning)
return space.w_False
raise
+ return space.newbool(res)
def descr_ne(self, space, w_other):
try:
- return space.newbool(self._val(space) != self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) != self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
if (e.match(space, space.w_UnicodeDecodeError) or
@@ -221,38 +227,43 @@
space.warn(space.wrap(msg), space.w_UnicodeWarning)
return space.w_True
raise
+ return space.newbool(res)
def descr_lt(self, space, w_other):
try:
- return space.newbool(self._val(space) < self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) < self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_le(self, space, w_other):
try:
- return space.newbool(self._val(space) <= self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) <= self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_gt(self, space, w_other):
try:
- return space.newbool(self._val(space) > self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) > self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_ge(self, space, w_other):
try:
- return space.newbool(self._val(space) >= self._op_val(space, w_other))
- except OperationError, e:
+ res = self._val(space) >= self._op_val(space, w_other)
+ except OperationError as e:
if e.match(space, space.w_TypeError):
return space.w_NotImplemented
raise
+ return space.newbool(res)
def descr_format(self, space, __args__):
return newformat.format_method(space, self, __args__, is_unicode=True)
@@ -272,12 +283,13 @@
def descr_translate(self, space, w_table):
selfvalue = self._value
w_sys = space.getbuiltinmodule('sys')
- maxunicode = space.int_w(space.getattr(w_sys, space.wrap("maxunicode")))
+ maxunicode = space.int_w(space.getattr(w_sys,
+ space.wrap("maxunicode")))
result = []
for unichar in selfvalue:
try:
w_newval = space.getitem(w_table, space.wrap(ord(unichar)))
- except OperationError, e:
+ except OperationError as e:
if e.match(space, space.w_LookupError):
result.append(unichar)
else:
@@ -288,20 +300,21 @@
elif space.isinstance_w(w_newval, space.w_int):
newval = space.int_w(w_newval)
if newval < 0 or newval > maxunicode:
- raise OperationError(
- space.w_TypeError,
- space.wrap("character mapping must be in range(0x%x)" % (maxunicode + 1,)))
+ msg = ("character mapping must be in range(0x%x)" %
+ (maxunicode + 1,))
+ raise operationerrfmt(space.w_TypeError, msg)
result.append(unichr(newval))
elif space.isinstance_w(w_newval, space.w_unicode):
result.append(space.unicode_w(w_newval))
else:
- raise OperationError(
- space.w_TypeError,
- space.wrap("character mapping must return integer, None or unicode"))
+ raise operationerrfmt(space.w_TypeError,
+ "character mapping must return "
+ "integer, None or unicode")
return W_UnicodeObject(u''.join(result))
def descr_encode(self, space, w_encoding=None, w_errors=None):
- encoding, errors = _get_encoding_and_errors(space, w_encoding, w_errors)
+ encoding, errors = _get_encoding_and_errors(space, w_encoding,
+ w_errors)
return encode_object(space, self, encoding, errors)
def _join_return_one(self, space, w_obj):
@@ -353,6 +366,7 @@
def wrapunicode(space, uni):
return W_UnicodeObject(uni)
+
def plain_str2unicode(space, s):
try:
return unicode(s)
@@ -378,17 +392,13 @@
def getdefaultencoding(space):
return space.sys.defaultencoding
+
def _get_encoding_and_errors(space, w_encoding, w_errors):
- if space.is_none(w_encoding):
- encoding = None
- else:
- encoding = space.str_w(w_encoding)
- if space.is_none(w_errors):
- errors = None
- else:
- errors = space.str_w(w_errors)
+ encoding = None if space.is_none(w_encoding) else space.str_w(w_encoding)
+ errors = None if space.is_none(w_errors) else space.str_w(w_errors)
return encoding, errors
+
def encode_object(space, w_object, encoding, errors):
if encoding is None:
# Get the encoder functions as a wrapped object.
@@ -416,11 +426,12 @@
w_restuple = space.call_function(w_encoder, w_object, w_errors)
w_retval = space.getitem(w_restuple, space.wrap(0))
if not space.isinstance_w(w_retval, space.w_str):
- raise operationerrfmt(space.w_TypeError,
- "encoder did not return an string object (type '%s')",
- space.type(w_retval).getname(space))
+ raise operationerrfmt(
+ space.w_TypeError,
+ "encoder did not return an string object (type '%T')", w_retval)
return w_retval
+
def decode_object(space, w_obj, encoding, errors):
if encoding is None:
encoding = getdefaultencoding(space)
@@ -451,17 +462,18 @@
# explicitly block bytearray on 2.7
from .bytearrayobject import W_BytearrayObject
if isinstance(w_obj, W_BytearrayObject):
- raise OperationError(space.w_TypeError,
- space.wrap("decoding bytearray is not supported"))
+ raise operationerrfmt(space.w_TypeError,
+ "decoding bytearray is not supported")
w_retval = decode_object(space, w_obj, encoding, errors)
if not space.isinstance_w(w_retval, space.w_unicode):
raise operationerrfmt(space.w_TypeError,
- "decoder did not return an unicode object (type '%s')",
- space.type(w_retval).getname(space))
+ "decoder did not return an unicode object (type '%T')",
+ w_retval)
assert isinstance(w_retval, W_UnicodeObject)
return w_retval
+
def unicode_from_object(space, w_obj):
if space.is_w(space.type(w_obj), space.w_unicode):
return w_obj
@@ -483,6 +495,7 @@
return w_res
return unicode_from_encoded_object(space, w_res, None, "strict")
+
def unicode_from_string(space, w_str):
# this is a performance and bootstrapping hack
encoding = getdefaultencoding(space)
@@ -651,8 +664,8 @@
def format():
"""S.format(*args, **kwargs) -> unicode
- Return a formatted version of S, using substitutions from args and kwargs.
- The substitutions are identified by braces ('{' and '}').
+ Return a formatted version of S, using substitutions from args and
+ kwargs. The substitutions are identified by braces ('{' and '}').
"""
def index():
@@ -789,16 +802,16 @@
def rjust():
"""S.rjust(width[, fillchar]) -> unicode
- Return S right-justified in a Unicode string of length width. Padding is
- done using the specified fill character (default is a space).
+ Return S right-justified in a Unicode string of length width. Padding
+ is done using the specified fill character (default is a space).
"""
def rpartition():
"""S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return
- the part before it, the separator itself, and the part after it. If the
- separator is not found, return two empty strings and S.
+ the part before it, the separator itself, and the part after it. If
+ the separator is not found, return two empty strings and S.
"""
def rsplit():
@@ -1036,6 +1049,7 @@
W_UnicodeObject.EMPTY = W_UnicodeObject(u'')
+
# Helper for converting int/long
def unicode_to_decimal_w(space, w_unistr):
if not isinstance(w_unistr, W_UnicodeObject):
@@ -1043,8 +1057,8 @@
w_unistr)
unistr = w_unistr._value
result = ['\0'] * len(unistr)
- digits = [ '0', '1', '2', '3', '4',
- '5', '6', '7', '8', '9']
+ digits = ['0', '1', '2', '3', '4',
+ '5', '6', '7', '8', '9']
for i in xrange(len(unistr)):
uchr = ord(unistr[i])
if unicodedb.isspace(uchr):
@@ -1060,7 +1074,10 @@
w_start = space.wrap(i)
w_end = space.wrap(i+1)
w_reason = space.wrap('invalid decimal Unicode string')
- raise OperationError(space.w_UnicodeEncodeError, space.newtuple([w_encoding, w_unistr, w_start, w_end, w_reason]))
+ raise OperationError(space.w_UnicodeEncodeError,
+ space.newtuple([w_encoding, w_unistr,
+ w_start, w_end,
+ w_reason]))
return ''.join(result)
More information about the pypy-commit
mailing list