Skip to content

Commit

Permalink
Merge pull request #210 from blueyed/buitin
Browse files Browse the repository at this point in the history
Clean up builtin for py27+
  • Loading branch information
nicoddemus authored Feb 18, 2019
2 parents 24de093 + 7412944 commit 43d70ed
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 136 deletions.
123 changes: 12 additions & 111 deletions py/_builtin.py
Original file line number Diff line number Diff line change
@@ -1,120 +1,21 @@
import sys

try:
reversed = reversed
except NameError:
def reversed(sequence):
"""reversed(sequence) -> reverse iterator over values of the sequence
Return a reverse iterator
"""
if hasattr(sequence, '__reversed__'):
return sequence.__reversed__()
if not hasattr(sequence, '__getitem__'):
raise TypeError("argument to reversed() must be a sequence")
return reversed_iterator(sequence)

class reversed_iterator(object):

def __init__(self, seq):
self.seq = seq
self.remaining = len(seq)

def __iter__(self):
return self

def next(self):
i = self.remaining
if i > 0:
i -= 1
item = self.seq[i]
self.remaining = i
return item
raise StopIteration

def __length_hint__(self):
return self.remaining

try:
any = any
except NameError:
def any(iterable):
for x in iterable:
if x:
return True
return False

try:
all = all
except NameError:
def all(iterable):
for x in iterable:
if not x:
return False
return True

try:
sorted = sorted
except NameError:
builtin_cmp = cmp # need to use cmp as keyword arg

def sorted(iterable, cmp=None, key=None, reverse=0):
use_cmp = None
if key is not None:
if cmp is None:
def use_cmp(x, y):
return builtin_cmp(x[0], y[0])
else:
def use_cmp(x, y):
return cmp(x[0], y[0])
l = [(key(element), element) for element in iterable]
else:
if cmp is not None:
use_cmp = cmp
l = list(iterable)
if use_cmp is not None:
l.sort(use_cmp)
else:
l.sort()
if reverse:
l.reverse()
if key is not None:
return [element for (_, element) in l]
return l

try:
set, frozenset = set, frozenset
except NameError:
from sets import set, frozenset

# pass through
enumerate = enumerate

try:
BaseException = BaseException
except NameError:
BaseException = Exception

try:
GeneratorExit = GeneratorExit
except NameError:
class GeneratorExit(Exception):
""" This exception is never raised, it is there to make it possible to
write code compatible with CPython 2.5 even in lower CPython
versions."""
pass
GeneratorExit.__module__ = 'exceptions'

# Passthrough for builtins supported with py27.
BaseException = BaseException
GeneratorExit = GeneratorExit
_sysex = (KeyboardInterrupt, SystemExit, MemoryError, GeneratorExit)
all = all
any = any
callable = callable
enumerate = enumerate
reversed = reversed
set, frozenset = set, frozenset
sorted = sorted

try:
callable = callable
except NameError:
def callable(obj):
return hasattr(obj, "__call__")

if sys.version_info >= (3, 0):
exec ("print_ = print ; exec_=exec")
exec("print_ = print ; exec_=exec")
import builtins

# some backward compatibility helpers
Expand All @@ -131,13 +32,13 @@ def _totext(obj, encoding=None, errors=None):

def _isbytes(x):
return isinstance(x, bytes)

def _istext(x):
return isinstance(x, str)

text = str
bytes = bytes


def _getimself(function):
return getattr(function, '__self__', None)

Expand Down
27 changes: 2 additions & 25 deletions testing/root/test_builtin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import sys
import types
import py
from py.builtin import set, frozenset, reversed, sorted
from py.builtin import set, frozenset

def test_enumerate():
l = [0,1,2]
Expand Down Expand Up @@ -53,29 +53,6 @@ def test_frozenset():
s = set([frozenset([0, 1]), frozenset([1, 0])])
assert len(s) == 1

def test_sorted():
if sorted == py.builtin.sorted:
return # don't test a real builtin
for s in [py.builtin.sorted]:
def test():
assert s([3, 2, 1]) == [1, 2, 3]
assert s([1, 2, 3], reverse=True) == [3, 2, 1]
l = s([1, 2, 3, 4, 5, 6], key=lambda x: x % 2)
assert l == [2, 4, 6, 1, 3, 5]
l = s([1, 2, 3, 4], cmp=lambda x, y: -cmp(x, y))
assert l == [4, 3, 2, 1]
l = s([1, 2, 3, 4], cmp=lambda x, y: -cmp(x, y),
key=lambda x: x % 2)
assert l == [1, 3, 2, 4]

def compare(x, y):
assert type(x) == str
assert type(y) == str
return cmp(x, y)
data = 'The quick Brown fox Jumped over The lazy Dog'.split()
s(data, cmp=compare, key=str.lower)
yield test


def test_print_simple():
from py.builtin import print_
Expand Down Expand Up @@ -116,7 +93,7 @@ class A:

def test_getfuncdict():
def f():
pass
raise NotImplementedError
f.x = 4
assert py.builtin._getfuncdict(f)["x"] == 4
assert py.builtin._getfuncdict(2) is None
Expand Down
3 changes: 3 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,6 @@ source = .
parallel = 1
[coverage:report]
include = py/*,testing/*
exclude_lines =
#\s*(pragma|PRAGMA)[:\s]?\s*(no|NO)\s*(cover|COVER)
^\s*raise NotImplementedError\b

0 comments on commit 43d70ed

Please sign in to comment.