[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.


class foo(object):
    import sys
    def __init__(this, descriptor = sys.stdin):
        this.descriptor = descriptor

    def domumble(descriptor):
        for line in this.descriptor:
            return line.strip()

    def __call__(this):
        return this.domumble(this.descriptor)

class foo2(foo):
    def __init__(this, filename):
        this.filename = filename

    def __call__(this):
        with open(this.filename) as f:
            return this.domumble(f)

Now you use it like:

    results = foo(sys.stdin)()
    results = foo2('myfile')()


More information about the Baypiggies mailing list