473,626 Members | 3,304 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

descriptor & docstring

Hello,

I try to use python descriptors to define attributes with default
value (the code is reported below).
But apparently, it breaks the docstring mechanism.

help(Basis) shows the right help but help(Rectangle) shows only two
lines :
"
Help on class Rectangle in module basis2:

Rectangle = <class 'basis2.Rectang le'>
"
If the Rectangle.lengt h attribute is removed, the help is OK.

Secondly, the __doc__ attribute of a PhysicalValue instance doesn't
seem to be read.

I don't understand.

Any idea ?

Thanks a lot

Cyril.

# A descriptor class with default value handling
class PhysicalValue(o bject):
"""
A physical value descriptor
"""
def __init__(self, default_value):
self.default_va lue = default_value
self.__doc__ = "Hello from Physical Value"

def __get__(self, obj, type=None):
if obj.__dict__.ha s_key(self.key) :
return getattr(obj, self.key)
else:
return self.default_va lue

def __set__(self, obj, value):
if value is DefaultValue:
setattr(obj, self.key, self.default_va lue)
else:
setattr(obj, self.key, value)

# A meta class which adds instance attributes
# If hasattr(cls, "attr") then add "_attr" attribute.
class MyMetaClass(typ e):
def __init__(cls, name, bases, dct):
super(MyMetaCla ss, cls).__init__(n ame, bases, dct)
print "Add property to ", name
def init(self):
pvl = [item for item in cls.__dict__.it ems()
if isinstance(item[1], PhysicalValue)]
for pv in pvl:
print "Add _%s property to %s" % (pv[0], name)
cls.__dict__[pv[0]].key = "_" + pv[0]
setattr(self, "_" + pv[0], getattr(self, pv[0]))
cls.__init__ = init

# A basis class
class Basis(object):
"""
Tempest basis class
"""
__metaclass__ = MyMetaClass

# A concrete class
class Rectangle(Basis ):
"""
A beautiful Rectangle
"""
length = PhysicalValue(1 2.)
Jun 27 '08 #1
3 1570
A precision, I use python 2.5.2 under linux mandiva 2007.0

Cyril.
Jun 27 '08 #2
On Apr 28, 10:59*pm, "Gabriel Genellina"
def property_defaul t(prop_name, default_value=N one, doc=None):

* * *attr_name = '_'+prop_name

* * *def fget(self, attr_name=attr_ name,
* * * * * * * * * * default_value=d efault_value):
* * * * *return getattr(self, attr_name, default_value)

* * *def fset(self, value,
* * * * * * * * * * attr_name=attr_ name,
* * * * * * * * * * default_value=d efault_value):
* * * * *if value == default_value:
* * * * * * *delattr(self, attr_name)
* * * * *else:
* * * * * * *setattr(self, attr_name, value)

* * *return property(fget=f get, fset=fset, doc=doc)

When setting the same value as the default, the instance attribute is *
removed (so the default will be used when retrieving the value later). I *
think this is what you intended to do.
Note that this will fail if the value is already equal to the default
and you try to reset it to the default, so it needs an extra
hasattr(self, attr_name) before the delattr. Regardless, I would be
surprised with the following behaviour:
>>r = Rectangle()
r.length = 4
type(r.length )
<type 'int'>
>>r.length = 12
type(r.length )
<type 'float'>

Another simpler alternative would be to (ab)use a decorator:

def defaultproperty (func):
attr = '_' + func.__name__
default = func.func_defau lts[0]
return property(
fget = lambda self: getattr(self, attr, default),
fset = lambda self,value: setattr(self, attr, value),
doc = func.__doc__)
class Rectangle(objec t):
'''A beautiful Rectangle'''

@defaultpropert y
def length(default= 12.0):
'''This is the length property'''

George
Jun 27 '08 #3
En Tue, 29 Apr 2008 01:29:40 -0300, George Sakkis
<ge***********@ gmail.comescrib ió:
On Apr 28, 10:59*pm, "Gabriel Genellina"
>def property_defaul t(prop_name, default_value=N one, doc=None):

* * *attr_name = '_'+prop_name

* * *def fget(self, attr_name=attr_ name,
* * * * * * * * * * default_value=d efault_value):
* * * * *return getattr(self, attr_name, default_value)

