Commits

Benjamin Peterson  committed 74db835

add print() function and print_function __future__

  • Participants
  • Parent commits 541d99a
  • Branches fast-forward

Comments (0)

Files changed (7)

File pypy/interpreter/astcompiler/consts.py

 CO_FUTURE_DIVISION = 0x2000
 CO_FUTURE_ABSOLUTE_IMPORT = 0x4000
 CO_FUTURE_WITH_STATEMENT = 0x8000
+CO_FUTURE_PRINT_FUNCTION = 0x10000
 
 PyCF_SOURCE_IS_UTF8 = 0x0100
 PyCF_DONT_IMPLY_DEDENT = 0x0200

File pypy/interpreter/pyparser/pygram.py

 
 
 python_grammar = _get_python_grammar()
+python_grammar_no_print = python_grammar.shared_copy()
+python_grammar_no_print.keyword_ids = python_grammar_no_print.keyword_ids.copy()
+del python_grammar_no_print.keyword_ids["print"]
 
 class _Tokens(object):
     pass

File pypy/interpreter/pyparser/pyparse.py

 
         flags = compile_info.flags
 
-        self.grammar = pygram.python_grammar
+        if flags & consts.CO_FUTURE_PRINT_FUNCTION:
+            self.grammar = pygram.python_grammar_no_print
+        else:
+            self.grammar = pygram.python_grammar
 
         # The tokenizer is very picky about how it wants its input.
         source_lines = textsrc.splitlines(True)

File pypy/interpreter/test/test_syntax.py

         assert record == [2, 1]
 
 
+class AppTestPrintFunction:
+
+    def test_simple_print(self):
+        import __builtin__
+        s = """from __future__ import print_function
+x = print
+"""
+        ns = {}
+        exec s in ns
+        assert ns["x"] is getattr(__builtin__, "print")
+
+    def test_print(self):
+        s = """from __future__ import print_function
+import StringIO
+s = StringIO.StringIO()
+print("Hello,", "person", file=s)
+"""
+        ns = {}
+        exec s in ns
+        assert ns["s"].getvalue() == "Hello, person\n"
+
 class AppTestWith:
     def test_with_simple(self):
 

File pypy/module/__builtin__/__init__.py

         'execfile'      : 'app_io.execfile',
         'raw_input'     : 'app_io.raw_input',
         'input'         : 'app_io.input',
+        'print'         : 'app_io.print_',
 
         'apply'         : 'app_functional.apply',
         #'range'         : 'app_functional.range',

File pypy/module/__builtin__/app_io.py

 def input(prompt=None):
     """Equivalent to eval(raw_input(prompt))."""
     return eval(raw_input(prompt))
+
+def print_(*args, **kwargs):
+    """The new-style print function from py3k."""
+    fp = kwargs.pop("file", sys.stdout)
+    if fp is None:
+        return
+    def write(data):
+        if not isinstance(data, basestring):
+            data = str(data)
+        fp.write(data)
+    want_unicode = False
+    sep = kwargs.pop("sep", None)
+    if sep is not None:
+        if isinstance(sep, unicode):
+            want_unicode = True
+        elif not isinstance(sep, str):
+            raise TypeError("sep must be None or a string")
+    end = kwargs.pop("end", None)
+    if end is not None:
+        if isinstance(end, unicode):
+            want_unicode = True
+        elif not isinstance(end, str):
+            raise TypeError("end must be None or a string")
+    if kwargs:
+        raise TypeError("invalid keyword arguments to print()")
+    if not want_unicode:
+        for arg in args:
+            if isinstance(arg, unicode):
+                want_unicode = True
+                break
+    if want_unicode:
+        newline = u"\n"
+        space = u" "
+    else:
+        newline = "\n"
+        space = " "
+    if sep is None:
+        sep = space
+    if end is None:
+        end = newline
+    for i, arg in enumerate(args):
+        if i:
+            write(sep)
+        write(arg)
+    write(end)

File pypy/module/__builtin__/test/test_builtin.py

         firstlineno = co.co_firstlineno
         assert firstlineno == 2
 
+    def test_print_function(self):
+        import __builtin__
+        import sys
+        import StringIO
+        pr = getattr(__builtin__, "print")
+        save = sys.stdout
+        out = sys.stdout = StringIO.StringIO()
+        try:
+            pr("Hello,", "person!")
+        finally:
+            sys.stdout = save
+        assert out.getvalue() == "Hello, person!\n"
+        out = StringIO.StringIO()
+        pr("Hello,", "person!", file=out)
+        assert out.getvalue() == "Hello, person!\n"
+        out = StringIO.StringIO()
+        pr("Hello,", "person!", file=out, end="")
+        assert out.getvalue() == "Hello, person!"
+        out = StringIO.StringIO()
+        pr("Hello,", "person!", file=out, sep="X")
+        assert out.getvalue() == "Hello,Xperson!\n"
+        out = StringIO.StringIO()
+        pr(u"Hello,", u"person!", file=out)
+        result = out.getvalue()
+        assert isinstance(result, unicode)
+        assert result == u"Hello, person!\n"
+        pr("Hello", file=None) # This works.
+        out = StringIO.StringIO()
+        pr(None, file=out)
+        assert out.getvalue == "None"
+
+    def test_print_exceptions(self):
+        import __builtin__
+        pr = getattr(__builtin__, "print")
+        raises(TypeError, pr, x=3)
+        raises(TypeError, pr, end=3)
+        raises(TypeError, pr, sep=42)
+
 class AppTestBuiltinOptimized(object):
     def setup_class(cls):
         from pypy.conftest import gettestobjspace