22

I'm using a recursive function to sort a list in Python, and I want to keep track of the number of sorts/merges as the function continues. However, when I declare/initialize the variable inside the function, it becomes a local variable inside each successive call of the function. If I declare the variable outside the function, the function thinks it doesn't exist (i.e. has no access to it). How can I share this value across different calls of the function?

I tried to use the "global" variable tag inside and outside the function like this:

global invcount  ## I tried here, with and without the global tag

def inv_sort (listIn):
    global invcount   ## and here, with and without the global tag

    if (invcount == undefined):  ## can't figure this part out
        invcount = 0

    #do stuff

But I cannot figure out how to check for the undefined status of the global variable and give it a value on the first recursion call (because on all successive recursions it should have a value and be defined).

My first thought was to return the variable out of each call of the function, but I can't figure out how to pass two objects out of the function, and I already have to pass the list out for the recursion sort to work. My second attempt to resolve this issue involved me adding the variable invcount to the list I'm passing as the last element with an identifier, like "i27". Then I could just check for the presence of the identifier (the letter i in this example) in the last element and if present pop() it off at the beginning of the function call and re-add it during the recursion. In practice this is becoming really convoluted and while it may work eventually, I'm wondering if there is a more practical or easier solution.

Is there a way to share a variable without directly passing/returning it?

2
  • What does your function currently return? Does it mutate listIn or create and return a new list?
    – jonrsharpe
    May 20, 2014 at 16:50
  • Well, I guess it returns a new list because I create a new list object to return, but it uses the same elements from the input list and just adds them in sorted order to the new list. You input a list and the function outputs the list in sorted order. I have it outputting the list in order correctly now, but I was just having an issue getting it to count the number of swaps or inversions in the ordering process, which was the actual assignment in my algorithms class. May 20, 2014 at 16:54

4 Answers 4

13

There's couple of things you can do. Taking your example you should modify it like this:

invcount = 0

def inv_sort (listIn):
    global invcount

    invcount += 1

    # do stuff

But this approach means that you should zero invcount before each call to inv_sort. So actually its better to return invcount as a part of result. For example using tuples like this:

def inv_sort(listIn):

    #somewhere in your code recursive call
    recursive_result, recursive_invcount = inv_sort(argument)

    # this_call_invcount includes recursive_invcount
    return this_call_result, this_call_invcount   
9
  • Can I return a list as part of a tuple? For example return this_list, this_integer? May 20, 2014 at 14:44
  • Yes, sure. Any object can be a part of a tuple
    – Alex Shkop
    May 20, 2014 at 14:47
  • Alright. Also, why exactly does this mean that I would have to zero-out the variable with each function call? I want the running total, and with local variables the value is forcibly reset to default. Are you saying the global variable is reset to 0 with each function call or are you suggesting I do this as best-practice? May 20, 2014 at 14:53
  • If you want to sort two lists you will have to assign invcount to zero, sort first list, store invcount value in other variable. Then set invcount to zero, sort second list and store its value. Otherwise after sorting two lists you will have sum of function calls for two sorts.
    – Alex Shkop
    May 20, 2014 at 14:57
  • 1
    I tried this out and it's working perfectly on all the test cases I've thrown at it so far. I'm selecting this as the answer since it includes both the easy answer (setting the invcount = 0 outside the function and then global invcount inside) and using the function to return both the sorted list and the count variable. Thanks! May 20, 2014 at 20:40
7

There's no such thing as an "undefined" variable in Python, and you don't need one.

Outside the function, set the variable to 0. Inside the loop, use the global keyword, then increment.

invcount = 0
def inv_sort (listIn):
    global invcount

    ... do stuff ...

    invcount += 1
4
  • So in this case, the inner global invcount only reserves the name of my variable in the internal namespace of the function? When I alter it, it will change the value of the outer variable with the same name? May 20, 2014 at 14:29
  • I'm not sure what you're asking. What global does is to tell the interpreter "in the current scope, the name "invcount" refers to the global variable" - so any assignment to that name affects the global variable. May 20, 2014 at 14:41
  • Ok, that's what I wanted to know. Thanks! May 20, 2014 at 14:54
  • can the global variable be a list?
    – Coddy
    May 26, 2020 at 20:35
5

An alternative might be using a default argument, e.g.:

def inv_sort(listIn, invcount=0):
    ...
    invcount += 1
    ...
    listIn, invcount = inv_sort(listIn, invcount)        
    ...
    return listIn, invcount

The downside of this is that your calls get slightly less neat:

l, _ = inv_sort(l) # i.e. ignore the second returned parameter

But this does mean that invcount automatically gets reset each time the function is called with a single argument (and also provides the opportunity to inject a value of invcount if necessary for testing: assert result, 6 == inv_sort(test, 5)).

4
  • This is an interesting idea. I didn't think about passing in the invcount variable, only passing it back out. I'll have to play around with it and see how it works. May 20, 2014 at 17:01
  • Also, you have a comma on the left side of the assignment operator - does this mean I could theoretically return a tuple and have each value of that tuple be assigned automatically to the corresponding variable on the left side? May 20, 2014 at 17:02
  • @AliumBritt yes, that is precisely what is happening - invcount returns a 2-tuple that is unpacked to two separate names e.g. l and _.
    – jonrsharpe
    May 20, 2014 at 17:03
  • Ok, I'm going to have to try the function out with that. Thanks! May 20, 2014 at 17:05
3

Assuming that you don't need to know the count inside the function, I would approach this using a decorator function:

import functools

def count_calls(f):
    @functools.wraps(f)
    def func(*args):
        func.count += 1
        return f(*args)
    func.count = 0
    return func

You can now decorate your recursive function:

@count_calls
def inv_sort(...):
    ...

And check or reset the count before or after calling it:

inv_sort.count = 0
l = inv_sort(l)
print(inv_sort.count)
6
  • So in this situation my inv_sort function would be a sub-function inside the count function? I'm not sure if I understand all the lines in your example. I've never used any function calls or declarations using the @ symbol. What exactly does using @ mean/do? May 20, 2014 at 14:50
  • @count_calls is syntactic sugar for inv_sort = count_calls(inv_sort) - the "decorator" function (count_calls) must take a function as an argument (f) and return a function (func). count isn't a function - it's an attribute of func, used to keep track of the number of times func is called (and therefore, as func calls f, how many times f is called).
    – jonrsharpe
    May 20, 2014 at 15:08
  • @AliumBritt note that I just corrected a typo - count_calls actually didn't return func!
    – jonrsharpe
    May 20, 2014 at 15:15
  • So, is this simply counting the number of times that the function is called? I actually need to know the results of various steps inside the function, so the number of times that I call the function won't be directly related to this value. In fact, I can call the function many times without ever incrementing my internal result variable invcount. May 20, 2014 at 15:17
  • @AliumBritt in that case, this approach probably isn't much use to you!
    – jonrsharpe
    May 20, 2014 at 15:30

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.