[pypy-svn] r9301 - in pypy/branch/dist-interpapp/pypy: interpreter interpreter/test/mixedmodule module module/builtin module/sys2

hpk at codespeak.net hpk at codespeak.net
Fri Feb 18 11:45:25 CET 2005


Author: hpk
Date: Fri Feb 18 11:45:25 2005
New Revision: 9301

Added:
   pypy/branch/dist-interpapp/pypy/interpreter/lazymodule.py
      - copied, changed from r9299, pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py
Removed:
   pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py
   pypy/branch/dist-interpapp/pypy/interpreter/oldextmodule.py
   pypy/branch/dist-interpapp/pypy/module/__builtin__interp.py
   pypy/branch/dist-interpapp/pypy/module/__builtin__module.py
   pypy/branch/dist-interpapp/pypy/module/sysinterp.py
   pypy/branch/dist-interpapp/pypy/module/sysmodule.py
Modified:
   pypy/branch/dist-interpapp/pypy/interpreter/module.py
   pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py
   pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py
   pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py
Log:
- removed support and definitions of old-style builtins/sys
  modules (yay!) in favour of the new lazy ones. 

- cleaned up interpreter/module.py because it doesn't have
  to care anymore for special sys-attributes

- moved newmodule.py -> lazymodule.py



Copied: pypy/branch/dist-interpapp/pypy/interpreter/lazymodule.py (from r9299, pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py)
==============================================================================
--- pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py	(original)
+++ pypy/branch/dist-interpapp/pypy/interpreter/lazymodule.py	Fri Feb 18 11:45:25 2005
@@ -5,7 +5,7 @@
 
 import inspect
 
-class ExtModule(Module):
+class LazyModule(Module):
 
     NOT_RPYTHON_ATTRIBUTES = ['loaders']
     

Modified: pypy/branch/dist-interpapp/pypy/interpreter/module.py
==============================================================================
--- pypy/branch/dist-interpapp/pypy/interpreter/module.py	(original)
+++ pypy/branch/dist-interpapp/pypy/interpreter/module.py	Fri Feb 18 11:45:25 2005
@@ -36,32 +36,3 @@
         w_dict = self.getdict()
         space.setitem(w_dict, space.wrap('__name__'), w_name)
         space.setitem(w_dict, space.wrap('__doc__'), w_doc)
-
-    def getdictvalue(self, space, attr): 
-        try: 
-            return space.getitem(self.w_dict, self.space.wrap(attr))
-        except OperationError, e: 
-            if not e.match(space, space.w_KeyError): 
-                raise 
-        # ______ for the 'sys' module only _____ XXX put that
-        # into a special subclass at some point 
-        if self is space.sys:
-            if attr == 'exc_type':
-                operror = space.getexecutioncontext().sys_exc_info()
-                if operror is None:
-                    return space.w_None
-                else:
-                    return operror.w_type
-            if attr == 'exc_value':
-                operror = space.getexecutioncontext().sys_exc_info()
-                if operror is None:
-                    return space.w_None
-                else:
-                    return operror.w_value
-            if attr == 'exc_traceback':
-                operror = space.getexecutioncontext().sys_exc_info()
-                if operror is None:
-                    return space.w_None
-                else:
-                    return space.wrap(operror.application_traceback)
-        return None 

Deleted: /pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py
==============================================================================
--- /pypy/branch/dist-interpapp/pypy/interpreter/newmodule.py	Fri Feb 18 11:45:25 2005
+++ (empty file)
@@ -1,105 +0,0 @@
-from pypy.interpreter.module import Module 
-from pypy.tool.cache import Cache
-from pypy.interpreter import gateway 
-from pypy.interpreter.error import OperationError 
-
-import inspect
-
-class ExtModule(Module):
-
-    NOT_RPYTHON_ATTRIBUTES = ['loaders']
-    
-    def __init__(self, space, w_name): 
-        """ NOT_RPYTHON """ 
-        Module.__init__(self, space, w_name) 
-        self.lazy = True 
-        self.__class__.buildloaders() 
-
-    def get(self, name):
-        space = self.space
-        w_value = self.getdictvalue(space, name) 
-        if w_value is None: 
-            raise OperationError(space.w_AttributeError, space.wrap(name))
-        return w_value 
-
-    def getdictvalue(self, space, name): 
-        try: 
-            return space.getitem(self.w_dict, space.wrap(name))
-        except OperationError, e: 
-            if not e.match(space, space.w_KeyError): 
-                raise 
-            if not self.lazy: 
-                return None 
-            try: 
-                loader = self.loaders[name]
-            except KeyError: 
-                return None 
-            else: 
-                #print "trying to load", name
-                w_value = loader(space) 
-                #print "loaded", w_value 
-                space.setitem(self.w_dict, space.wrap(name), w_value) 
-                return w_value 
-
-    def getdict(self): 
-        if self.lazy: 
-            space = self.space
-            for name in self.loaders: 
-                w_value = self.get(name)  
-                space.setitem(self.w_dict, space.wrap(name), w_value) 
-            self.lazy = False 
-        return self.w_dict 
-
-    def buildloaders(cls): 
-        """ NOT_RPYTHON """ 
-        if not hasattr(cls, 'loaders'): 
-            # build a constant dictionary out of
-            # applevel/interplevel definitions 
-            cls.loaders = loaders = {}
-            pkgroot = cls.__module__
-            for name, spec in cls.interpleveldefs.items(): 
-                loaders[name] = getinterpevalloader(pkgroot, spec) 
-            for name, spec in cls.appleveldefs.items(): 
-                loaders[name] = getappfileloader(pkgroot, spec) 
-    buildloaders = classmethod(buildloaders) 
-
-def getinterpevalloader(pkgroot, spec):
-    """ NOT_RPYTHON """     
-    def ifileloader(space): 
-        d = {'space' : space}
-        # EVIL HACK (but it works, and this is not RPython :-) 
-        while 1: 
-            try: 
-                value = eval(spec, d) 
-            except NameError, ex: 
-                #assert name not in d, "huh, am i looping?" 
-                name = ex.args[0].split("'")[1] # super-Evil 
-                try: 
-                    d[name] = __import__(pkgroot+'.'+name, None, None, [name])
-                except ImportError: 
-                    d[name] = __import__(name, None, None, [name])
-            else: 
-                #print spec, "->", value
-                if hasattr(value, 'func_code'):  # semi-evil 
-                    return space.wrap(gateway.interp2app(value))
-                assert value is not None 
-                return value 
-    return ifileloader 
-        
-applevelcache = Cache()
-def getappfileloader(pkgroot, spec):
-    """ NOT_RPYTHON """ 
-    # hum, it's a bit more involved, because we usually 
-    # want the import at applevel
-    modname, attrname = spec.split('.')
-    impbase = pkgroot + '.' + modname 
-    mod = __import__(impbase, None, None, ['attrname'])
-    app = applevelcache.getorbuild(mod, buildapplevelfrommodule, None)
-    def afileloader(space): 
-        return app.wget(space, attrname)
-    return afileloader 
-
-def buildapplevelfrommodule(mod, _):
-    """ NOT_RPYTHON """ 
-    source = inspect.getsource(mod) 
-    return gateway.applevel(source) 

