print tuple as number of arguments - python

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

Related

Unpacking a list in print for Python 2

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.

How can I apply a list as a variable number of arguments to the python print built-in?

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.

Python: Sending the print function as a parameter

My professor had mentioned that it's possible to pass functions like print as a parameter, but when I try and actually implement it I get a syntax error. Is it something small that I am missing here?
def goTime(sequence, action):
for element in sequence:
action(element)
def main():
print("Testing Begins")
test = list ( range( 0 , 20, 2) )
goTime(test, print)
print("Testing Complete")
Upon running the following, I receive this syntax error:
goTime(test, print)
^
SyntaxError: invalid syntax
If I define my own function that uses print, it works, like so:
def printy(element):
print(element)
def goTime(sequence, action):
for element in sequence:
action(element)
def main():
print("Testing Begins")
test = list ( range( 0 , 20, 2) )
goTime(test, printy)
print("Testing Complete")
In Python 3 that will work out of the box. In Python 2.7 however, you can do:
from __future__ import print_function
def foo(f,a):
f(a)
foo(print,2)
2
Note that in Python2.7 after you do from __future__ import print_function you won't be able to use print like a keyword any more:
>>> from __future__ import print_function
>>> print 'hi'
File "<stdin>", line 1
print 'hi'
^
SyntaxError: invalid syntax
Although I think your professor only wanted to make a point that functions in Python are first class citizens (ie: objects) and they can be passed around as any other variable. He used a controversial example though :)
Hope this helps!
You can't pass print in Python2, because it's a keyword rather than a function. It's possible in Python3.
You can try to import new print function from future. Check this question:
How to gracefully deal with failed future feature (__future__) imports due to old interpreter version?
and then you can use it as a function.
You can try sys.stdout
import sys
def printy(element):
sys.stdout.write(str(element)+'\n')
In python2 You can wrap print inside of a wrapper function and pass that:
def PrintWrapper(arg):
print(arg)
def MyFunc(x, func):
func(x)
# call the function with the wrapper as an argument
MyFunc("Hello world", PrintWrapper)

from past import print_statement

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).

is print a function in Python?

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)

Categories