def obtain_valid_object(obj_class, **kwargs):
    """
    Try to obtain a valid instance of obj_class, using those args of kwargs that
    can be given to its __init__ function.
    """
    try:
        obj = obj_class(**kwargs)
    except TypeError:
        obj = obj_class()
        args_okay = {}
        for arg in kwargs:
            if hasattr(obj, arg):
                args_okay[arg] = kwargs[arg]
        obj = obj_class(**args_okay)
    return obj