11

I was looking through some Python source code, when I came across this:

print >> sys.stderr, __doc__

What does the >> mean? I've never seen syntax like this before.

yyyyQqxKNqHyy
  • 343
  • 3
  • 10
  • 2
    @Shashank: Deprecated? I thought it was straight up annihilated. Deprecated implies it is still available but people are advised not to use it, which I don't think is the case here. – Amadan Mar 24 '15 at 04:15
  • 1
    @Amadan Yes, sorry, what I mean to say is that it's deprecated in Python 2 and removed in Python 3. Usage of this syntax should not be encouraged, even if found in respected source code. – Shashank Mar 24 '15 at 09:39
  • This thing is so difficult to search for, since too many examples use the python interactive shell and paste the triple greater-than sign everywhere... – Qi Fan May 02 '16 at 19:35

2 Answers2

12

See the "print chevron" description in the Python 2.7 docs:

print also has an extended form, defined by the second portion of the syntax described above. This form is sometimes referred to as “print chevron.” In this form, the first expression after the >> must evaluate to a “file-like” object, specifically an object that has a write() method as described above. With this extended form, the subsequent expressions are printed to this file object. If the first expression evaluates to None, then sys.stdout is used as the file for output.

The special syntax has disappeared in Python 3, as print was converted from a statement to a function.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Would you know what it does in a line like this? `m = (1 + 5) >> 1` – MadPhysicist Sep 16 '22 at 10:42
  • 1
    @MadPhysicist In that case it is a completely different thing: a [right bit-shift operator](https://docs.python.org/3/reference/expressions.html#shifting-operations). – Amadan Sep 16 '22 at 11:08
2

This syntax is specific to the print statement. Rather than the output going to standard output it sends the output to the file-like named after the >>, in this case standard error.

In an expression this is the right shift operator.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358