[pypy-commit] pypy builtin-module: issue945 in-progress. The goal is to rename all modules that in pypy

arigo noreply at buildbot.pypy.org
Sat Dec 3 22:14:27 CET 2011


Author: Armin Rigo <arigo at tunes.org>
Branch: builtin-module
Changeset: r50099:34a3d737b0d4
Date: 2011-12-03 22:11 +0100
http://bitbucket.org/pypy/pypy/changeset/34a3d737b0d4/

Log:	issue945 in-progress. The goal is to rename all modules that in
	pypy are built-in, but in cpython are merely extension modules.

diff --git a/lib_pypy/_collections.py b/lib_pypy/__collections.py
copy from lib_pypy/_collections.py
copy to lib_pypy/__collections.py
diff --git a/lib_pypy/array.py b/lib_pypy/_array.py
copy from lib_pypy/array.py
copy to lib_pypy/_array.py
--- a/lib_pypy/array.py
+++ b/lib_pypy/_array.py
@@ -1,29 +1,3 @@
-"""This module defines an object type which can efficiently represent
-an array of basic values: characters, integers, floating point
-numbers.  Arrays are sequence types and behave very much like lists,
-except that the type of objects stored in them is constrained.  The
-type is specified at object creation time by using a type code, which
-is a single character.  The following type codes are defined:
-
-    Type code   C Type             Minimum size in bytes 
-    'c'         character          1 
-    'b'         signed integer     1 
-    'B'         unsigned integer   1 
-    'u'         Unicode character  2 
-    'h'         signed integer     2 
-    'H'         unsigned integer   2 
-    'i'         signed integer     2 
-    'I'         unsigned integer   2 
-    'l'         signed integer     4 
-    'L'         unsigned integer   4 
-    'f'         floating point     4 
-    'd'         floating point     8 
-
-The constructor is:
-
-array(typecode [, initializer]) -- create a new array
-"""
-
 from struct import calcsize, pack, pack_into, unpack_from
 import operator
 
diff --git a/lib_pypy/_bisect.py b/lib_pypy/_bisect.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/_bisect.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "_bisect" shadows
+# any file _bisect.py that would be found in the user dirs
+from __builtin__bisect import *
diff --git a/lib_pypy/_collections.py b/lib_pypy/_collections.py
--- a/lib_pypy/_collections.py
+++ b/lib_pypy/_collections.py
@@ -1,425 +1,6 @@
-"""High performance data structures
-"""
-#
-# Copied and completed from the sandbox of CPython
-#   (nondist/sandbox/collections/pydeque.py rev 1.1, Raymond Hettinger)
-#
-
-import operator
+# indirection needed; otherwise the built-in module "_collections" shadows
+# any file _collections.py that would be found in the user dirs
 try:
-    from thread import get_ident as _thread_ident
+    from __builtin__collections import *
 except ImportError:
