1

I wrote two example codes which share a same pattern.

As you can read below, I used if statement to not to pass keyword argument down to a sub function if the argument is None. I want to do it in a better way.

Please share your thoughts if you have an idea.

# example_1
def mysort(alist, key=None):
    if key is None:
        alist = sorted(alist)
    else:
        alist = sorted(alist, key=key)

    return alist

# example_2
def create_index(index_name, mapping=None):
    es = Elasticsearch()
    if mapping in None:
        response = es.indices.create(index=index_name)
    else:
        response = es.indices.create(index=index_name, body=mapping)
    return respone
vishes_shell
  • 22,409
  • 6
  • 71
  • 81
Ryan Kang
  • 61
  • 1
  • 5

3 Answers3

0

For the first example the default value for key is None, so you can just pass it directly:

# example_1
def mysort(alist, key=None):
    alist = sorted(alist, key=key)
    return alist

You can also setup a different default value. For instance the new default value of 123 would be passed to sorted.

# example_1
def mysort(alist, key=some_key):
    alist = sorted(alist, key=key)
    return alist
101
  • 8,514
  • 6
  • 43
  • 69
0

The default value of the parameter key of the function sorted is None. Because of this, your first if/else is not necessary. Simple use

alist = sorted(alist, key=key)

Use the default value of body of es.indices.create as the default value for mapping in your function create_index. Then you can get rid of the if/else in this function, too.

Edit: The documentation says:

body – The document

Try to find out if this is a JSON string or a Python dictionary that represents the document. In the JSON string case, use the string "{}"as the default value:

def create_index(index_name, mapping="{}"):

Edit 2: Using an empty dict would not work (see link in comment). So in the second case, you would have to use if/else.

  • 1
    careful with `mapping={}`https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – Chris_Rands Jul 19 '18 at 08:18
  • @intentionallyleftblank Thank your for your insights on my question. You're right. If a default value for a keyword argument is None, I don't need to use if-else statement. And in other cases I could find what the default value is and put it in my wapper function. – Ryan Kang Jul 19 '18 at 08:31
0

As already stated, for sorted, you are basically just packing the original function. I don't think you can avoid the if for the second example, but you can shorten it a little.

def create_index(index_name, mapping=None):
    kwargs = {'index': index_name}
    if mapping is not None:
        kwargs['body'] = mapping
    return Elasticsearch().indices.create(**kwargs)
e.s.
  • 1,351
  • 8
  • 12