Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

idioms

Imagine this:

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

The line overpass the 79 characters, so, what's the pythonic way to multiline it?

like image 773
Htechno Avatar asked Jun 28 '10 20:06

Htechno


People also ask

How can you accept multiple arguments into a function?

The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.

Can you write functions that accept multiple arguments in Python?

Luckily, you can write functions that take in more than one parameter by defining as many parameters as needed, for example: def function_name(data_1, data_2):

Can a function have too many arguments?

Many times, we tend to add too many parameters to a function. But that's not the best idea: on the contrary, when a function requires too many arguments, grouping them into coherent objects helps writing simpler code.


1 Answers

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).

like image 125
David Z Avatar answered Oct 14 '22 00:10

David Z