mixin helper class for unknown attribute access?

A

Alex Hunsley

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

class example:
def __getattr__(self, 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....)
 
S

Steven D'Aprano

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

class example:
def __getattr__(self, 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.
 
A

Alex Hunsley

Steven said:
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
 
S

Sam Pointon

One alrady exists, __slots__.
__slots__ = ['bar', 'baz', 'qig']


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

Steven D'Aprano

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__(self, name, value):
if self.__dict__.has_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__(self, 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__(self, name, value):
if self.__dict__.has_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.
 
S

Steven D'Aprano

One alrady exists, __slots__.
__slots__ = ['bar', 'baz', 'qig']


Traceback (most recent call last):
File "<pyshell#5>", line 1, in -toplevel-
f.foo = 'bar'
AttributeError: 'Foo' object has no attribute '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/Cookbook/Python/Recipe/252158
 
A

Alex Martelli

Steven D'Aprano said:
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__(self, 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
 

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

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top