Setting a read-only attribute

T

tleeuwenburg

I have an object and wish to set an attribute on it which,
unfortunately for me, is read-only.

How can I go about this?

Cheers.
-T
 
W

Wildemar Wildenburger

Arnaud said:
If it's read-only then you can't set it!


Joke aside, I think you need to be more specific.
To be more specific about much more specific you should be:
If you know the exact problem/hurdle you have to overcome, explain it.
Otherwise kindly provide the traceback (error message) you get when
attempting to set the attribute.

/W
 
G

Gerardo Herzig

I have an object and wish to set an attribute on it which,
unfortunately for me, is read-only.

How can I go about this?

Cheers.
-T
I guess we all need an code example to show us the way 'read only' is
implemented.
If you cant access to the class wich you are instantiated from, well,
maybe you can just post the error or exception you get.

Cheers.
Gerardo
 
J

James Stroud

I have an object and wish to set an attribute on it which,
unfortunately for me, is read-only.

How can I go about this?

Can you simply subclass the object's class, intercept __setattr__ and
__getattribute__, and spoof the read-only attribute? E.g.:

class A(object):
def get_ro(self):
return 'readonly'
ro = property(get_ro)

class B(A):
def __setattr__(self, anatt, aval):
if anatt == 'ro':
anatt = '_ro'
super(A, self).__setattr__(anatt, aval)
def __getattribute__(self, anatt):
if anatt == 'ro' and hasattr(self, '_ro'):
anatt = '_ro'
return super(A, self).__getattribute__(anatt)

The output:

py> class A(object):
.... def get_ro(self):
.... return 'readonly'
.... ro = property(get_ro)
....
py> class B(A):
.... def __setattr__(self, anatt, aval):
.... if anatt == 'ro':
.... anatt = '_ro'
.... super(A, self).__setattr__(anatt, aval)
.... def __getattribute__(self, anatt):
.... if anatt == 'ro' and hasattr(self, '_ro'):
.... anatt = '_ro'
.... return super(A, self).__getattribute__(anatt)
....
py> a = A()
py> print a.ro
readonly
py> a.ro = 4
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
<type 'exceptions.AttributeError'>: can't set attribute

py>
py> b = B()
py> b.x = 10
py> print b.x
10
py> print b.ro
readonly
py> b.ro = 4
py> print b.ro
4


I'm not so sure this is the least clunky way to do this.

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
 
A

Alexandre Badez

I have an object and wish to set an attribute on it which,
unfortunately for me, is read-only.

How can I go about this?

Cheers.
-T


Could you show the object you want to set his attribute?
Until that, it's difficult to answer to you.

PS: If the attribut is on read only, their must a good reason for
that ;)
 
S

Steve Holden

I have an object and wish to set an attribute on it which,
unfortunately for me, is read-only.

How can I go about this?
This seems like a bizarre requirement. Why is the attribute read-only in
the first place? How is the read-only mechanism enforced? Is the object
created in Python or in an extension module? Do you have any evidence
that "setting" the attribute will effect the required change in the
behavior of the object.

A little more information would be helpful.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------
 
T

tleeuwenburg

Could you show the object you want to set his attribute?
Until that, it's difficult to answer to you.

PS: If the attribut is on read only, their must a good reason for
that ;)

Hi all,

Thanks for all the responses. What I'm trying to do is kludge around
something. sys.settrace takes a method whose arguments are (frame,
event, arg). I want to have a tracer class which can be instantiated
and listen in on these trace calls.

Another way to go about it *might* be to have a module-level list of
registered Tracer objects which a module-level trace method informs of
events. It would probably be easier. In fact, I'll go do that.

*That said*, I still think it makes sense to be able to have objects
register with sys.settrace.

So what I did then was declare a static method with the same pattern
expected by sys.settrace. I then want to use something like __dict__
or __setattr__ to give that method a reference to the owning object.
And this is what I'm trying to do -- declare a static method, then "un-
static it" by adding a reference to the callable object...

Here's some code:
------------------------------------------------------------

import sys


class Tracer:
'''
Instantiate this in order to access program trace information.

'''

def _getcallback(self):

@staticmethod
def callback(frame, event, arg):
print "tracing ...", tracerReference
#print "line ", frame.f_lineno, frame.f_locals

return callback

def startTrace(self):
callback = self._getcallback()
callback.__dict__['tracerReference'] = self
sys.settrace(callback)


def foo(dict):
for i in range(2):
pass

if __name__ == "__main__":
t = Tracer()
t.startTrace()
foo({1 : 5})
 
S

Steve Holden

Could you show the object you want to set his attribute?
Until that, it's difficult to answer to you.

PS: If the attribut is on read only, their must a good reason for
that ;)

Hi all,

Thanks for all the responses. What I'm trying to do is kludge around
something. sys.settrace takes a method whose arguments are (frame,
event, arg). I want to have a tracer class which can be instantiated
and listen in on these trace calls.

Another way to go about it *might* be to have a module-level list of
registered Tracer objects which a module-level trace method informs of
events. It would probably be easier. In fact, I'll go do that.

*That said*, I still think it makes sense to be able to have objects
register with sys.settrace.

So what I did then was declare a static method with the same pattern
expected by sys.settrace. I then want to use something like __dict__
or __setattr__ to give that method a reference to the owning object.
And this is what I'm trying to do -- declare a static method, then "un-
static it" by adding a reference to the callable object...

Here's some code:
------------------------------------------------------------

import sys


class Tracer:
'''
Instantiate this in order to access program trace information.

'''

def _getcallback(self):

@staticmethod
def callback(frame, event, arg):
print "tracing ...", tracerReference
#print "line ", frame.f_lineno, frame.f_locals

return callback

def startTrace(self):
callback = self._getcallback()
callback.__dict__['tracerReference'] = self
sys.settrace(callback)


def foo(dict):
for i in range(2):
pass

if __name__ == "__main__":
t = Tracer()
t.startTrace()
foo({1 : 5})
Surely the thing to do, if I understand you, is to declare callback as a
standard method and then pass a reference to a bound method (the most
obvious candidate being self.callback) to sys.settrace().

sholden@bigboy ~/Projects/Python
$ cat test05.py
import sys


class Tracer:
'''
Instantiate this in order to access program trace information.

'''


def callback(self, frame, event, arg):
print "tracing ...", self
print "line ", frame.f_lineno, frame.f_locals

def startTrace(self):
sys.settrace(self.callback)


def foo(dict):
for i in range(2):
pass

if __name__ == "__main__":
t = Tracer()
t.startTrace()
foo({1 : 5})

sholden@bigboy ~/Projects/Python
$ python test05.py
tracing ... <__main__.Tracer instance at 0x7ff2514c>
line 19 {'dict': {1: 5}}

sholden@bigboy ~/Projects/Python
$

Does this do what you want?

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top