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:
- make f return a tuple (str,bool)
- 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)