473,289 Members | 1,780 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,289 software developers and data experts.

Bypassing __getattribute__ for attribute access

As an exercise I'm attempting to write a metaclass that causes an
exception to be thrown whenever a user tries to access
'attributes' (in the traditional sense) via a direct reference.

Consider:

class X( object ):
y = 'private value'
def get_y( self ): return self.y

Normally one can access y here via:

X().y

or

X().get_y()

I want the former case, however, to throw an exception.

I figured the way to do this would be to introduce a metaclass that
overrides the default __getattrribute__ call and throws an exception.
So my first attempt was something like:

class XType( type ):
def __my_getattribute__( self, name ):
raise AttributeError()
def __init__( klass, name, bases, dict ):
super( XType, klass ).__init__( name, bases, dict )
setattr( klass, '__getattribute__',
klass.__my_getattribute__ )

But whereas the X().y attribute behaves as I intend, the X().get_y()
returns raises that exception as well:
>>X().y
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __my_getattribute__
AttributeError
>>X().get_y()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __my_getattribute__
AttributeError

So it looks as if 'attribute' here means any key in self.__dict__,
whether referenced via self.var, self.__dict__['var'] (because this
references __dict__), or getattr( self, 'var' ) (which is the same as
a direct self.var access, I believe).

So I tried:

class XType( type ):
def __my_getattribute__( self, name ):
if name != '__dict__':
raise AttributeError()
return super( self.__class__,
self ).__getattribute__( name )
def __init__( klass, name, bases, dict ):
super( XType, klass ).__init__( name, bases, dict )
setattr( klass, '__getattribute__',
klass.__my_getattribute__ )

This allows me to access X().__dict__ directly (and then
X().__dict__['y']), but it still limits caller access to the get_y()
method.

It sounds then like the "solution" will be to check whether the name
referenced is called __dict__ or is a method or function type,
otherwise throw the exception, and to ensure all internal calls are
handled via self.__dict__[name] not self.name.

Something like:

import types
class XType( type ):
def __my_getattribute__( self, name ):
if name != '__dict__' and not
isinstance( self.__dict__[name], types.FunctionType ):
raise AttributeError()
return super( self.__class__,
self ).__getattribute__( name )
def __init__( klass, name, bases, dict ):
super( XType, klass ).__init__( name, bases, dict )
setattr( klass, '__getattribute__',
klass.__my_getattribute__ )

Of course this is imperfect as a user can simply bypass the
__getattribute__ call too and access __dict__ directly, but it's
closer to what I was thinking. The problem is the return value for
functions is not bound - how do I bind these to the associated
instance?

(Caveat - I am not sure whether using __get__ itself in lieu of
__getattribute__ would be a better solution; but I would like to see
how binding would be done here for general knowledge.)

Thanks.

Adam

Oct 25 '07 #1
6 3517
Adam Donahue a écrit :
As an exercise I'm attempting to write a metaclass that causes an
exception to be thrown whenever a user tries to access
'attributes' (in the traditional sense) via a direct reference.
I guess you're new to Python, and coming from either C++ or Java. Am I
wrong ?-)

And without even reading further, I can tell you're doing something
pretty complicated that just don't work.

(Ok, I cheated - I did read further !-)
Consider:

class X( object ):
y = 'private value'
def get_y( self ): return self.y

Normally one can access y here via:

X().y

or

X().get_y()

I want the former case, however, to throw an exception.
So called "private" or "protected" attributes (IOW, implementation stuff
the client code should not mess with) are denoted by a single leading
underscore. IOW, 'y' should be '_y'. It won't of course prevent anyone
to access the attribute, but then it's not your responsability anymore.

I know this sound surprising to C++/Java programmers, but experience
prove that it just work.
Now if all you want is to reproduce the Java systematic-getter-setter
dance - that is, use getters/setters 'just in case' you'd want to
refactor (which, FWIW, is the only rationale behind accessors), you just
don't need this with Python. We do have computed attributes here, so the
simplest thing is to start with a plain attribute, then refactor it into
a computed one if and when the need arises. This is *totally*
transparent to client code.

I figured the way to do this would be to introduce a metaclass that
overrides the default __getattrribute__ call and throws an exception.
So my first attempt was something like:

class XType( type ):
def __my_getattribute__( self, name ):
raise AttributeError()
def __init__( klass, name, bases, dict ):
super( XType, klass ).__init__( name, bases, dict )
setattr( klass, '__getattribute__',
klass.__my_getattribute__ )

But whereas the X().y attribute behaves as I intend, the X().get_y()
returns raises that exception as well:
Indeed. __getattribute__ is invoked for *each and every* attribute
lookup - including methods, since methods are attributes too. FWIW,
__getattribute__ it's something you should not mess with unless you know
what you're doing and why you're doing it.
>
So it looks as if 'attribute' here means any key in self.__dict__,
The '.' is the lookup operator. As soon as you have obj.anyname, you do
an attribute lookup (wether it fails or succeeds is another question).
And __getattribute__ is the implementation for this operator. So given
how you wrote your custom __getattribute__, you just made attribute
lookup impossible.

