I'm having problem with understanding why unpacking does not work with list and print statement in Python 2.7:
>>> l=['a', 'b', 'c']
>>> print (*l, sep='')
Python 3.x works fine and prints:
abc
Python 2.7, however, raises an error:
print (*l, sep='')
^
SyntaxError: invalid syntax
How can I make it work for Python 2.7?
I know I can alternatively code it using join with: ''.join(l)
Because print isn't a function in Python 2; unpacking a list and providing it as positional args isn't possible if it isn't a function.
You'll need to import the print_function from __future__ in order to support this:
>>> from __future__ import print_function
Now unpacking is possible:
>>> l = ['a', 'b', 'c']
>>> print(*l, sep='')
abc
You have two options:
Convert to strings and join with spaces manually:
print ''.join(map(str, l))
Use the print() function, by using the from __future__ import that disables the print statement:
from __future__ import print_function
print(*l, sep='')
or directly call the function by accessing it via the __builtin__ module:
import __builtin__
print_function = getattr(__builtin__, 'print')
print_function(*l, sep='')
The same function is available in both Python 2 and 3, but in Python 2 you can't use it directly without first disabling keyword.
Related
How can we get the function pointer of the builtin print function in python.
It seems to behave differently than the other builtin functions:
>>> a = print
SyntaxError: invalid syntax
>>>> dir(print)
SyntaxError: invalid syntax
>>>> m = map
OK
>>>> dir(map)
['__call__', '__class__', [...] '__str__', '__subclasshook__']
You can't do this because print is a keyword in Python 2.7, so it would be along the lines of saying something like:
>>> a = if
Doesn't make too much sense.
You have two options.
Use python 3
Import the python equivalent: from __future__ import print_function
In Python 2.7 , print is a statement not a function (whereas map is a built-in function).
If you want the print function in Python 2.x , you would need to do -
from __future__ import print_function
Please note, this would make print function for the rest of your program.
I can't import a module using the eval() function.
So, I have a function where if I do import vfs_tests as v it works. However, the same import using eval() like eval('import vfs_tests as v') throws a syntax error.
Why is this so?
Use exec:
exec 'import vfs_tests as v'
eval works only on expressions, import is a statement.
exec is a function in Python 3 : exec('import vfs_tests as v')
To import a module using a string you should use importlib module:
import importlib
mod = importlib.import_module('vfs_tests')
In Python 2.6 and earlier use __import__.
Actually. if you absolutely need to import using eval (for example, code injection), you can do it as follow in Python 3, since exec is a function:
eval("exec('import whatever_you_want')")
For example:
>>> eval('exec("from math import *")')
>>> sqrt(2)
1.4142135623730951
My little trick if you want to pass all the code as string to eval function:
>>> eval('exec("import uuid") or str(uuid.uuid4())')
'bc4b921a-98da-447d-be91-8fc1cebc2f90'
>>> eval('exec("import math") or math.sqrt(2)')
1.4142135623730951
You can use __import__ inside of eval to import something.
eval("__import__('os').system('ls')")
I want to pass the variadic number of arguments and then print them (if some conditions are true).
When I try to do so:
def my_print(*args)
print args
It prints a tuple. How do I make python act my_print(a,b) as print a,b ?
You could do this:
from __future__ import print_function
print(*args)
This gets you the 3.x style print function so you can unpack the arguments. Do note that you then need to use the 3.x syntax everywhere in that module, however.
In Python 2.x you can use str.join:
def my_print(*args):
print ' '.join(map(str, args))
If you are using Python 3.x then it's even easier because there's a print function:
def my_print(*args):
print(*args)
Other answers also mention that you can from __future__ import print_function, but this has the disadvantage that all your existing code that uses the print statement will break.
Use builtin print function:
from __future__ import print_function
my_print = print
Or
my_print = getattr(__builtins__, 'print')
You could try
for _ in len(range(args)):
print a[_],
But it looks like the other answers are more correct
In python everything is an object and you can pass it around easily.
So I can do :
>> def b():
....print "b"
>> a = b
>> a()
b
But if I do
a = print
I get SyntaxError . Why so ?
In Python 2.x, print is a statement not a function. In 2.6+ you can enable it to be a function within a given module using from __future__ import print_function. In Python 3.x it is a function that can be passed around.
In python2, print is a statement. If you do from __future__ import print_function, you can do as you described. In python3, what you tried works without any imports, since print was made a function.
This is covered in PEP3105
The other answers are correct. print is a statement, not a function in python2.x. What you have will work on python3. The only thing that I have to add is that if you want something that will work on python2 and python3, you can pass around sys.stdout.write. This doesn't write a newline (unlike print) -- it acts like any other file object.
print is not a function in pre 3.x python. It doesn't even look like one, you don't need to call it by (params)
Environment: python 2.x
If print is a built-in function, why does it not behave like other functions ? What is so special about print ?
-----------start session--------------
>>> ord 'a'
Exception : invalid syntax
>>> ord('a')
97
>>> print 'a'
a
>>> print('a')
a
>>> ord
<built-in function ord>
>>> print
-----------finish session--------------
The short answer is that in Python 2, print is not a function but a statement.
In all versions of Python, almost everything is an object. All objects have a type. We can discover an object's type by applying the type function to the object.
Using the interpreter we can see that the builtin functions sum and ord are exactly that in Python's type system:
>>> type(sum)
<type 'builtin_function_or_method'>
>>> type(ord)
<type 'builtin_function_or_method'>
But the following expression is not even valid Python:
>>> type(print)
SyntaxError: invalid syntax
This is because the name print itself is a keyword, like if or return. Keywords are not objects.
The more complete answer is that print can be either a statement or a function depending on the context.
In Python 3, print is no longer a statement but a function.
In Python 2, you can replace the print statement in a module with the equivalent of Python 3's print function by including this statement at the top of the module:
from __future__ import print_function
This special import is available only in Python 2.6 and above.
Refer to the documentation links in my answer for a more complete explanation.
print in Python versions below 3, is not a function. There's a separate print statement which is part of the language grammar. print is not an identifier. It's a keyword.
The deal is that print is built-in function only starting from python 3 branch. Looks like you are using python2.
Check out:
print "foo"; # Works in python2, not in python3
print("foo"); # Works in python3
print is more treated like a keyword than a function in python. The parser "knows" the special syntax of print (no parenthesis around the argument) and how to deal with it. I think the Python creator wanted to keep the syntax simple by doing so. As maverik already mentioned, in python3 print is being called like any other function and a syntx error is being thrown if you do it the old way.