avoid the redefinition of a function
Tim Chase
python.list at tim.thechases.com
Wed Sep 12 13:34:06 EDT 2012
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[i]("some args")
else:
print("Please choose a valid option")
More information about the Python-list
mailing list