Search code examples
pythonpython-3.xfunctionparameterspep570

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

Solution

  • Update: this answer will become increasingly out-dated; please see Eugene Yarmash's answer 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.)