1

I have a python function that takes a large amount of parameters :

def func(p1=0, p2=0, p3=0, p4=0, p5=0, ..., pN=0) -> None: pass

I wanted to force the user to set the parameters as keyword arguments.

I thought about one solution that seems off to me:

def func(*_, p1=0, p2=0, p3=0, p4=0, p5=0, ..., pN=0) -> None: pass

I can even raise an error if unwanted ordered arguments were given and even separate ordered arguments from unordered arguments:

def func(p1, p2, p3, *unwanted, p4=0, p5=0, p6=0, ..., pN=0) -> None:
    if unwanted: raise TypeError

I haven't seen anyone do this, is there a problem with this?

2
  • I am not quite sure whether I understood the question, but try func(p1, p2, p3, *, p4=0, ..., pN=0) Commented Nov 13, 2022 at 19:24
  • You don't actually need the _; * alone is sufficient to mark the "boundary" between ordinary parameters and keyword-only parameters. (*_ is the same as *args: it's a parameter named _ that gathers any positional arguments not assigned to other parameters. It can also mark the boundary between ordinary and keyword-only parameters.) Commented Nov 13, 2022 at 19:32

1 Answer 1

2

This is already a standard method. It is defined in PEP3102

It's used in many libraries.

To give you one example: in ' drop function, all parameters after * are keywords only:

DataFrame.drop(labels=None, *, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

Note that you don't need the _ if you just want to ignore the parameters, a bare * is sufficient.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.