0

disclaimer: My title may not be accurate as far as what I would like to accomplish, but I can update if someone can correct my terminology

I have 2 functions, each with a separate purpose and usable on its own, but occasionally I would like to combine the two to perform both actions at once and return a single result, and to do this I would like to assign to a variable name

I know I can create a 3rd function that does basically what I want as it is really simple.. though it's become a bit of a challenge to myself to find a way of doing this

def str2bool(string):
    return string.lower() in ("yes", "true", "t", "1")

def get_setting(string):
    if string == 'cat':
        return 'yes'
    else:
        return 'no'

VALID_BOOL = str2bool(get_setting)

print VALID_BOOL('cat')

So basically I would like to assign the combination of the 2 functions to a variable that I can call and pass in the string parameter to evaluate

In my real world code, get_setting() would retrieve a user setting and return the value, I would then like to test that value and return it as a boolean

Again I know I can just create a 3rd function that would get the value and do the quick test.. but this is more for learning to see if it can be done as I'm trying to do.. and so far my different variations of assigning and calling aren't working, is it even possible or would it turn too complex?

2
  • You can combine them like str2bool(get_setting(valid_string)). If you want a single name to call to chain both of them, you'll need a third function (which could just be a lambda, if you don't want to def it for whatever reason). Commented Dec 18, 2017 at 16:37
  • Sorry I had some typo's in the function names in my sample code, I've updated Commented Dec 18, 2017 at 16:42

1 Answer 1

1

Using lambda is easy, but i don't know if it is exactly what you are looking for.

Example:

f = lambda astring : str2bool(get_setting(astring))

Outputs:

>>> f('cat')
True
Sign up to request clarification or add additional context in comments.

2 Comments

Damn.. I could have sworn I tried it with lambda! Must have messed up the syntax, this works perfect thanks!
Glad i could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.