473,757 Members | 2,284 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Setting an attribute without calling __setattr__()

OK, I'm sure the answer is staring me right in the face--whether that answer
be "you can't do that" or "here's the really easy way--but I am stuck. I'm
writing an object to proxy both lists (subscriptable iterables, really) and
dicts.

My init lookslike this:

def __init__(self, obj=None):
if type(obj).__nam e__ in 'list|tuple|set |frozenset':
self.me = []
for v in obj:
self.me.append( ObjectProxy(v))
elif type(obj) == dict:
self.me = {}
for k,v in obj.items():
self.me[k] = ObjectProxy(v)

and I have a __setattr__ defined like so:

def __setattr__(sel f, name, value):
self.me[name] = ObjectProxy(val ue)

You can probably see the problem.

While doing an init, self.me = {} or self.me = [] calls __setattr__, which
then ends up in an infinite loop, and even it it succeeded

self.me['me'] = {}

is not what I wanted in the first place.

Is there a way to define self.me without it firing __setattr__?

If not, it's not a huge deal, as having this class read-only for now won't
be a problem, but I was just trying to make it read/write.

Thanks!

j

Jun 27 '08 #1
12 1229
Joshua Kugler <jk*****@bigfoo t.comwrites:
self.me = []
self.me = {}
Use "object.__setat tr__(self, 'me') = []" and likewise for {}.
Jun 27 '08 #2
On Apr 26, 7:01 am, Joshua Kugler <jkug...@bigfoo t.comwrote:
OK, I'm sure the answer is staring me right in the face--whether that answer
be "you can't do that" or "here's the really easy way--but I am stuck. I'm
writing an object to proxy both lists (subscriptable iterables, really) and
dicts.

My init lookslike this:

def __init__(self, obj=None):
if type(obj).__nam e__ in 'list|tuple|set |frozenset':
self.me = []
for v in obj:
self.me.append( ObjectProxy(v))
elif type(obj) == dict:
self.me = {}
for k,v in obj.items():
self.me[k] = ObjectProxy(v)

and I have a __setattr__ defined like so:

def __setattr__(sel f, name, value):
self.me[name] = ObjectProxy(val ue)

You can probably see the problem.

While doing an init, self.me = {} or self.me = [] calls __setattr__, which
then ends up in an infinite loop, and even it it succeeded

self.me['me'] = {}

is not what I wanted in the first place.

Is there a way to define self.me without it firing __setattr__?
Consider reading the *second* paragraph about __setattr__ in section
3.4.2 of the Python Reference Manual.
Jun 27 '08 #3
Hrvoje Niksic <hn*****@xemacs .orgwrites:
Joshua Kugler <jk*****@bigfoo t.comwrites:
> self.me = []
self.me = {}

Use "object.__setat tr__(self, 'me') = []" and likewise for {}.
Oops, that should of course be "object.__setat tr__(self, 'me', [])".
Jun 27 '08 #4
John Machin wrote:
>Is there a way to define self.me without it firing __setattr__?
Consider reading the *second* paragraph about __setattr__ in section
3.4.2 of the Python Reference Manual.
Like I said in my original post, it was probably staring me right in the
face. I had read through a bit of the documentation on special methods,
but for some reason I missed that part.

Thanks to all for your responses!

j

Jun 27 '08 #5
On Apr 25, 5:01 pm, Joshua Kugler <jkug...@bigfoo t.comwrote:
My init lookslike this:

def __init__(self, obj=None):
if type(obj).__nam e__ in 'list|tuple|set |frozenset':
self.me = []
for v in obj:
self.me.append( ObjectProxy(v))
elif type(obj) == dict:
self.me = {}
for k,v in obj.items():
self.me[k] = ObjectProxy(v)
As an aside, unrelated to your question, Python encourages "duck
typing" instead of exact type matching. Unless you have a good reason
to restrict obj to one of the 5 types you hardcoded (a rather rare
need), it is more flexible to write it as:

def __init__(self, obj=None):
if hasattr(obj, 'items'):
# assume obj is a mapping type instance
self.me = dict((k,ObjectP roxy(v)) for k,v in obj.items())
else:
try: # check if obj is an iterable instance
self.me = map(ObjectProxy , obj)
except TypeError:
# handle other cases here
# self.me = ...
A downside of this flexibility is that it may be more liberal than it
should. For instance, if obj just happens to have an 'items()' method
but it's not really a mapping type, the assumption is violated. Python
3 deals with such potential ambiguities by introducing Abstract Base
Classes (ABCs) [1] that allow a class to make explicit its semantics.
So in Py3K the hasattr() test above would rather be written as
"isinstance(obj , Mapping)", where Mapping is the ABC that represents
(read-only) mappings.

