difference with parenthese

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Mon Oct 17 11:25:34 EDT 2016


On 17.10.2016 16:45, chenyong20000 at gmail.com wrote:
> Hi Wolfgang,
>
> thanks for your kind reply. I try to explain what I got from your reply:
>
> for code1, when running "foo = outer()", since outer() is callable, function outer() is running and it returns an object, which referring to function inner(). When "foo" is running, it indicates it is referring to object inner(). When "foo()" is running, object inner() is called, so it prints "inside inner".
>
> for code2, when running "foo = outer()", since outer() is callable, function outer() is running and returns results from function inner(), which prints "inside inner". so "foo" now is a string, which contains "inside inner". since this string isn't a function, foo() will make an error.
>
> Do you think my understanding is right? thanks.
>
>
> regards
> skyworld chen
>

Not quite. Your understanding of code 1 is correct.
In your example code 2, however:

 > ----------------code 2-------------------------------
 > >>> def outer():
 > ...   def inner():
 > ...     print 'inside inner'
 > ...   return inner()
 > ...
 > >>> foo = outer()
 > inside inner
 > >>> foo
 > >>> foo()
 > Traceback (most recent call last):
 >   File "<stdin>", line 1, in <module>
 > TypeError: 'NoneType' object is not callable

calling outer returns the result of inner, as you are saying, but that 
result is *not* the string 'inside inner', but None (implicitly 
returned). As I explained before, the printed string is a side-effect of 
the function inner, but it is *not* what that function returns.

So:

foo = outer()

*prints* the string 'inside inner', but sets foo to refer to None. 
That's why the following TypeError mentions NoneType.

Best,
Wolfgang




More information about the Python-list mailing list