473,387 Members | 1,548 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

readonly class attribute ?

Hi

How can I make a *class* attribute read-only ?

The answer must be pretty obvious but I just can't find it (it's late
and I've spent all day on metaclasses, descriptors and the like, which,
as fun as it is, may have side-effects on intellectual abilities...)

*The context:*

# library code
class AbstractBaseClass(object):
# snip some stuff here,
# a part of it depending on the derived classes
# defining class attribute class_private_attrib

# client code
class SubClass(AbstractBaseClass):
class_private_attrib = "my private attrib"
# snip
*What I'm looking for: (if possible)*
SubClass.class_private_attrib "my private attrib"SubClass.class_private_attrib = "toto" AttributeError : SubClass.class_private_attrib is read onlys = SubClass()
s.class_private_attribute = "toto" AttributeError : SubClass.class_private_attrib is read only

*What I've tried: (simplified as possible)*

class ReadOnlyDescriptor(object):
def __init__(self, name, initval=None):
self._val = initval
self._name = name

def __get__(self, obj, objtype):
print 'Retrieving', self._name
return self._val

def __set__(self, obj, val):
raise AttributeError, \
"%s.%s is ReadOnly" % (obj.__class.__.__name__, self._name)

class SubClass(object):
class_private_attrib = ReadOnlyDescriptor("class_private_attrib",
"my private attrib")
# snip

*What i get:*SubClass.class_private_attrib Retrieving class_private_attrib
"my private attrib"SubClass.class_private_attrib = "toto"
SubClass.class_private_attrib "toto"SubClass.__dict__['class_private_attrib'] "toto" s = SubClass()
s.class_private_attrib

"toto" # of course :(

*What I understand:*
Ok, I've re-read the manual, noticed that data descriptors __set__()
method was only called when an instance attribute is set (which is
obvious from the prototypes of the methods). My solution is plain wrong
and I should have guess without ever trying. duh :(
Now please have mercy, you Noble Pythoneers : what's the trick to
prevent client code to accidentally mess with the class's dict ? (most
client code - apart from subclass definitions - shouldn't even bother
about the existence of this attribute, it's there for the library
internal usage)

NB : in the real code I'm also messing with the AbstractBaseClass's
meta_class for other stuff (so it's not a problem if the solution
involves metaclasses), but I've tested with the simplified example
above, which exhibits the same problem.

TIA
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 18 '05 #1
4 2579
Start the attribute name with "_" and don't document it. If clients
mess with it, they're to blame.

Jul 18 '05 #2
On Tue, 15 Mar 2005 20:21:19 +0100, bruno modulix <on***@xiludom.gro> wrote:
Hi

How can I make a *class* attribute read-only ?

The answer must be pretty obvious but I just can't find it (it's late
and I've spent all day on metaclasses, descriptors and the like, which,
as fun as it is, may have side-effects on intellectual abilities...)

*The context:*

# library code
class AbstractBaseClass(object):
# snip some stuff here,
# a part of it depending on the derived classes
# defining class attribute class_private_attrib

# client code
class SubClass(AbstractBaseClass):
class_private_attrib = "my private attrib"
# snip
*What I'm looking for: (if possible)*
SubClass.class_private_attrib"my private attrib"SubClass.class_private_attrib = "toto"AttributeError : SubClass.class_private_attrib is read onlys = SubClass()
s.class_private_attribute = "toto"AttributeError : SubClass.class_private_attrib is read only

*What I've tried: (simplified as possible)*

class ReadOnlyDescriptor(object):
def __init__(self, name, initval=None):
self._val = initval
self._name = name

def __get__(self, obj, objtype):
print 'Retrieving', self._name
return self._val

def __set__(self, obj, val):
raise AttributeError, \
"%s.%s is ReadOnly" % (obj.__class.__.__name__, self._name)

class SubClass(object):
class_private_attrib = ReadOnlyDescriptor("class_private_attrib",
"my private attrib")
# snip

*What i get:*SubClass.class_private_attribRetrieving class_private_attrib
"my private attrib"SubClass.class_private_attrib = "toto"
SubClass.class_private_attrib"toto"SubClass.__dict__['class_private_attrib']"toto" s = SubClass()
s.class_private_attrib"toto" # of course :(