A more difficult problem is that even if a class derives from some
ABC, you may not always want to treat its instances as such. The
typical gotcha is that strings are iterable, but in many (most?)
applications they are to be treated as atomic values, not as sequences
of characters. So in the example above if obj is a string, self.me
will be a list of ObjectProxy instances, one per character; probably
not what you intend. Of course we can check for "isinstance(obj ,str)"
but then we're back at explicit type checking. There is no general way
to express something lke "atomic value that also happens to be
iterable (but pretend it's not)" because it's inherently domain-
dependent.

George

[1] http://www.python.org/dev/peps/pep-3119/
Jun 27 '08 #6
Joshua Kugler <jk*****@bigfoo t.comwrites:

[...]
self.me = []
for v in obj:
self.me.append( ObjectProxy(v))
Note that is could be spelt:

self.me = map(ObjectProxy , v)

--
Arnaud
Jun 27 '08 #7


Hrvoje Niksic wrote:
Hrvoje Niksic <hn*****@xemacs .orgwrites:
Joshua Kugler <jk*****@bigfoo t.comwrites:
self.me = []
self.me = {}
Use "object.__setat tr__(self, 'me') = []" and likewise for {}.

Oops, that should of course be "object.__setat tr__(self, 'me', [])".
Jun 27 '08 #8
Consider reading the *second* paragraph about __setattr__ in section
3.4.2 of the Python Reference Manual.
if you are simply going to answer rtfm - might as well kept it to
yourself.
Jun 27 '08 #9
In article <m2************ @googlemail.com >,
Arnaud Delobelle <ar*****@google mail.comwrote:
>Joshua Kugler <jk*****@bigfoo t.comwrites:
>>
self.me = []
for v in obj:
self.me.append( ObjectProxy(v))

Note that is could be spelt:

self.me = map(ObjectProxy , v)
It could also be spelt:

self.me = [ObjectProxy(v) for v in obj]

which is my preferred spelling....
--
Aahz (aa**@pythoncra ft.com) <* http://www.pythoncraft.com/

Why is this newsgroup different from all other newsgroups?
Jun 27 '08 #10

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

Similar topics

4
1869
by: Maarten van Reeuwijk | last post by:
Hello, Maybe I was a little too detailed in my previous post . I can boil down my problem to this: say I have a class A that I encapsulate with a class Proxy. Now I just want to override and add some functionality (see my other post why). All functionality not defined in the Proxy class should be delegated (I can't use inheritance, see other post). It should be possible to achieve this using Python's great introspection possibilities,...
6
1426
by: Chris... | last post by:
Two simple questions regarding future of Python: 1) Is there already a "fix" to avoid writing to an attribute that isn't defined yet? I remember this being an often discussed problem, but didn't see any changes. The only way I can think of is overriding __setattr__, but this is huge overhead. While I like the idea of being able to add new attributes on the fly, in great projects I'd like to restrict some classes not to do so. 2)...
1
2113
by: Thomas Heller | last post by:
I have a subclassable type implemented in C, which has a 'value' attribute implemented in the tp_getset slot. The type is named c_long. The value attribute accepts and returns integers. Now I want to derive a subclass 'BOOL' (in Python) from it, where the 'value' attribute should accept and return bool instances: from ctypes import c_long class BOOL(c_long):
3
3137
by: Christian Dieterich | last post by:
Hi, I need to create many instances of a class D that inherits from a class B. Since the constructor of B is expensive I'd like to execute it only if it's really unavoidable. Below is an example and two workarounds, but I feel they are not really good solutions. Does somebody have any ideas how to inherit the data attributes and the methods of a class without calling it's constructor over and over again? Thank,
9
1719
by: úÁÕÒ ûÉÂÚÕÈÏ× | last post by:
There is a syntactic sugar for item access in dictionaries and sequences: o = v <-> o.__setitem__(e, v) o <-> o.__getitem__(e) where e is an expression. There is no similar way for set/get attribute for objects. If e is a given name, then
5
1331
by: Joel Andres Granados | last post by:
Hi list: I have googled quite a bit on this matter and I can't seem to find what I need (I think Im just looking where I'm not suppose to :). I'm working with code that is not of my authorship and there is a class attribute that is changes by directly referencing it (object.attr = value) instead of using a getter/setter (object.setAttr(Value) ) function. The thing is that I have no idea when the change occurs and I would REALLY like...
0
742
by: Terry Reedy | last post by:
"Joshua Kugler" <jkugler@bigfoot.comwrote in message news:futgrq$ih6$1@ger.gmane.org... | OK, I'm sure the answer is staring me right in the face--whether that answer | be "you can't do that" or "here's the really easy way--but I am stuck. I'm | writing an object to proxy both lists (subscriptable iterables, really) and | dicts. |
8
1202
by: Ken Starks | last post by:
I have a class with an attribute called 'gridsize' and I want a derived class to force and keep it at 0.8 (representing 8mm). Is this a correct, or the most pythonic approach? #################### def __getattr__(self,attrname): if attrname == 'gridsize': return 0.8
2
1436
by: Jan Schilleman | last post by:
Hi all, I am trying to redefine __setattr__. The base class is in a library (actually, it is win32com.client.DispatchBaseClass) and I do not want to touch it. My problem is exemplified below. To my surprise, __setattr__ and __str__ behave differently; I can redefine __str__ and the inherited __str__ is still the redefined one. But redefining __setattr__ on the base class does not get inherited. In Base.__dict__ the __setattr__ is the...
0
9487
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
9904
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9884
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
9735
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
7285
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
5168
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...
1
3828
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
3
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2697
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.