• 12
• 12
• 9
• 10
• 13

# Python: A dictionary of functions?

This topic is 4262 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Basicly what I'm trying to do is create a dictionary of functions so that I can call a function based upon a typed in command. The way I'm doing it right now is that I define a class for every command, and inside that class define a __call__ function in which I perform the actions I want. However, this seems sort of hackish. This is what I'm doing:
class Print_Class:
def __init__(self):
return
def __call__(self):
print "Print was Called"
return

and then I do this:
class Token:
done = False
var = "f"
Print_Command = Print_Class()
Call_Command = Call_Class()
Pi_Command = Pi_Class()

command_dict = {}
command_dict['Print'] = Print_Command
command_dict['Call'] = Call_Command
command_dict['Pi'] = Pi_Command

and when I call the function I do this: self.command_dict[self.var]() Is there any other way of doing this? Basicly, something like like an std::map<string, void (*funcptr)()>//Not sure on the syntax on that in C++, or am I doing it the right way?

##### Share on other sites
It sounds like what you want to do is use a dictionary of unbound (non-method) functions instead.

def Print_Command():    # ...    passdef Call_Command():    # ...    passdef Pi_Command():    # ...    passfunction_dict = {        "Print": Print_Command,        "Call": Call_Command,        "Pi": Pi_Command}# to execute any of these functions, simply do:token = "Print"function_dict[token]()To execute every function in alphabetical order, try:commands = function_dict.keys()commands.sort()for command in commands:    function_dict[command]

##### Share on other sites
Thanks, it worked.

EDIT: I couldn't get the dictionary to accept the functions before, which is why I switched to the class method. Apparently Python is quite picky [grin]

##### Share on other sites
Tac-tics is correct. You have to keep in mind that *everything* in Python is an object, including plain simple functions.

However, I don't think the first solution has anything particularly "hackish" in it, it could be useful in other situations.

##### Share on other sites
Quote:
 Original post by SticksandStonesApparently Python is quite picky [grin]

I don't think Python's that picky, but it can be a bit tricky.

Despite it's very precise, easy-going appearance, when it comes to how classes and functions as objects work, you can easily fall into some problems.

Always check your parenthesises with functions. Normally, if you have

def do():    print "Do!"# works as expected, prints "Do!" to the STDOUTdo() # uh oh! Returns a function object, prints nothing to the screen.do# Sometimes it can be even nastier...def get_some_primes():    return (2,3,5,7,11,13)# primes becomes the tuple: (2,3,5,7,11,13)primes = get_some_primes()# primes is *not* a a tuple of primes, it becomes a function.primes = get_some_primes # TypeError, unsubscribable object!primes [0]

Classes can be just as mean, because, although writting a class requires relatively few keywords, Python has more "behind the scenes" magic going on than even Java. I remember one particular trouble I had early on was with the __getattr__ attribute, which makes creating infinite loops easy as pie.

##### Share on other sites
You might want to have a look at the cmd module. shlex and asynchat may also be useful, depending on what you're doing.

##### Share on other sites
Quote:
 Original post by FrunyYou might want to have a look at the cmd module. shlex and asynchat may also be useful, depending on what you're doing.

Thanks!