Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double greater-than sign in Python

Tags:

python

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.

like image 984
yyyyQqxKNqHyy Avatar asked Mar 24 '15 01:03

yyyyQqxKNqHyy


People also ask

What does >> mean in Python?

In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand. Leading bits as towards left as a result of shifting are set to 0.

What is double greater than symbol in Python?

In an expression this is the right shift operator.

What is >> and << in Python?

They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.

Can you use >= in Python?

Well, to write greater than or equal to in Python, you need to use the >= comparison operator. It will return a Boolean value – either True or False. The "greater than or equal to" operator is known as a comparison operator. These operators compare numbers or strings and return a value of either True or False .


2 Answers

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.

like image 58
Amadan Avatar answered Oct 25 '22 06:10

Amadan


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.

like image 20
Ignacio Vazquez-Abrams Avatar answered Oct 25 '22 06:10

Ignacio Vazquez-Abrams