473,883 Members | 1,646 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

design question: no new attributes

I have a class whose instances should only receive attribute
assignments for attributes that were created at inititializatio n.
If slots are not appropriate, what is the Pythonic design for this?

Thanks,
Alan Isaac
Feb 26 '07 #1
28 1485
Alan Isaac wrote:
I have a class whose instances should only receive attribute
assignments for attributes that were created at inititializatio n.
If slots are not appropriate, what is the Pythonic design for this?

Thanks,
Alan Isaac

My understanding of "Pythonic design" is not to worry about it.
If users want to set attributes that won't accomplish anything
productive (within your class) let them.

-Larry
Feb 26 '07 #2
"Alan Isaac" <ai****@america n.eduwrites:
I have a class whose instances should only receive attribute
assignments for attributes that were created at inititializatio n.
If slots are not appropriate, what is the Pythonic design for this?
The Pythonic design is: don't expect to have such control over users
of your code. (I encountered this in trying to design an Enum class,
with enumeration members as attributes.)

Document, in the class doc string and anywhere else you feel
appropriate, the fact that attributes shouldn't be added, and let your
users deal with their own bugs if they ignore that.

--
\ "No one ever went broke underestimating the taste of the |
`\ American public." -- Henry L. Mencken |
_o__) |
Ben Finney

Feb 27 '07 #3
"Ben Finney" <bi************ ****@benfinney. id.auwrote in message
news:ma******** *************** *************** *@python.org...
The Pythonic design is: don't expect to have such control over users
of your code.
I know this is a popular response,
but the fact of the matter remains that
it can be helpful to know when someone
tries to set a value for a nonexisting attribute.
This is especially true if there have been any
interface changes.

So my question remains:
how best to trap any such attempt
subsequent to object initialization?
(I am willing to have properties for
all data attributes, if that helps.)

Thank you,
Alan Isaac
Feb 27 '07 #4
On Tue, 27 Feb 2007 06:40:29 +0000, Alan Isaac wrote:
"Ben Finney" <bi************ ****@benfinney. id.auwrote in message
news:ma******** *************** *************** *@python.org...
>The Pythonic design is: don't expect to have such control over users
of your code.

I know this is a popular response,
It's popular for good reason.

but the fact of the matter remains that
it can be helpful to know when someone
tries to set a value for a nonexisting attribute.
I'm afraid your understanding of the word "fact" is different from my
understanding of the word "fact".

But be that as it may, if you wish to waste^H^H^H^H^H spend time
trying to prevent people from adding attributes to their instances,
Just Because, you can do something like this:

class Difficult(objec t):
def __setattr__(sel f, name, value):
if self.__dict__.h as_key(name):
print "'%s' exists as an instance attribute" % name
self.__dict__[name] = value
elif self.__class__. __dict__.has_ke y(name):
print "'%s' exists as a class attribute" % name
self.__class__. __dict__[name] = value
else:
print "Can't create new attributes, 'cos I said so!"
There ought to be a name for that anti-pattern of molly-coddling,
bondage-and-domination philosophy of "you're only allowed to use my class
the way I want you to use it".

(Excuse my cynicism, for all I know you've got a really good reason for
wanting to do this, perhaps as part of a cold-fusion machine.)

--
Steven D'Aprano

Feb 27 '07 #5
On 27 Feb, 06:40, "Alan Isaac" <ais...@america n.eduwrote:
So my question remains:
how best to trap any such attempt
subsequent to object initialization?
(I am willing to have properties for
all data attributes, if that helps.)
You can define the __setattr__ method in your class as

def __setattr__(sel f, attr, val):
if hasattr(self, attr):
self.__dict__[attr] = val
else:
# Tell the user off

but of course the user can set attributes through
instance.__dict __['attrname'] = val

So to really do it you would need to design your own metaclass

--
Arnaud
Feb 27 '07 #6
"Alan Isaac" <ai****@america n.eduwrites:
"Ben Finney" <bi************ ****@benfinney. id.auwrote:
The Pythonic design is: don't expect to have such control over
users of your code.

I know this is a popular response, but the fact of the matter
remains that it can be helpful to know when someone tries to set a
value for a nonexisting attribute.
That's quite a different request from your original request asking the
Pythonic design for *preventing* setting of new attributes.
This is especially true if there have been any interface changes.
If the interface has changed, then you don't need to trap *every*
setting of an attribute; only the names that you know have changed.

===== foo_v1.py =====

class Foo(object):
def bar(self):
return 17

spam = 42
=====

===== foo_v2.py =====

import logging

class Foo(object):
def baz(self):
return 13

eggs = 69

def bar(self):
""" Obsolete interface for Foo.baz() """
logging.warn("D eprecated Foo.bar() call, please use Foo.baz()")
return self.baz()

def _get_spam(self) :
""" Obsolete interface for Foo.eggs """
logging.warn("D eprecated Foo.spam reference, please use Foo.eggs")
return self.eggs
def _set_spam(self, value):
""" Obsolete interface for Foo.eggs """
logging.warn("D eprecated Foo.spam reference, please use Foo.eggs")
self.eggs = value
spam = property(_get_s pam, _set_spam)
=====

After a reasonable grace period, you can drop these compatibility
interfaces in a future version.

--
\ "For every complex problem, there is a solution that is simple, |
`\ neat, and wrong." -- Henry L. Mencken |
_o__) |
Ben Finney

