Pythonic way to write functions/methods with a lot of arguments

I think the 'Pythonic' way of answering this is to look deeper than syntax. Passing in that many arguments to a method indicates a likely problem with your object model.

  1. First of all, do you really need to pass that many arguments to this method? Perhaps this is an indication that the work could be better done elsewhere (by an object that already has access to the variables)?

  2. If this really is the best place for the method, then could some of those arguments be supplied as instance variables of this object itself (via self)?

  3. If not, can you redefine the responsibilities of the parent object to include them?

  4. If not, can you encapsulate any of the individual arguments in a composite object that formalizes the relationship between them? If any of the arguments have anything in common, then this should be possible.


You can include line breaks within parentheses (or brackets), e.g.

def method(self, alpha, beta, gamma, delta, epsilon, zeta,
                 eta, theta, iota, kappa):
    pass

(the amount of whitespace to include is, of course, up to you)

But in this case, you could also consider

def method(self, *args):
    pass

and/or

def method(self, **kwargs):
    pass

depending on how you use the arguments (and how you want the function to be called).

Tags:

Python

Idioms