Function calling a function; why does this return NoneType instead of reading file?

88 views Asked by At

After reading about file objects in Pydoc as well as seeing how functions can call functions, I rewrote one of Zed Shaw's LPTHW scripts in an attempt to understand how it works.

Here is the code:

def open_file(f):
    open(f)

def read_file(f):
    f.read()

read_file(open_file('test.txt'))

And here is the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in read_file
AttributeError: 'NoneType' object has no attribute 'read'

And yet this works fine:

input_file = 'test.txt'

print open(input_file).read()

Why does the function calling a function version return NoneType instead of reading the file?

2

There are 2 answers

1
glibdud On BEST ANSWER

Your open_file() function doesn't actually return anything. What you want is:

def open_file(f):
    return open(f)

A function that reaches its end without explicitly returning a value returns None, so you're getting the exception because your code is trying to execute read_file(None), which in turn tries to execute None.read(). None objects do not have a read() method.

3
MadHatter On

Here is the answer:

def open_file(f):
    return open(f)

def read_file(f):
    print f.read()

read_file(open_file('test.txt'))

Which gives the output of:

Mary had a little lamb.
Its fleece was white as snow.
It was also very tasty.