Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print.__doc__ vs getattr(__builtin__,"print").__doc__

print.__doc__ outputs:

SyntaxError: invalid syntax

where as

>>> getattr(__builtin__,"print").__doc__

Outputs:

print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments:

file : a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.

Can anyone help me understand why print.__doc__ is giving a syntax error instead of printing the doc string

like image 489
claudius Avatar asked May 30 '14 09:05

claudius


2 Answers

In Python 2 (or Python < 2.6 to be very exact) print is absolutely nothing like a function, and thus does not have docstring. It doesn't even evaluate all of its arguments before it starts printing:

>>> print 42, a
42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

42 was printed before the a was evaluated. print is a statement that expects 0 to N comma separated expression following it, optionally preceded by the construct >> file, the construct print.__doc__ is illegal. It makes as little sense as if.__doc__, or return.__doc__.

However starting with Python 2.6, the print function is available in the __builtin__ module, but is not used by default as the print statement collides with it, unless the parsing for print the statement is disabled by from __future__ import print_function.


Print isn't globally available as a function in Python 2, so you can't treat it as an object. It's a statement.

In Python 3, or Python 2 with from __future__ import print_function, however, print is a normal function and you can read the __doc__ attribute.

See: https://docs.python.org/2/library/functions.html#print

Note: This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module:

from __future__ import print_function
like image 20
Kos Avatar answered Oct 08 '22 22:10

Kos