简体   繁体   中英

Python, How not to pass a keyword argument to a method when the argument is None?

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

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

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM