Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does using from __future__ import print_function breaks Python2-style print? [closed]

People also ask

What is from __ future __ import Print_function?

Using the print keyword as a function instead of a statement brings a lot of flexibility to it, which helps extend the print keyword's ability. The main function of from __future__ import print_function is to bring the print function from Python 3 into Python 2.

What does from __ future __ mean?

For example, from __future__ import with_statement allows you to use the with statement in Python 2.5 but it is part of the language as of Python 2.6. The syntax from module import function generally means that the function from the specified module is made available in the current scope and that it can be called.

What is Absolute_import?

from __future__ import absolute_import means that if you import string , Python will always look for a top-level string module, rather than current_package.string . However, it does not affect the logic Python uses to decide what file is the string module.

How do you define print in Python?

Python print() FunctionThe print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.


First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.