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)
Related
How can you rename functions in python, like renaming print to something like say?
Things like little changes in python's code that you could potentially make into a module (for something like an addon pack).
I am not sure why you would want to rename print but this is how I would do it.
For python 3.X:
myvar = "Hello World"
say = print
say (myvar)
my example for Python 3.X does not seam to be viable for Python 2.X unless anyone else knows a way similar to my example. Otherwise here is way you can do for Python 2.X
myvar = "Hello World"
def printFun(stuff):
print(stuff)
say = printFun
say (myvar) # note that like python 3 you must put this in ()
Anytime you want to "rename" a function all you need to do is assign that function to a variable and then use that variable as the function.
Edit: On a related note you can also import the python 3 function to python 2:
# this is good to use in 2.X to help future proof your code.
# for at least the print statement
from __future__ import print_function
myvar = 'Hello World'
say = print
say (myvar)
So you can apply a variable amount of arguments from a list to a normal function by doing this
someFunc(*[1,2,3])
But it doesn't work when I used the built-in print
print(*[1,2,3])
^
SyntaxError: invalid syntax
How can I achieve the same effect with print?
The issue is that in python prior to python 3, print is a keyword of the language and not a function, so it doesn't work the same way. If you want to achieve a similar effect you can just make your own print function
def output(*args):
print ' '.join(str(i) for i in args)
then use output(*[1,2,3])
Or if your version of python2 is recent enough (>= 2.6) you can do
from __future__ import print_function
to get the python 3 semantics.
Is there some equivalent to from __future__ import print_function that forward-ports the print statement from python 2.x?
An answer involving some ipython magic that lets me print without need of surrounding parens during prototyping is also acceptable.
Some suggestion for IPython
%autocall
print "Hi"
Define magic with autocall on
from IPython.core.magic import register_line_magic
#register_line_magic
def p(line):
print(line)
p "Hi"
Define magic with autocall off
from IPython.core.magic import register_line_magic
#register_line_magic
def p(line):
print(eval(line))
%p "Again"
You could create a .config/ipython/profile_default/startup/autoprint.py file for you line magic functions.
Provisional answer (A solution that doesn't involve a leading / will be preferred.): IPython automatically calls an object if line begins with a /, even if it's indented:
def f():
/print 'foo'
f()
prints foo.
Edit:
IPython also has an %autocall magic function that, well, automatically calls functions, so after doing %autocall 1, typing print 3 in a cell acts like print in python 2.x (though this unfortunately doesn't work in function definitions like / does.
Also, since it's a function and not a statement, you can simply do p = print, so later /p 'foo' calls give you almost pdb-like behavior (something I was going for but that wasn't explicitly stated in the question).
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
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.