Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the conventions for ordering parameters in Python?

What are the conventions for ordering parameters in Python? For instance,

def plot_graph(G, filename, ...)

# OR

def plot_graph(filename, G, ...)

There is no discussion in PEP 0008 -- Style Guide for Python Code | Python.org

Excerpt from the answer of Conventions for order of parameters in a function,

If a language allows passing a hash/map/associative array as a single parameter, try to opt for passing that. This is especially useful for methods with >=3 parameters, ESPECIALLY when those same parameters will be passed to nested function calls.

Is it extreme to convert each parameter into a key-value pair, like def plot_graph(graph=None, filename=None, ...)?

like image 711
SparkAndShine Avatar asked Oct 20 '25 22:10

SparkAndShine


1 Answers

There's really no convention for ordering function parameters, except a limitation that positional non-default parameters must go before parameters with defaults and only then keyword parameters, i.e. def func(pos_1, pos_n, pos_1_w_default='default_val', pos_n_w_default='default_val', *args, kw_1, kw_n, kw_1_w_default='default_val', kw_n_w_default='default_val', **kwargs).

Usually you define parameters order logically based on their meaning for the function, e.g. if you define a function that does subtraction, it's logical, that minuend should be the first parameter and subtrahend should be second. In this case reverse order is possible, but it's not logical.

Also, if you consider that your function might be used partially, that might affect your decision on parameter ordering.

Most things you need to know about function parameters are in the official tutorial.

P.S. Regarding your particular example with graph function... Considering your function name, it is used for displaying a graph, so a graph must be provided as argument, otherwise there's nothing to display, so making graph=None by default doesn't make much sense.

like image 188
Nikita Avatar answered Oct 22 '25 12:10

Nikita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!