* * *def fset(self, value,
* * * * * * * * * * attr_name=attr_ name,
* * * * * * * * * * default_value=d efault_value):
* * * * *if value == default_value:
* * * * * * *delattr(self, attr_name)
* * * * *else:
* * * * * * *setattr(self, attr_name, value)

* * *return property(fget=f get, fset=fset, doc=doc)

When setting the same value as the default, the instance attribute is *
removed (so the default will be used when retrieving the value later).
I think this is what you intended to do.

Note that this will fail if the value is already equal to the default
and you try to reset it to the default, so it needs an extra
hasattr(self, attr_name) before the delattr. Regardless, I would be
surprised with the following behaviour:
>>>r = Rectangle()
r.length = 4
type(r.lengt h)
<type 'int'>
>>>r.length = 12
type(r.lengt h)
<type 'float'>
Yep, probably the best thing to do is to always call setattr and avoid
special cases.
Another simpler alternative would be to (ab)use a decorator:

def defaultproperty (func):
attr = '_' + func.__name__
default = func.func_defau lts[0]
return property(
fget = lambda self: getattr(self, attr, default),
fset = lambda self,value: setattr(self, attr, value),
doc = func.__doc__)
class Rectangle(objec t):
'''A beautiful Rectangle'''

@defaultpropert y
def length(default= 12.0):
'''This is the length property'''

Nice, although that empty function looks somewhat strange...

--
Gabriel Genellina

Jun 27 '08 #4

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

Similar topics

0
1443
by: drs | last post by:
I am periodically getting a Bad File Descriptor error from Python DCOM servers. I have seen a number of posts regarding this error and threads, but these are not multithreaded servers. Further, if i register the servers with the --debug flag, the errors go away, so I am not able to find out much in the way of information. Has anyone else seen this? Any suggestions? Python 2.0/2.1/2.2 on win2k pro/server
3
7073
by: Max Khesin | last post by:
Is there a way to access an htaccess-protected directory with urllib, password being known? thanks, max -- ======================================== Max Khesin, software developer - max@cNvOiSsPiAoMntech.com www.cvisiontech.com, JBIG2-PDF compression @
0
1231
by: Benoît Dejean | last post by:
does swig handle docstring ? i have written a C module using siwg, and i want to add some documentation using docstring. how can i do ?
1
2079
by: Andrew Durdin | last post by:
How do you get the docstring of a property? Suppose I have the following: class Foo: def _prop_get(self): return 1 prop = property(_prop_get, doc="This is the docstring") foo = Foo() print foo.prop print foo.prop.__doc__
0
1095
by: Eric Huss | last post by:
I'm trying to write a descriptor (similar to the EiffelDescriptor example in the Demo directory). However, I noticed an odd behavior that descriptors written in pure Python mask the underlying object they are wrapping, whereas the descriptors written in C do not. For example, taking the code from http://users.rcn.com/python/download/Descriptor.htm which implements what one would think is a straightforward implementation: class...
1
2790
by: rbt | last post by:
The below script produces a ' Bad File Descriptor' when executed. If I remove the try: except: statements, the script stops when the error occurs. The purpose of the script is to monitor the size of the three main logs on a Windows 2003 server and send and email should any of the logs get shorter. It works fine... just don't know *why* it produces the ' Bad File Descriptor' error. I'm running Python 2.4.1 on Windows 2003 SP1 Server...
3
1925
by: Berthold Höllmann | last post by:
Saving the following code to a file and running the code through python does not give the expected error. disableling the "@decor" line leads to the expected error message. Is this a bug or an overseen feature? --- snip dectest.py --- class decor(object): def __init__(self, f): self.f = f
4
1333
by: Colin J. Williams | last post by:
Is there some way that the user can access the docstring specified for a property? Please see the example below: # propDocTest class A(object): def __init__(self, value): self.value= value def vGet(self):
2
1541
by: WaterWalk | last post by:
Hello, I was recently learning python decorator and descriptor and emulated a @classmethod decorator: class EmuClassMethod(object): def __init__(self, f=None): self.f = f def __get__(self, obj, klass=None): if klass is None: klass = type(obj) def wrapped(*args): return self.f(klass, *args)
0
8203
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,...
0
8642
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...
0
8512
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
7203
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
6125
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
5576
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
4206
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2630
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
2
1515
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.