-    def _thread_ident():
-        return -1
-
-
-n = 30
-LFTLNK = n
-RGTLNK = n+1
-BLOCKSIZ = n+2
-
-# The deque's size limit is d.maxlen.  The limit can be zero or positive, or
-# None.  After an item is added to a deque, we check to see if the size has
-# grown past the limit. If it has, we get the size back down to the limit by
-# popping an item off of the opposite end.  The methods that can trigger this
-# are append(), appendleft(), extend(), and extendleft().
-
-class deque(object):
-
-    def __new__(cls, iterable=(), *args, **kw):
-        self = super(deque, cls).__new__(cls, *args, **kw)
-        self.clear()
-        return self
-
-    def __init__(self, iterable=(), maxlen=None):
-        self.clear()
-        if maxlen is not None:
-            if maxlen < 0:
-                raise ValueError("maxlen must be non-negative")
-        self._maxlen = maxlen
-        add = self.append
-        for elem in iterable:
-            add(elem)
-
-    @property
-    def maxlen(self):
-        return self._maxlen
-
-    def clear(self):
-        self.right = self.left = [None] * BLOCKSIZ
-        self.rightndx = n//2   # points to last written element
-        self.leftndx = n//2+1
-        self.length = 0
-        self.state = 0
-
-    def append(self, x):
-        self.state += 1
-        self.rightndx += 1
-        if self.rightndx == n:
-            newblock = [None] * BLOCKSIZ
-            self.right[RGTLNK] = newblock
-            newblock[LFTLNK] = self.right
-            self.right = newblock
-            self.rightndx = 0
-        self.length += 1
-        self.right[self.rightndx] = x
-        if self.maxlen is not None and self.length > self.maxlen:
-            self.popleft()
-
-    def appendleft(self, x):
-        self.state += 1
-        self.leftndx -= 1
-        if self.leftndx == -1:
-            newblock = [None] * BLOCKSIZ
-            self.left[LFTLNK] = newblock
-            newblock[RGTLNK] = self.left
-            self.left = newblock
-            self.leftndx = n-1
-        self.length += 1
-        self.left[self.leftndx] = x
-        if self.maxlen is not None and self.length > self.maxlen:
-            self.pop()
-
-    def extend(self, iterable):
-        if iterable is self:
-            iterable = list(iterable)
-        for elem in iterable:
-            self.append(elem)
-
-    def extendleft(self, iterable):
-        if iterable is self:
-            iterable = list(iterable)
-        for elem in iterable:
-            self.appendleft(elem)
-
-    def pop(self):
-        if self.left is self.right and self.leftndx > self.rightndx:
-            raise IndexError, "pop from an empty deque"
-        x = self.right[self.rightndx]
-        self.right[self.rightndx] = None
-        self.length -= 1
-        self.rightndx -= 1
-        self.state += 1
-        if self.rightndx == -1:
-            prevblock = self.right[LFTLNK]
-            if prevblock is None:
-                # the deque has become empty; recenter instead of freeing block
-                self.rightndx = n//2
-                self.leftndx = n//2+1
-            else:
-                prevblock[RGTLNK] = None
-                self.right[LFTLNK] = None
-                self.right = prevblock
-                self.rightndx = n-1
-        return x
-
-    def popleft(self):
-        if self.left is self.right and self.leftndx > self.rightndx:
-            raise IndexError, "pop from an empty deque"
-        x = self.left[self.leftndx]
-        self.left[self.leftndx] = None
-        self.length -= 1
-        self.leftndx += 1
-        self.state += 1
-        if self.leftndx == n:
-            prevblock = self.left[RGTLNK]
-            if prevblock is None:
-                # the deque has become empty; recenter instead of freeing block
-                self.rightndx = n//2
-                self.leftndx = n//2+1
-            else:
-                prevblock[LFTLNK] = None
-                self.left[RGTLNK] = None
-                self.left = prevblock
-                self.leftndx = 0
-        return x
-
-    def count(self, value):
-        c = 0
-        for item in self:
-            if item == value:
-                c += 1
-        return c
-
-    def remove(self, value):
-        # Need to be defensive for mutating comparisons
-        for i in range(len(self)):
-            if self[i] == value:
-                del self[i]
-                return
-        raise ValueError("deque.remove(x): x not in deque")
-
-    def rotate(self, n=1):
-        length = len(self)
-        if length == 0:
-            return
-        halflen = (length+1) >> 1
-        if n > halflen or n < -halflen:
-            n %= length
-            if n > halflen:
-                n -= length
-            elif n < -halflen:
-                n += length
-        while n > 0:
-            self.appendleft(self.pop())
-            n -= 1
-        while n < 0:
-            self.append(self.popleft())
-            n += 1
-
-    def reverse(self):
-        "reverse *IN PLACE*"
-        leftblock = self.left
-        rightblock = self.right
-        leftindex = self.leftndx
-        rightindex = self.rightndx
-        for i in range(self.length // 2):
-            # Validate that pointers haven't met in the middle
-            assert leftblock != rightblock or leftindex < rightindex
-
-            # Swap
-            (rightblock[rightindex], leftblock[leftindex]) = (
-                leftblock[leftindex], rightblock[rightindex])
-
-            # Advance left block/index pair
-            leftindex += 1
-            if leftindex == n:
-                leftblock = leftblock[RGTLNK]
-                assert leftblock is not None
-                leftindex = 0
-
-            # Step backwards with the right block/index pair
-            rightindex -= 1
-            if rightindex == -1:
-                rightblock = rightblock[LFTLNK]
-                assert rightblock is not None
-                rightindex = n - 1
-
-    def __repr__(self):
-        threadlocalattr = '__repr' + str(_thread_ident())
-        if threadlocalattr in self.__dict__:
-            return 'deque([...])'
-        else:
-            self.__dict__[threadlocalattr] = True
-            try:
-                if self.maxlen is not None:
-                    return 'deque(%r, maxlen=%s)' % (list(self), self.maxlen)
-                else:
-                    return 'deque(%r)' % (list(self),)
-            finally:
-                del self.__dict__[threadlocalattr]
-
-    def __iter__(self):
-        return deque_iterator(self, self._iter_impl)
-
-    def _iter_impl(self, original_state, giveup):
-        if self.state != original_state:
-            giveup()
-        block = self.left
-        while block:
-            l, r = 0, n
-            if block is self.left:
-                l = self.leftndx
-            if block is self.right:
-                r = self.rightndx + 1
-            for elem in block[l:r]:
-                yield elem
-                if self.state != original_state:
-                    giveup()
-            block = block[RGTLNK]
-
-    def __reversed__(self):
-        return deque_iterator(self, self._reversed_impl)
-
-    def _reversed_impl(self, original_state, giveup):
-        if self.state != original_state:
-            giveup()
-        block = self.right
-        while block:
-            l, r = 0, n
-            if block is self.left:
-                l = self.leftndx
-            if block is self.right:
-                r = self.rightndx + 1
-            for elem in reversed(block[l:r]):
-                yield elem
-                if self.state != original_state:
-                    giveup()
-            block = block[LFTLNK]
-
-    def __len__(self):
-        #sum = 0
-        #block = self.left
-        #while block:
-        #    sum += n
-        #    block = block[RGTLNK]
-        #return sum + self.rightndx - self.leftndx + 1 - n
-        return self.length
-
-    def __getref(self, index):
-        if index >= 0:
-            block = self.left
-            while block:
-                l, r = 0, n
-                if block is self.left:
-                    l = self.leftndx
-                if block is self.right:
-                    r = self.rightndx + 1
-                span = r-l
-                if index < span:
-                    return block, l+index
-                index -= span
-                block = block[RGTLNK]
-        else:
-            block = self.right
-            while block:
-                l, r = 0, n
-                if block is self.left:
-                    l = self.leftndx
-                if block is self.right:
-                    r = self.rightndx + 1
-                negative_span = l-r
-                if index >= negative_span:
-                    return block, r+index
-                index -= negative_span
-                block = block[LFTLNK]
-        raise IndexError("deque index out of range")
-
-    def __getitem__(self, index):
-        block, index = self.__getref(index)
-        return block[index]
-
-    def __setitem__(self, index, value):
-        block, index = self.__getref(index)
-        block[index] = value
-
-    def __delitem__(self, index):
-        length = len(self)
-        if index >= 0:
-            if index >= length:
-                raise IndexError("deque index out of range")
-            self.rotate(-index)
-            self.popleft()
-            self.rotate(index)
-        else:
-            index = ~index
-            if index >= length:
-                raise IndexError("deque index out of range")
-            self.rotate(index)
-            self.pop()
-            self.rotate(-index)
-
-    def __reduce_ex__(self, proto):
-        return type(self), (list(self), self.maxlen)
-
-    def __hash__(self):
-        raise TypeError, "deque objects are unhashable"
-
-    def __copy__(self):
-        return self.__class__(self, self.maxlen)
-
-    # XXX make comparison more efficient
-    def __eq__(self, other):
-        if isinstance(other, deque):
-            return list(self) == list(other)
-        else:
-            return NotImplemented
-
-    def __ne__(self, other):
-        if isinstance(other, deque):
-            return list(self) != list(other)
-        else:
-            return NotImplemented
-
-    def __lt__(self, other):
-        if isinstance(other, deque):
-            return list(self) < list(other)
-        else:
-            return NotImplemented
-
-    def __le__(self, other):
-        if isinstance(other, deque):
-            return list(self) <= list(other)
-        else:
-            return NotImplemented
-
-    def __gt__(self, other):
-        if isinstance(other, deque):
-            return list(self) > list(other)
-        else:
-            return NotImplemented
-
-    def __ge__(self, other):
-        if isinstance(other, deque):
-            return list(self) >= list(other)
-        else:
-            return NotImplemented
-
-    def __iadd__(self, other):
-        self.extend(other)
-        return self
-
-class deque_iterator(object):
-
-    def __init__(self, deq, itergen):
-        self.counter = len(deq)
-        def giveup():
-            self.counter = 0
-            raise RuntimeError, "deque mutated during iteration"
-        self._gen = itergen(deq.state, giveup)
-
-    def next(self):
-        res =  self._gen.next()
-        self.counter -= 1
-        return res
-
-    def __iter__(self):
-        return self
-
-class defaultdict(dict):
-    
-    def __init__(self, *args, **kwds):
-        self.default_factory = None
-        if 'default_factory' in kwds:
-            self.default_factory = kwds.pop('default_factory')
-        elif len(args) > 0 and (callable(args[0]) or args[0] is None):
-            self.default_factory = args[0]
-            args = args[1:]
-        super(defaultdict, self).__init__(*args, **kwds)
- 
-    def __missing__(self, key):
-        # from defaultdict docs
-        if self.default_factory is None: 
-            raise KeyError(key)
-        self[key] = value = self.default_factory()
-        return value
-
-    def __repr__(self, recurse=set()):
-        if id(self) in recurse:
-            return "defaultdict(...)"
-        try:
-            recurse.add(id(self))
-            return "defaultdict(%s, %s)" % (repr(self.default_factory), super(defaultdict, self).__repr__())
-        finally:
-            recurse.remove(id(self))
-
-    def copy(self):
-        return type(self)(self, default_factory=self.default_factory)
-    
-    def __copy__(self):
-        return self.copy()
-
-    def __reduce__(self):
-        """
-        __reduce__ must return a 5-tuple as follows:
-
-           - factory function
-           - tuple of args for the factory function
-           - additional state (here None)
-           - sequence iterator (here None)
-           - dictionary iterator (yielding successive (key, value) pairs
-
-           This API is used by pickle.py and copy.py.
-        """
-        return (type(self), (self.default_factory,), None, None, self.iteritems())
-
+    from __collections import *
diff --git a/lib_pypy/_continuation.py b/lib_pypy/_continuation.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/_continuation.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "_continuation" shadows
+# any file _continuation.py that would be found in the user dirs
+from __builtin__continuation import *
diff --git a/lib_pypy/_io.py b/lib_pypy/_io.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/_io.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "_io" shadows
+# any file _io.py that would be found in the user dirs
+from __builtin__io import *
diff --git a/lib_pypy/_random.py b/lib_pypy/_random.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/_random.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "_random" shadows
+# any file _random.py that would be found in the user dirs
+from __builtin__random import *
diff --git a/lib_pypy/_socket.py b/lib_pypy/_socket.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/_socket.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "_socket" shadows
+# any file _socket.py that would be found in the user dirs
+from __builtin__socket import *
diff --git a/lib_pypy/_ssl.py b/lib_pypy/_ssl.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/_ssl.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "_ssl" shadows
+# any file _ssl.py that would be found in the user dirs
+from __builtin__ssl import *
diff --git a/lib_pypy/array.py b/lib_pypy/array.py
--- a/lib_pypy/array.py
+++ b/lib_pypy/array.py
@@ -24,508 +24,9 @@
 array(typecode [, initializer]) -- create a new array
 """
 
-from struct import calcsize, pack, pack_into, unpack_from
-import operator
-
-# the buffer-like object to use internally: trying from
-# various places in order...
+# indirection needed; otherwise the built-in module "array" shadows
+# any file array.py that would be found in the user dirs
 try:
-    import _rawffi                    # a reasonable implementation based
-    _RAWARRAY = _rawffi.Array('c')    # on raw_malloc, and providing a
-    def bytebuffer(size):             # real address
-        return _RAWARRAY(size, autofree=True)
-    def getbufaddress(buf):
-        return buf.buffer
+    from __builtin_array import *
 except ImportError:
-    try:
-        from __pypy__ import bytebuffer     # a reasonable implementation
-        def getbufaddress(buf):             # compatible with oo backends,
-            return 0                        # but no address
-    except ImportError:
-        # not running on PyPy.  Fall back to ctypes...
-        import ctypes
-        bytebuffer = ctypes.create_string_buffer
-        def getbufaddress(buf):
-            voidp = ctypes.cast(ctypes.pointer(buf), ctypes.c_void_p)
-            return voidp.value
-
-# ____________________________________________________________
-
-TYPECODES = "cbBuhHiIlLfd"
-
-class array(object):
-    """array(typecode [, initializer]) -> array
-    
-    Return a new array whose items are restricted by typecode, and
-    initialized from the optional initializer value, which must be a list,
-    string. or iterable over elements of the appropriate type.
-    
-    Arrays represent basic values and behave very much like lists, except
-    the type of objects stored in them is constrained.
-    
-    Methods:
-    
-    append() -- append a new item to the end of the array
-    buffer_info() -- return information giving the current memory info
-    byteswap() -- byteswap all the items of the array
-    count() -- return number of occurences of an object
-    extend() -- extend array by appending multiple elements from an iterable
-    fromfile() -- read items from a file object
-    fromlist() -- append items from the list
-    fromstring() -- append items from the string
-    index() -- return index of first occurence of an object
-    insert() -- insert a new item into the array at a provided position
-    pop() -- remove and return item (default last)
-    read() -- DEPRECATED, use fromfile()
-    remove() -- remove first occurence of an object
-    reverse() -- reverse the order of the items in the array
-    tofile() -- write all items to a file object
-    tolist() -- return the array converted to an ordinary list
-    tostring() -- return the array converted to a string
-    write() -- DEPRECATED, use tofile()
-    
-    Attributes:
-    
-    typecode -- the typecode character used to create the array
-    itemsize -- the length in bytes of one array item
-    """
-    __slots__ = ["typecode", "itemsize", "_data", "_descriptor", "__weakref__"]
-
-    def __new__(cls, typecode, initializer=[], **extrakwds):
-        self = object.__new__(cls)
-        if cls is array and extrakwds:
-            raise TypeError("array() does not take keyword arguments")
-        if not isinstance(typecode, str) or len(typecode) != 1:
-            raise TypeError(
-                     "array() argument 1 must be char, not %s" % type(typecode))
-        if typecode not in TYPECODES:
-            raise ValueError(
-                  "bad typecode (must be one of %s)" % ', '.join(TYPECODES))
-        self._data = bytebuffer(0)
-        self.typecode = typecode
-        self.itemsize = calcsize(typecode)
-        if isinstance(initializer, list):
-            self.fromlist(initializer)
-        elif isinstance(initializer, str):
-            self.fromstring(initializer)
-        elif isinstance(initializer, unicode) and self.typecode == "u":
-            self.fromunicode(initializer)
-        else:
-            self.extend(initializer)
-        return self
-
-    def _clear(self):
-        self._data = bytebuffer(0)
-
-    ##### array-specific operations
-
-    def fromfile(self, f, n):
-        """Read n objects from the file object f and append them to the end of
-        the array. Also called as read."""
-        if not isinstance(f, file):
-            raise TypeError("arg1 must be open file")
-        size = self.itemsize * n
-        item = f.read(size)
-        if len(item) < size:
-            raise EOFError("not enough items in file")
-        self.fromstring(item)
-
-    def fromlist(self, l):
-        """Append items to array from list."""
-        if not isinstance(l, list):
-            raise TypeError("arg must be list")
-        self._fromiterable(l)
-        
-    def fromstring(self, s):
-        """Appends items from the string, interpreting it as an array of machine
-        values, as if it had been read from a file using the fromfile()
-        method."""
-        if isinstance(s, unicode):
-            s = str(s)
-        self._frombuffer(s)
-
-    def _frombuffer(self, s):
-        length = len(s)
-        if length % self.itemsize != 0:
-            raise ValueError("string length not a multiple of item size")
-        boundary = len(self._data)
-        newdata = bytebuffer(boundary + length)
-        newdata[:boundary] = self._data
-        newdata[boundary:] = s
-        self._data = newdata
-
-    def fromunicode(self, ustr):
-        """Extends this array with data from the unicode string ustr. The array
-        must be a type 'u' array; otherwise a ValueError is raised. Use
-        array.fromstring(ustr.encode(...)) to append Unicode data to an array of
-        some other type."""
-        if not self.typecode == "u":
-            raise ValueError(
-                          "fromunicode() may only be called on type 'u' arrays")
-        # XXX the following probable bug is not emulated:
-        # CPython accepts a non-unicode string or a buffer, and then
-        # behaves just like fromstring(), except that it strangely truncates
-        # string arguments at multiples of the unicode byte size.
-        # Let's only accept unicode arguments for now.
-        if not isinstance(ustr, unicode):
-            raise TypeError("fromunicode() argument should probably be "
-                            "a unicode string")
-        # _frombuffer() does the currect thing using
-        # the buffer behavior of unicode objects
-        self._frombuffer(buffer(ustr))
-
-    def tofile(self, f):
-        """Write all items (as machine values) to the file object f.  Also
-        called as write."""
-        if not isinstance(f, file):
-            raise TypeError("arg must be open file")
-        f.write(self.tostring())
-        
-    def tolist(self):
-        """Convert array to an ordinary list with the same items."""
-        count = len(self._data) // self.itemsize
-        return list(unpack_from('%d%s' % (count, self.typecode), self._data))
-
-    def tostring(self):
-        return self._data[:]
-
-    def __buffer__(self):
-        return buffer(self._data)
-
-    def tounicode(self):
-        """Convert the array to a unicode string. The array must be a type 'u'
-        array; otherwise a ValueError is raised. Use array.tostring().decode()
-        to obtain a unicode string from an array of some other type."""
-        if self.typecode != "u":
-            raise ValueError("tounicode() may only be called on type 'u' arrays")
-        # XXX performance is not too good
-        return u"".join(self.tolist())
-
-    def byteswap(self):
-        """Byteswap all items of the array.  If the items in the array are not
-        1, 2, 4, or 8 bytes in size, RuntimeError is raised."""
-        if self.itemsize not in [1, 2, 4, 8]:
-            raise RuntimeError("byteswap not supported for this array")
-        # XXX slowish
-        itemsize = self.itemsize
-        bytes = self._data
-        for start in range(0, len(bytes), itemsize):
-            stop = start + itemsize
-            bytes[start:stop] = bytes[start:stop][::-1]
-
-    def buffer_info(self):
-        """Return a tuple (address, length) giving the current memory address
-        and the length in items of the buffer used to hold array's contents. The
-        length should be multiplied by the itemsize attribute to calculate the
-        buffer length in bytes. On PyPy the address might be meaningless
-        (returned as 0), depending on the available modules."""
-        return (getbufaddress(self._data), len(self))
-    
-    read = fromfile
-
-    write = tofile
-
-    ##### general object protocol
-    
-    def __repr__(self):
-        if len(self._data) == 0:
-            return "array('%s')" % self.typecode
-        elif self.typecode == "c":
-            return "array('%s', %s)" % (self.typecode, repr(self.tostring()))
-        elif self.typecode == "u":
-            return "array('%s', %s)" % (self.typecode, repr(self.tounicode()))
-        else:
-            return "array('%s', %s)" % (self.typecode, repr(self.tolist()))
-
-    def __copy__(self):
-        a = array(self.typecode)
-        a._data = bytebuffer(len(self._data))
-        a._data[:] = self._data
-        return a
-
-    def __eq__(self, other):
-        if not isinstance(other, array):
-            return NotImplemented
-        if self.typecode == 'c':
-            return buffer(self._data) == buffer(other._data)
-        else:
-            return self.tolist() == other.tolist()
-
-    def __ne__(self, other):
-        if not isinstance(other, array):
-            return NotImplemented
-        if self.typecode == 'c':
-            return buffer(self._data) != buffer(other._data)
-        else:
-            return self.tolist() != other.tolist()
-
-    def __lt__(self, other):
-        if not isinstance(other, array):
-            return NotImplemented
-        if self.typecode == 'c':
-            return buffer(self._data) < buffer(other._data)
-        else:
-            return self.tolist() < other.tolist()
-
-    def __gt__(self, other):
-        if not isinstance(other, array):
-            return NotImplemented
-        if self.typecode == 'c':
-            return buffer(self._data) > buffer(other._data)
-        else:
-            return self.tolist() > other.tolist()
-
-    def __le__(self, other):
-        if not isinstance(other, array):
-            return NotImplemented
-        if self.typecode == 'c':
-            return buffer(self._data) <= buffer(other._data)
-        else:
-            return self.tolist() <= other.tolist()
-
-    def __ge__(self, other):
-        if not isinstance(other, array):
-            return NotImplemented
-        if self.typecode == 'c':
-            return buffer(self._data) >= buffer(other._data)
-        else:
-            return self.tolist() >= other.tolist()
-
-    def __reduce__(self):
-        dict = getattr(self, '__dict__', None)
-        data = self.tostring()
-        if data:
-            initargs = (self.typecode, data)
-        else:
-            initargs = (self.typecode,)
-        return (type(self), initargs, dict)
-
-    ##### list methods
-    
-    def append(self, x):
-        """Append new value x to the end of the array."""
-        self._frombuffer(pack(self.typecode, x))
-
-    def count(self, x):
-        """Return number of occurences of x in the array."""
-        return operator.countOf(self, x)
-
-    def extend(self, iterable):
-        """Append items to the end of the array."""
-        if isinstance(iterable, array) \
-                                    and not self.typecode == iterable.typecode:
-            raise TypeError("can only extend with array of same kind")
-        self._fromiterable(iterable)
-
-    def index(self, x):
-        """Return index of first occurence of x in the array."""
-        return operator.indexOf(self, x)
-    
-    def insert(self, i, x):
-        """Insert a new item x into the array before position i."""
-        seqlength = len(self)
-        if i < 0:
-            i += seqlength
-            if i < 0:
-                i = 0
-        elif i > seqlength:
-            i = seqlength
-        boundary = i * self.itemsize
-        data = pack(self.typecode, x)
-        newdata = bytebuffer(len(self._data) + len(data))
-        newdata[:boundary] = self._data[:boundary]
-        newdata[boundary:boundary+self.itemsize] = data
-        newdata[boundary+self.itemsize:] = self._data[boundary:]
-        self._data = newdata
-        
-    def pop(self, i=-1):
-        """Return the i-th element and delete it from the array. i defaults to
-        -1."""
-        seqlength = len(self)
-        if i < 0:
-            i += seqlength
-        if not (0 <= i < seqlength):
-            raise IndexError(i)
-        boundary = i * self.itemsize
-        result = unpack_from(self.typecode, self._data, boundary)[0]
-        newdata = bytebuffer(len(self._data) - self.itemsize)
-        newdata[:boundary] = self._data[:boundary]
-        newdata[boundary:] = self._data[boundary+self.itemsize:]
-        self._data = newdata
-        return result
-        
-    def remove(self, x):
-        """Remove the first occurence of x in the array."""
-        self.pop(self.index(x))
-        
-    def reverse(self):
-        """Reverse the order of the items in the array."""
-        lst = self.tolist()
-        lst.reverse()
-        self._clear()
-        self.fromlist(lst)
-
-    ##### list protocol
-    
-    def __len__(self):
-        return len(self._data) // self.itemsize
-    
-    def __add__(self, other):
-        if not isinstance(other, array):
-            raise TypeError("can only append array to array")
-        if self.typecode != other.typecode:
-            raise TypeError("bad argument type for built-in operation")
-        return array(self.typecode, buffer(self._data) + buffer(other._data))
-
-    def __mul__(self, repeat):
-        return array(self.typecode, buffer(self._data) * repeat)
-
-    __rmul__ = __mul__
-
-    def __getitem__(self, i):
-        seqlength = len(self)
-        if isinstance(i, slice):
-            start, stop, step = i.indices(seqlength)
-            if step != 1:
-                sublist = self.tolist()[i]    # fall-back
-                return array(self.typecode, sublist)
-            if start < 0:
-                start = 0
-            if stop < start:
-                stop = start
-            assert stop <= seqlength
-            return array(self.typecode, self._data[start * self.itemsize :
-                                                   stop * self.itemsize])
-        else:
-            if i < 0:
-                i += seqlength
-            if self.typecode == 'c':  # speed trick
-                return self._data[i]
-            if not (0 <= i < seqlength):
-                raise IndexError(i)
-            boundary = i * self.itemsize
-            return unpack_from(self.typecode, self._data, boundary)[0]
-
-    def __getslice__(self, i, j):
-        return self.__getitem__(slice(i, j))
-
-    def __setitem__(self, i, x):
-        if isinstance(i, slice):
-            if (not isinstance(x, array)
-                or self.typecode != x.typecode):
-                raise TypeError("can only assign array of same kind"
-                                " to array slice")
-            seqlength = len(self)
-            start, stop, step = i.indices(seqlength)
-            if step != 1:
-                sublist = self.tolist()    # fall-back
-                sublist[i] = x.tolist()
-                self._clear()
-                self.fromlist(sublist)
-                return
-            if start < 0:
-                start = 0
-            if stop < start:
-                stop = start
-            assert stop <= seqlength
-            boundary1 = start * self.itemsize
-            boundary2 = stop * self.itemsize
-            boundary2new = boundary1 + len(x._data)
-            if boundary2 == boundary2new:
-                self._data[boundary1:boundary2] = x._data
-            else:
-                newdata = bytebuffer(len(self._data) + boundary2new-boundary2)
-                newdata[:boundary1] = self._data[:boundary1]
-                newdata[boundary1:boundary2new] = x._data
-                newdata[boundary2new:] = self._data[boundary2:]
-                self._data = newdata
-        else:
-            seqlength = len(self)
-            if i < 0:
-                i += seqlength
-            if self.typecode == 'c':  # speed trick
-                self._data[i] = x
-                return
-            if not (0 <= i < seqlength):
-                raise IndexError(i)
-            boundary = i * self.itemsize
-            pack_into(self.typecode, self._data, boundary, x)
-
-    def __setslice__(self, i, j, x):
-        self.__setitem__(slice(i, j), x)
-
-    def __delitem__(self, i):
-        if isinstance(i, slice):
-            seqlength = len(self)
-            start, stop, step = i.indices(seqlength)
-            if start < 0:
-                start = 0
-            if stop < start:
-                stop = start
-            assert stop <= seqlength
-            if step != 1:
-                sublist = self.tolist()    # fall-back
-                del sublist[i]
-                self._clear()
-                self.fromlist(sublist)
-                return
-            dellength = stop - start
-            boundary1 = start * self.itemsize
-            boundary2 = stop * self.itemsize
-            newdata = bytebuffer(len(self._data) - (boundary2-boundary1))
-            newdata[:boundary1] = self._data[:boundary1]
-            newdata[boundary1:] = self._data[boundary2:]
-            self._data = newdata
-        else:            
-            seqlength = len(self)
-            if i < 0:
-                i += seqlength
-            if not (0 <= i < seqlength):
-                raise IndexError(i)
-            boundary = i * self.itemsize
-            newdata = bytebuffer(len(self._data) - self.itemsize)
-            newdata[:boundary] = self._data[:boundary]
-            newdata[boundary:] = self._data[boundary+self.itemsize:]
-            self._data = newdata
-
-    def __delslice__(self, i, j):
-        self.__delitem__(slice(i, j))
-
-    def __contains__(self, item):
-        for x in self:
-            if x == item:
-                return True
-        return False
-
-    def __iadd__(self, other):
-        if not isinstance(other, array):
-            raise TypeError("can only extend array with array")
-        self.extend(other)
-        return self
-
-    def __imul__(self, repeat):
-        newdata = buffer(self._data) * repeat
-        self._data = bytebuffer(len(newdata))
-        self._data[:] = newdata
-        return self
-
-    def __iter__(self):
-        p = 0
-        typecode = self.typecode
-        itemsize = self.itemsize
-        while p < len(self._data):
-            yield unpack_from(typecode, self._data, p)[0]
-            p += itemsize
-
-    ##### internal methods
-
-    def _fromiterable(self, iterable):
-        iterable = tuple(iterable)
-        n = len(iterable)
-        boundary = len(self._data)
-        newdata = bytebuffer(boundary + n * self.itemsize)
-        newdata[:boundary] = self._data
-        pack_into('%d%s' % (n, self.typecode), newdata, boundary, *iterable)
-        self._data = newdata
-
-ArrayType = array
+    from _array import array, ArrayType
diff --git a/lib_pypy/cmath.py b/lib_pypy/cmath.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/cmath.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "cmath" shadows
+# any file cmath.py that would be found in the user dirs
+from __builtin_cmath import *
diff --git a/lib_pypy/itertools.py b/lib_pypy/itertools.py
--- a/lib_pypy/itertools.py
+++ b/lib_pypy/itertools.py
@@ -1,3 +1,5 @@
+# indirection needed; otherwise the built-in module "itertools" shadows
+# any file itertools.py that would be found in the user dirs
 try:
     from __builtin_itertools import *
     from __builtin_itertools import __doc__
diff --git a/lib_pypy/math.py b/lib_pypy/math.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/math.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "math" shadows
+# any file math.py that would be found in the user dirs
+from __builtin_math import *
diff --git a/lib_pypy/operator.py b/lib_pypy/operator.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/operator.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "operator" shadows
+# any file operator.py that would be found in the user dirs
+from __builtin_operator import *
diff --git a/lib_pypy/symbol.py b/lib_pypy/symbol.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/symbol.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "symbol" shadows
+# any file symbol.py that would be found in the user dirs
+from __builtin_symbol import *
diff --git a/lib_pypy/token.py b/lib_pypy/token.py
new file mode 100644
--- /dev/null
+++ b/lib_pypy/token.py
@@ -0,0 +1,3 @@
+# indirection needed; otherwise the built-in module "token" shadows
+# any file token.py that would be found in the user dirs
+from __builtin_token import *
diff --git a/pypy/interpreter/function.py b/pypy/interpreter/function.py
--- a/pypy/interpreter/function.py
+++ b/pypy/interpreter/function.py
@@ -259,7 +259,7 @@
     def descr_function__reduce__(self, space):
         from pypy.interpreter.gateway import BuiltinCode
         from pypy.interpreter.mixedmodule import MixedModule
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         code = self.code
         if isinstance(code, BuiltinCode):
@@ -559,7 +559,7 @@
     def descr_method__reduce__(self, space):
         from pypy.interpreter.mixedmodule import MixedModule
         from pypy.interpreter.gateway import BuiltinCode
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         new_inst = mod.get('method_new')
         w        = space.wrap
diff --git a/pypy/interpreter/gateway.py b/pypy/interpreter/gateway.py
--- a/pypy/interpreter/gateway.py
+++ b/pypy/interpreter/gateway.py
@@ -584,7 +584,7 @@
 
     def descr__reduce__(self, space):
         from pypy.interpreter.mixedmodule import MixedModule
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         builtin_code = mod.get('builtin_code')
         return space.newtuple([builtin_code,
diff --git a/pypy/interpreter/generator.py b/pypy/interpreter/generator.py
--- a/pypy/interpreter/generator.py
+++ b/pypy/interpreter/generator.py
@@ -24,7 +24,7 @@
 
     def descr__reduce__(self, space):
         from pypy.interpreter.mixedmodule import MixedModule
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         new_inst = mod.get('generator_new')
         w        = space.wrap
@@ -196,4 +196,4 @@
                 self.frame = None
         return unpack_into
     unpack_into = _create_unpack_into()
-    unpack_into_w = _create_unpack_into()
\ No newline at end of file
+    unpack_into_w = _create_unpack_into()
diff --git a/pypy/interpreter/mixedmodule.py b/pypy/interpreter/mixedmodule.py
--- a/pypy/interpreter/mixedmodule.py
+++ b/pypy/interpreter/mixedmodule.py
@@ -62,11 +62,14 @@
 
     def get_applevel_name(cls):
         """ NOT_RPYTHON """
-        if cls.applevel_name is not None:
-            return cls.applevel_name
-        else:
-            pkgroot = cls.__module__
-            return pkgroot.split('.')[-1]
+        assert cls.applevel_name is not None, (
+            "%r: please add an explicit applevel_name to this built-in "
+            "module.  Note that built-in modules shadow all normal app-level "
+            "imports, so consider naming the built-in module "
+            "'__builtin_%s' and adding a regular '%s.py' file in "
+            "lib_pypy that imports * from __builtin_%s." %
+            ((cls,) + (cls.__module__.split('.')[-1],) * 3))
+        return cls.applevel_name
     get_applevel_name = classmethod(get_applevel_name)
 
     def get(self, name):
diff --git a/pypy/interpreter/module.py b/pypy/interpreter/module.py
--- a/pypy/interpreter/module.py
+++ b/pypy/interpreter/module.py
@@ -86,7 +86,7 @@
         if space.finditem(w_modules, w_name) is None:
             #not imported case
             from pypy.interpreter.mixedmodule import MixedModule
-            w_mod    = space.getbuiltinmodule('_pickle_support')
+            w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
             mod      = space.interp_w(MixedModule, w_mod)
             new_inst = mod.get('module_new')
             return space.newtuple([new_inst,
diff --git a/pypy/interpreter/nestedscope.py b/pypy/interpreter/nestedscope.py
--- a/pypy/interpreter/nestedscope.py
+++ b/pypy/interpreter/nestedscope.py
@@ -46,7 +46,7 @@
         return space.cmp(self.w_value, other.w_value)
 
     def descr__reduce__(self, space):
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         new_inst = mod.get('cell_new')
         if self.w_value is None:    #when would this happen?
diff --git a/pypy/interpreter/pycode.py b/pypy/interpreter/pycode.py
--- a/pypy/interpreter/pycode.py
+++ b/pypy/interpreter/pycode.py
@@ -368,7 +368,7 @@
 
     def descr__reduce__(self, space):
         from pypy.interpreter.mixedmodule import MixedModule
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         new_inst = mod.get('code_new')
         w        = space.wrap
diff --git a/pypy/interpreter/pyframe.py b/pypy/interpreter/pyframe.py
--- a/pypy/interpreter/pyframe.py
+++ b/pypy/interpreter/pyframe.py
@@ -303,7 +303,7 @@
     def descr__reduce__(self, space):
         from pypy.interpreter.mixedmodule import MixedModule
         from pypy.module._pickle_support import maker # helper fns
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         new_inst = mod.get('frame_new')
         w        = space.wrap
diff --git a/pypy/interpreter/pytraceback.py b/pypy/interpreter/pytraceback.py
--- a/pypy/interpreter/pytraceback.py
+++ b/pypy/interpreter/pytraceback.py
@@ -26,7 +26,7 @@
 
     def descr__reduce__(self, space):
         from pypy.interpreter.mixedmodule import MixedModule
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         new_inst = mod.get('traceback_new')
         w        = space.wrap
diff --git a/pypy/interpreter/test/demomixedmod/__init__.py b/pypy/interpreter/test/demomixedmod/__init__.py
--- a/pypy/interpreter/test/demomixedmod/__init__.py
+++ b/pypy/interpreter/test/demomixedmod/__init__.py
@@ -1,6 +1,8 @@
 from pypy.interpreter.mixedmodule import MixedModule 
 
-class Module(MixedModule): 
+class Module(MixedModule):
+    applevel_name = 'demomixedmod'
+
     interpleveldefs = {
         '__name__' : '(space.wrap("mixedmodule"))',
         '__doc__'  : '(space.wrap("mixedmodule doc"))',
diff --git a/pypy/interpreter/test/test_appinterp.py b/pypy/interpreter/test/test_appinterp.py
--- a/pypy/interpreter/test/test_appinterp.py
+++ b/pypy/interpreter/test/test_appinterp.py
@@ -143,6 +143,7 @@
         from pypy.conftest import maketestobjspace
 
         class MyModule(MixedModule):
+            applevel_name = 'mymod'
             interpleveldefs = {}
             appleveldefs = {}
             def __init__(self, space, w_name):
@@ -172,8 +173,8 @@
         from pypy.conftest import gettestobjspace
         space = gettestobjspace(usemodules=('_ssl', '_socket'))
 
-        w_socket = space.builtin_modules['_socket']
-        w_ssl = space.builtin_modules['_ssl']
+        w_socket = space.builtin_modules['__builtin__socket']
+        w_ssl = space.builtin_modules['__builtin__ssl']
 
         # Uncomment this line for a workaround
         # space.getattr(w_ssl, space.wrap('SSLError'))
diff --git a/pypy/interpreter/test/test_extmodules.py b/pypy/interpreter/test/test_extmodules.py
--- a/pypy/interpreter/test/test_extmodules.py
+++ b/pypy/interpreter/test/test_extmodules.py
@@ -11,6 +11,7 @@
 import time
 
 class Module(MixedModule):
+    applevel_name = 'extmod'
 
     appleveldefs = {}
 
diff --git a/pypy/interpreter/test/test_mixedmodule.py b/pypy/interpreter/test/test_mixedmodule.py
--- a/pypy/interpreter/test/test_mixedmodule.py
+++ b/pypy/interpreter/test/test_mixedmodule.py
@@ -5,6 +5,7 @@
 class TestMixedModule(object):
     def test_install(self):
         class Module(MixedModule):
+            applevel_name = 'test_module'
             interpleveldefs = {}
             appleveldefs = {}
 
@@ -15,10 +16,12 @@
 
     def test_submodule(self):
         class SubModule(MixedModule):
+            applevel_name = 'test_module.sub'
             interpleveldefs = {}
             appleveldefs = {}
 
         class Module(MixedModule):
+            applevel_name = 'test_module'
             interpleveldefs = {}
             appleveldefs = {}
             submodules = {
@@ -38,12 +41,14 @@
         space = cls.space
 
         class SubModule(MixedModule):
+            applevel_name = 'test_module.sub'
             interpleveldefs = {
                 "value": "space.wrap(14)"
             }
             appleveldefs = {}
 
         class Module(MixedModule):
+            applevel_name = 'test_module'
             interpleveldefs = {}
             appleveldefs = {}
             submodules = {
diff --git a/pypy/interpreter/test/test_pyframe.py b/pypy/interpreter/test/test_pyframe.py
--- a/pypy/interpreter/test/test_pyframe.py
+++ b/pypy/interpreter/test/test_pyframe.py
@@ -240,7 +240,7 @@
 
     def test_trace_ignore_hidden(self):
         import sys
-        import _testing
+        import __builtin__testing as _testing
             
         l = []
         def trace(a,b,c):
diff --git a/pypy/module/__builtin__/__init__.py b/pypy/module/__builtin__/__init__.py
--- a/pypy/module/__builtin__/__init__.py
+++ b/pypy/module/__builtin__/__init__.py
@@ -9,6 +9,8 @@
     """Built-in functions, exceptions, and other objects."""
     expose__file__attribute = False
 
+    applevel_name = '__builtin__'
+
     appleveldefs = {
         'execfile'      : 'app_io.execfile',
         'raw_input'     : 'app_io.raw_input',
diff --git a/pypy/module/__builtin__/functional.py b/pypy/module/__builtin__/functional.py
--- a/pypy/module/__builtin__/functional.py
+++ b/pypy/module/__builtin__/functional.py
@@ -227,7 +227,7 @@
 
     def descr___reduce__(self, space):
         from pypy.interpreter.mixedmodule import MixedModule
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         w_new_inst = mod.get('enumerate_new')
         w_info = space.newtuple([self.w_iter, self.w_index])
@@ -288,7 +288,7 @@
 
     def descr___reduce__(self, space):
         from pypy.interpreter.mixedmodule import MixedModule
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         w_new_inst = mod.get('reversed_new')
         info_w = [self.w_sequence, space.wrap(self.remaining)]
@@ -412,7 +412,7 @@
     def descr_reduce(self):
         from pypy.interpreter.mixedmodule import MixedModule
         space    = self.space
-        w_mod    = space.getbuiltinmodule('_pickle_support')
+        w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
         mod      = space.interp_w(MixedModule, w_mod)
         new_inst = mod.get('xrangeiter_new')
         w        = space.wrap
diff --git a/pypy/module/__builtin__/state.py b/pypy/module/__builtin__/state.py
--- a/pypy/module/__builtin__/state.py
+++ b/pypy/module/__builtin__/state.py
@@ -2,8 +2,8 @@
 class State:
     def __init__(self, space):
         self.w_file = space.appexec([], """():
-                import _file;
-                return _file.file""")
+                import __builtin__file;
+                return __builtin__file.file""")
         
 def get(space):
     return space.fromcache(State)