And FWIW, attribute lookup is much more complex than just looking up the
instance's __dict__ - it also looks up the class __dict__, then the
parent's classes __dict__, then look for a custom __getattr__ method
(which is used when the attribute has not been found so far). And if the
attribute found is a class attribute that implements the descriptor
protocol, then __getattribute__ is responsible for invoking this
protocol. IOW, __getattribute__ is one of the most critical magic methods.
whether referenced via self.var, self.__dict__['var'] (because this
references __dict__), or getattr( self, 'var' ) (which is the same as
a direct self.var access, I believe).
Practically, yes.
>
So I tried:

class XType( type ):
def __my_getattribute__( self, name ):
if name != '__dict__':
raise AttributeError()
return super( self.__class__,
self ).__getattribute__( name )
def __init__( klass, name, bases, dict ):
super( XType, klass ).__init__( name, bases, dict )
setattr( klass, '__getattribute__',
klass.__my_getattribute__ )

This allows me to access X().__dict__ directly (and then
X().__dict__['y']), but it still limits caller access to the get_y()
method.
cf above.
It sounds then like the "solution" will be to check whether the name
referenced is called __dict__ or is a method or function type,
otherwise throw the exception, and to ensure all internal calls are
handled via self.__dict__[name] not self.name.
My my my. Trouble ahead...
Something like:

import types
class XType( type ):
def __my_getattribute__( self, name ):
if name != '__dict__' and not
isinstance( self.__dict__[name], types.FunctionType ):
raise AttributeError()
return super( self.__class__,
*never* use self.__class__ (or type(self) etc) when calling super(). You
*really* want to pass the exact class here - else you'll have *very*
strange results.
self ).__getattribute__( name )
def __init__( klass, name, bases, dict ):
super( XType, klass ).__init__( name, bases, dict )
setattr( klass, '__getattribute__',
klass.__my_getattribute__ )
My my my...
Of course this is imperfect as a user can simply bypass the
__getattribute__ call too and access __dict__ directly,
Indeed. The fact is that there's just no way to prevent client code to
access your implementation. Period. So relax, stop fighting against the
langage, and learn to use it how it is.
but it's
closer to what I was thinking. The problem is the return value for
functions is not bound - how do I bind these to the associated
instance?
func.__get__(obj, obj.__class__)

But that should not be done when the function is an instance attribute -
only when it's a class one. And any class attribute implementing the
descriptor protocol should be treated that way.
(Caveat - I am not sure whether using __get__ itself in lieu of
__getattribute__ would be a better solution; but I would like to see
how binding would be done here for general knowledge.)
(simplified) In the normal case, when the attribute looked up happens to
be a class attribute and implements the descriptor protocol,
__getattribute__ returns attr.__get__(obj, type(obj). What attr.__get__
returns is up to whoever implemented type(attr). In the case of
functions, anyway, __get__ returns a method object, which is a callable
object wrapping the function, the target object and the class. When
called, this method object insert the target object (or class if it's a
classmethod) in front of the args list, and invoke the function with
this new args list. Which is why you need to declare self (or cls) as
first argument of a 'method' but not to explicitely pass it at call time.

Anyway : forget about "real" privacy in Python (FWIW, neither Java nor
C++ have "real" privacy - there are ways to bypass access restrictors in
both languages), just use the single leading underscore convention and
you'll be fine. And don't write explicit accessors - in fact, don't
write accessors at all until you need them, and when you need them, use
a property or a custom descriptor object, so it's transparant to client
code.

HTH
Oct 25 '07 #2
Adam Donahue wrote:
>>>class X( object ):
... def c( self ): pass
...
>>>X.c
<unbound method X.c>
>>>x = X()
x.c
<bound method X.c of <__main__.X object at 0x81b2b4c>>

If my interpretation is correct, the X.c's __getattribute__ call knows
the attribute reference is via a class, and thus returns an unbound
method (though it does convert the value to a method).
No, that's wrong. It's not the __getattribute__ of "X.c", it's the
__getattribute__ of "X" itself::
>>type.__getattribute__(X, 'c')
<unbound method X.c>
>>X.c.__getattribute__('c')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: 'function' object has no attribute 'c'

In the former case, we use the type's __getattribute__, and we get the
unbound method as expected. In the latter case, we ask the unbound
method object for an attribute which it doesn't have

Basically, classes define a __getattribute__ that looks something like::

def __getattribute__(self, name):
value = object.__getattribute__(self, name)
if hasattr(value , '__get__'):
return value .__get__(None, self)
return value

For more information, read:

http://users.rcn.com/python/download/Descriptor.htm

STeVe
Oct 25 '07 #3

On Thu, 2007-10-25 at 23:13 +0200, Bruno Desthuilliers wrote:
<snip excellent breakdown>
The logical next question then is how does one best add a new method
to this class so that future references to x.set_x() and X.set_x will
properly resolve? It seems the answer would be to somehow add to
X.__dict__ a new value, with key 'set_x', value the function set_x.

Yes. Which is very simply done by just binding set_x to X.set_x. Just
like I did above. Dynamically adding methods to classes is pretty
straightforward, the tricky point is to dynamically add methods to
instances, since the descriptor protocol is only triggered for class
attributes. But you obviously found how to do it using func.__get__(obj,
type(obj)) !-)
This is the greasy, getting your hands dirty way. I vastly prefer (and
reccomend) using the new module:
>>import new
class X(object):
.... pass
....
>>def bar(self):
.... print self
....
>>x = X()
x.bar = new.instancemethod(bar, x, X)
x.bar()
<__main__.X object at 0x87dca0c>
>>>

>From there on the . operator I assume would perform the binding to X
or x as needed on-the-fly.

Yes.

NB: please some guru around correct me if I said something wrong (Alex ?
Tim ? Fredrick ? If you hear me ?)
Oct 25 '07 #4
Chris Mellon a écrit :
On Thu, 2007-10-25 at 23:13 +0200, Bruno Desthuilliers wrote:
<snip excellent breakdown>
<blush />
>Dynamically adding methods to classes is pretty
straightforward, the tricky point is to dynamically add methods to
instances, since the descriptor protocol is only triggered for class
attributes. But you obviously found how to do it using func.__get__(obj,
type(obj)) !-)

This is the greasy, getting your hands dirty way. I vastly prefer (and
reccomend) using the new module:
Indeed.
Oct 26 '07 #5
Thank you all for the detailed replies, I appreciate it. I only read
up on this yesterday morning, but I feel I've gotten a lot of insight
in a short time thanks to your contributions to this thread. Useful
all around!

Adam

On Oct 26, 2:50 am, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
Chris Mellon a écrit :
On Thu, 2007-10-25 at 23:13 +0200, Bruno Desthuilliers wrote:
<snip excellent breakdown>

<blush />
Dynamically adding methods to classes is pretty
straightforward, the tricky point is to dynamically add methods to
instances, since the descriptor protocol is only triggered for class
attributes. But you obviously found how to do it using func.__get__(obj,
type(obj)) !-)
This is the greasy, getting your hands dirty way. I vastly prefer (and
reccomend) using the new module:

Indeed.

Oct 26 '07 #6
On Oct 25, 5:07 pm, Adam Donahue <adam.dona...@gmail.comwrote:
As an exercise I'm attempting to write a metaclass that causes an
exception to be thrown whenever a user tries to access
'attributes' (in the traditional sense) via a direct reference.
Well, now thanks to Bruno and the others you know everything about
attribute access in Python. Still, you may be interested in this
recipe, which involves __setattr__ and non __getattribute__:
http://aspn.activestate.com/ASPN/Coo.../Recipe/252158

Michele Simionato

Oct 27 '07 #7

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

Similar topics

6
by: Ruud de Jong | last post by:
I have the situation where I need to construct the name of a static method, and then retrieve the corresponding function from a class object. I thought I could just use __getattribute__ for this...
2
by: Henry 'Pi' James | last post by:
I'm pretty sure this must not be a new idea, but it seems no one else has voiced their agitation about the name "__getattribute__" so far. Its closeness to "__getattr__" is only one thing that...
0
by: Gigi | last post by:
Hi, In the Python documentation regarding __getattribute__ (more attribute access for new style classes) it is mentioned that if __getattribute__ is defined __getattr__ will never be called...
3
by: Sylvain Ferriol | last post by:
hello when i define __getattribute__ in a class, it is for the class instances but if i want to have a __getattribute__ for class attributes how can i do that ? sylvain
5
by: Stefan Sonnenberg-Carstens | last post by:
Hi there, I'm facing some strange things - but maybe only me is strange - anyway... i wrote the following code: +++ class T(object): def __init__(self,name='',port=80): self.name=name
1
by: pascal.parent | last post by:
Hi, I try to define a (new-style) class who: - have a __slots__ defined to be strict attributes, - return None if the attribute is 'ok' but not set, or raise a 'normal' error if the attribute...
5
by: Barry Kelly | last post by:
I'm running this version of Python: Python 2.4.3 (#1, May 18 2006, 07:40:45) on cygwin I read in the documentation that these two expressions are interchangeable: ...
4
by: Pedro Werneck | last post by:
Hi all I noticed something strange here while explaining decorators to someone. Not any real use code, but I think it's worth mentioning. When I access a class attribute, on a class with a...
8
by: bukzor | last post by:
I want to make a MixIn class that waits to initialize its super- classes until an attribute of the object is accessed. Not generally useful, but desirable in my case. I've written this, and it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

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.