3

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

Community
  • 1
  • 1
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
  • 1
    It really depends on if you want to give a default value or some args are optional etc.. If all args are necessary and you go giving default values it will be a mess checking each arg, if args1 is None if args2 is None .. that will get ugly pretty quick – Padraic Cunningham Mar 23 '16 at 16:53
  • 1
    As others mentioned, there is no convention and limitation other then if you gonna have default values, but I would make it so that the function signature reads as a complete sentence. Like, "function to plat a graph G and filename foo". – Sergey Mar 23 '16 at 17:52

2 Answers2

4

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.

Nikita
  • 6,101
  • 2
  • 26
  • 44
1

It is not extreme to use only keyword arguments. I have seen that in many codebases. This allows you to extend functionalities (by adding new keyword arguments to your functions) without breaking your previous code. It can be slightly more tedious to use, but definitely easier to maintain and to extend.

Also have a look at PEP 3102 -- Keyword-Only Arguments, which is a way to force the use of keyword arguments in python 3.

DevShark
  • 8,558
  • 9
  • 32
  • 56