import importlib


def my_optimizer(params, opts):
    """Selects and instantiates optimizer object according to parsed options.

    Selects function from the module optimization.optimizer with name
    opts.opts2optimzer to instantiate optimizer object.

    Args:
        opts (obj): Namespace object with options. Required attribute is
            attribute opts.opts2optimizer.
    
    Returns:
        my_optimizer (obj): Instantiated optimizer object.

    Raises:
        NotImplementedError: When no function with name opts.opts2optimizer
            exists in module optimization.optimizer.

    """

    optimizer_import = 'optimization.optimizer'
    optimizer_lib = importlib.import_module(optimizer_import)
    
    #Pick function to create optimizer object from module
    #optimization.optimizer
    my_optimizer = None
    for name, fct in optimizer_lib.__dict__.items():
        if name == opts.opts2optimizer:
            my_optimizer = fct(params, opts)

    if my_optimizer==None:
        raise NotImplementedError(
                """In {optimizer_import} is no function with name 
                {opts2optimizer} implemented.""".format(
                    optimizer_import=optimizer_import, 
                    opts2optimizer=opts.opts2optimizer
                    )
                )
    
    print("""Optimizer object instantiated via function with name
            {opts2optimizer} from module 
            {optimizer_import}.""".format(
                opts2optimizer=opts.opts2optimizer,
                optimizer_import=optimizer_import 
                )
            )
     
    return my_optimizer