Problem deriving a class from the built-in file object

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pierre Rouleau

    #1

    Problem deriving a class from the built-in file object

    Hi all!

    I'm trying to extend the functionality of the file object by creating a
    class that derives from file. MyFile class re-implements __init__(),
    write(), writelines() and close() to augment the capabilities of file.

    All works fine, except for one thing: 'print >> myfile' does not
    execute Myfile.write(), it executes the file.write(). If I execute
    myfile.write() explicitly, then Myfile.write() is called as expected.

    I was not expecting that behaviour. I though that 'print >> afileobject
    ' would execute the afileobject.wri te() as you can easily obtain by
    defining a simple file-like class that implements write() and writeline().

    I am running Python 2.3.4. Can't move to 2.4 yet.

    Is it the expected behavior?



    # M y F i l e -- Testing inheritance from file --
    # ^^^^^^^^^^^
    #
    class MyFile(file):
    """ Testing new-style class inheritance from file"""

    #
    def __init__(self, name, mode="r", buffering=-1, verbose=False):
    """Constructor" ""

    self.was_modifi ed = False
    self.verbose = verbose
    super(MyFile, self).__init__( name, mode, buffering)
    if self.verbose:
    print "MyFile %s is opened. The mode is: %s" % (self.name,
    self.mode)

    #
    def write(self, a_string):
    """ Write a string to the file."""

    super(MyFile, self).write(a_s tring)
    self.was_modifi ed = True

    #
    def writelines(self , sequence):
    """ Write a sequence of strings to the file. """

    super(MyFile, self).writeline s(sequence)
    self.was_modifi ed = True

    #
    def close(self) :
    """Close the file."""

    if self.verbose:
    print "Closing file %s" % self.name

    super(MyFile, self).close()
    self.was_modifi ed = False




  • Peter Otten

    #2
    Re: Problem deriving a class from the built-in file object

    Pierre Rouleau wrote:
    [color=blue]
    > I'm trying to extend the functionality of the file object by creating a
    > class that derives from file.  MyFile class re-implements __init__(),
    > write(), writelines() and close() to augment the capabilities of file.
    >
    > All works fine, except for one thing:  'print >> myfile'  does not
    > execute Myfile.write(), it executes the file.write().   If I execute
    > myfile.write() explicitly, then Myfile.write() is called as expected.[/color]

    As a workaround, you can use delegation instead of inheritance:
    [color=blue][color=green][color=darkred]
    >>> class File(object):[/color][/color][/color]
    .... def __init__(self, *args):
    .... self.file = file(*args)
    .... def __getattr__(sel f, name):
    .... return getattr(self.fi le, name)
    .... def write(self, s):
    .... print "writing", s
    .... self.file.write (s)
    ....[color=blue][color=green][color=darkred]
    >>> f = File("tmp.txt", "w")
    >>> for s in ["alpha", "beta", "gamma"]:[/color][/color][/color]
    .... print >> f, s
    ....
    writing alpha
    writing

    writing beta
    writing

    writing gamma
    writing
    [color=blue][color=green][color=darkred]
    >>> f.close()
    >>> File("tmp.txt") .read()[/color][/color][/color]
    'alpha\nbeta\ng amma\n'
    [color=blue]
    > I was not expecting that behaviour.  I though that 'print >> afileobject
    > ' would execute the afileobject.wri te() as you can easily obtain by
    > defining a simple file-like class that implements write() and writeline().
    >
    > I am running Python 2.3.4.  Can't move to 2.4 yet.[/color]

    Nothing has changed with 2.4 in that respect.
    [color=blue]
    > Is it the expected behavior?[/color]

    I certainly didn't expect it either when I saw it for the first time.

    Peter

    Comment

    • Pierre Rouleau

      #3
      Re: Problem deriving a class from the built-in file object

      Peter Otten wrote:[color=blue]
      > Pierre Rouleau wrote:
      >
      >[color=green]
      >>I'm trying to extend the functionality of the file object by creating a
      >>class that derives from file. MyFile class re-implements __init__(),
      >>write(), writelines() and close() to augment the capabilities of file.
      >>
      >>All works fine, except for one thing: 'print >> myfile' does not
      >>execute Myfile.write(), it executes the file.write(). If I execute
      >>myfile.write( ) explicitly, then Myfile.write() is called as expected.[/color]
      >
      >
      > As a workaround, you can use delegation instead of inheritance:
      >
      >[/color]

      Good idea, thanks!
      [color=blue][color=green]
      >>Is it the expected behavior?[/color]
      >
      >
      > I certainly didn't expect it either when I saw it for the first time.
      >
      > Peter
      >[/color]

      Is it something that will (or should) be changed in future version of
      Python? I can't see any reason to keep the current behaviour.

      Pierre

      Comment

      Working...