Search code examples
pythonfilesubclassing

Python: file with programmer-defined attributes


Using Python 2.5, I'd like to create a temporary file, but add (& modify) attributes of my own. I've tried the following:

class  TempFileWithAttributes ( ) :
    __slots__   =   [   '_tempFile' ,  'Value'  ]
    def __init__ ( self ) :
        self._tempFile  =  tempfile.TemporaryFile()
        object.__setattr__ ( self, '_tempFile', tempfile.TemporaryFile() )
        object.__setattr__ ( self, 'Value', 123 )
    def __getattr__ ( self, name ) :
        if  name  ==  'Value' :
            object.__getattr__ ( self, 'Value' )
        elif  name  ==  '_tempFile' :
            return  getattr ( self._tempFile, name )
    def __setattr__ ( self, name, newValue ) :
        if name == 'Value' :
            object.__setattr__ ( self, 'Value', newValue )
        elif  name == '_tempFile' :
            setattr ( self._tempFile, newValue )

myFile  =  TempFileWithAttributes ( )
myFile.write ( 'Hello, Jayson!' )
print myFile.Value
myFile.Value  =  456
print myFile.Value
myFile.seek ( 0, os.SEEK_END )
print myFile.tell()

However, I am greeted with the following error messages:

object.__setattr__ ( self, '_tempFile', tempfile.TemporaryFile() )
TypeError: can't apply this __setattr__ to instance object

I've also tried subclassing file, but that wasn't working, either.

Any suggestions?


Solution

  • Why are you overriding __setattr__ at all?! You're not doing anything useful in your override -- and your override of __getattr__ isn't being very helpful either. I think what you want is rather something like:

    >>> class  TempFileWithAttributes(object):
    ...   __slots__ = ['_tempFile', 'Value']
    ...   def __init__(self):
    ...     self._tempFile  =  tempfile.TemporaryFile()
    ...     self.Value = 123
    ...   def __getattr__(self, name):
    ...     return getattr(self._tempFile, name)
    ... 
    

    This does let the rest of your sample code work, presumably as intended.