473,770 Members | 1,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why do descriptors (and thus properties) only work on attributes.

Can anyone explain why descriptors only work when they are an attribute
to an object or class. I think a lot of interesting things one can
do with descriptors would be just as interesting if the object stood
on itself instead of being an attribute to an other object.

So what are the reasons for limiting this feature in such a way?

--
Antoon Pardon
Jul 18 '05
14 1646
Antoon Pardon wrote:
Can anyone explain why descriptors only work when they are an attribute
to an object or class. I think a lot of interesting things one can
do with descriptors would be just as interesting if the object stood
on itself instead of being an attribute to an other object.


Not sure what "stood on itself" really means, but if you just want to be
able to have module-level properties, you can do something like:

py> class Module(object):
.... oldimporter = __builtins__.__ import__
.... def __init__(self, *args):
.... mod = self.oldimporte r(*args)
.... self.__dict__ = mod.__dict__
.... p = property(lambda self: 42)
....
py> __builtins__.__ import__ = Module
py> import __main__
py> __main__.p
42
py> __main__.p = 3
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
AttributeError: can't set attribute

where you replace module objects with a different object. Note that
this is also nasty since properties reside in the class, so all modules
now share the same properties:

py> import sys
py> sys.p
42
py> sys.p = 13
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
AttributeError: can't set attribute

STeVe
Jul 18 '05 #11
Steven Bethard wrote:
Antoon Pardon wrote:
Can anyone explain why descriptors only work when they are an attribute
to an object or class. I think a lot of interesting things one can
do with descriptors would be just as interesting if the object stood
on itself instead of being an attribute to an other object.

Not sure what "stood on itself" really means, but if you just want to be
able to have module-level properties, you can do something like:

Think in non-English (stand outside yourself?) for a second, rememberinf
Antoon is Belgian (if you knew that):

"on" => "by"

"stood on itself" => "stood by itself"
=> "standalone "

regards
Steve
Jul 18 '05 #12
Op 2005-02-28, Dima Dorfman schreef <di**@trit.inva lid>:
On 2005-02-28, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-02-28, Diez B. Roggisch schreef <de*********@we b.de>:
I still don't see how that is supposed to work for "a lot of interesting
things". Can you provide examples for one of these interesting things?


Lazy evaluation where the value of something is calculated the first
time it is needed but accessed from some storage if it is needed again.


I do this all the time. It's not very hard and doesn't require any
extra language support, but I would like for there to be an
authoritative list of type slots (autopromise_op s).

import operator

def promise(thunk):
x = []
def promised():
if not x:
x.append(thunk( ))
return x[0]
return promised

autopromise_ops = [x for x in dir(operator) if x.startswith('_ _')]
autopromise_ops += ['__getattribute __', '__call__', '__str__', '__repr__']
autopromise_ops += ['__getattr__', '__setattr__', '__delattr__']

def autopromise(thu nk):
p = promise(thunk)
d = {}
for op in autopromise_ops :
def bindhack(op=op) :
return lambda self, *a, **kw: getattr(p(), op)(*a, **kw)
d[op] = bindhack()
return type('autopromi se', (), d)()

def test():

lis = []

def thunk():
lis.append('ran thunk')
return 'value'

s = autopromise(thu nk)
p = s * 30
assert p == 'value' * 30
p = s * 10
assert p == 'value' * 10
assert lis == ['ran thunk'] # Just once

print 'autopromise sanity test passed'

An autopromise object is good almost everywhere the real one would be,
and usually the only way to tell the difference is to call id or type
on it. The main exception is when the thunk returns a builtin type
(like a string or int) and you want to pass it to a builtin function
that expects a particular type (this would also apply to Python
functions that break duck typing on purpose, but those would just be
getting the breakage they deserve).


Hmm, I'll have to take your word for it, because for the moment I
don't see what is going on. I'll have to study this some time.

--
Antoon Pardon
Jul 18 '05 #13
Steve Holden wrote:
Steven Bethard wrote:
Antoon Pardon wrote:
Can anyone explain why descriptors only work when they are an attribute
to an object or class. I think a lot of interesting things one can
do with descriptors would be just as interesting if the object stood
on itself instead of being an attribute to an other object.


Not sure what "stood on itself" really means, but if you just want to
be able to have module-level properties, you can do something like:

Think in non-English (stand outside yourself?) for a second, rememberinf
Antoon is Belgian (if you knew that):

"on" => "by"

"stood on itself" => "stood by itself"
=> "standalone "


Sorry, I gathered that this meant "standalone ". My problem was that I'm
not sure what "standalone " means in the context of descriptors.
Descriptors are invoked when dotted-attribute access is used. When
exactly is he proposing "standalone " descriptors would be invoked?

STeVe
Jul 18 '05 #14
Steven Bethard wrote:
Steve Holden wrote:
Steven Bethard wrote:
Antoon Pardon wrote:

Can anyone explain why descriptors only work when they are an attribute
to an object or class. I think a lot of interesting things one can
do with descriptors would be just as interesting if the object stood
on itself instead of being an attribute to an other object.
Not sure what "stood on itself" really means, but if you just want to
be able to have module-level properties, you can do something like:

Think in non-English (stand outside yourself?) for a second,
rememberinf Antoon is Belgian (if you knew that):

"on" => "by"

"stood on itself" => "stood by itself"
=> "standalone "


Sorry, I gathered that this meant "standalone ". My problem was that I'm
not sure what "standalone " means in the context of descriptors.
Descriptors are invoked when dotted-attribute access is used. When
exactly is he proposing "standalone " descriptors would be invoked?


Well, my *guess* was Antoon was referring to module attributes - names
that can be referenced without qualification using a "." operator.

Which, I suppose, is how you read it too. Sorry.

regards
stEvE
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #15

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

Similar topics

8
1620
by: David S. | last post by:
I am looking for a way to implement the same simple validation on many instance attributes and I thought descriptors (http://users.rcn.com/python/download/Descriptor.htm) looked like the right tool. But I am confused by their behavior on instance of my class. I can only get the approximate behavior by using class variables. I am looking for something like:
3
2169
by: redefined.horizons | last post by:
I've been reading about Python Classes, and I'm a little confused about how Python stores the state of an object. I was hoping for some help. I realize that you can't create an empty place holder for a member variable of a Python object. It has to be given a value when defined, or set within a method. But what is the difference between an Attribute of a Class, a Descriptor in a Class, and a Property in a Class?
7
1351
by: mrkafk | last post by:
Hello everyone, I'm trying to do seemingly trivial thing with descriptors: have another attribute updated on dot access in object defined using descriptors. For example, let's take a simple example where you set an attribute s to a string and have another attribute l set automatically to its length.
1
1196
by: Chris Leary | last post by:
As I understand it, the appeal of properties (and descriptors in general) in new-style classes is that they provide a way to "intercept" direct attribute accesses. This lets us write more clear and concise code that accesses members directly without fear of future API changes. I love this feature of the language, but find that I still have to call getter/setter methods of module instances. Since module attributes are accessed by way of...
0
9617
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
10099
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
10036
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
8929
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...
1
7451
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
5354
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
5481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
2849
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.