Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python library functions taking no keyword arguments

This problem originated when I tried to apply a more functional approach to problems in python. What I tried to do is simply square a list of numbers, no biggie.

from operator import pow
from functools import partial 

squared = list(map(partial(pow, b=2), range(10))

As it turns out, this didn't work. TypeError: pow() takes no keyword arguments

Confused I checked if pow(b=2, a=3) did. It didn't.

I've checked the operator source code, nothing suspicious.

Confused, I've begun to doubt my own python knowledge, I made a pow function myself.

def pow(a, b):
  return a ** b

Then I tried doing the same thing with my function and surprisingly, everything worked.

I'm not going to guess what is the cause of the problem, what I'm asking is simply why is this a thing and if there exists a workaround.

like image 875
Welperooni Avatar asked May 03 '19 12:05

Welperooni


People also ask

How do you force keyword arguments in Python?

However, in Python 3, there is a simple way to enforce it! By adding a * in the function arguments, we force all succeeding arguments to be named. E.g. by having the first argument be * , we force all arguments to be named.

Can function work without arguments in Python?

Functions do not have declared return types. A function without an explicit return statement returns None . In the case of no arguments and no return value, the definition is very simple. Calling the function is performed by using the call operator () after the name of the function.

Does Python support keyword arguments?

Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed.

What is non keyword arguments in Python?

When a function is invoked, all formal (required and default) arguments are assigned to their corresponding local variables as given in the function declaration. The remaining non-keyword variable arguments are inserted in order into a tuple for access.


1 Answers

If you check the signature of the built-in pow() or operator.pow() using the help() function in the interactive shell, you'll see that they require positional-only parameters (note the trailing slashes):

pow(x, y, z=None, /)
pow(a, b, /)

The reason is that both functions are implemented in C and don't have names for their arguments. You have to provide the arguments positionally. As a workaround, you can create a pure Python pow() function:

def pow(a, b):
    return a ** b

See also What does the slash(/) in the parameter list of a function mean? in the FAQ.

like image 99
Eugene Yarmash Avatar answered Sep 17 '22 16:09

Eugene Yarmash