Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Forcing python function parameters to not have order

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading