JaysonFix
JaysonFix

Reputation: 2575

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?

Upvotes: 1

Views: 618

Answers (3)

zvone
zvone

Reputation: 19352

Python complains about object.__setattr__ (self, 'Value', newValue ) because self is not an object.

What you need is to inherit from object:

class  TempFileWithAttributes(object):

In Python3 that happens by default, but in Python2 it does not.

Upvotes: 2

Alex Martelli
Alex Martelli

Reputation: 881635

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.

Upvotes: 2

Lennart Regebro
Lennart Regebro

Reputation: 172249

First step: use setattr() instead of object.__setattr__()

Second step: Instead of setattr(anobject, 'string', value) just use anobject.string = value

Because your code makes no sense whatsoever. I can't even figure out what you are trying to do.

Upvotes: 0

Related Questions