Hi.
I would like to have declarative properties in Python, ie. something
like slots definitions in defclass in Common Lisp. It seems that even
Java will have it, using a library ( https://bean-properties.dev.java.net/
).
I know about 'property' function in Python, but it's normal usage
isn't declarative, because I have to code imperatively getters and
setters:
class Person(object):
def __init__(self, name):
self._name = name
def _get_name(self) :
return self._name
def _set_name(self, new_name):
self._name = new_name
name = property(_get_n ame, _set_name)
I would like to have something like that:
class Person(object):
name = property('_name ')
I assume that this causes "generation " of instance field '_name' and
default getters and setters. And if I would like to customize (g|
s)etters, I would write them by hand, or, better, use more declarative
approach (like @NotNull annotations in Java version).
I could probably code a solution to my problem with help of wonderful
introspection functionalities . But I'm looking for a standard and/or
proven way of doing this. Maybe some PEP is being prepared for this?
Regards,
Artur 20 2323
On Thu, 11 Oct 2007 11:48:18 +0000, Artur Siekielski wrote:
class Person(object):
def __init__(self, name):
self._name = name
def _get_name(self) :
return self._name
def _set_name(self, new_name):
self._name = new_name
name = property(_get_n ame, _set_name)
This is more easily spelled:
class Person(object):
def __init__(self, name):
self.name = name
I would like to have something like that:
class Person(object):
name = property('_name ')
I assume that this causes "generation " of instance field '_name' and
default getters and setters.
But why? Default getters and setters are unnecessary and if you need
something other than the default you need to write it anyway more
explicitly.
Ciao,
Marc 'BlackJack' Rintsch
Artur Siekielski a écrit :
Hi.
I would like to have declarative properties in Python, ie. something
like slots definitions in defclass in Common Lisp. It seems that even
Java will have it, using a library ( https://bean-properties.dev.java.net/
).
I know about 'property' function
Actually, it's a class.
in Python, but it's normal usage
isn't declarative, because I have to code imperatively getters and
setters:
Indeed. What would be the use of a property (AKA computed attribute) if
you don't need to do something specific ?
class Person(object):
def __init__(self, name):
self._name = name
def _get_name(self) :
return self._name
def _set_name(self, new_name):
self._name = new_name
name = property(_get_n ame, _set_name)
While it's often seen as demonstration code for a property, it's
actually totally useless. If all you want to do is to get and set an
attribute (I mean, without any computation anywhere), then just use an
attribute - you will always be able to turn it into a property if and
whene the need arises.
I would like to have something like that:
class Person(object):
name = property('_name ')
I assume that this causes "generation " of instance field '_name' and
default getters and setters.
So far, it's a waste of time. That's exactly what you'd get with a plain
attribute, with far less complexity and overhead.
And if I would like to customize (g|
s)etters, I would write them by hand,
Which bring us back to how properties actually work !-)
or, better, use more declarative
approach (like @NotNull annotations in Java version).
I could probably code a solution to my problem with help of wonderful
introspection functionalities . But I'm looking for a standard and/or
proven way of doing this. Maybe some PEP is being prepared for this?
I guess you want to have a look at the descriptor protocol - it's what
makes properties work, and it allow you to write your own custom 'smart
attributes'. If you want automatic validation/conversion, you could
write custom descriptors working with the FormEncode package (I started
such a thing for Elixir, but had no time to finish it so far). It would
then looks like:
class Person(object):
name = StringField(emp ty=False)
// etc
HTH
On Thu, 11 Oct 2007 13:46:12 +0000, Marc 'BlackJack' Rintsch wrote:
On Thu, 11 Oct 2007 13:04:53 +0000, Artur Siekielski wrote:
>On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch <bj_...@gmx.net wrote:
>>But why? Default getters and setters are unnecessary and if you need something other than the default you need to write it anyway more explicitly.
I see some problems with your approach:
1. If I use instance field 'name' which is accessed directly by other classes, and later I decide to implement nonstandard getter, I must refactor 'Person' class and in some places change 'name' to '_name' (assuming this is now the field's name). The problem is that I cannot automatically change 'name' to '_name' everywhere, because in some places I want public property value (eg. validated and formatted), and in other places raw property value.
So what? Otherwise you carry *always* the baggage of a public property
and a private attribute whether you need this or not. At least for me it
would be unnecessary in most cases.
That "baggage" of carrying around "unneeded" methods is something the
computer carries for you - IE, no big deal in 99.99% of all cases.
The "baggage" of possibly fixing (AKA "generalizi ng") how your attributes
are accessed is something you lug around while your deadline looms.
Here's some code that defines such methods for you:
#!/usr/bin/env python
def gimme_set_get(f oo, attribute):
lst = [ \
'def set_%s(self, value):' % attribute, \
' self._%s = value' % attribute, \
'def get_%s(self):' % attribute, \
' return self._%s' % attribute, \
'foo.set_%s = set_%s' % (attribute, attribute), \
'foo.get_%s = get_%s' % (attribute, attribute) \
]
s = '\n'.join(lst)
code = compile(s, '<string>', 'exec')
eval(code)
class foo:
def __init__(self, value):
self.public_val ue = value
gimme_set_get(f oo, 'via_accessor_m ethod_only')
f = foo(1)
f.set_via_acces sor_method_only (1/9.0)
print f.get_via_acces sor_method_only ()
print dir(f)
On Thu, 11 Oct 2007 09:58:48 -0700, Dan Stromberg wrote:
On Thu, 11 Oct 2007 13:46:12 +0000, Marc 'BlackJack' Rintsch wrote:
>On Thu, 11 Oct 2007 13:04:53 +0000, Artur Siekielski wrote:
>>1. If I use instance field 'name' which is accessed directly by other classes, and later I decide to implement nonstandard getter, I must refactor 'Person' class and in some places change 'name' to '_name' (assuming this is now the field's name). The problem is that I cannot automatically change 'name' to '_name' everywhere, because in some places I want public property value (eg. validated and formatted), and in other places raw property value.
So what? Otherwise you carry *always* the baggage of a public property and a private attribute whether you need this or not. At least for me it would be unnecessary in most cases.
That "baggage" of carrying around "unneeded" methods is something the
computer carries for you - IE, no big deal in 99.99% of all cases.
It shows twice as much attributes if I inspect the objects and I don't know
which are merely useless default getters and setters. And it is more and
more complex code. Code can be cut down a bit by some metaclass magic but
this brings in another complexity.
The "baggage" of possibly fixing (AKA "generalizi ng") how your attributes
are accessed is something you lug around while your deadline looms.
Sorry I don't get it. If I want to customize the access to a "normal"
attribute I simply turn it into a property.
Here's some code that defines such methods for you:
#!/usr/bin/env python
def gimme_set_get(f oo, attribute):
lst = [ \
'def set_%s(self, value):' % attribute, \
' self._%s = value' % attribute, \
'def get_%s(self):' % attribute, \
' return self._%s' % attribute, \
'foo.set_%s = set_%s' % (attribute, attribute), \
'foo.get_%s = get_%s' % (attribute, attribute) \
]
s = '\n'.join(lst)
code = compile(s, '<string>', 'exec')
eval(code)
class foo:
def __init__(self, value):
self.public_val ue = value
gimme_set_get(f oo, 'via_accessor_m ethod_only')
f = foo(1)
f.set_via_acces sor_method_only (1/9.0)
print f.get_via_acces sor_method_only ()
print dir(f)
And the benefit of this evil ``eval`` dance is exactly what!?
Ciao,
Marc 'BlackJack' Rintsch
On Oct 11, 12:48 pm, Artur Siekielski <artur.siekiel. ..@gmail.com>
wrote:
Hi.
I would like to have declarative properties in Python, ie. something
like slots definitions in defclass in Common Lisp. It seems that even
Java will have it, using a library (https://bean-properties.dev.java.net/
).
I know about 'property' function in Python, but it's normal usage
isn't declarative, because I have to code imperatively getters and
setters:
class Person(object):
def __init__(self, name):
self._name = name
def _get_name(self) :
return self._name
def _set_name(self, new_name):
self._name = new_name
name = property(_get_n ame, _set_name)
I would like to have something like that:
class Person(object):
name = property('_name ')
Here's something that does what I think you want. I think your use
case is quite unusual in that you expect the public accessors to
change (keeping private use the same), and that you know you're going
to have a costly rewrite of your class when that happens.
Attributes that are declared with 'magic_attribut e' access the private
attribute '_<name>', unless there's a '_get_<name>' or '_set_<name>'
method in which case those are called instead.
def magic_attribute (_name):
def set(self, value):
try:
getattr(self, '_set' + _name)(value)
except AttributeError:
setattr(self, _name, value)
def get(self):
try:
return getattr(self, '_get' + _name)()
except AttributeError:
return getattr(self, _name)
return property(get, set)
# An example use...
class C(object):
x = magic_attribute ('_x')
y = magic_attribute ('_y')
# Override the default set method for x
def _set_x(self, value):
self._x = value + ' world'
# Override the default get method for y
def _get_y(self):
return self._y.upper()
# Test it works...
c = C()
c.x = c.y = 'hello'
print c.x
print c.y
# hello world
# HELLO
--
Paul Hankin
On Oct 11, 7:42 pm, Marc 'BlackJack' Rintsch <bj_...@gmx.net wrote:
Sorry I don't get it. If I want to customize the access to a "normal"
attribute I simply turn it into a property.
I *think* I understand Artur's problem: he wants to be able to add
(for example) clean-up and validation code to public accesses of these
attributes, but he doesn't want this code run internally to the class.
Or another way of saying the same thing: he wants two views of a
variable; one internal to the class, another to the public.
If I understand correctly, his plan is to use 'X._name' internally to
code in his class, but the public uses 'X.name'. Initially, one is an
alias for the other, but later he writes getters and setters to
customise access through the public version.
[I could be totally wrong of course]
--
Paul Hankin
On Oct 11, 7:48 am, Artur Siekielski <artur.siekiel. ..@gmail.com>
wrote:
I know about 'property' function in Python, but it's normal usage
isn't declarative, because I have to code imperatively getters and
setters:
class Person(object):
def __init__(self, name):
self._name = name
def _get_name(self) :
return self._name
def _set_name(self, new_name):
self._name = new_name
name = property(_get_n ame, _set_name)
I would like to have something like that:
class Person(object):
name = property('_name ')
By now you must have been convinced that default getters/setters is
not a very useful idea in Python but this does not mean you can't do
it; it's actually straightforward :
def make_property(a ttr):
return property(lambda self: getattr(self,at tr),
lambda self, value: setattr(self, attr, value))
class Person(object):
name = make_property(' _name')
def __init__(self, name):
self.name = name
You could take it even further by removing the need to repeat the
attribute's name twice. Currently this can done only through
metaclasses but in the future a class decorator would be even better:
def PropertyMaker(* names, **kwds):
format = kwds.get('forma t', '_%s')
def meta(cls,bases, attrdict):
for name in names:
attrdict[name] = make_property(f ormat % name)
return type(cls,bases, attrdict)
return meta
class Person(object):
__metaclass__ = PropertyMaker(' name', format='__%s__' )
def __init__(self, name):
self.name = name
print self.__name__
George
On Oct 11, 7:04 pm, George Sakkis <george.sak...@ gmail.comwrote:
You could take it even further by removing the need to repeat the
attribute's name twice. Currently this can done only through
metaclasses but in the future a class decorator would be even
better:
Replying to myself here, but actually metaclasses is not the only way;
another solution involves a descriptor class:
class Property(object ):
# cache the mapping of types to 'private' attribute names
_type2attrname = {}
def __init__(self, format='_%s'):
self._format = format
def __get__(self, obj, type=None):
try: name = self._type2attr name[type(obj)]
except KeyError:
self._type2attr name[type(obj)] = name =
self._get_propn ame(obj)
return getattr(obj, name)
def __set__(self, obj, value):
try: name = self._type2attr name[type(obj)]
except KeyError:
self._type2attr name[type(obj)] = name =
self._get_propn ame(obj)
setattr(obj, name, value)
def _get_propname(s elf, obj):
for cls in type(obj).mro() :
for name,value in cls.__dict__.it eritems():
if value is self:
return self._format % name
assert False # unreachable
#---- example ------------------------------------
class Person(object):
name = Property()
def __init__(self, name):
self.name = name
p = Person('John')
q = Person('Mike')
print p.name, q.name
print p.__dict__
George
George Sakkis wrote:
By now you must have been convinced that default getters/setters is
not a very useful idea in Python but this does not mean you can't do
it;
It's a perfect summary of my thoughts after reading this thread. I
will use public attributes (with access customizable with properties)
and remember that in Python I can do everything :).
Thanks everybody. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Eric Newton |
last post by:
VB's more declarative nature of handling events is golden. I'm hoping C#
will acquire this type of deal, in addition to the anonymous delegates.
could do same as vb (actually would be easier to parse then vb due to
braces) whereas you look for Handles keyword after method sig, but before
opening brace of the method.
compiler would implicitly build event handling code for all typed
constructions, ie, any variables instances constructed...
|
by: Ann Huxtable |
last post by:
I keep coming accross C# code that has sections of code like this:
could any one please explain what these sections are (reminds me of
XDoclet tags in Java programming) or better still - a reference to where
I can read up on this.
Thanks
|
by: s.gregory |
last post by:
Is it no longer possible to declaretively define SQLConnections and
SQLCommands in the Web Service design page AND reference a connection
string in the Web.Config file?
..NET 1.x had dynamic properties but they seem to no longer exist. It
also doesn't seem possible to use the new Expression Builders in a Web
Service project either.
Any advice would be most welcome!
|
by: Nick |
last post by:
Is there a way to do declarative security on abstract classes? I am working
on a data access layer and would like to place all permission requirements on
the base class so all inherited classes contain the permissions. Is this
possible, and if so can anyone provide an example?
|
by: |
last post by:
I'm finishing an .ascx control that takes custom properties. I've made a
generalized administrative form that can be made specific by calling the
user control with a bunch of parameters (e.g. <uc1:IconicNews
ControlsTemplateName="FlashNewsBar" ControlsContentCategoryID="35"
ControlsIconWidth="100" ControlsIconAspectRatio="1.538"
ControlsPhysicalPathForImages=...)
I want customized titles to appear on the administrative forms associated...
| |
by: Steven T. Hatton |
last post by:
All of the following terms are used in some way to describe where and how a
name is relevant to a particular location in a program: visible,
declarative region, scope, potential scope, valid, introduced, used,
potentially evaluated and accessible. They all seem to have subtle
difference in meanings.
Any positive contribution to the following will be appreciated.
Here is my attempt to make sense of these:
|
by: MULTISY |
last post by:
Here is the situation, the WebPartManager exists on the masterpage, and the
web part is being declared in the contentplaceholder on the aspx page like
so:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
<myWP:nowNeedPersonalization runat="server" ID="help" />
</asp:Content>
Now this web part need additional properties added and persisted for the
shared view of users, but when using...
|
by: Ken Cox [Microsoft MVP] |
last post by:
I've been going around and around on this one. I can't believe that it is
"by design" as Microsoft says.
Here's the situation:
In *declarative* syntax, I'm trying to create a default datetime value for a
SqlDataSource parameter. (I know how to insert this parameter in code. I
want to use declarative markup.)
Here's the declarative markup with ???????? indicating where I'm stumped.
|
by: drop |
last post by:
Hi all,
I'd like to know if it's possible to declare an implicit type
conversion for when I use declarative Synthax in html.
For example, when I have the DropDownList, I can declatively set it's
Selected value like this : SelectedValue='<%# Bind("TaxCondition")
%>'. In this case, TaxCondition is an int, and the conversion from int
to string and string to int is made automatically.
|
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...
|
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,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |