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?
Your
open_file()
function doesn't actually return anything. What you want is: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 executeread_file(None)
, which in turn tries to executeNone.read()
.None
objects do not have aread()
method.