473,803 Members | 3,422 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

mixin helper class for unknown attribute access?

I know that I can catch access to unknown attributes with code something
like the following:

class example:
def __getattr__(sel f, name):
if name == 'age':
return __age
else:
raise AttributeError
but is there an existing mixin helper class in Python (or one someone
has written) already that will assist with this? (Just not wanting to
reinvent the wheel....)
Oct 31 '05 #1
6 2487
On Mon, 31 Oct 2005 10:39:40 +0000, Alex Hunsley wrote:
I know that I can catch access to unknown attributes with code something
like the following:

class example:
def __getattr__(sel f, name):
if name == 'age':
return __age
else:
raise AttributeError
but is there an existing mixin helper class in Python (or one someone
has written) already that will assist with this? (Just not wanting to
reinvent the wheel....)


Too late.

py> class Example:
.... age = 0
....
py> Example.age
0
py> Example.aeg
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: class Example has no attribute 'aeg'

It works for instances too:

py> Example().aeg
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: Example instance has no attribute 'aeg'
Your __getattr__ code is completely unnecessary.

--
Steven.

Oct 31 '05 #2
Steven D'Aprano wrote:
On Mon, 31 Oct 2005 10:39:40 +0000, Alex Hunsley wrote:

I know that I can catch access to unknown attributes with code something
like the following:

class example:
def __getattr__(sel f, name):
if name == 'age':
return __age
else:
raise AttributeError
but is there an existing mixin helper class in Python (or one someone
has written) already that will assist with this? (Just not wanting to
reinvent the wheel....)

Too late.

py> class Example:
... age = 0
...
py> Example.age
0
py> Example.aeg
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: class Example has no attribute 'aeg'

It works for instances too:

py> Example().aeg
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: Example instance has no attribute 'aeg'
Your __getattr__ code is completely unnecessary.


Sorry, as I noted in another reply not long ago, I was having a 'braino'
and not saying what I actually meant!
What I was talking about was the accidental _setting_ of the wrong
attribute.
And the mixin class I'm looking for is one that could be told what were
valid attributes for the class, and would then catch the situation where
you mis-spelt an attribute name when setting an attrib.

thanks!
alex



Oct 31 '05 #3
One alrady exists, __slots__.
class Foo(object): __slots__ = ['bar', 'baz', 'qig']

f = Foo()
f.foo = 'bar'
Traceback (most recent call last):
File "<pyshell#5 >", line 1, in -toplevel-
f.foo = 'bar'
AttributeError: 'Foo' object has no attribute 'foo' f.bar = 'foo'


However, __slots__ only works for class instances, so if you're messing
around with uninitialised classes (not a good idea outside the
singleton pattern or very functional-style code) it won't work.

Oct 31 '05 #4
On Mon, 31 Oct 2005 12:47:16 +0000, Alex Hunsley wrote:
Sorry, as I noted in another reply not long ago, I was having a 'braino'
and not saying what I actually meant!
What I was talking about was the accidental _setting_ of the wrong
attribute.
And the mixin class I'm looking for is one that could be told what were
valid attributes for the class,
Who decides what are valid attributes for a class? The class writer, or
the class user who may want to use it in ways the writer never imagined?

and would then catch the situation where
you mis-spelt an attribute name when setting an attrib.


If all you care about is preventing developers from adding any new
attributes at run time, you can do something like this:

# warning: untested
class Example:
def __init__(self, data):
self.__dict__['data'] = data
def __setattr__(sel f, name, value):
if self.__dict__.h as_key(name):
self.__dict__[name] = value
else:
raise AttributeError

except that the developers will then simply bypass your code:

p = Example(None)
p.__dict__['surprise'] = 1
p.surprise

Trying to prevent setting new attributes is a pretty heavy-handed act just
to prevent a tiny subset of errors. Many people argue strongly that even
if you could do it, it would be pointless -- or at least, the cost is far
greater than whatever small benefit there is.

But, if you insist, something like this:

# Warning: untested.
class Declare:
def __init__(self, names):
"""names is a list of attribute names which are allowed.
Attributes are NOT initialised.
"""
self.__dict__['__ALLOWED'] = names
def __setattr__(sel f, name, value):
if name in self.__ALLOWED:
self.__dict__[name] = value
else:
raise AttributeError( "No such attribute.")

If you want to initialise your attributes at the same time you declare
them, use:

# Warning: untested.
class DeclareInit:
def __init__(self, names):
"""names is a dictionary of attribute names/values which are
allowed.
"""
self.__dict__ = names
def __setattr__(sel f, name, value):
if self.__dict__.h as_key(name):
self.__dict__[name] = value
else:
raise AttributeError( "No such attribute.")

Of the two approaches, I would say the second is marginally less of a bad
idea.

--
Steven.

Oct 31 '05 #5
On Mon, 31 Oct 2005 05:12:11 -0800, Sam Pointon wrote:
One alrady exists, __slots__.
class Foo(object): __slots__ = ['bar', 'baz', 'qig']

