2

If I write my function f as this:

def f(a, b, c, d = 4, e = 5, f = 6):
    print(a, b, c, d, e, f)

I can call it normally with positional arguments:

f(1, 2, 3)

And I can also call it using the positional arguments as keyword arguments:

f(c=3, a=1, b=2)

However, if I do that with the print function, I get an error:

>>> print(value=42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'value' is an invalid keyword argument for this function

I tried to use value as keyword because it was what it showed me when I did help(print):

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

edit:

Now I understand the *objects and I get that print is looking for a tuple of values. The pow function illustrates what I ask better:

>>> pow(x=2, y=3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pow() takes no keyword arguments

Why can't I never seem to refer to the parameters by their names if I use python functions? As I showed above it worked for my f function.

plx
  • 397
  • 3
  • 15
  • 3
    But you show an error that has nothing to do with your code fragment, since it shows attribute `value`. To answer your question, here Python uses `*args`. – Willem Van Onsem Nov 14 '17 at 11:36
  • Print function doesn't have any argument named `value`. for reference read https://docs.python.org/3/library/functions.html#print – Himanshu Bansal Nov 14 '17 at 11:42
  • 1
    Himanshu Bansal I see, at that page they call it *objects instead of value. It's the first time I see the *, what does it mean? – plx Nov 14 '17 at 11:46
  • @plx for * and ** in python read this https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters – Himanshu Bansal Nov 14 '17 at 11:53
  • Also here: https://stackoverflow.com/questions/55970072/python-library-functions-taking-no-keyword-arguments – Jeyekomon Jun 28 '19 at 13:54

1 Answers1

0

The implementation of print is this:

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

The objects parameter has a * before, so it is expected to be a variable number of positional arguments*

*Edited after @brunodesthuilliers comment.

FcoRodr
  • 1,583
  • 7
  • 15
  • 1
    The `objects` parameter as a `*` before which means the function accepts a variable number of positional arguments (which will be available as a `tuple` inside the function's body). This _certainly_ doesn't mean you're 'expected' to pass a list to `print()`. – bruno desthuilliers Nov 14 '17 at 13:09