-3

In C/C++, it is common to write a function which returns a success or failure flag and indicates the pass-by-reference object/list is ready to use. For example,

bool get_list(List& l)
{
    ...
    if (ready)
    {
        l = m_list
    }
    return ok
}

In python, I understand we can return more than one thing in a function but this does not look neat. What is the equivalent way to return the object/list and the boolean flag?

Edit

Thanks for the comments. I understand we should use exception in modern C++ code but you can see a lot of similar C/C++ code lying around. As mentioned in my question, I know we can return tuple in python (i.e. more than one thing -- sorry for not using the python context). I think I did not use the correct example which leads to the confusion here. For example, it can be something like if you want to return a member variable with list type when it is ready (some condition matches). Instead of returning the list and do the check outside, you can use a flag to indicate if the list is ready to use, which is more efficient.

But as per the below answers suggested, returning tuples is the way to achieve it.

chesschi
  • 666
  • 1
  • 8
  • 36
  • 5
    Possible duplicate of [What's the best way to return multiple values from a function in Python?](https://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python) – JLev Jan 03 '18 at 08:39
  • 2
    You actually shouldn't be doing this in modern C++ code. – StoryTeller - Unslander Monica Jan 03 '18 at 08:41
  • In C++ we tend to return the object by const reference if possible and throw an exception if things are going pear-shaped. – Bathsheba Jan 03 '18 at 08:41
  • 1
    I don't think that's *the way*, though. Python has very nice exceptions. I'd say that the idea (**most** of the time) is return only one value and break (throw an exception) if something didn't go ok – Savir Jan 03 '18 at 08:41
  • @BorrajaX, sometimes that is just a marriage to problems, sometimes is the solution, lets just stick to answer since there is never a holy grail for everything. – Netwave Jan 03 '18 at 08:44
  • 1
    I didn't write an answer, @Netwave And the OP is saying that it does not look neat. Indeed, it doesn't. And it is rarely used. – Savir Jan 03 '18 at 08:46
  • @chesschi i have added another possible solution to my answer, after the new edit you had. it is i think the answer you were looking for – Avishay Cohen Jan 03 '18 at 09:45
  • @JLev I do not mean to return multiple values explicitly. For example, it can mean to return a member object/list when it is ready. I have updated the question to reflect this – chesschi Jan 03 '18 at 09:49

3 Answers3

3

in python you can return a tuple of values

def get_object(object):
    # start of some code
    code
    # end of some code
    if ok:
        object = something

    return ok, object

and then have:

flag, result = get_object(myobj)

after the edit from OP, there's also the possibility of having the get_object be a kind of Mutator function follow the following logic example:

class classy(object):
    # this is your object
    def __init__(self):
        self.att = 1
        self.btt = 2

def mutate_obj(classy_obj):
    # this is your get_object for example
    # code
    ok = True  # or False whetever
    if ok:
        classy_obj.att = 10  # or a new classy, or any other object manipulation, on classy_obj
    return ok

then: in ipython:

In [4]: myclassy = classy()

In [5]: myclassy
Out[5]: <__main__.classy at 0x3c03250>

In [6]: myclassy.att
Out[6]: 1

In [7]: myclassy.btt
Out[7]: 2

In [8]: flag = mutator_func(myclassy)

In [9]: myclassy
Out[9]: <__main__.classy at 0x3c03250>

In [10]: myclassy.att
Out[10]: 10
Avishay Cohen
  • 1,978
  • 2
  • 21
  • 34
  • In modern C++ (c++17) you have structured bindings, which works similar to have returning a tuple of values: `auto [i, j] = function_that_returns_a_structure_pair_or_tuple_with_two_values();` – Clearer Jan 03 '18 at 09:26
  • Mutator function is the answer I'm looking for. Many thanks! – chesschi Jan 03 '18 at 10:07
1

Since you have tagged python also in the question I'm gonna go ahead and help you out in python. Introducing tuple unpacking to your rescue (Please do google it out).

def do_something(*args, **kwargs):
    some_data_structure = []        # optionally choose whatever DS you want here
    some_flag = False
    # write your logic to change or set the flag
    if some_flag:
       # write some logic here to manipulate your DS now
        some_data_structure.append(1) # just an example
    return (some_flag, some_data_structure)

returned_flag, data_structure = do_something() # make sure you study about tuple unpacking to understand it.

But also if you think you need to stick return one param then you can check the elements in your some_data_structure if that is empty then it means some_flag is False.

Play around and let me know if you need more help!

d-coder
  • 12,813
  • 4
  • 26
  • 36
1

Essentially what you want to do is return an optional value. Usually you do not need tuples for that at all because the extra indicator flag is superfluous. Returning None is the usual way to indicate no value. For example the get() method of Python’s built-in dictionaries returns the value if it exists, otherwise None (or an explicitly specified alternative value, but None is the default.)

This pattern is so common that it is explicitly supported in Python’s new type annotations as Optional[SomeType], which means either SomeType or None.

For that reason, unless you need None for something else, the most idiomatic way to solve your problem is:

def get_list():
    if ready:
        return the_list
    return None
besc
  • 2,507
  • 13
  • 10