*What I understand:*
Ok, I've re-read the manual, noticed that data descriptors __set__()
method was only called when an instance attribute is set (which is
obvious from the prototypes of the methods). My solution is plain wrong
and I should have guess without ever trying. duh :(
Now please have mercy, you Noble Pythoneers : what's the trick to
prevent client code to accidentally mess with the class's dict ? (most
client code - apart from subclass definitions - shouldn't even bother
about the existence of this attribute, it's there for the library
internal usage)

NB : in the real code I'm also messing with the AbstractBaseClass's
meta_class for other stuff (so it's not a problem if the solution
involves metaclasses), but I've tested with the simplified example
above, which exhibits the same problem.

Does this help, or did I misunderstand?
class Base(object): ... class __metaclass__(type):
... def __setattr__(cls, name, value):
... raise AttributeError, 'setting %r to %r not allowed' %(name, value)
... class Sub(Base): ... def m(self): print 'method m called'
... x = 123
... obj = Sub()
Instance attributes work normally: obj.x 123 obj.x = 456
obj.x 456 del obj.x
If not shadowed, the class var is found Sub.x 123

But it is read-only: Sub.x = 456 Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in __setattr__
AttributeError: setting 'x' to 456 not allowed
Base.x = 456 Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in __setattr__
AttributeError: setting 'x' to 456 not allowed Sub.anything = 'something'

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in __setattr__
AttributeError: setting 'anything' to 'something' not allowed

Regards,
Bengt Richter
Jul 18 '05 #3
Simon Percivall a écrit :
Start the attribute name with "_" and don't document it. If clients
mess with it, they're to blame.


The problem is that client code must *define* this attribute when
subclassing BaseClass - and that's (well, in most case that should be)
the only place where they have to deal with it (unless they want to do
mumbo-jumbo thangs, in which case that's not my problem anymore !-).

What I want is to prevent client code to accidentally mess with it, and
have strange bugs that they may have hard time to fix. At the same time,
I want to have the cleanest syntax for the subclass declaration. In
fact, in most cases, the client code should not have much more to do
than defining a handfull of class attributes to end up with a
taylor-made fully functional subclass.

Bruno
Jul 18 '05 #4
Bengt Richter a écrit :
On Tue, 15 Mar 2005 20:21:19 +0100, bruno modulix <on***@xiludom.gro> wrote:

Hi

How can I make a *class* attribute read-only ?
(snip)

Does this help, or did I misunderstand?
>>> class Base(object):

... class __metaclass__(type):
... def __setattr__(cls, name, value):
... raise AttributeError, 'setting %r to %r not allowed' %(name, value)


Pretty obvious, indeed !

Bengt, if we meet one day, remind me to pay you a couple of your
favorite drink !-)
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Matt | last post by:
I want to know if readOnly attribute doesn't work for drop down list? If I try disabled attribute, it works fine for drop down list. When I try text box, it works fine for both disabled and...
2
by: Alan | last post by:
Hi all, I have one class including one collection. I use propertygrid to display and edit its properties. I'm trying to use reflection to change the status of one element to be readonly, for...
0
by: Brian Young | last post by:
Hi all. I'm using the Property Grid control in a control to manage a windows service we have developed here. The windows service runs a set of other jobs that need to be managed. The control...
5
by: fred | last post by:
With a Class is there any difference between a readonly property and function besides having to use Get/End Get. Are there any performance/resource advantages for either. Thanks Fred
3
by: Tom | last post by:
I'm using the PropertyGrid, and have it bound to a class object. Works fine - however, I have some properties that I want to show up on the grid (i.e. they are browsable) -YET- I don't want the...
7
by: Jimbo | last post by:
Hi, I am trying to set the readonly attribute of a text input tag dynamically from javascript. The input element already exists in the form and I want to make it readonly when a particular...
1
by: Raja | last post by:
Hi Everybody Just playing with ObjectDataSource and noticed the following. I have a Gridview which binds to a ObjectDataSource. ObjectDataSource gets data from a typed dataset created with VWD. In...
3
by: Hamed | last post by:
Hello I have a DataGrid object in my ASP.NET page that has the following template column. When I put the "readonly" attribute in the INPUT tag, it generates readonly="". <asp:TemplateColumn...
10
by: sunil | last post by:
Hello, I am new to c# . I have some basic programming doubts. Please help me in clarifying these doubts. I want to initialize a static and readonly field with a value returned by a static...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.