Deleted: /pypy/branch/dist-interpapp/pypy/interpreter/oldextmodule.py
==============================================================================
--- /pypy/branch/dist-interpapp/pypy/interpreter/oldextmodule.py	Fri Feb 18 11:45:25 2005
+++ (empty file)
@@ -1,180 +0,0 @@
-"""
-
-Helpers to build extension modules.
-
-"""
-
-from __future__ import generators   # for generators.compiler_flag
-import os, sys
-import autopath
-from pypy.interpreter import gateway
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.pycode import PyCode
-from pypy.interpreter.function import Function
-from pypy.interpreter.module import Module
-
-class interplevelimport_interp2app(gateway.interp2app):
-
-    def __init__(self, f, w_globals):
-        "NOT_RPYTHON"
-        gateway.interp2app.__init__(self, f, ismethod=False, spacearg=False)
-        self.w_globals = w_globals
-
-    def _getglobals(self, space):
-        "NOT_RPYTHON"
-        return self.w_globals
-
-
-class BuiltinModule(Module):
-    """A Module subclass specifically for built-in modules."""
-
-    # '__builtins__' is stored in self.__dict__ by
-    # self.interplevel{exec,eval,execfile}()
-    NOT_RPYTHON_ATTRIBUTES = ['__builtins__']
-
-    def __init__(self, space, modulename, w_dict=None, sourcefile=None):
-        """NOT_RPYTHON
-        Load the named built-in module, by default from the source file
-        'pypy/module/<name>module.py', which is app-level Python code
-        with a few special features that allow it to include interp-level
-        bits.  (See pypy/module/test/foomodule.py)
-
-        The module has two parts: the interp-level objects, stored as
-        attributes of 'self', and the app-level objects, stored in the
-        dictionary 'self.w_dict'.  The app-level definition of the module
-        runs with 'self.w_dict' as globals.  The interp-level bits are
-        executed with 'self.__dict__' as globals, i.e. they can read and
-        change the attributes of 'self' as global variables.
-        """
-        Module.__init__(self, space, space.wrap(modulename), w_dict)
-        w_dict = self.w_dict
-
-        # Compile the xxxmodule.py source file
-        self.__name__ = 'interpreter-level %s' % modulename
-        self.__file__ = sourcefile or os.path.join(autopath.pypydir, 'module',
-                                                   modulename+'module.py')
-        space.setitem(w_dict, space.wrap('__file__'),
-                              space.wrap(self.__file__))
-        f = open(self.__file__, 'r')
-        modulesource = f.read()
-        f.close()
-        code = compile(modulesource, self.__file__, 'exec',
-                       generators.compiler_flag)
-        pycode = PyCode(space)._from_code(code)
-
-        # Set the hooks that call back from app-level to interp-level
-        w_builtins = space.w_builtins
-        self.__saved_hooks = {}
-        newhooks = {}
-        
-        for name, impl in [
-            ('__interplevel__exec',     self.interplevelexec.im_func),
-            ('__interplevel__eval',     self.interpleveleval.im_func),
-            ('__interplevel__execfile', self.interplevelexecfile.im_func),
-            ('__import__',              self.interplevelimport.im_func)]:
-            hook = gateway.interp2app_temp(impl).get_method(self)
-            w_name = space.wrap(name)
-            try:
-                self.__saved_hooks[name] = space.getitem(w_builtins, w_name)
-            except OperationError:
-                pass
-            w_hook = space.wrap(hook)
-            space.setitem(w_builtins, w_name, w_hook)
-            newhooks[name] = w_hook
-        space.setitem(self.w_dict, space.wrap('__builtins__'),
-                      space.w_builtins)
-
-        # Temporarily install an '__applevel__' pseudo-module
-        sys.modules['__applevel__'] = AppModuleHack(self)
-
-        # Run the app-level module definition (xxxmodule.py)
-        pycode.exec_code(space, w_dict, w_dict)
-
-        # Remove the pseudo-module
-        del sys.modules['__applevel__']
-        try:
-            del self.__applevel__
-        except AttributeError:
-            pass
-
-        # Remove/restore the hooks unless they have been modified at app-level
-        for name, w_hook in newhooks.items():
-            w_name = space.wrap(name)
-            try:
-                w_current = space.getitem(w_builtins, w_name)
-            except OperationError:
-                pass
-            else:
-                if space.is_true(space.is_(w_current, w_hook)):
-                    if name in self.__saved_hooks:
-                        space.setitem(w_builtins, w_name,
-                                      self.__saved_hooks[name])
-                    else:
-                        space.delitem(w_builtins, w_name)
-        del self.__saved_hooks
-
-    def interplevelexec(self, w_codestring):
-        "NOT_RPYTHON: 'exec' a string at interp-level."
-        codestring = self.space.str_w(w_codestring)
-        exec codestring in self.__dict__
-        return self.space.w_None
-
-    def interpleveleval(self, w_codestring):
-        """NOT_RPYTHON: 'eval' a string at interp-level.  The result must
-        be None or a wrapped object, which is returned to the caller."""
-        space = self.space
-        codestring = space.str_w(w_codestring)
-        w_result = eval(codestring, self.__dict__)
-        if w_result is None:
-            w_result = space.w_None   # else assume that it is already wrapped
-        return w_result
-
-    def interplevelexecfile(self, w_filename):
-        """NOT_RPYTON: 'exec' a file at interp-level.  The file should be in
-        the same directory as the xxxmodule.py source file of the module."""
-        filename = self.space.str_w(w_filename)
-        filename = os.path.join(os.path.dirname(self.__file__), filename)
-        execfile(filename, self.__dict__)
-        return self.space.w_None
-
-    def interplevelimport(self, w_modulename, w_globals, w_locals, w_fromlist):
-        """NOT_RPYTHON: Hook for 'from __interplevel__ import something'.
-        If there is a wrapped interp-level object 'w_something', returns it.
-        If there is an interp-level function 'def something(w_x, w_y...)',
-        build an appropriate gateway and returns it.
-        """
-        space = self.space
-        w = space.wrap
-        if space.is_true(space.eq(w_modulename, w('__interplevel__'))):
-            if w_fromlist == space.w_None:
-                raise ImportError, "must use 'from __interplevel__ import xx'"
-            for w_name in space.unpacktuple(w_fromlist):
-                name = space.str_w(w_name)
-                if not hasattr(self, 'w_' + name):
-                    f = getattr(self, name)
-                    func = interplevelimport_interp2app(f, self.w_dict)
-                    w_result = space.wrap(func)
-                else:
-                    w_result = getattr(self, 'w_' + name)
-                space.setitem(self.w_dict, w_name, w_result)
-            return space.wrap(self)
-        else:
-            return space.call_function(self.__saved_hooks['__import__'],
-                                       w_modulename, w_globals,
-                                       w_locals, w_fromlist)
-
-class AppModuleHack:
-    """NOT_RPYTHON
-    For interp-level convenience: 'from __applevel__ import func'
-    imports the app-level function 'func' via an appropriate gateway.
-    """
-    def __init__(self, builtinmodule):
-        self.space = builtinmodule.space
-        self.w_dict = builtinmodule.w_dict
-    def __getattr__(self, name):
-        if name.startswith('__'):
-            raise AttributeError, name
-        w_func = self.space.getitem(self.w_dict, self.space.wrap(name))
-        def caller(*args):
-            return self.space.call_function(w_func, *args)
-        return caller

Modified: pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py
==============================================================================
--- pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py	(original)
+++ pypy/branch/dist-interpapp/pypy/interpreter/test/mixedmodule/__init__.py	Fri Feb 18 11:45:25 2005
@@ -1,6 +1,6 @@
-from pypy.interpreter.newmodule import ExtModule 
+from pypy.interpreter.lazymodule import LazyModule 
 
