Comment 5 for bug 1324972

Revision history for this message
Daniel Reed (nmlorg) wrote :

I ended up implementing this in:

https://github.com/nmlorg/metabot/blob/c63dfce6e1e9556ef1b22133b8bfd3de97ebc9c1/metabot/util/tzutil.py

(It looks like I just changed `pieces = line.split(None, 4)` to `pieces = line.rstrip().split(None, 3)`.)

An example use is:

https://github.com/nmlorg/metabot/blob/c63dfce6e1e9556ef1b22133b8bfd3de97ebc9c1/metabot/util/adminui.py#L290

And as early as Python 2.7.15, at least, generator functions don't execute *any* statements until the first attempt to dereference them:

```
>>> def F():
... print "I'm running!"
... with open('/usr/share/zoneinfo/zone.tab') as fobj:
... print "I've opened zone.tab!"
... for line in fobj:
... print 'I read %r!' % line
... yield line
... print "I'm done reading!"
... print "I'm done executing!"
...
>>> ZONE_TAB = F()
>>> for _ in ZONE_TAB: pass
...
I'm running!
I've opened zone.tab!
I read '# tzdb timezone descriptions (deprecated version)\n'!
I read '#\n'!
 [...]
I read 'ZW\t-1750+03103\tAfrica/Harare\n'!
I'm done reading!
I'm done executing!
```

Specifically:

```
>>> ZONE_TAB = F()
>>> ZONE_TAB.next()
I'm running!
I've opened zone.tab!
I read '# tzdb timezone descriptions (deprecated version)\n'!
'# tzdb timezone descriptions (deprecated version)\n'
>>> ZONE_TAB.next()
I read '#\n'!
'#\n'
>>>
```

This seems to be intended behavior; from https://www.python.org/dev/peps/pep-0255/:

"When a generator function is called, [...] no code in the body of the function is executed. Instead a generator-iterator object is returned [...]

Each time the .next() method of a generator-iterator is invoked, the code in the body of the generator-function is executed until a yield or return statement (see below) is encountered, or until the end of the body is reached.

If a yield statement is encountered, the state of the function is frozen, and the value of expression_list is returned to .next()'s caller."

I actually just popped in and need to run again, but if that still sounds alright I'd be happy to put together an updated patch without "with".