Syntax error when passing unpacked argument for printing in Python

Instead of a simple debug / logarithmic print:

print "error ", error_number 

I would like to use a log function that I can expand if necessary, looking something like this:

 def log(condition, *message): if(<do something here...>): print(*message) <perhaps do something more...> 

and name it as follows:

 log(condition, "error ", error_number) 

But I get the following syntax error:

 print *message ^ SyntaxError: invalid syntax 

Is this a limitation of the print function, or is there a way to make it work? If not, is there a print equivalent that I could use?

I am using Python 2.7 by the way ...

+4
source share
4 answers

print not a function in Python 2.x. In the first fragment, you print a tuple, and the last one has invalid syntax. If you want to use the print function, you need to enable it through from __future__ import print_function .

+7
source

If you do not want to use __future__ , you can define the logging function as follows:

 def log(condition, *message): if(<do something here...>): print ' '.join(str(a) for a in message) <perhaps do something more...> 
+7
source

You should use print message directly, which is enough (it will print a tuple of additional arguments).


A small addition to the previous answers: in Python 2.x, print not a function, but an operator , but print(arg1, arg2) valid ... like using the print statement on tuple (arg1, arg2) .

This is slightly different from print arg1, arg2 , as you can see:

 >>> print 'aaa', 'bbb' aaa bbb >>> print('aaa', 'bbb') ('aaa', 'bbb') 

Now, in addition to the answer to the topic:

case 1 : do not use * to expand tuple argument

 >>> def p(*args): ... a(args) # <== args is a tuple >>> def a(*args): ... print args # <== args is a tuple (but nothing else can be used) >>> p('bb') (('bb',),) 

The result is a tuple of a tuple.

Case 2 : expanding arguments in p :

 >>> def p(*args): ... a(*args) # <== now arguments are expanding ... >>> p('bb') ('bb',) 

The result is a tuple of arguments given by p .

So *args is the correct use, but it is not allowed in the instruction.

+2
source

You simply use *args to declare a tuple of arguments, and not to access it. See the example in the docs :

 def write_multiple_items(file, separator, *args): file.write(separator.join(args)) 

The fact that you get a SyntaxError should upset you that it has nothing to do with print .

-2
source

Source: https://habr.com/ru/post/1380351/


All Articles