Home > database >  Forcing python function parameters to not have order
Forcing python function parameters to not have order

Time:11-14

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?

CodePudding user response:

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.

  • Related