-2

This is a function I've defined:

import sys

def hello():
    print("hello")

class parser():

    def parseSubcommand(self, name, function):
        if name == sys.argv[1]:
            result = function()
            return(result)


    def findArgument(self, name, function):
        print("dummy") #not started working on findArgument yet

But when I try to call it like this:

parser().parseSubcommand(name="hello", function="hello")

I'm getting the error

function() TypeError: 'str' object is not callable

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
reuta
  • 101
  • 6

3 Answers3

1

You can do the following:

def function1():
    return 'hello world'

def function2(function_to_run):
    result = function_to_run()
    return result

function2(function1)
DeJaVo
  • 3,091
  • 2
  • 17
  • 32
1

You need to map the functions to the string representation of their names:

def hello():
    print("hello")

class parser():    
    funcs = {"hello": hello}
    def parseSubcommand(self, name):
         return self.funcs.get(name,lambda: print("Invalid name"))()



parser().parseSubcommand(name="hello")
parser().parseSubcommand(name="foo")
hello
Invalid name

Which if you are using sys.argv[1] you will need as you will always be getting strings.

If you want to take args using argparse for python3 or optaprse for python2 might be a better idea.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

hello is not the same as "hello"

"hello" is a string that can only be used as a string. It can't refer to variables unless used as a dictionary key to access a specific reference.

You want to use hello because that's the actual name of your function. Variable names are never accessed by string.

parser().parseSubcommand(name="hello", function=hello)

If you need to pass in the function names as a string, then you need to reference them in a dictionary, like this:

functionNames = {"hello":hello}
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73