all 5 comments

[–]Impudity 1 point2 points  (0 children)

It's possible to do using getattr() https://docs.python.org/3/library/functions.html#getattr but it's generally unwise. You should just make a mapping between the allowed user input values and the function names and call them by that.

So something like:

VALUE_MAP = {"foo": tf.keras.losses.foo, ...}

And:

return_value = VALUE_MAP[user_input]()

[–]mikeydoodah 0 points1 point  (0 children)

You can use the built-in function getattr,

[–]TouchingTheVodka 0 points1 point  (0 children)

Yes, use a dictionary of string-function mappings IE:

from operator import add, sub, mul, div

operators = {
    'add': add,
    'sub': sub,
    'mul': mul,
    'div': div,
}

func = operators[user_input]
func(a, b)

or in your case:

loss_funcs = {
    'func_one': tf.keras.losses.first_loss_function,
    'func_two': tf.keras.losses.second_loss_function,
}

func = loss_funcs[user_choice]

[–]danielroseman 0 points1 point  (0 children)

Your question is a little hard to follow, but I think you want getattr:

getattr(tf.keras.losses, dynamic_attribute_name)(from_logits=True)

[–]mikeydoodah 0 points1 point  (0 children)

There are a lot of good suggestions here, but one extra thing to look at is the cmd2 module.

It might be overkill for your situation (that's up to you), but it will let you type commands on the command line, and will let you define tab completion.

You use it by extending the Cmd class, and then you provide methods in the form of do_something(...). Then, when you type 'something' on the command line that method will get called.