Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass boolean argument by reference

In C++ you can always pass something as reference and anything that happens within the callee would be known to caller by just examining the referenced variable.

Imagine this scenario:

def x():
   a = f()
   print(a)

def f():
   return "hello"

What I want is add a boolean flag that returns from f to x. There are several ways to do that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. make f return a tuple (str,bool)
  2. pass a reference to a boolean variable into f

option 1 is currently not possible since there are many callers to f() and I cant change them to accept tuple as return value, so it must stay as it is.

option 2 is not possible since boolean argument is immutable (as I’ve learned recently).

Only f can calculate the boolean value, and x needs to know about it.

Is there any good way to achieve that? Looking for something that is not bad practice in Python coding in general.

>Solution :

The option that’s closest to passing a pointer/reference into f would be to pass it a mutable object, like a list:

def f(ok=None):
    if isinstance(ok, list):
        ok.append(True)
    return "hello"

def x():
    ok = []
    a = f(ok)
    print(a, ok.pop())

But the better solution IMO would be to return a tuple, and refactor that behavior into a new function so that you’re sharing code without disturbing the existing API:

def f_with_flag():
    return "hello", True

def f():
    return f_with_flag()[0]

def x():
    a, ok = f_with_flag()
    print(a, ok)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading