How to think smarter when you need diff args in functions I have this code, and the point is I want to dynamically change the mongo connecter to change between ssl, not ssl and with and without username in the same connecter function.

if auth_required:
    if config.getboolean(component, 'ssl', fallback=False):
        client = MongoClient(
            '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']),
            ssl=True,
            ssl_ca_certs=config.get(component, 'ssl_path'),
            serverSelectionTimeoutMS=timeout,
            username=username,
            password=password,
            authSource=auth_source,
            authMechanism=auth_mechanism
        )
    else:
        client = MongoClient(
            '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']),
            serverSelectionTimeoutMS=timeout,
            username=username,
            password=password,
            authSource=auth_source,
            authMechanism=auth_mechanism
        )
else:
    if config.getboolean(component, 'ssl', fallback=False):
        client = MongoClient(
            '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']),
            ssl=True,
            ssl_ca_certs=config.get(component, 'ssl_path'),
            serverSelectionTimeoutMS=timeout
        )
    else:
        client = MongoClient(
            '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']),
            serverSelectionTimeoutMS=timeout
        )
If you build a dictionary of keyword arguments (customarily called kwargs), you can address the two options separately and consolidate everything into one call to MongoClient. This has the advantage that if you update e.g. the SSL part, you only need to change it in one place instead of remembering to change it twice:

host = '{host}:{port}'.format(**config[component])
kwargs = {"serverSelectionTimeoutMS": timeout}

if config.getboolean(component, 'ssl', fallback=False):
    kwargs["ssl"] = True
    kwargs["ssl_ca_certs"] = config.get(component, 'ssl_path')

if auth_required:
    kwargs.update({"username": username, "password": password,
                   "authSource": auth_source, "authMechanism": auth_mechanism})

client = MongoClient(host, **kwargs)


I also used the fact that config[component] seems to be a dictionary, so you can unpack it in the format and the host and port keys will be used.

I used two different ways to change the values in the dictionary so you can choose, depending on which one is easier to read. Using both is also fine, as I did here. For the SSL part there is few values, so using dict.update would make it more cluttered, but for the auth part there are enough values that typing kwargs[...] = ... would get tedious.