Feb 27 '07 #7
"Steven D'Aprano" <st***@REMOVEME .cybersource.co m.auwrote in message
news:pa******** *************** *****@REMOVEME. cybersource.com .au...
class Difficult(objec t):
def __setattr__(sel f, name, value):
if self.__dict__.h as_key(name):
print "'%s' exists as an instance attribute" % name
self.__dict__[name] = value
elif self.__class__. __dict__.has_ke y(name):
print "'%s' exists as a class attribute" % name
self.__class__. __dict__[name] = value
else:
print "Can't create new attributes, 'cos I said so!"

But this prevents setting attributes during initialization,
so it does not meet the spec.
Cheers,
Alan
Feb 27 '07 #8
"Arnaud Delobelle" <ar*****@google mail.comwrote in message
news:11******** **************@ h3g2000cwc.goog legroups.com...
def __setattr__(sel f, attr, val):
if hasattr(self, attr):
self.__dict__[attr] = val
else:
# Tell the user off
But then you cannot even set attributes during initialization, right?
I want that restriction only after an object is initialized.
(I realize that I could condition on an attribute set during initialization,
but I am asking for the most elegant way to achieve this.)

Alan
Feb 27 '07 #9
On 2/27/07, Alan Isaac <ai****@america n.eduwrote:
"Arnaud Delobelle" <ar*****@google mail.comwrote in message
news:11******** **************@ h3g2000cwc.goog legroups.com...
def __setattr__(sel f, attr, val):
if hasattr(self, attr):
self.__dict__[attr] = val
else:
# Tell the user off

But then you cannot even set attributes during initialization, right?
I want that restriction only after an object is initialized.
(I realize that I could condition on an attribute set during initialization,
but I am asking for the most elegant way to achieve this.)

Alan
You specifically excluded slots in your spec, but why? It's as close
to a working, elegant solution you will find. Nothing else will work,
and will be horribly inelegant.

You can still do it the above way, with nasty hacking (but not really
any nastier than what you're doing) by pushing the __setattr__ hook on
as the last part of your __init__. Of course, if they subclass and
don't call your base class __init__, then they can get by you. So
maybe you should inspect the call stack in your __setattr__ and only
allow instance setting if you're within your "approved" __init__
method. Even then, you can't stop them from grabbing your class,
removing or overwriting the hook, and creating classes on the fly.

I think at this point (actually quite a while before this point)
you're getting into silly amounts of thinking about it. Python for
consenting adults and all that.
Feb 27 '07 #10

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

Similar topics

4
1748
by: Danimal | last post by:
I have been using PHP for a long time... since it was called PHP/FI. I have a programming design question: Let say I have this class: class attrib { var $lenght; var $type; ... }
2
3725
by: Anders | last post by:
We need to create a lookup structure that can contain a flexible amount of attributes. We have discussed different design solutions for lookup-functionality, and come up with this suggestion: The "lookup" structure will be defined by three tables. The "Element" table, the "Attribute" table and the "Value" table. I will specify with an example:
6
375
by: Tim Mavers | last post by:
I have a series of database objects that represent things such as people, accounts, etc. I have a set of options (boolean) that I need to add to these objects. Normally I would just create a bit field for each one and be done with it. The challenge however is that there could be hundreds of these options (maybe 300) and a user decides which of these options (actually attributes) that should apply to these db objects. For example, a...
9
2946
by: sk | last post by:
I have an applicaton in which I collect data for different parameters for a set of devices. The data are entered into a single table, each set of name, value pairs time-stamped and associated with a device. The definition of the table is as follows: CREATE TABLE devicedata ( device_id int NOT NULL REFERENCES devices(id), -- id in the device
17
2736
by: tshad | last post by:
Many (if not most) have said that code-behind is best if working in teams - which does seem logical. How do you deal with the flow of the work? I have someone who is good at designing, but know nothing about ASP. He can build the design of the pages in HTML with tables, labels, textboxes etc. But then I would need to change them to ASP.net objects and write the code to make the page work (normally I do this as I go - can't do this...
3
1758
by: Allerdyce.John | last post by:
I have a design type of quesiton. What is the advantages of using accessor (a getter/setter method) instead of making the attribute 'public'? If a class has public accessor (a getter/setter method) for its attribute, why not just make the attribute 'public'? It requires less code/typing. Or is there something I am missing? Thank you.
11
2878
by: manstey | last post by:
Hi, I am having trouble designing my classes. I have two classes. The first one wraps around an old-style class called oref Class CacheClass(object): def __init__(self, obj):
9
1457
by: mliptak | last post by:
Hi, I'm implementing a class which will serve as a callback. It will have multiple virtual operations, which will be called upon certain events. The user of the class can inherit from this class and implement the virtual operations to fit his/her needs. Each operation will have up to 3 parameters of either basic integral types (e.g. int, unsigned, size_t) or pointers (e.g. const char*). However these parameters can be stored in the class...
12
7039
by: nyathancha | last post by:
Hi, I have a question regarding best practices in database design. In a relational database, is it wise/necessary to sometimes create tables that are not related to other tables through a foreign Key relationship or does this always indicate some sort of underlying design flaw. Something that requires a re evaluation of the problem domain? The reason I ask is because in our application, the user can perform x
0
9778
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10833
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10405
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7959
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5784
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5980
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4602
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4205
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3228
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.