-class Module(ExtModule): 
+class Module(LazyModule): 
     interpleveldefs = {
         '__name__' : '(space.wrap("mixedmodule"))',
         '__doc__'  : '(space.wrap("mixedmodule doc"))',

Deleted: /pypy/branch/dist-interpapp/pypy/module/__builtin__interp.py
==============================================================================
--- /pypy/branch/dist-interpapp/pypy/module/__builtin__interp.py	Fri Feb 18 11:45:25 2005
+++ (empty file)
@@ -1,326 +0,0 @@
-"""
-Implementation of interpreter-level builtins.
-"""
-from pypy.interpreter.module import Module
-from pypy.interpreter.pycode import PyCode
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.baseobjspace import BaseWrappable, W_Root
-from pypy.interpreter.gateway import NoneNotWrapped
-
-import __builtin__ as cpy_builtin
-
-# import useful app-level functions
-from __applevel__ import execfile, callable, _iter_generator
-
-
-def _actframe(position=0):
-    return space.getexecutioncontext().framestack.top(position)
-
-def globals():
-    return _actframe().w_globals
-
-def locals():
-    return _actframe().getdictscope()
-
-def _caller_globals(position=1):
-    return _actframe(position).w_globals
-#
-_caller_globals.unwrap_spec = [int]
-
-def _caller_locals(position=1):
-    return _actframe(position).getdictscope()
-#
-_caller_locals.unwrap_spec = [int]
-
-
-def try_import_mod(w_modulename, f, w_parent, w_name, pkgdir=None):
-    import os
-    w = space.wrap
-    if os.path.exists(f):
-        w_mod = space.wrap(Module(space, w_modulename))
-        space.sys.setmodule(w_mod)
-        space.setattr(w_mod, w('__file__'), w(f))
-        if pkgdir is not None:
-            space.setattr(w_mod, w('__path__'), space.newlist([w(pkgdir)]))
-        w_dict = space.getattr(w_mod, w('__dict__'))
-        execfile(w(f), w_dict, w_dict)
-        w_mod = check_sys_modules(w_modulename)
-        if w_mod is not None and w_parent is not None:
-            space.setattr(w_parent, w_name, w_mod)
-        return w_mod
-    else:
-        return None
-
-def try_getattr(w_obj,w_name):
-    try:
-        return space.getattr(w_obj, w_name)
-    except OperationError, e:
-        # ugh, but blame CPython :-/ this is supposed to emulate
-        # hasattr, which eats all exceptions.
-        return None
-
-def try_getitem(w_obj,w_key):
-    try:
-        return space.getitem(w_obj, w_key)
-    except OperationError, e:
-        if not e.match(space, space.w_KeyError):
-            raise
-        return None
-
-
-def check_sys_modules(w_modulename):
-    try:
-        w_mod = space.getitem(space.sys.w_modules, w_modulename)
-    except OperationError, e:
-        pass
-    else:
-        return w_mod
-    if not e.match(space, space.w_KeyError):
-        raise
-    return None
-
-il_len = len
-
-def __import__(modulename, w_globals=None,
-               w_locals=None, w_fromlist=None):
-    if not isinstance(modulename, str):
-        try:
-            helper = ', not ' + modulename.__class__.__name__
-        except AttributeError:
-            helper = ''
-        raise OperationError(space.w_TypeError,
-              space.wrap("__import__() argument 1 must be string" + helper))
-    w = space.wrap
-
-    if w_globals is not None and not space.is_true(space.is_(w_globals, space.w_None)):
-        ctxt_w_name = try_getitem(w_globals,w('__name__'))
-        ctxt_w_path = try_getitem(w_globals,w('__path__'))
-    else:
-        ctxt_w_name = None
-        ctxt_w_path = None
-
-    rel_modulename = None
-    if ctxt_w_name is not None:
-
-        ctxt_name_prefix_parts = space.str_w(ctxt_w_name).split('.')
-        if ctxt_w_path is None: # context is a plain module
-            ctxt_name_prefix_parts = ctxt_name_prefix_parts[:-1]
-            if ctxt_name_prefix_parts:
-                rel_modulename = '.'.join(ctxt_name_prefix_parts+[modulename])
-        else: # context is a package module
-            rel_modulename = space.str_w(ctxt_w_name)+'.'+modulename
-        if rel_modulename is not None:
-            w_mod = check_sys_modules(w(rel_modulename))
-            if (w_mod is None or
-                not space.is_true(space.is_(w_mod,space.w_None))):
-                
-                w_mod = absolute_import(rel_modulename,
-                                        il_len(ctxt_name_prefix_parts),
-                                        w_fromlist, tentative=1)
-                if w_mod is not None:
-                    return w_mod
-            else:
-                rel_modulename = None
-
-    w_mod = absolute_import(modulename,0,w_fromlist, tentative=0)
-    if rel_modulename is not None:
-        space.setitem(space.sys.w_modules, w(rel_modulename),space.w_None)
-    return w_mod
-#
-__import__.unwrap_spec = [str,W_Root,W_Root,W_Root]
-
-def absolute_import(modulename, baselevel, w_fromlist, tentative):
-    w = space.wrap
-    
-    w_mod = None
-    parts = modulename.split('.')
-    prefix = []
-    # it would be nice if we could do here: w_path = space.sys.w_path
-    # instead:
-    w_path = space.getitem(space.sys.w_dict, space.wrap('path'))
-
-    first = None
-    level = 0
-
-    for part in parts:
-        w_mod = load_part(w_path, prefix, part, w_mod, tentative=tentative)
-        if w_mod is None:
-            return None
-
-        if baselevel == level:
-            first = w_mod
-            tentative = 0
-        prefix.append(part)
-        w_path = try_getattr(w_mod,w('__path__'))
-        level += 1
-
-    if w_fromlist is not None and space.is_true(w_fromlist):
-        if w_path is not None:
-            for w_name in space.unpackiterable(w_fromlist):
-                load_part(w_path, prefix, space.str_w(w_name), w_mod,
-                          tentative=1)
-        return w_mod
-    else:
-        return first
-
-def load_part(w_path, prefix, partname, w_parent, tentative):
-    w = space.wrap
-    modulename = '.'.join(prefix+[partname])
-    w_modulename = w(modulename)
-    w_mod = check_sys_modules(w_modulename)
-    if w_mod is not None:
-        if not space.is_true(space.is_(w_mod,space.w_None)):
-            return w_mod
-    else:
-        w_mod = space.get_builtin_module(modulename)
-        if w_mod is not None:
-            return w_mod
-        import os
-        for path in space.unpackiterable(w_path):
-            dir = os.path.join(space.str_w(path), partname)
-            if os.path.isdir(dir):
-                f = os.path.join(dir,'__init__.py')
-                w_mod = try_import_mod(w_modulename, f, w_parent, w(partname),
-                                       pkgdir=dir)
-                if w_mod is not None:
-                    return w_mod
-            f = os.path.join(space.str_w(path), partname + '.py')
-            w_mod = try_import_mod(w_modulename, f, w_parent, w(partname))
-            if w_mod is not None:
-                return w_mod
-
-    if tentative:
-        return None
-    else:
-        # ImportError
-        w_failing = w_modulename
-        w_exc = space.call_function(space.w_ImportError, w_failing)
-        raise OperationError(space.w_ImportError, w_exc)
-
-def compile(str_, filename, startstr,
-            supplied_flags=0, dont_inherit=0):
-    #print (str_, filename, startstr, supplied_flags, dont_inherit)
-    # XXX we additionally allow GENERATORS because compiling some builtins
-    #     requires it. doesn't feel quite right to do that here.
-    supplied_flags |= 4096 
-    if not dont_inherit:
-        try:
-            frame = _actframe()
-        except IndexError:
-            pass
-        else:
-            supplied_flags |= frame.get_compile_flags()
-    try:
-        c = cpy_builtin.compile(str_, filename, startstr, supplied_flags, 1)
-    # It would be nice to propagate all exceptions to app level,
-    # but here we only propagate the 'usual' ones, until we figure
-    # out how to do it generically.
-    except SyntaxError,e:
-        raise OperationError(space.w_SyntaxError,space.wrap(str(e)))
-    except ValueError,e:
-        raise OperationError(space.w_ValueError,space.wrap(str(e)))
-    except TypeError,e:
-        raise OperationError(space.w_TypeError,space.wrap(str(e)))
-    return space.wrap(PyCode(space)._from_code(c))
-#
-compile.unwrap_spec = [str,str,str,int,int]
-
-
-def eval(w_source, w_globals=NoneNotWrapped, w_locals=NoneNotWrapped):
-    w = space.wrap
-
-    if space.is_true(space.isinstance(w_source, space.w_str)):
-        w_codeobj = compile(space.str_w(w_source).lstrip(' \t'), "<string>", "eval")
-    elif isinstance(space.interpclass_w(w_source), PyCode):
-        w_codeobj = w_source
-    else:
-        raise OperationError(space.w_TypeError,
-              w('eval() arg 1 must be a string or code object'))
-
-    if w_globals is None:
-        w_globals = globals()
-        w_locals = locals()
-    elif w_locals is None:
-        w_locals = w_globals
-
-    return space.interpclass_w(w_codeobj).exec_code(space, w_globals, w_locals)
-
-def abs(w_val):
-    "abs(number) -> number\n\nReturn the absolute value of the argument."
-    return space.abs(w_val)
-
-def chr(w_ascii):
-    w_character = space.newstring([w_ascii])
-    return w_character
-
-def len(w_obj):
-    return space.len(w_obj)
-
-def delattr(w_object, w_name):
-    space.delattr(w_object, w_name)
-    return space.w_None
-
-def getattr(w_object, w_name, w_defvalue=NoneNotWrapped):
-    try:
-        return space.getattr(w_object, w_name)
-    except OperationError, e:
-        if e.match(space, space.w_AttributeError):
-            if w_defvalue is not None:
-                return w_defvalue
-        raise
-
-def hash(w_object):
-    return space.hash(w_object)
-
-def oct(w_val):
-    # XXX does this need to be a space operation?
-    return space.oct(w_val)
-
-def hex(w_val):
-    return space.hex(w_val)
-
-def round(w_val, w_n=0):
-    return space.round(w_val, w_n)
-
-def id(w_object):
-    return space.id(w_object)
-
-def cmp(w_x, w_y):
-    """return 0 when x == y, -1 when x < y and 1 when x > y """
-    return space.cmp(w_x, w_y)
-
-def coerce(w_x, w_y):
-    """coerce(x, y) -> (x1, y1)
-
-    Return a tuple consisting of the two numeric arguments converted to
-    a common type, using the same rules as used by arithmetic operations.
-    If coercion is not possible, raise TypeError."""
-    return space.coerce(w_x, w_y)
-
-
-#XXX works only for new-style classes.
-#So we have to fix it, when we add support for old-style classes
-def _issubtype(w_cls1, w_cls2):
-    return space.issubtype(w_cls1, w_cls2)
-
-def iter(w_collection_or_callable, w_sentinel=NoneNotWrapped):
-    if w_sentinel is None:
-        return space.iter(w_collection_or_callable)
-    else:
-        if not space.is_true(callable(w_collection_or_callable)):
-            raise OperationError(space.w_TypeError,
-                    space.wrap('iter(v, w): w must be callable'))
-        return _iter_generator(w_collection_or_callable, w_sentinel)
-
-def ord(w_val):
-    return space.ord(w_val)
-
-def pow(w_base, w_exponent, w_modulus=None):
-    return space.pow(w_base, w_exponent, w_modulus)
-
-def repr(w_object):
-    return space.repr(w_object)
-
-def setattr(w_object, w_name, w_val):
-    space.setattr(w_object, w_name, w_val)
-    return space.w_None

Deleted: /pypy/branch/dist-interpapp/pypy/module/__builtin__module.py
==============================================================================
--- /pypy/branch/dist-interpapp/pypy/module/__builtin__module.py	Fri Feb 18 11:45:25 2005
+++ (empty file)
@@ -1,1049 +0,0 @@
-"""Built-in functions, exceptions, and other objects.
-
-Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.
-"""
-
-__builtins__['None']       = __interplevel__eval('space.w_None')
-__builtins__['False']      = __interplevel__eval('space.w_False')
-__builtins__['True']       = __interplevel__eval('space.w_True')
-__builtins__['type']       = __interplevel__eval('space.w_type')
-__builtins__['__debug__']  = True
-
-object = __interplevel__eval('space.w_object')
-# XXX these are faked:
-unicode = __interplevel__eval('space.wrap(unicode)')
-file = __interplevel__eval('space.wrap(file)')
-open = file
-
-# old-style classes dummy support
-__builtins__['_classobj'] = __interplevel__eval('space.w_classobj')
-__builtins__['_instance'] = __interplevel__eval('space.w_instance')
-
-
-# TODO Fix this later to show Ctrl-D on Unix
-quit = exit = "Use Ctrl-Z (i.e. EOF) to exit."
-
-def execfile(filename, glob=None, loc=None):
-    if glob is None:
-        glob = _caller_globals()
-        if loc is None:
-            loc = _caller_locals()
-    elif loc is None:
-        loc = glob
-    f = file(filename)
-    try:
-        source = f.read()
-    finally:
-        f.close()
-    #Don't exec the source directly, as this loses the filename info
-    co = compile(source, filename, 'exec')
-    exec co in glob, loc
-
-def raw_input(prompt=None):
-    import sys
-    try:
-        sys.stdin
-    except AttributeError:
-        raise RuntimeError("[raw_]input: lost sys.stdin");
-    try:
-        sys.stdout
-    except AttributeError:
-        raise RuntimeError("[raw_]input: lost sys.stdout");
-    if prompt is not None:
-        sys.stdout.write(prompt)
-        try:
-            flush = sys.stdout.flush
-        except AttributeError:
-            pass
-        else:
-            flush()
-    line = sys.stdin.readline()
-    if not line:    # inputting an empty line gives line == '\n'
-        raise EOFError
-    if line[-1] == '\n':
-        return line[:-1]
-    return line
-
-def input(prompt=None):
-    return eval(raw_input(prompt))
-
-
-def sum(sequence, total=0):
-    # must forbid "summing" strings, per specs of built-in 'sum'
-    if isinstance(total, str): raise TypeError
-    for item in sequence:
-        total = total + item
-    return total
-
-def _iter_generator(callable_, sentinel):
-    """ This generator implements the __iter__(callable,sentinel) protocol """
-    while 1:
-        result = callable_()
-        if result == sentinel:
-            return
-        yield result
-
-
-def apply(function, args, kwds={}):
-    """call a function (or other callable object) and return its result"""
-    return function(*args, **kwds)
-
-def map(function, *collections):
-    """does 3 separate things, hence this enormous docstring.
-       1.  if function is None, return a list of tuples, each with one
-           item from each collection.  If the collections have different
-           lengths,  shorter ones are padded with None.
-
-       2.  if function is not None, and there is only one collection,
-           apply function to every item in the collection and return a
-           list of the results.
-
-       3.  if function is not None, and there are several collections,
-           repeatedly call the function with one argument from each
-           collection.  If the collections have different lengths,
-           shorter ones are padded with None
-    """
-
-    if len(collections) == 0:
-        raise TypeError, "map() requires at least one sequence"
-
-    if len(collections) == 1:
-        #it's the most common case, so make it faster
-        if function is None:
-            return list(collections[0])
-        return [function(x) for x in collections[0]]
-
-    iterators = [ iter(collection) for collection in collections ]
-    res = []
-    while 1:
-        cont = False     #is any collection not empty?
-        args = []
-        for iterator in iterators:
-            try:
-                elem = iterator.next()
-                cont = True
-            except StopIteration:
-                elem = None
-            args.append(elem)
-        if cont:
-            if function is None:
-                res.append(tuple(args))
-            else:
-                res.append(function(*args))
-        else:
-            return res
-
-def filter(function, collection):
-    """construct a list of those elements of collection for which function
-       is True.  If function is None, then return the items in the sequence
-       which are True."""
-    str_type = None
-    if isinstance(collection, str):
-        str_type = str
-    elif isinstance(collection, unicode):
-        str_type = unicode
-
-    if str_type is not None:
-        if function is None and type(collection) is str_type:
-            return collection
-        res = []
-        for i in xrange(len(collection)):
-            c = collection[i]
-            if function is None or function(c):
-                if not isinstance(c, str_type):
-                    raise TypeError("can't filter %s to %s: __getitem__ returned different type", str_type.__name__, str_type.__name__)
-                res.append(c)
-        return str_type().join(res)
-        
-    if function is None:
-        res = [item for item in collection if item]
-    else:
-        res = [item for item in collection if function(item)]
-
-    if isinstance(collection, tuple):
-       return tuple(res)
-    else:
-       return res
-
-def zip(*collections):
-    """return a list of tuples, where the nth tuple contains every
-       nth item of each collection.  If the collections have different
-       lengths, zip returns a list as long as the shortest collection,
-       ignoring the trailing items in the other collections."""
-
-    if len(collections) == 0:
-        import sys
-        if sys.version_info < (2,4):
-            raise TypeError("zip() requires at least one sequence")
-        return []
-    res = []
-    iterators = [ iter(collection) for collection in collections ]
-    while 1:
-        try:
-            elems = []
-            for iterator in iterators:
-                elems.append(iterator.next())
-            res.append(tuple(elems))
-        except StopIteration:
-            return res
-
-def reduce(function, seq, *initialt):
-    """ Apply function of two arguments cumulatively to the items of
-        sequence, from left to right, so as to reduce the sequence to a
-        single value.  Optionally begin with an initial value."""
-
-    seqiter = iter(seq)
-    if initialt:
-       initial, = initialt
-    else:
-       try:
-          initial = seqiter.next()
-       except StopIteration:
-          raise TypeError, "reduce() of empty sequence with no initial value"
-    while 1:
-        try:
-            arg = seqiter.next()
-        except StopIteration:
-            break
-        initial = function(initial, arg)
-
-    return initial
-
-def _recursive_issubclass(cls, klass_or_tuple):
-    if cls is klass_or_tuple:
-        return True
-    for base in cls.__bases__:
-        if _recursive_issubclass(base, klass_or_tuple):
-            return True
-    return False
-
-def issubclass(cls, klass_or_tuple):
-    if _issubtype(type(klass_or_tuple), tuple):
-        for klass in klass_or_tuple:
-            if issubclass(cls, klass):
-                return True
-        return False
-    try:
-        return _issubtype(cls, klass_or_tuple)
-    except TypeError:
-        if not hasattr(cls, '__bases__'):
-            raise TypeError, "arg 1 must be a class or type"
-        if not hasattr(klass_or_tuple, '__bases__'):
-            raise TypeError, "arg 2 must be a class or type or a tuple thereof"
-        return _recursive_issubclass(cls, klass_or_tuple)
-        
-
-def isinstance(obj, klass_or_tuple):
-    if issubclass(type(obj), klass_or_tuple):
-        return True
-    try:
-        objcls = obj.__class__
-    except AttributeError:
-        return False
-    else:
-        return objcls is not type(obj) and issubclass(objcls, klass_or_tuple)
-
-def range(x, y=None, step=1):
-    """ returns a list of integers in arithmetic position from start (defaults
-        to zero) to stop - 1 by step (defaults to 1).  Use a negative step to
-        get a list in decending order."""
-
-
-    if y is None: 
-            start = 0
-            stop = x
-    else:
-            start = x
-            stop = y
-
-    if not isinstance(start, (int, long)):
-        raise TypeError('range() interger start argument expected, got %s' % type(start))
-    if not isinstance(stop, (int, long)):
-        raise TypeError('range() interger stop argument expected, got %s' % type(stop))
-    if not isinstance(step, (int, long)):
-        raise TypeError('range() interger step argument expected, got %s' % type(step))
-
-    if step == 0:
-        raise ValueError, 'range() arg 3 must not be zero'
-
-    elif step > 0:
-        if stop <= start: # no work for us
-            return []
-        howmany = (stop - start + step - 1)/step
-
-    else:  # step must be < 0, or we would have raised ValueError
-        if stop >= start: # no work for us
-            return []
-        howmany = (start - stop - step  - 1)/-step
-
-    arr = [None] * howmany  # this is to avoid using append.
-
-    i = start
-    n = 0
-    while n < howmany:
-        arr[n] = i
-        i += step
-        n += 1
-
-    return arr
-
-# min and max could be one function if we had operator.__gt__ and
-# operator.__lt__  Perhaps later when we have operator.
-
-def min(*arr):
-    """return the smallest number in a list"""
-
-    if not arr:
-        raise TypeError, 'min() takes at least one argument'
-
-    if len(arr) == 1:
-        arr = arr[0]
-
-    iterator = iter(arr)
-    try:
-        min = iterator.next()
-    except StopIteration:
-        raise ValueError, 'min() arg is an empty sequence'
-
-    for i in iterator:
-        if min > i:
-            min = i
-    return min
-
-def max(*arr):
-    """return the largest number in a list"""
-
-    if not arr:
-        raise TypeError, 'max() takes at least one argument'
-
-    if len(arr) == 1:
-        arr = arr[0]
-
-    iterator = iter(arr)
-    try:
-        max = iterator.next()
-    except StopIteration:
-        raise ValueError, 'max() arg is an empty sequence'
-
-    for i in iterator:
-        if max < i:
-            max = i
-    return max
-
-def divmod(x, y):
-    return x//y, x%y
-
-def vars(*obj):
-    """return a dictionary of all the attributes currently bound in obj.  If
-    called with no argument, return the variables bound in local scope."""
-
-    if len(obj) == 0:
-        return _caller_locals()
-    elif len(obj) != 1:
-        raise TypeError, "vars() takes at most 1 argument."
-    else:
-        try:
-            return obj[0].__dict__
-        except AttributeError:
-            raise TypeError, "vars() argument must have __dict__ attribute"
-
-def hasattr(ob, attr):
-    try:
-        getattr(ob, attr)
-        return True
-    except AttributeError:
-        return False
-
-def callable(ob):
-    for c in type(ob).__mro__:
-        if '__call__' in c.__dict__:
-            return True
-    else:
-        return False
-
-def dir(*args):
-    """dir([object]) -> list of strings
-
-    Return an alphabetized list of names comprising (some of) the attributes
-    of the given object, and of attributes reachable from it:
-
-    No argument:  the names in the current scope.
-    Module object:  the module attributes.
-    Type or class object:  its attributes, and recursively the attributes of
-        its bases.
-    Otherwise:  its attributes, its class's attributes, and recursively the
-        attributes of its class's base classes.
-    """
-    if len(args) > 1:
-        raise TypeError("dir expected at most 1 arguments, got %d"
-                        % len(args))
-    if len(args) == 0:
-        local_names = _caller_locals().keys() # 2 stackframes away
-        local_names.sort()
-        return local_names
-
-    import types
-    def _classdir(klass):
-        """Return a dict of the accessible attributes of class/type klass.
-
-        This includes all attributes of klass and all of the
-        base classes recursively.
-
-        The values of this dict have no meaning - only the keys have
-        meaning.  
-        """
-        Dict = {}
-        try:
-            Dict.update(klass.__dict__)
-        except AttributeError: pass 
-        try:
-            # XXX - Use of .__mro__ would be suggested, if the existance
-            #   of that attribute could be guarranted.
-            bases = klass.__bases__
-        except AttributeError: pass
-        else:
-            try:
-                #Note that since we are only interested in the keys,
-                #  the order we merge classes is unimportant
-                for base in bases:
-                    Dict.update(_classdir(base))
-            except TypeError: pass
-        return Dict
-    #End _classdir
-
-    obj = args[0]
-
-    if isinstance(obj, types.ModuleType):
-        try:
-            result = obj.__dict__.keys()
-            result.sort()
-            return result
-        except AttributeError:
-            return []
-
-    elif isinstance(obj, (types.TypeType, types.ClassType)):
-        #Don't look at __class__, as metaclass methods would be confusing.
-        result = _classdir(obj).keys()
-        result.sort()
-        return result
-
-    else: #(regular item)
-        Dict = {}
-        try:
-            Dict.update(obj.__dict__)
-        except AttributeError: pass
-        try:
-            Dict.update(_classdir(obj.__class__))
-        except AttributeError: pass
-
-        ## Comment from object.c:
-        ## /* Merge in __members__ and __methods__ (if any).
-        ## XXX Would like this to go away someday; for now, it's
-        ## XXX needed to get at im_self etc of method objects. */
-        for attr in ['__members__','__methods__']:
-            try:
-                for item in getattr(obj, attr):
-                    if isinstance(item, types.StringTypes):
-                        Dict[item] = None
-            except (AttributeError, TypeError): pass
-
-        result = Dict.keys()
-        result.sort()
-        return result
-
-_stringtable = {}
-def intern(s):
-    # XXX CPython has also non-immortal interned strings
-    if not isinstance(s, str):
-        raise TypeError("intern() argument 1 must be string.")
-    return _stringtable.setdefault(s,s)
-
-def copyright():
-    print 'Copyright 2003-2004 Pypy development team.\nAll rights reserved.\nFor further information see http://www.codespaek.net/pypy.\nSome materials may have a different copyright.\nIn these cases, this is explicitly noted in the source code file.'
-
-def license():
-    print \
-"""
-Copyright (c) <2003-2004> <Pypy development team>
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-"""
-
-def help():
-    print "You must be joking."
-
-def unichr(code):
-    import sys
-    if (code < 0 or code > sys.maxunicode):
-        raise ValueError('unichr() arg not in range(%#x)'%(sys.maxunicode + 1))
-    return unicode('\\U%08x' %(code), 'unicode-escape')
-# ______________________________________________________________________
-#
-#   Interpreter-level function definitions
-#
-
-__interplevel__execfile('__builtin__interp.py')
-
-from __interplevel__ import abs, chr, len, ord, pow, repr
-from __interplevel__ import hash, oct, hex, round, cmp, coerce
-from __interplevel__ import getattr, setattr, delattr, iter, hash, id
-from __interplevel__ import _issubtype
-from __interplevel__ import compile, eval
-from __interplevel__ import globals, locals, _caller_globals, _caller_locals
-
-# The following must be the last import from __interplevel__ because it
-# overwrites the special __import__ hook with the normal one.
-
-from __interplevel__ import __import__
-
-
-# ________________________________________________________________________
-def enumerate(collection):
-    'Generates an indexed series:  (0,coll[0]), (1,coll[1]) ...'
-    it = iter(collection)   # raises a TypeError early
-    def do_enumerate(it):
-        index = 0
-        for value in it:
-            yield index, value
-            index += 1
-    return do_enumerate(it)
-
-class xrange(object):
-    def __init__(self, start, stop=None, step=1):
-        if not isinstance(start, (int, long, float)):
-            raise TypeError('an integer is required')
-        start = int(start)
-        if stop is None:
-            self.start = 0
-            self.stop = start
-        else:
-            if not isinstance(stop, (int, long, float)):
-                raise TypeError('an integer is required')
-            stop = int(stop)
-            self.start = start
-            self.stop = stop
-        if not isinstance(step, (int, long, float)):
-            raise TypeError('an integer is required')
-        step = int(step)
-        if step == 0:
-            raise ValueError, 'xrange() step-argument (arg 3) must not be zero'
-        self.step = step
-
-    def __len__(self):
-        if not hasattr(self, '_len'):
-            slicelength = self.stop - self.start
-            lengthsign = cmp(slicelength, 0)
-            stepsign = cmp(self.step, 0)
-            if stepsign == lengthsign:
-                self._len = (slicelength - lengthsign) // self.step + 1
-            else:
-                self._len = 0
-        return self._len
-
-    def __getitem__(self, index):
-        # xrange does NOT support slicing
-        if not isinstance(index, int):
-            raise TypeError, "sequence index must be integer"
-        len = self.__len__()
-        if index<0:
-            index += len
-        if 0 <= index < len:
-            return self.start + index * self.step
-        raise IndexError, "xrange object index out of range"
-
-    def __iter__(self):
-        start, stop, step = self.start, self.stop, self.step
-        i = start
-        if step > 0:
-            while i < stop:
-                yield i
-                i+=step
-        else:
-            while i > stop:
-                yield i
-                i+=step
-
-
-# Descriptor code, shamelessly stolen to Raymond Hettinger:
-#    http://users.rcn.com/python/download/Descriptor.htm
-class property(object):
-
-    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
-        self.fget = fget
-        self.fset = fset
-        self.fdel = fdel
-        self.__doc__ = doc or ""   # XXX why:  or ""  ?
-
-    def __get__(self, obj, objtype=None):
-        if obj is None:
-            return self         
-        if self.fget is None:
-            raise AttributeError, "unreadable attribute"
-        return self.fget(obj)
-
-    def __set__(self, obj, value):
-        if self.fset is None:
-            raise AttributeError, "can't set attribute"
-        self.fset(obj, value)
-
-    def __delete__(self, obj):
-        if self.fdel is None:
-            raise AttributeError, "can't delete attribute"
-        self.fdel(obj)
-
-
-# XXX there is an interp-level pypy.interpreter.function.StaticMethod
-# XXX because __new__ needs to be a StaticMethod early.
-class staticmethod(object):
-
-    def __init__(self, f):
-        self.f = f
-
-    def __get__(self, obj, objtype=None):
-        return self.f
-
-
-class classmethod(object):
-
-    def __init__(self, f):
-        self.f = f
-
-    def __get__(self, obj, klass=None):
-        if klass is None:
-            klass = type(obj)
-        def newfunc(*args, **kwargs):
-            return self.f(klass, *args, **kwargs)
-        return newfunc
-
-if not hasattr(dict, 'fromkeys'):
-    def _fromkeys(cls, seq, value=None):
-        r = cls()
-        for s in seq:
-            r[s] = value
-        return r
-
-    try:
-        dict.fromkeys = classmethod(_fromkeys)
-    except TypeError:
-        pass   # Python2.2 with trivial object space
-
-    del _fromkeys
-
-
-# super is a modified version from Guido's tutorial
-#     http://www.python.org/2.2.3/descrintro.html
-# it exposes the same special attributes as CPython's.
-class super(object):
-    def __init__(self, typ, obj=None):
-        if obj is None:
-            objcls = None        # unbound super object
-        elif _issubtype(type(obj), type) and _issubtype(obj, type):
-            objcls = obj         # special case for class methods
-        elif _issubtype(type(obj), typ):
-            objcls = type(obj)   # normal case
-        else:
-            objcls = getattr(obj, '__class__', type(obj))
-            if not _issubtype(objcls, typ):
-                raise TypeError, ("super(type, obj): "
-                                  "obj must be an instance or subtype of type")
-        self.__thisclass__ = typ
-        self.__self__ = obj
-        self.__self_class__ = objcls
-    def __get__(self, obj, type=None):
-        ga = object.__getattribute__
-        if ga(self, '__self__') is None and obj is not None:
-            return super(ga(self, '__thisclass__'), obj)
-        else:
-            return self
-    def __getattribute__(self, attr):
-        d = object.__getattribute__(self, '__dict__')
-        if attr != '__class__' and d['__self_class__'] is not None:
-            # we want super().__class__ to be the real class
-            # and we don't do anything for unbound type objects
-            mro = iter(d['__self_class__'].__mro__)
-            for cls in mro:
-                if cls is d['__thisclass__']:
-                    break
-            # Note: mro is an iterator, so the second loop
-            # picks up where the first one left off!
-            for cls in mro:
-                try:                
-                    x = cls.__dict__[attr]
-                except KeyError:
-                    continue
-                if hasattr(x, '__get__'):
-                    x = x.__get__(d['__self__'], type(d['__self__']))
-                return x
-        return object.__getattribute__(self, attr)     # fall-back
-    
-class complex(object):
-    """complex(real[, imag]) -> complex number
-
-    Create a complex number from a real part and an optional imaginary part.
-    This is equivalent to (real + imag*1j) where imag defaults to 0."""
-    PREC_REPR = 17
-    PREC_STR = 12
-
-    # XXX this class is not well tested
-
-    def __init__(self, real=0.0, imag=None):
-        if isinstance(real, str) and imag is not None:
-            msg = "complex() can't take second arg if first is a string"
-            raise TypeError, msg
-
-        if isinstance(imag, str): 
-            msg = "complex() second arg can't be a string"
-            raise TypeError, msg
-
-        if isinstance(real, str): 
-            real, imag = self._makeComplexFromString(real)
-            self.__dict__['real'] = real
-            self.__dict__['imag'] = imag
-        else:
-            if imag is None:
-               imag = 0.
-            self.__dict__['real'] = float(real)
-            self.__dict__['imag'] = float(imag)
-        
-
-    def __setattr__(self, name, value):
-        if name in ('real', 'imag'):
-            raise AttributeError, "readonly attribute"
-        else:
-            raise AttributeError, "'complex' object has no attribute %s" % name
-
-    def _makeComplexFromString(self, string):
-        import re
-        pat = re.compile(" *([\+\-]?\d*\.?\d*)([\+\-]?\d*\.?\d*)[jJ] *")
-        m = pat.match(string)
-        x, y = m.groups()
-        if len(y) == 1 and y in '+-':
-            y = y + '1.0'
-        x, y = map(float, [x, y])
-        return x, y
-
-
-    def __description(self, precision):
-        if self.real != 0.:
-            return "(%.*g%+.*gj)"%(precision, self.real, precision, self.imag)
-        else:
-            return "%.*gj"%(precision, self.imag)
-
-
-    def __repr__(self):
-        return self.__description(self.PREC_REPR)
-
-
-    def __str__(self):
-        return self.__description(self.PREC_STR)
-
-        
-    def __hash__(self):
-        hashreal = hash(self.real)
-        hashimag = hash(self.imag)
-
-        # Note:  if the imaginary part is 0, hashimag is 0 now,
-        # so the following returns hashreal unchanged.  This is
-        # important because numbers of different types that
-        # compare equal must have the same hash value, so that
-        # hash(x + 0*j) must equal hash(x).
-
-        return hashreal + 1000003 * hashimag
-
-
-    def __add__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        real = self.real + other.real
-        imag = self.imag + other.imag
-        return complex(real, imag)
-
-    __radd__ = __add__
-
-    def __sub__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        real = self.real - other.real
-        imag = self.imag - other.imag
-        return complex(real, imag)
-    
-    def __rsub__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__sub__(self)
-
-    def __mul__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        real = self.real*other.real - self.imag*other.imag
-        imag = self.real*other.imag + self.imag*other.real
-        return complex(real, imag)
-
-    __rmul__ = __mul__
-
-    def __div__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        if abs(other.real) >= abs(other.imag):
-            # divide tops and bottom by other.real
-            try:
-                ratio = other.imag / other.real
-            except ZeroDivisionError:
-                raise ZeroDivisionError, "complex division"
-            denom = other.real + other.imag * ratio
-            real = (self.real + self.imag * ratio) / denom
-            imag = (self.imag - self.real * ratio) / denom
-        else:
-            # divide tops and bottom by other.imag
-            assert other.imag != 0.0
-            ratio = other.real / other.imag
-            denom = other.real * ratio + other.imag
-            real = (self.real * ratio + self.imag) / denom
-            imag = (self.imag * ratio - self.real) / denom
-
-        return complex(real, imag)
-
-    def __rdiv__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__div__(self)
-
-    def __floordiv__(self, other):
-        result = self.__divmod__(other)
-        if result is NotImplemented:
-            return result
-        div, mod = result
-        return div
-
-    def __rfloordiv__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__floordiv__(self)
-
-    __truediv__ = __div__
-    __rtruediv__ = __rdiv__
-
-    def __mod__(self, other):
-        result = self.__divmod__(other)
-        if result is NotImplemented:
-            return result
-        div, mod = result
-        return mod
-
-    def __rmod__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__mod__(self)
-
-    def __divmod__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-
-        import warnings, math
-        warnings.warn("complex divmod(), // and % are deprecated", DeprecationWarning)
-
-        try:
-            div = self/other # The raw divisor value.
-        except ZeroDivisionError:
-            raise ZeroDivisionError, "complex remainder"
-        div = complex(math.floor(div.real), 0.0)
-        mod = self - div*other
-        return div, mod
-
-
-    def __pow__(self, other, mod=None):
-        if mod is not None:
-            raise ValueError("complex modulo")
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        a, b = result
-        import math
-
-        if b.real == 0. and b.imag == 0.:
-            real = 1.
-            imag = 0.
-        elif a.real == 0. and a.imag == 0.:
-            real = 0.
-            imag = 0.
-        else:
-            vabs = math.hypot(a.real,a.imag)
-            len = math.pow(vabs,b.real)
-            at = math.atan2(a.imag, a.real)
-            phase = at*b.real
-            if b.imag != 0.0:
-                len /= math.exp(at*b.imag)
-                phase += b.imag*math.log(vabs)
-            real = len*math.cos(phase)
-            imag = len*math.sin(phase)
-
-        result = complex(real, imag)
-        return result
-
-    def __rpow__(self, other, mod=None):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return other.__pow__(self, mod)
-
-    def __neg__(self):
-        return complex(-self.real, -self.imag)
-
-
-    def __pos__(self):
-        return complex(self.real, self.imag)
-
-
-    def __abs__(self):
-        import math
-        result = math.hypot(self.real, self.imag)
-        return float(result)
-
-
-    def __nonzero__(self):
-        return self.real != 0.0 or self.imag != 0.0
-
-
-    def __coerce__(self, other):
-        if isinstance(other, complex):
-            return self, other
-        if isinstance(other, (int, long, float)):
-            return self, complex(other)
-        return NotImplemented
-
-    def conjugate(self):
-        return complex(self.real, -self.imag)
-
-    def __eq__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return self.real == other.real and self.imag == other.imag
-
-    def __ne__(self, other):
-        result = self.__coerce__(other)
-        if result is NotImplemented:
-            return result
-        self, other = result
-        return self.real != other.real or self.imag != other.imag
-
-
-    # unsupported operations
-    
-    def __lt__(self, other):
-        raise TypeError, "cannot compare complex numbers using <, <=, >, >="
-
-        
-    def __le__(self, other):
-        raise TypeError, "cannot compare complex numbers using <, <=, >, >="
-
-        
-    def __gt__(self, other):
-        raise TypeError, "cannot compare complex numbers using <, <=, >, >="
-
-        
-    def __ge__(self, other):
-        raise TypeError, "cannot compare complex numbers using <, <=, >, >="
-
-
-    def __int__(self):
-        raise TypeError, "can't convert complex to int; use e.g. int(abs(z))"
-
-
-    def __long__(self):
-        raise TypeError, "can't convert complex to long; use e.g. long(abs(z))"
-
-
-    def __float__(self):
-        raise TypeError, "can't convert complex to float; use e.g. float(abs(z))"
-
-
-# ________________________________________________________________________
-
-class buffer(object):
-    def __init__(self, object, offset=None, size=None):
-        raise NotImplementedError, "XXX nobody needs this anyway"
-
-def sorted(lst, cmp=None, key=None, reverse=None):
-    "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list"
-    sorted_lst = list(lst)
-    sorted_lst.sort(cmp, key, reverse)
-    return sorted_lst
-
-def reversed(iterable):
-    """reversed(sequence) -> reverse iterator over values of the sequence
-
-    Return a reverse iterator
-    """
-    if hasattr(iterable, '__reversed__'):
-        return iterable.__reversed__()
-    seq = list(iterable)
-    def reversed_gen(local_iterable):
-        len_iterable = len(local_iterable)
-        for index in range(len_iterable-1, -1, -1):
-            yield local_iterable[index]
-    return reversed_gen(seq)
-
-def reload(module):
-    import imp, sys, errno
-
-    if type(module) not in (type(imp), type(errno)):
-        raise TypeError("reload() argument must be module")
-
-    name = module.__name__
-    if module is not sys.modules[name]:
-        raise ImportError("reload(): module %.200s not in sys.modules" % name)
-
-    namepath = name.split('.')
-    subname = namepath[-1]
-    parent_name = '.'.join(namepath[:-1])
-    parent = None
-    path = None
-    if parent_name:
-        try:
-            parent = sys.modules[parent_name]
-        except KeyError:
-            raise ImportError("reload(): parent %.200s not in sys.modules" %
-                              parent_name)
-        path = parent.__path__
-
-    f, filename, description = imp.find_module(subname, path)
-    try:
-        new_module = imp.load_module(name, f, filename, description)
-    finally:
-        sys.modules[name] = module
-        if f is not None:
-            f.close()
-
-    return new_module
-
-#from _file import file
-#open = file
-
-#default __metaclass__
-# XXX can use _classobj when we have a working one integrated
-__metaclass__ = type

Modified: pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py
==============================================================================
--- pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py	(original)
+++ pypy/branch/dist-interpapp/pypy/module/builtin/__init__.py	Fri Feb 18 11:45:25 2005
@@ -1,8 +1,8 @@
 from pypy.interpreter.error import OperationError
 from pypy.interpreter import module
-from pypy.interpreter.newmodule import ExtModule
+from pypy.interpreter.lazymodule import LazyModule 
 
-class Module(ExtModule):
+class Module(LazyModule):
     """Built-in functions, exceptions, and other objects.
 
 Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.

Modified: pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py
==============================================================================
--- pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py	(original)
+++ pypy/branch/dist-interpapp/pypy/module/sys2/__init__.py	Fri Feb 18 11:45:25 2005
@@ -1,7 +1,7 @@
-from pypy.interpreter.newmodule import ExtModule
+from pypy.interpreter.lazymodule import LazyModule 
 from pypy.interpreter.error import OperationError 
 
-class Module(ExtModule):
+class Module(LazyModule):
     """Sys Builtin Module. """
     def __init__(self, space, w_name): 
         super(Module, self).__init__(space, w_name) 
@@ -87,7 +87,7 @@
 
     def getdictvalue(self, space, attr): 
         """ specialize access to dynamic exc_* attributes. """ 
-        value = ExtModule.getdictvalue(self, space, attr) 
+        value = LazyModule.getdictvalue(self, space, attr) 
         if value is not None: 
             return value 
         if attr == 'exc_type':

Deleted: /pypy/branch/dist-interpapp/pypy/module/sysinterp.py
==============================================================================
--- /pypy/branch/dist-interpapp/pypy/module/sysinterp.py	Fri Feb 18 11:45:25 2005
+++ (empty file)
@@ -1,202 +0,0 @@
-"""
-Implementation of interpreter-level 'sys' routines.
-"""
-#from pypy.interpreter.module import Module
-from pypy.interpreter.error import OperationError
-
-import sys as cpy_sys
-
-def hack_cpython_module(modname):
-    "NOT_RPYTHON. Steal a module from CPython."
-    cpy_module = __import__(modname, globals(), locals(), None)
-    return cpy_module
-##    # to build the dictionary of the module, we get all the objects
-##    # accessible as 'self.xxx'. Methods are bound.
-##    contents = []
-##    for name in cpy_module.__dict__:
-##        # ignore names in '_xyz'
-##        if not name.startswith('_') or name.endswith('_'):
-##            value = cpy_module.__dict__[name]
-##            contents.append((space.wrap(name), space.wrap(value)))
-##    w_contents = space.newdict(contents)
-##    return Module(space, space.wrap(modname), w_contents)
-
-# ____________________________________________________________
-#
-# List of built-in modules.
-# It should contain the name of all the files 'module/*module.py'.
-builtin_module_names = ['__builtin__', 'sys', 'exceptions'
-                        ]
-
-# Create the builtin_modules dictionary, mapping names to Module instances
-builtin_modules = {}
-for fn in builtin_module_names:
-    builtin_modules[fn] = None
-
-# The following built-in modules are not written in PyPy, so we
-# steal them from Python.
-for fn in ['posix', 'nt', 'os2', 'mac', 'ce', 'riscos',
-           'math', '_codecs', 'array',
-           '_random', '_sre', 'time', '_socket', 'errno',
-           'marshal', 'binascii', 'parser']:
-    if fn not in builtin_modules:
-        try:
-            builtin_modules[fn] = hack_cpython_module(fn)
-        except ImportError:
-            pass
-        else:
-            builtin_module_names.append(fn)
-
-# ____________________________________________________________
-#
-# Common data structures
-w_modules              = space.newdict([])
-w_warnoptions          = space.newlist([])
-w_argv                 = space.newlist([])
-builtin_module_names.sort()
-w_builtin_module_names = space.newtuple([space.wrap(fn)
-                                         for fn in builtin_module_names])
-
-# Initialize the default path
-import os
-from pypy.interpreter import autopath
-srcdir = os.path.dirname(autopath.pypydir)
-python_std_lib = os.path.normpath(
-        os.path.join(autopath.pypydir, '..','lib-python-2.3.4'))
-pypy_override_lib = os.path.join(autopath.pypydir, 'lib') 
-assert os.path.exists(python_std_lib) 
-del os, autopath # XXX for the translator. Something is very wrong around here.
-
-w_initialpath = space.newlist([space.wrap(''), 
-                       space.wrap(pypy_override_lib), 
-                       space.wrap(python_std_lib), 
-                       ] +
-                       [space.wrap(p) for p in cpy_sys.path if p!= srcdir])
-
-# XXX - Replace with appropriate PyPy version numbering
-w_platform   = space.wrap(cpy_sys.platform)
-w_maxint     = space.wrap(cpy_sys.maxint)
-w_byteorder  = space.wrap(cpy_sys.byteorder)
-w_exec_prefix = space.wrap(cpy_sys.exec_prefix)
-w_prefix = space.wrap(cpy_sys.prefix)
-w_maxunicode = space.wrap(cpy_sys.maxunicode)
-w_stdin  = space.wrap(cpy_sys.stdin)
-w_stdout = space.wrap(cpy_sys.stdout)
-w_stderr = space.wrap(cpy_sys.stderr)
-
-w_pypy_objspaceclass = space.wrap(space.__class__.__name__)
-
-# ____________________________________________________________
-
-def setmodule(w_module):
-    """ put a module into the modules dict """
-    w_name = space.getattr(w_module, space.wrap('__name__'))
-    space.setitem(w_modules, w_name, w_module)
-
-def setbuiltinmodule(w_module, name):
-    """ put a module into the modules builtin_modules dicts """
-    if builtin_modules[name] is None:
-        builtin_modules[name] = space.unwrap(w_module)
-    else:
-        assert builtin_modules[name] is space.unwrap(w_module), (
-            "trying to change the builtin-in module %r" % (name,))
-    space.setitem(w_modules, space.wrap(name), w_module)
-
-##def displayhook(w_x):
-##    w = space.wrap
-##    if not space.is_true(space.is_(w_x, space.w_None)):
-##        w_stdout = space.getattr(space.w_sys, space.wrap('stdout'))
-##        try:
-##            w_repr = space.repr(w_x)
-##        except OperationError:
-##            w_repr = space.wrap("! __repr__ raised an exception")
-##        w_repr = space.add(w_repr, space.wrap("\n"))
-##        space.call_method(w_stdout, 'write', 
-##        space.setitem(space.w_builtins, w('_'), w_x)
-
-def _getframe(w_depth=0):
-    depth = space.int_w(w_depth)
-    try:
-        f = space.getexecutioncontext().framestack.top(depth)
-    except IndexError:
-        raise OperationError(space.w_ValueError,
-                             space.wrap("call stack is not deep enough"))
-    except ValueError:
-        raise OperationError(space.w_ValueError,
-                             space.wrap("frame index must not be negative"))
-    return space.wrap(f)
-
-# directly from the C code in ceval.c, might be moved somewhere else.
-
-def setrecursionlimit(w_new_limit):
-    """setrecursionlimit(n)
-
-Set the maximum depth of the Python interpreter stack to n.  This
-limit prevents infinite recursion from causing an overflow of the C
-stack and crashing Python.  The highest possible limit is platform
-dependent."""
-    new_limit = space.int_w(w_new_limit)
-    if new_limit <= 0:
-        raise OperationError(space.w_ValueError,
-                             space.wrap("recursion limit must be positive"))
-    # global recursion_limit
-    # we need to do it without writing globals.
-    space.recursion_limit = new_limit
-
-def getrecursionlimit():
-    """getrecursionlimit()
-
-Return the current value of the recursion limit, the maximum depth
-of the Python interpreter stack.  This limit prevents infinite
-recursion from causing an overflow of the C stack and crashing Python."""
-
-    return space.newint(space.recursion_limit)
-
-checkinterval = 100
-
-def setcheckinterval(w_interval):
-    """setcheckinterval(n)
-
-Tell the Python interpreter to check for asynchronous events every
-n instructions.  This also affects how often thread switches occur."""
-
-    space.sys.checkinterval = space.int_w(w_interval)
-
-def getcheckinterval():
-    """getcheckinterval() -> current check interval; see setcheckinterval()."""
-    return space.newint(checkinterval)
-
-
-def exc_info():
-    operror = space.getexecutioncontext().sys_exc_info()
-    if operror is None:
-        return space.newtuple([space.w_None,space.w_None,space.w_None])
-    else:
-        return space.newtuple([operror.w_type,operror.w_value,
-                               space.wrap(operror.application_traceback)])
-
-def exc_clear():
-    operror = space.getexecutioncontext().sys_exc_info()
-    if operror is not None:
-        operror.clear(space)
-
-def pypy_getudir():
-    """NOT_RPYTHON"""
-    from pypy.tool.udir import udir
-    return space.wrap(str(udir))
-
-def getdefaultencoding():
-    """getdefaultencoding() -> return the default encoding used for UNICODE"""
-    return space.wrap(cpy_sys.getdefaultencoding())
-
-def getrefcount(w_obj):
-    """getrefcount(object) -> integer
-
-Return the reference count of object.  The count returned is generally
-one higher than you might expect, because it includes the (temporary)
-reference as an argument to getrefcount().
-"""
-    # From the results i get when using this i need to apply a fudge
-    # value of 6 to get results comparable to cpythons. /Arre
-    return space.wrap(cpy_sys.getrefcount(w_obj) - 6)
-

Deleted: /pypy/branch/dist-interpapp/pypy/module/sysmodule.py
==============================================================================
--- /pypy/branch/dist-interpapp/pypy/module/sysmodule.py	Fri Feb 18 11:45:25 2005
+++ (empty file)
@@ -1,70 +0,0 @@
-"""
-The 'sys' module.
-"""
-
-__interplevel__execfile('sysinterp.py')
-
-# Common data structures
-from __interplevel__ import initialpath as path
-from __interplevel__ import modules, argv
-from __interplevel__ import warnoptions, builtin_module_names
-from __interplevel__ import maxunicode
-
-# Objects from interpreter-level
-from __interplevel__ import stdin, stdout, stderr, maxint
-from __interplevel__ import platform, byteorder
-from __interplevel__ import pypy_objspaceclass
-from __interplevel__ import exec_prefix, prefix
-
-# Functions from interpreter-level
-from __interplevel__ import _getframe, exc_info, exc_clear, pypy_getudir
-from __interplevel__ import getrecursionlimit, setrecursionlimit
-from __interplevel__ import getcheckinterval, setcheckinterval
-from __interplevel__ import getdefaultencoding, getrefcount
-
-# Dummy
-executable = 'py.py'
-api_version = 0
-copyright = ''
-version = '2.3a0 (pypy build)'
-version_info = (2, 3, 0, 'alpha', 0)
-hexversion = 0x020300a0
-ps1 = '>>>> '
-ps2 = '.... '
-
-
-# XXX not called by the core yet
-def excepthook(exctype, value, traceback):
-    from traceback import print_exception
-    print_exception(exctype, value, traceback)
-
-__excepthook__ = excepthook  # this is exactly like in CPython
-
-def exit(exitcode=0):
-    # note that we cannot use SystemExit(exitcode) here.
-    # The comma version leads to an extra de-tupelizing
-    # in normalize_exception, which is exactlylike CPython.
-    raise SystemExit, exitcode
-
-def displayhook(obj):
-    if obj is not None:
-        __builtins__['_'] = obj
-        # NB. this is slightly more complicated in CPython,
-        # see e.g. the difference with  >>> print 5,; 8
-        print `obj`
-
-__displayhook__ = displayhook  # this is exactly like in CPython
-
-def getfilesystemencoding():
-    """getfilesystemencoding() -> string
-
-Return the encoding used to convert Unicode filenames in
-operating system filenames."""
-    
-    if platform == "win32":
-        encoding = "mbcs"
-    elif platform == "darwin":
-        encoding = "utf-8"
-    else:
-        encoding = None
-    return encoding



More information about the Pypy-commit mailing list