[Baypiggies] Conditional Context Managers
K. Richard Pixley
rich at noir.com
Tue Oct 27 18:45:32 CET 2009
I'm pretty new to python, so take me with a spoonful of sugar.
Your #2 doesn't work. The thing in the "with" statement isn't a
conditional. It's something that returns a context manager.
All of your ".readlines()" are redundant and can simply be dropped. A
file object is an iterator which returns the lines of it's content. And
you don't really want to iterate through all of those anyway. If your
datafile happens to have a billion lines, you can just skip reading
those other billion - 1.
Personally, I'd make it a class because I think explicit type testing
should be limited to very specific cases of language rewriting.
def __init__(this, descriptor = sys.stdin):
this.descriptor = descriptor
for line in this.descriptor:
def __init__(this, filename):
this.filename = filename
with open(this.filename) as f:
Now you use it like:
results = foo(sys.stdin)()
results = foo2('myfile')()
More information about the Baypiggies