krishna lodha
krishna lodha

Reputation: 417

How to add function as Value in dictionary in python?

I have another .py file where all functions are written, e.g.

def EqualToCheck(value, comparingValue, ExpectedVal:bool):
    if (value == comparingValue):
        return ExpectedVal
    else :
        return not ExpectedVal

def LessThanCheck(value, comparingValue, ExpectedVal:bool):
    if (value < comparingValue):
        return ExpectedVal
    else :
        return not ExpectedVal

I want to call these functions from another py file where I want to call these functions if my data has a certain string. e.g.

callFunc = {
 "checkEqual" : EqualToCheck(value, comparingValue, ExpectedVal),
 "lessthanEqual" : LessThanCheck(value, comparingValue, ExpectedVal)
}

I have already imported the py file, i.e. I'm able to access these functions, but I need to use these functions as a value for a dictionary.

so that I can call it something like this

if a == "checkEqual":
   callFunc['checkEqual'](5,6,True)

How can I do it?

Upvotes: 0

Views: 493

Answers (1)

gilch
gilch

Reputation: 11681

Use the functions themselves in the dict definition, without calling them:

callFunc = {
 "checkEqual": EqualToCheck,
 "lessthanEqual": LessThanCheck,
}

In Python, functions are first-class objects which live in the same namespaces as any other type of variables. A function definition creates a variable binding just like an assignment. You can use these variables in expressions like any other data type.

if a == "checkEqual":
   callFunc['checkEqual'](5,6,True)

Upvotes: 1

Related Questions