0

I need some help trying to figure out how do I call a specific method based on user input. Example I've got an app called main_app.py that is structured as follows:

|main_app.py
|operations
    - __init__.py
    - operation_model.py
    - operation1.py
    - operation2.py

I want a way to call the appropriate operation based on user args for main_app.py. Example:

$ main_app.py --operation operation2

Since user wrote operation2, I want main_app to use operation2.logic method. Operations are defined by other users, and use the Operation class defined in operation_model.py as a template:

class Operation:
   def logic(self, site_code):
       pass

operation1.py looks like:

from operation_model import Operation 
operation1 = Operation()

def custom_function():
    print("This is my custom function")
    input("Enter something")

operation1.logic = custom_function()

I can't simply import operation1 or else it will execute the code. Wondering if there is a way to register the different operations and execute one based on user input? I was looking at options like class-registry and decorators to register but I can't figure out what they do. Any help would be appreciated. Open to other implementations of operations, but has to follow some structure.

PS: Is there a way we can pass further args to operations as well?

CybaTronX
  • 29
  • 6
  • Seems that you want: https://stackoverflow.com/questions/301134/how-to-import-a-module-given-its-name-as-string. – CristiFati Jul 15 '21 at 12:42
  • Seems like you want something like https://www.programiz.com/python-programming/methods/built-in/globals or https://docs.python.org/3/library/importlib.html#importlib.import_module – Ana Lívia Jul 15 '21 at 12:53
  • `operations = {"+": operation_add, ...}`, `text = input()` `func = operations[text]` and finally `func(args)` – furas Jul 15 '21 at 14:49
  • in `operation1.py` you should keep code in function and then you can `import operation1` and execute it only when you need it `operation1.some_function()` – furas Jul 15 '21 at 14:51

0 Answers0