You are not logged in.

#1 2014-01-17 21:55:54

alphaniner
Member
From: Ancapistan
Registered: 2010-07-12
Posts: 2,810

[Brainfart] (Python) Why does this function return None?

Edit: Durrr. Apparently I had a senior moment. The solution, of course, is that line 7 of the function must be return splitstring(c, list)

Before I realized Python strings have a split() method, I made the following function:

def splitstring(string, list=None):
    if list is None:
        list = []
    a, b, c = string.partition(' ')
    list.append(a)
    if c:
        splitstring(c, list)
    else:
         return list

But it returns None unless no splitting is done, and I don't understand why.

>>> if splitstring('d s t n') is None:
...  print('WTF!?!')
... 
WTF!?!

If I print(list) instead of return list, the expected list is printed. So list isn't actually None...

Last edited by alphaniner (2014-01-17 22:02:47)


But whether the Constitution really be one thing, or another, this much is certain - that it has either authorized such a government as we have had, or has been powerless to prevent it. In either case, it is unfit to exist.
-Lysander Spooner

Offline

#2 2014-01-17 22:02:43

benob
Member
Registered: 2008-11-11
Posts: 187

Re: [Brainfart] (Python) Why does this function return None?

My guess is that your there is a codepath in your function that doesn't return anything, which is python is None.

if c:
    splitstring(c, list)
    # nothing returned
else:
    return list

Offline

#3 2014-01-24 21:20:53

Boris Bolgradov
Member
From: Bulgaria
Registered: 2008-07-27
Posts: 185

Re: [Brainfart] (Python) Why does this function return None?

Remove the else, it must return the list after the recursion ends.

if c:
    splitstring(c, list)
return list

Offline

#4 2014-01-24 23:01:21

alphaniner
Member
From: Ancapistan
Registered: 2010-07-12
Posts: 2,810

Re: [Brainfart] (Python) Why does this function return None?

This really was just a brainfart. I've made functions like this before, always in the form

if foo:
    return foobar
else:
    return bar

I've even explained to others why that works and what I originally posted fails. Oy.

But I had never realized it could be done in the way you suggest. Thanks!


But whether the Constitution really be one thing, or another, this much is certain - that it has either authorized such a government as we have had, or has been powerless to prevent it. In either case, it is unfit to exist.
-Lysander Spooner

Offline

Board footer

Powered by FluxBB