diff --git a/pypy/module/__pypy__/__init__.py b/pypy/module/__pypy__/__init__.py
--- a/pypy/module/__pypy__/__init__.py
+++ b/pypy/module/__pypy__/__init__.py
@@ -5,6 +5,8 @@
 
 
 class BuildersModule(MixedModule):
+    applevel_name = '__pypy__.builders'
+
     appleveldefs = {}
 
     interpleveldefs = {
@@ -13,6 +15,8 @@
     }
 
 class Module(MixedModule):
+    applevel_name = '__pypy__'
+
     appleveldefs = {
     }
 
diff --git a/pypy/module/_ast/__init__.py b/pypy/module/_ast/__init__.py
--- a/pypy/module/_ast/__init__.py
+++ b/pypy/module/_ast/__init__.py
@@ -3,12 +3,15 @@
 
 
 class Module(MixedModule):
+    applevel_name = '_ast'
+
+    appleveldefs = {
+        }
 
     interpleveldefs = {
         "PyCF_ONLY_AST" : "space.wrap(%s)" % consts.PyCF_ONLY_AST,
         "__version__"   : "space.wrap('82160')",  # from CPython's svn.
         }
-    appleveldefs = {}
 
 
 def _setup():
diff --git a/pypy/module/_bisect/__init__.py b/pypy/module/_bisect/__init__.py
--- a/pypy/module/_bisect/__init__.py
+++ b/pypy/module/_bisect/__init__.py
@@ -13,6 +13,7 @@
 having to sort the list after each insertion. For long lists of items with
 expensive comparison operations, this can be an improvement over the more
 common approach."""
+    applevel_name = '__builtin__bisect'
 
     appleveldefs = {
         'insort':        'app_bisect.insort_right',
diff --git a/pypy/module/_codecs/__init__.py b/pypy/module/_codecs/__init__.py
--- a/pypy/module/_codecs/__init__.py
+++ b/pypy/module/_codecs/__init__.py
@@ -38,6 +38,8 @@
 Copyright (c) Corporation for National Research Initiatives.
 """
 
