Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement "positional-only parameter" in a user defined function in python?

How can I implement "positional-only parameter" for a function that is user defined in python?

def fun(a, b, /):
    print(a**b)

fun(5,2)        # 25
fun(a=5, b=2)   # should show error
like image 263
Damodara Sahu Avatar asked Oct 16 '18 16:10

Damodara Sahu


2 Answers

Before Python 3.8, the / syntax was only documentational. Starting from 3.8, you can use it for specifying positional-only parameters in function definitions. Example:

def pow(x, y, z=None, /):
    r = x**y
    if z is not None:
        r %= z
    return r

Now pow(2, 10) and pow(2, 10, 17) are valid calls, but pow(x=2, y=10) and pow(2, 10, z=17) are invalid.

See PEP 570 for more details.

like image 121
Eugene Yarmash Avatar answered Nov 14 '22 23:11

Eugene Yarmash


Update: this answer will become increasingly out-dated; please see https://stackoverflow.com/a/56149093/1126841 instead.


The only solution would be to use a *-parameter, like so:

def fun(*args):
    print(args[0] ** args[1])

But this comes with its own problems: you can't guaranteed the caller will provide exactly two arguments; your function has to be prepared to handle 0 or 1 arguments. (It's easy enough to ignore extra arguments, so I won't belabor the point.)

like image 44
chepner Avatar answered Nov 14 '22 22:11

chepner