1

I currently have a function with many optional arguments, something like this:

def many_argument_function(required1, required2, optional1=1, optional2=2,
                           optional3=None, optional4="Test", optional5="g",
                           optional6=2, optional7=(0, 255, 0), optional8=0.5):
                           # Do stuff

But in reality, it has over 20 optional arguments which take five lines even with 120 character line limit.

Is there a design pattern to simplify this/make it prettier?

P.S. I have considered making a separate configuration file for this function, but then calling it would be annoying since most of the time only one or two optional arguments are used.

EDIT1: I don't want to use kwargs as I want names of arguments and default values visible in my IDE (PyCharm)

12
  • Possible duplicate of Is there a way to pass optional parameters to a function? Commented Sep 24, 2018 at 16:31
  • I don't want to use kwargs as I want names and default values visible in IDE Commented Sep 24, 2018 at 16:34
  • couldn't you put your optionals into a list and pass the list Commented Sep 24, 2018 at 16:35
  • @vash_the_stampede In python if you have a list as a default for an argument it is mutable, so can't do that. Commented Sep 24, 2018 at 16:37
  • No i'm saying don use a default and just pass a list containing all the default variables, if you have changes you can make a list copy with the change, and pass that Commented Sep 24, 2018 at 16:38

1 Answer 1

6

There's nothing wrong with just listing one parameter per line.

def many_argument_function(
        required1,
        required2,
        optional1=1,
        optional2=2,
        optional3=None,
        optional4="Test",
        optional5="g",
        optional6=2,
        optional7=(0, 255, 0),
        optional8=0.5
    ):

    """
    This function does some stuff.
    """

    # Do stuff

PEP 8 endorses this style of indentation, and although its own example puts multiple parameters on a single line, I find it much easier to scan a large list of parameters if each is on its own line.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.