Re: avoid the redefinition of a function

Discussion in 'Python' started by Tim Chase, Sep 12, 2012.

  1. Tim Chase

    Tim Chase Guest

    On 09/12/12 11:56, Jabba Laci wrote:
    >> For example:
    >>
    >> def install_java():
    >> pass
    >>
    >> def install_tomcat():
    >> pass

    >
    > Thanks for the answers. I decided to use numbers in the name of the
    > functions to facilitate function calls. Now if you have this menu
    > option for instance:
    >
    > (5) install mc
    >
    > You can type just "5" as user input and step_5() is called
    > automatically. If I use descriptive names like install_java() then
    > selecting a menu point would be more difficult. And I don't want users
    > to type "java", I want to stick to simple numbers.


    You can do something like the below that I tossed together in a
    couple minutes. It sniffs for globals callables (usually functions,
    though could be objects with a __call__ method) that are named
    "install_*" and then maps the user's numeric answer to the
    corresponding function and calls it.

    -tkc

    import sys
    PREFIX = "install_"
    def install_java(*args, **kwargs):
    print "Java!"
    def install_tomcat(*args, **kwargs):
    print "Tomcat!"
    def install_mc(*args, **kwargs):
    print "mc!"
    def install_exit(*args, **kwargs):
    sys.exit(0)

    functions = [
    (name, value)
    for name, value
    in sorted(globals().items())
    if name.startswith(PREFIX)
    and callable(value)
    ]
    dispatch = dict(
    (i+1, value)
    for i, (name, value)
    in enumerate(functions)
    )

    for i, (name, value) in enumerate(functions):
    print("%i) %s" % (i+1, name[len(PREFIX):]))

    while True:
    choice = raw_input("Choose to install/quit: ")
    try:
    i = int(choice)
    except:
    continue
    if i in dispatch:
    dispatch("some args")
    else:
    print("Please choose a valid option")
     
    Tim Chase, Sep 12, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jabba Laci

    avoid the redefinition of a function

    Jabba Laci, Sep 12, 2012, in forum: Python
    Replies:
    2
    Views:
    194
    Ramchandra Apte
    Sep 12, 2012
  2. D'Arcy Cain
    Replies:
    0
    Views:
    189
    D'Arcy Cain
    Sep 12, 2012
  3. Michael Torrie

    Re: avoid the redefinition of a function

    Michael Torrie, Sep 12, 2012, in forum: Python
    Replies:
    0
    Views:
    191
    Michael Torrie
    Sep 12, 2012
  4. Jabba Laci
    Replies:
    3
    Views:
    205
    Peter Otten
    Sep 13, 2012
  5. Terry Reedy
    Replies:
    0
    Views:
    189
    Terry Reedy
    Sep 12, 2012
Loading...

Share This Page