2

Morning all,

Can someone advise, is it possible to achieve something like this:

def myFunction(someParam)
   if someParam == 1:
      return "This and that"
   else:
      return None

someVariable = someVariable || myFunction(valuePassedIn)

ie, given "someVariable" has an existing value, I want to preserve that value, or replace it with the value returned from "myFunction", provided that is not None?

Obviously, I can do something like:

if myFunction(valuePassedIn) != None:
    someVariable = myFunction(valuePassedIn)

But this of course is calling myFunction twice. Alternatively, I could do:

myFuncRes = myFunction(valuePassedIn)
if MyFuncRes != None:
    someVariable = myFuncRes

But it'd be good if I could reduce this to a single line of code, as per my "||" line in the first code snippet above. Obviously I've seen the conditional expressions documentation, but unless I'm misunderstanding, this would still involve calling myFunction twice?

I guess one other option would be to pass someVariable in as an additional param to myFunction and use this as the "else" return instead of None, but I can't help feeling this is kinda messy - and Python probably has something more slick I could use?

Thanks

3
  • Note that if someParam = 1 in your myFunction is actually doing an assignment, not a comparison. Commented Nov 28, 2014 at 9:31
  • 1
    @Wieland it would be if it wasn't a SyntaxError Commented Nov 28, 2014 at 9:35
  • Sorry, typo on my part.... Edited ;) Commented Nov 28, 2014 at 9:37

1 Answer 1

4

Yes you can do this

Please check below code

>>> a = 1
>>> def test(b):
...     return b*10
...
>>> c = a or test(2)
>>> c
1
>>> a = 0
>>> c = a or test(2)
>>> c
20
Sign up to request clarification or add additional context in comments.

Comments

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.