It is quite risky to call unknown user input directly.
The allowed function names can be put as keys in a dictionary pointing to the actual functions:
def intercept():
print("Function intercept.")
user_functions = dict(
intercept=intercept,
# ...
)
user_input = input("Input function name: ") # Python 3, raw_input for Python 2
if user_input in user_functions:
user_functions[user_input]()
else:
print("Error: Unknown function.")
Result:
$ python3 test.py
Input function name: intercept
Function intercept.
$ python3 test.py
Input function name: foobar
Error: Unknown function.
Functions can also be dynamically created, e.g.:
def intercept():
print("Function intercept.")
def jimmy():
print("Function Jimmy.")
user_functions = {
'intercept': intercept,
# ...
}
def create_new_profile(name):
print("Creating profile for " + name)
def profile_function():
print("Profile " + name)
user_functions[name] = profile_function
while 1:
user_input = input("Input function name: ")
if user_input in user_functions:
user_functions[user_input]()
else:
create_new_profile(user_input)
print()
Result:
$ python3 test.py
Input function name: intercept
Function intercept.
Input function name: Jimmy
Creating profile for Jimmy
Input function name: Alice
Creating profile for Alice
Input function name: Alice
Profile Alice
Input function name: Bob
Creating profile for Bob
Input function name: Bob
Profile Bob
Input function name: Alice
Profile Alice
I do not know, what the "profile functions" are supposed to do. Maybe, a data driven approach may be better. A dictionary maps user names to user data. If the user input name is not inside the profile dictionary, then the function create_new_profile
is called that adds the new user. The following example implements the user data as class including the function that is run.
class UserProfile:
def __init__(self, name):
self.name = name
def run(self):
print("User: " + self.name)
def intercept():
print("Function intercept.")
user_profiles = {
'Jimmy' : UserProfile('Jimmy'),
}
def create_new_profile(name):
print("Creating new profile for " + name)
user_profiles[name] = UserProfile(name)
user_functions = {
'intercept': intercept,
# ...
}
while 1:
user_input = input("Input function name: ")
if user_input in user_functions:
user_functions[user_input]()
elif user_input in user_profiles:
user_profiles[user_input].run()
else:
create_new_profile(user_input)
print()
$ python3 test.py
Input function name: intercept
Function intercept.
Input function name: Jimmy
User: Jimmy
Input function name: Alice
Creating new profile for Alice
Input function name: Alice
User: Alice