f = Foo()
f.foo = 'bar'
Traceback (most recent call last):
File "<pyshell#5 >", line 1, in -toplevel-
f.foo = 'bar'
AttributeError: 'Foo' object has no attribute 'foo' f.bar = 'foo'


__slots__ are NOT intended to be used to limit Python's dynamic nature.
Whether you call this usage a misuse or a serendipitous side-effect is a
matter of opinion.

However, __slots__ only works for class instances, so if you're messing
around with uninitialised classes (not a good idea outside the
singleton pattern or very functional-style code) it won't work.

__slots__ only work with new-style classes, not classic classes.

Before using __slots__, read this:

http://www.python.org/doc/current/ref/slots.html

Then read this recipe:

http://aspn.activestate.com/ASPN/Coo.../Recipe/252158
--
Steven.

Oct 31 '05 #6
Steven D'Aprano <st***@REMOVETH IScyber.com.au> wrote:
...
Trying to prevent setting new attributes is a pretty heavy-handed act just
to prevent a tiny subset of errors. Many people argue strongly that even
if you could do it, it would be pointless -- or at least, the cost is far
greater than whatever small benefit there is.


I entirely agree with you (also about the use of __slots__ being a
particularly WRONG way to achieve this). When I have to suggest a mixin
to avoid accidental setting of misspelled attributes (which does appear
to be a clinically certifiable phobia of programmers coming to Python
from certain other languages) I suggest something like:

class Rats(object):
def __setattr__(sel f, name, value):
if hasattr(self, name):
super(Rats, self).__setattr __(name, value)
else:
raise AttributeError, "can't set attribute %r" % (name,)

The key idea is to exploit hasattr's semantics -- it checks the class as
well as the specific instance.

Example use case:

class Bah(Rats):
foo = bar = baz = 23

now, given b=Bah(), you can set b.foo, b.bar and b.baz, but no other
attribute of b (of course you can bypass the restriction easily -- such
restrictions are always intended against *accidental* cases, not against
deliberate attacks).

Differently from __slots__, Rats gives no problems with pickling,
inheritance, etc, etc.
Alex
Oct 31 '05 #7

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

Similar topics

0
1624
by: zimba | last post by:
Hello ! If somebody is interested, here is a small hack I've done today. There are still some curious effects, but I'm pretty satisfied by the results, since PHP is not very flexible. Let me know what you think, I'm looking into talking about somethin ;)
5
2739
by: Udo Gleich | last post by:
Hi, I try to implement mixin classes. Thats why I need to make a new class at runtime. --tmp.py------------------------------------- import new class K1(object):
1
2583
by: Mac | last post by:
I have a MixIn class which defines a method foo(), and is then mixed in with another class by being prepended to that class's __bases__ member, thus overriding that class's definition of foo(). In my application though it is necessary for the MixIn's foo() to call the overridden foo(). How can I do this? My current hack is to do this: def foo(): # MixIn's method orig_bases = self.__class__.__bases__
0
9028
by: David Moore | last post by:
Hello I posted a thread about this a while back, but I can't actually find it again so I can reply to it with the solution I found, so I'm making a new thread and hoping it goes to the top of the Google search results for the error like the previous thread. This is actually a solution to a problem, not a call for help, so you can stop reading now unless you're actually interested in the solution :)
0
1334
by: Paolino | last post by:
I had always been negative on the boldeness of python on insisting that unbound methods should have been applied only to its im_class instances. Anyway this time I mixed in rightly, so I post this for comments. ###### looking for a discovery .Start ################# class _Mixin(object): def __init__(self,main,instance,*args,**kwargs): # do mixin businnes main.__reinit__(self,instance) # the caveated interface
0
345
by: barnesc | last post by:
>So mixins are just a sub-class of sub-classing? > >I've just found this: > > >A mixin class is a parent class that is inherited from - but not as >a means of specialization. Typically, the mixin will export services to a >child class, but no semantics will be implied about the child "being a >kind of" the parent. >
2
2211
by: ish | last post by:
I think this is more of a style question than anything else... I'm doing a C++ wrapper around a C event library I have and one of the items is a timer class, I'm also using this task to learn C++. Is it cleaner to have users subclass my Timer class and implement the on_timeout() method? Or should the user use a mixin and provide the mixin to my Timer class? The subclass method kinda looks like this..
6
3537
by: mailforpr | last post by:
Suppose you have a couple of helper classes that are used by 2 client classes only. How can I hide these helper classes from other programmers? Do you think this solution is a good idea?: class Hidden_functionality { protected: // These helper classes provide some functionality that is // only used by the client classes class Helper1 {};
1
1434
by: Ole Nielsby | last post by:
Given these 3 classes class A {virtual void a(){}}; class B {virtual void b(){}}; class C: public A, public B {}; I want the offset of B in C, as a size_t value, and preferably as a constant expression. I got a solution that seems to work on VC9Express:
0
9703
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9565
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
10295
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
10069
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...
0
9125
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6844
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5501
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
5633
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3799
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.