AKKO
AKKO

Reputation: 1081

Difficulty comprehending the behavior of a function which has returned an empty list unto itself

I am working with some codes that make use of a property that is best exemplified with the examples below that I am demonstrating with my interpreter. I have difficulty understanding why the codes work the way they do.

In [377]: def a():
   .....:     return []
   .....: 

First I have defined a simple function that returns an empty list unto itself.

In [381]: a()
Out[381]: []

Next, I iterate over this function to try an print out something:

In [397]: for i in a():
   .....:     print a.hello
   .....:     print a.hello()
   .....:     

In [398]: 

I did not get any output. I noticed that I get the exact same thing when doing the for loop when I did a return of a tuple instead of list:

In [399]: def a():
   .....:     return ()
   .....: 

It seems to me that it has something to do with the list and tuples being empty. However, what really puzzled was why I did not get any sort of error when I called the hello attribute on a as part of the for loop. Shouldn't I be getting like a TypeError telling me that object a has no attribute hello and hello() or at least something along those lines? What's going on here?

I appreciate any explanations, and please correct my misconceptions if I'm mistaken.

Thank you.

Upvotes: 0

Views: 19

Answers (1)

mgilson
mgilson

Reputation: 309919

for whatever in a():
  do_stuff_with_whatever(whatever)

only executes do_stuff_with_whatever if a() returns an iterable that has elements in it. Otherwise, what would be the value of whatever on the first pass?

In other words, the statements a.hello and a.hello() never have a chance to get executed because there is nothing to iterate over. If you change your function to:

def a():
    return [1]

Then you'll start seeing an AttributeError because a has no hello attribute.

Upvotes: 2

Related Questions