leban ali
leban ali

Reputation: 15

Call function from within dictionary

I've been trying to wrap my head around this problem, I've found a few solutions but no joy. Basically I have a dictionary with keys and a corresponding function. The purpose of the dictionary is to link to particular support guide. I take input from the user. Using this input i search the dictionary and if the keys the function is called.

Python3.6

class Help():
  def load_guide(self):
    while True:

        print("Which Guide would you like to view")

        for manual in Help.manuals:
            print (f"{manual}",end =', ')

        guide_input= input("\n> ")
        if guide_input in Help.manuals:

            Help.manuals.get(guide_input)
            return False 

        else:

            print("Guide not avalible")

  def manual():
      print("Build in progress")
  def introduction():
      print("Build in progress")


  manuals = {
  'Manual' : manual(),
  'Introduction' : introduction()
  }

I've tried a few variations but each presents a different problem.

Help.manuals[guide_input] | No action performed 
Help.manuals[str(guide_input)] | Error: TypeError: 'NoneType' object is not callable
Help.manuals[guide_input]() | Error: TypeError: 'NoneType' object is not callable
Help.manuals.get(guide_input) | No action performed

Upvotes: 1

Views: 44

Answers (1)

Aleksander Lidtke
Aleksander Lidtke

Reputation: 2926

When you initialise your dictionary like this:

def manual():
    print("Build in progress")

manuals = {'Manual' : manual()}`

the return value of the manual function will be stored in the dict because you call the function during the initialisation (manuals() is a function call). Because the function doesn't return anything, the value stored in the dictionary under the 'Manual' key is NoneType:

>>> type(manuals['Manual'])
<class 'NoneType'>

So you have to change the way the dictionary is initialised in order to have a reference to the function stored in the dict. You can do this by not calling the function during the dictionary initialisation (note the missing ()):

>>> manuals = {'Manual' : manual}
>>> type(manuals['Manual'])
<class 'function'>

Then all you need is get a reference to the function from the dictionary by using manuals['Manual'], and call that function manuals['Manual']().

>>> manuals['Manual']
<function manual at 0x7fb9f2c25f28>
>>> manuals['Manual']()
Build in progress

Upvotes: 2

Related Questions