+    applevel_name = '_codecs'
+
     appleveldefs = {}
 
     interpleveldefs = {
diff --git a/pypy/module/_collections/__init__.py b/pypy/module/_collections/__init__.py
--- a/pypy/module/_collections/__init__.py
+++ b/pypy/module/_collections/__init__.py
@@ -7,6 +7,7 @@
 - deque:        ordered collection accessible from endpoints only
 - defaultdict:  dict subclass with a default value factory
 """
+    applevel_name = '__builtin__collections'
 
     appleveldefs = {
         'defaultdict': 'app_defaultdict.defaultdict',
diff --git a/pypy/module/_continuation/__init__.py b/pypy/module/_continuation/__init__.py
--- a/pypy/module/_continuation/__init__.py
+++ b/pypy/module/_continuation/__init__.py
@@ -28,6 +28,7 @@
 The most primitive API is actually 'permute()', which just permutes the
 one-shot continuation stored in two (or more) continulets.
 """
+    applevel_name = '__builtin__continuation'
 
     appleveldefs = {
         'error': 'app_continuation.error',
diff --git a/pypy/module/_file/__init__.py b/pypy/module/_file/__init__.py
--- a/pypy/module/_file/__init__.py
+++ b/pypy/module/_file/__init__.py
@@ -4,6 +4,8 @@
 import sys
 
 class Module(MixedModule):
+    applevel_name = '__builtin__file'
+
     appleveldefs = {
     }
 
diff --git a/pypy/module/_file/test/test_file.py b/pypy/module/_file/test/test_file.py
--- a/pypy/module/_file/test/test_file.py
+++ b/pypy/module/_file/test/test_file.py
@@ -6,8 +6,8 @@
 def getfile(space):
     return space.appexec([], """():
         try:
-            import _file
-            return _file.file
+            import __builtin__file
+            return __builtin__file.file
         except ImportError:     # when running with py.test -A
             return file
     """)
@@ -208,7 +208,7 @@
         assert exc.value.filename == os.curdir
 
     def test_encoding_errors(self):
-        import _file
+        import __builtin__file as _file
 
         with self.file(self.temppath, "w") as f:
             _file.set_file_encoding(f, "utf-8")
diff --git a/pypy/module/_io/__init__.py b/pypy/module/_io/__init__.py
--- a/pypy/module/_io/__init__.py
+++ b/pypy/module/_io/__init__.py
@@ -2,6 +2,7 @@
 import sys
 
 class Module(MixedModule):
+    applevel_name = '__builtin__io'
 
     appleveldefs = {
         }
diff --git a/pypy/module/_pickle_support/__init__.py b/pypy/module/_pickle_support/__init__.py
--- a/pypy/module/_pickle_support/__init__.py
+++ b/pypy/module/_pickle_support/__init__.py
@@ -2,6 +2,7 @@
 
 class Module(MixedModule):
     """Built-in functions, exceptions, and other objects."""
+    applevel_name = '__builtin__pickle_support'
 
     appleveldefs = {
     }
diff --git a/pypy/module/_random/__init__.py b/pypy/module/_random/__init__.py
--- a/pypy/module/_random/__init__.py
+++ b/pypy/module/_random/__init__.py
@@ -3,9 +3,10 @@
 from pypy.interpreter.mixedmodule import MixedModule
 
 class Module(MixedModule):
+    applevel_name = '__builtin__random'
+
     appleveldefs = {}
-  
+
     interpleveldefs = {
         'Random'          : 'interp_random.W_Random',
         }
-    
diff --git a/pypy/module/_socket/__init__.py b/pypy/module/_socket/__init__.py
--- a/pypy/module/_socket/__init__.py
+++ b/pypy/module/_socket/__init__.py
@@ -3,6 +3,7 @@
 import sys
 
 class Module(MixedModule):
+    applevel_name = '__builtin__socket'
 
     appleveldefs = {
     }
diff --git a/pypy/module/_sre/__init__.py b/pypy/module/_sre/__init__.py
--- a/pypy/module/_sre/__init__.py
+++ b/pypy/module/_sre/__init__.py
@@ -1,6 +1,7 @@
 from pypy.interpreter.mixedmodule import MixedModule 
 
 class Module(MixedModule):
+    applevel_name = '_sre'
 
     appleveldefs = {
     }
diff --git a/pypy/module/_ssl/__init__.py b/pypy/module/_ssl/__init__.py
--- a/pypy/module/_ssl/__init__.py
+++ b/pypy/module/_ssl/__init__.py
@@ -3,6 +3,7 @@
 class Module(MixedModule):
     """Implementation module for SSL socket operations.
     See the socket module for documentation."""
+    applevel_name = '__builtin__ssl'
 
     interpleveldefs = {
         'sslwrap': 'interp_ssl.sslwrap',
diff --git a/pypy/module/_testing/__init__.py b/pypy/module/_testing/__init__.py
--- a/pypy/module/_testing/__init__.py
+++ b/pypy/module/_testing/__init__.py
@@ -9,6 +9,8 @@
 class Module(MixedModule):
     """PyPy own testing"""
 
+    applevel_name = '__builtin__testing'
+
     interpleveldefs = {
         }
 
diff --git a/pypy/module/_weakref/__init__.py b/pypy/module/_weakref/__init__.py
--- a/pypy/module/_weakref/__init__.py
+++ b/pypy/module/_weakref/__init__.py
@@ -1,8 +1,11 @@
 from pypy.interpreter.mixedmodule import MixedModule
     
 class Module(MixedModule):
+    applevel_name = '_weakref'
+
     appleveldefs = {
     }
+
     interpleveldefs = {
         'ref': 'interp__weakref.W_Weakref',
         'getweakrefcount': 'interp__weakref.getweakrefcount',
diff --git a/pypy/module/array/__init__.py b/pypy/module/array/__init__.py
--- a/pypy/module/array/__init__.py
+++ b/pypy/module/array/__init__.py
@@ -7,6 +7,7 @@
 
 
 class Module(MixedModule):
+    applevel_name = '__builtin_array'
 
     interpleveldefs = {
         'array': 'interp_array.W_ArrayBase',
diff --git a/pypy/module/cmath/__init__.py b/pypy/module/cmath/__init__.py
--- a/pypy/module/cmath/__init__.py
+++ b/pypy/module/cmath/__init__.py
@@ -33,6 +33,8 @@
 
 
 class Module(MixedModule):
+    applevel_name = '__builtin_cmath'
+
     appleveldefs = {
     }
 
diff --git a/pypy/module/errno/__init__.py b/pypy/module/errno/__init__.py
--- a/pypy/module/errno/__init__.py
+++ b/pypy/module/errno/__init__.py
@@ -16,6 +16,7 @@
     To map error codes to error messages, use the function os.strerror(),
     e.g. os.strerror(2) could return 'No such file or directory'."""
 
+    applevel_name = 'errno'
     appleveldefs = {}
     interpleveldefs = {"errorcode": "interp_errno.get_errorcode(space)"}
     
diff --git a/pypy/module/exceptions/__init__.py b/pypy/module/exceptions/__init__.py
--- a/pypy/module/exceptions/__init__.py
+++ b/pypy/module/exceptions/__init__.py
@@ -2,8 +2,10 @@
 from pypy.interpreter.mixedmodule import MixedModule
 
 class Module(MixedModule):
+    applevel_name = 'exceptions'
+
     appleveldefs = {}
-    
+
     interpleveldefs = {
         'ArithmeticError' : 'interp_exceptions.W_ArithmeticError',
         'AssertionError' : 'interp_exceptions.W_AssertionError',
diff --git a/pypy/module/gc/__init__.py b/pypy/module/gc/__init__.py
--- a/pypy/module/gc/__init__.py
+++ b/pypy/module/gc/__init__.py
@@ -1,6 +1,8 @@
 from pypy.interpreter.mixedmodule import MixedModule
     
 class Module(MixedModule):
+    applevel_name = 'gc'
+
     appleveldefs = {
         'enable': 'app_gc.enable',
         'disable': 'app_gc.disable',
diff --git a/pypy/module/imp/__init__.py b/pypy/module/imp/__init__.py
--- a/pypy/module/imp/__init__.py
+++ b/pypy/module/imp/__init__.py
@@ -5,6 +5,8 @@
     This module provides the components needed to build your own
     __import__ function.
     """
+    applevel_name = 'imp'
+
     interpleveldefs = {
         'PY_SOURCE':       'space.wrap(importing.PY_SOURCE)',
         'PY_COMPILED':     'space.wrap(importing.PY_COMPILED)',
diff --git a/pypy/module/marshal/__init__.py b/pypy/module/marshal/__init__.py
--- a/pypy/module/marshal/__init__.py
+++ b/pypy/module/marshal/__init__.py
@@ -5,6 +5,7 @@
     """
     This module implements marshal at interpreter level.
     """
+    applevel_name = 'marshal'
 
     appleveldefs = {
     }
diff --git a/pypy/module/math/__init__.py b/pypy/module/math/__init__.py
--- a/pypy/module/math/__init__.py
+++ b/pypy/module/math/__init__.py
@@ -3,6 +3,8 @@
 from pypy.interpreter.mixedmodule import MixedModule
 
 class Module(MixedModule):
+    applevel_name = '__builtin_math'
+
     appleveldefs = {
        'factorial' : 'app_math.factorial'
     }
diff --git a/pypy/module/operator/__init__.py b/pypy/module/operator/__init__.py
--- a/pypy/module/operator/__init__.py
+++ b/pypy/module/operator/__init__.py
@@ -4,6 +4,8 @@
 class Module(MixedModule):
     """Operator Builtin Module. """
 
+    applevel_name = '__builtin_operator'
+
     # HACK! override loaders to be able to access different operations
     # under same name. I.e., operator.eq == operator.__eq__
 
diff --git a/pypy/module/symbol/__init__.py b/pypy/module/symbol/__init__.py
--- a/pypy/module/symbol/__init__.py
+++ b/pypy/module/symbol/__init__.py
@@ -10,6 +10,7 @@
 
 class Module(MixedModule):
     """Non-terminal symbols of Python grammar."""
+    applevel_name = '__builtin_symbol'
     appleveldefs = {}
     interpleveldefs = {}     # see below
 
diff --git a/pypy/module/sys/__init__.py b/pypy/module/sys/__init__.py
--- a/pypy/module/sys/__init__.py
+++ b/pypy/module/sys/__init__.py
@@ -9,6 +9,8 @@
     """Sys Builtin Module. """
     _immutable_fields_ = ["defaultencoding?"]
 
+    applevel_name = 'sys'
+
     def __init__(self, space, w_name):
         """NOT_RPYTHON""" # because parent __init__ isn't
         if space.config.translating:
diff --git a/pypy/module/token/__init__.py b/pypy/module/token/__init__.py
--- a/pypy/module/token/__init__.py
+++ b/pypy/module/token/__init__.py
@@ -4,6 +4,7 @@
 
 
 class Module(MixedModule):
+    applevel_name = '__builtin_token'
 
     appleveldefs = {}
     interpleveldefs = {
diff --git a/pypy/objspace/std/dicttype.py b/pypy/objspace/std/dicttype.py
--- a/pypy/objspace/std/dicttype.py
+++ b/pypy/objspace/std/dicttype.py
@@ -148,7 +148,7 @@
     XXX to do: remove this __reduce__ method and do
     a registration with copy_reg, instead.
     """
-    w_mod    = space.getbuiltinmodule('_pickle_support')
+    w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
     mod      = space.interp_w(MixedModule, w_mod)
     new_inst = mod.get('dictiter_surrogate_new')
     w_typeobj = space.gettypeobject(dictiter_typedef)
diff --git a/pypy/objspace/std/itertype.py b/pypy/objspace/std/itertype.py
--- a/pypy/objspace/std/itertype.py
+++ b/pypy/objspace/std/itertype.py
@@ -17,7 +17,7 @@
     from pypy.objspace.std.iterobject import W_AbstractSeqIterObject
     assert isinstance(w_self, W_AbstractSeqIterObject)
     from pypy.interpreter.mixedmodule import MixedModule
-    w_mod    = space.getbuiltinmodule('_pickle_support')
+    w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
     mod      = space.interp_w(MixedModule, w_mod)
     new_inst = mod.get('seqiter_new')
     tup      = [w_self.w_seq, space.wrap(w_self.index)]
@@ -33,7 +33,7 @@
     from pypy.objspace.std.iterobject import W_ReverseSeqIterObject
     assert isinstance(w_self, W_ReverseSeqIterObject)
     from pypy.interpreter.mixedmodule import MixedModule
-    w_mod    = space.getbuiltinmodule('_pickle_support')
+    w_mod    = space.getbuiltinmodule('__builtin__pickle_support')
     mod      = space.interp_w(MixedModule, w_mod)
     new_inst = mod.get('reverseseqiter_new')
     tup      = [w_self.w_seq, space.wrap(w_self.index)]
diff --git a/pypy/translator/goal/app_main.py b/pypy/translator/goal/app_main.py
--- a/pypy/translator/goal/app_main.py
+++ b/pypy/translator/goal/app_main.py
@@ -258,7 +258,7 @@
 
 def set_io_encoding(io_encoding):
     try:
-        import _file
+        import __builtin__file
     except ImportError:
         if sys.version_info < (2, 7):
             return
@@ -266,7 +266,7 @@
         set_file_encoding = ctypes.pythonapi.PyFile_SetEncodingAndErrors
         set_file_encoding.argtypes = [ctypes.py_object, ctypes.c_char_p, ctypes.c_char_p]
     else:
-        set_file_encoding = _file.set_file_encoding
+        set_file_encoding = __builtin__file.set_file_encoding
     if ":" in io_encoding:
         encoding, errors = io_encoding.split(":", 1)
     else:


More information about the pypy-commit mailing list