import warnings

import brian2.units as brian2units

def convert_string_to_unit(string):
    if isinstance(string, brian2units.fundamentalunits.Quantity):
        return string

    try:
        assert isinstance(string, str)
    except AssertionError as err:
        print("{} cannot be converted to a value with units".format(string))
        raise AssertionError
    return eval(string, brian2units.__dict__)

def set_parameters_from_dict(brian2_object, dictionary_of_parameters):
    for param_key, param_value in dictionary_of_parameters.items():
        try:
            brian2_object.__setattr__(param_key, convert_string_to_unit(param_value))
        except AttributeError as err:
            warnings.warn("{:s} has no paramater {:s}".format(brian2_object.name, param_key))
