1

Recently I noticed that range() does not accept keyword arguments, and I thought this was a little bit strange: Even if we define no defaults we can still do

def f(a, b):
    return a + b

f(a=3, b=5)

Is it therefore somehow possible to disable the use of keyword arguments in a function written in Python? Or is this just reserved for built in functions?

flawr
  • 10,814
  • 3
  • 41
  • 71
  • It was introduced in Python3.8 for easier use (https://deepsource.io/blog/python-positional-only-arguments/). – user2390182 Apr 02 '20 at 13:16
  • @schwobaseggl Interesting, thanks for the link! Pleas consider adding that as an anwer! – flawr Apr 02 '20 at 13:44
  • That wouldn't be satisfying. It was obviously possible for builtins before that change, and I am sure you could introspectively find out how an argument was passed and raise an Exception. Maybe someone will enlighten us to that end ;-) – user2390182 Apr 02 '20 at 13:46
  • Ok yes you could try that, but that wasn't really what I wanted to know (but you're right, I didn't exclude that possibility in my question:). If you define defaults it is indeed possible to check whether a keyword argument was used: https://stackoverflow.com/questions/14749328/how-to-check-whether-optional-function-parameter-is-set But then again there are probably ways to circumvent that in the case that you call use a keyword with the default object extracted from the functions __defaults__ but that gets hairy:) – flawr Apr 02 '20 at 13:53

1 Answers1

1

Since this came up as the top result for me, figured I'd go ahead and add the answer even though this is 2 years old...

def f(a, b, /):
    return a + b

Any arguments before the / must be passed in as positional args.

See: https://peps.python.org/pep-0570/

Timothy Aaron
  • 3,059
  • 19
  • 22