#!/usr/bin/python

# pushfile.py
#       --copyright--                   Copyright 2007 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       January 12, 2007        bar
#       November 18, 2007       bar     turn on doxygen
#       November 20, 2007       bar     comments
#                                       next()
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       --eodstamps--
##      \file
#
#       File input whose readline() understands pushline().
#
#

class   a_pushfile(file) :
    """ Class that overloads built in 'file' class to allow text lines to be pushed back in to a file that the owner wants to call readline() on. """

    def __init__(me, name, mode = "r") :
        """ Constructor. """

        file.__init__(me, name, mode)

        me.pushed_lines     = []
        me.line_nm          = 0

        pass


    def next(me) :
        """ Overload routine to get the next text line starting with lines pushed. """

        if  len(me.pushed_lines) :
            return(me.pushed_lines.pop())

        me.line_nm += 1

        return(file.next(me))


    def readline(me) :
        """ Overload routine to get the next text line starting with lines pushed. """

        if  len(me.pushed_lines) :
            return(me.pushed_lines.pop())

        me.line_nm += 1

        return(file.readline(me))


    def pushline(me, li) :
        """ Push a text line back in to the file. """

        if  li :
            me.pushed_lines.append(li)
            # me.pushed_lines.insert(0, li)     # completely different logic, eh?

        return(li)

    pass        # a_pushfile


#
#
#
if __name__ == '__main__' :

    f   = a_pushfile("x.y")
    li  = f.readline()
    print li
    f.pushline("p1 " + li)
    f.pushline("p2 " + li)
    print   f.readline()
    print   f.readline()
    print   f.readline()

    f.close()

#
#
#
# eof
