Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

functions running in list as parameter

I am making a library for creating text adventure games.

Here is my main.py code:

from txtadvlib import utils

utils.menu("Main Menu", ["play","about","quit"])
utils.getInput(prompt="user>",
               ifs=[
                 "1",
                 "2",
                 "3"
               ],
               thens=[
                 print(1),
                 print(2),
               ],
               catch="print('caught')"
              )

Here is the code I use for the library:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import os
import time
import random
import colorama
from datetime import date
from colorama import Fore

class utils:
  def menu(title,optionsArray,):
    print(title)
    cycles = 0
    for i in optionsArray:
      cycles += 1
      print(f"[{cycles}].{i}")
      
  def getInput(prompt, ifs, thens, catch):
    choice = input(prompt)
    for i in ifs:
      if choice == i:
        eval(thens[ifs.index(i)])
        break
      else:
        eval(catch)

I do not want to be using eval for every function as it requires the library user to format any functions as strings.

Here is the problem:
the functions in the thens list run immediately and then the input goes.

Here is the output:

Main Menu
[1].play
[2].about
[3].quit
1    <--- function in the list ran
2    <--- function in the list ran
user>   <--- input prompt

I have tried making the function parameters one line, and I can’t think of anything else to try.

>Solution :

You could expect the library user to pass in a callable, which will be called in case this option is selected:

...
import functools 

def catch():
  print('caught')

utils.getInput(prompt="user>",
               ifs=[
                 "1",
                 "2",
                 "3"
               ],
               thens=[
                 lambda: print(1),
                 functools.partial(print, 2),
               ],
               catch=catch
              )

Then you code should look sth like this:

...
  def getInput(prompt, ifs, thens, catch):
    choice = input(prompt)
    for i in ifs:
      if choice == i:
        thens[ifs.index(i)]()
        break
      else:
        catch()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading