Quote:
Originally Posted by HMW
...out of curiosity, why do you import print function when running Python 3?
|
Because it's
safe to do so. It's similar to saying, Turn on the new print_function. If it's already on, do nothing.
I put it in there because my original code used print like this: print(obj, end=''). The end='' is a syntax error in 2.7.
Upon refactoring, I did not need that anymore but neglected to remove the __future__ (no harm though)
Quote:
The features recognized by Python 3.0 are absolute_import, division, generators, unicode_literals, print_function, nested_scopes and with_statement. They are all redundant because they are always enabled, and only kept for backwards compatibility.
...
No feature description will ever be deleted from __future__. Since its introduction in Python 2.1 the following features have found their way into the language using this mechanism:
|
This way, if someone runs python script.py, they will not get a error. Effectively, there's no harm in writing the below in every script to help get rid of a lot of issues of 2.7 users running 3x code (especially the print and division ones). As long of course, you are writing it for python3. It may break code written for python2.7 since it changes fundamental behavior of python.
Code:
from __future__ import absolute_import, division, generators, unicode_literals, print_function, nested_scopes
In your code, if I run it as is: python2.7 yourscript.py I get the syntax error with this line:
print(line, end="").
However, if I prepend
from __future__ import print_function it suddenly works in python2.7 and python3!
Some demo code:
Code:
$ python2.7
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print('foo', end='')
File "<stdin>", line 1
print('foo', end='')
^
SyntaxError: invalid syntax
>>> from __future__ import print_function
>>> print('foo', end='')
foo>>>
Code:
$ python3.6
Python 3.6.2 (default, Jul 17 2017, 23:14:31)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('foo', end='')
foo>>> from __future__ import print_function
>>> print('foo', end='')
foo>>>