4 ms·
Following that advice, it seems that's py3 compatible only. Print statements are function calls without having imported from future.
by samuel 10y ago
Following that advice, it seems that's py3 compatible only. Print statements are function calls without having imported from future.
- sixhobbits 10y agoit only works the other way -- 2.7+ allows both print("hello") print "hello" while 3+ allows only print("hello")
- dr_zoidberg 10y agoIn Py2.7 you need: from __future__ import print_function to get the print("hello") behaviour.
- dylz 10y agoI don't remember ever having to do that, and my intro to cs class was py3 - I don't really run 2.7 day to day, is this a specific version? airbears2-10-142-34-161:~ ecx$ echo 'print("hello")' >0.py airbears2-10-142-34-161:~ ecx$ python2.7 0.py hello airbears2-10-142-34-161:~ ecx$ python2.7 -V Python 2.7.10
- geoelectric 10y agoNo, because the () just ends up being a no-op as grouping parentheses in the expression in Python 2. What the import from __future__ does is make the original non-parens version illegal syntax in Python 2. You have to treat it like a function call with that import.
- BerislavLopac 10y agoThere is another, less obvious difference: in Python 2, if you print multiple items in parentheses, you're actually printing a tuple: >>> print "foo", 1, 2, "bar", "baz" foo 1 2 bar baz >>> print("foo", 1, 2, "bar", "baz") ('foo', 1, 2, 'bar', 'baz') >>> from __future__ import print_function >>> print("foo", 1, 2, "bar", "baz") foo 1 2 bar baz
- geoelectric 10y agoTrue, that, behavior-wise. It's the comma that actually defines the tuple, though, hence (1) being different than (1,) and x = 1,2 assigning (1,2). In the particular case of a print statement, the grouping parens disambiguate between the comma meaning multiple args and a single arg that's a tuple, once Python 2 implicitly wraps the entire right side with function calling parens. In the end it's really a form of operator precedence. The from __future__ version behaves differently only because the function calling parens are now explicit and so tuple grouping parens must be added too if desired.