A better way of making subsclassing of built-in types stick for attributes?

T

telesphore4

Is there a better way to make the subclassing of built-in types stick?

The goal is to have the the fields of a class behave like strings with
extra methods attached. That is, I want the fact that the fields are
not strings to be invisible to the client programmers. But I always
want the extras to be there for the clients too.

What I'm doing is subclassing str. Of course, whenever you then set
mystr = 'a string' you loose the extra goodies that I have attached in
the subclass. So, to get around this I set up __get__ers and __set__ers
for the fields.

The question is there a more succinct way to have the extended string
behavior stick than using descriptors?

Just to make things concrete here's some abbreviated sample code:

class Person(Table.Table):
def __init__(self, tcs, gender=None, first=None, last=None,
status=None):
self.gender = gender
self.first = first
self.last = last
self.status = status

# Using mix-ins to get the desired behavior
class Gender(Field.InitAlways, Field.SqlVarchar):
table = ('F', 'M')
fillNext = -1
@classmethod
def fill(cls, rec):
cls.fillNext += 1
return cls.table[cls.fillNext % 2]

#classes First, Last, & Status are analogous but more complicated

# The descriptors are set up at the bottom of the module like so:
Person.first = Field.Descriptor(First)
Person.gender = Field.Descriptor(Gender)
Person.status = Field.Descriptor(Status)

# Moving along to other stripped supporting code

class Descriptor(object):
def __init__(self, cls, name=None):
self.cls = cls
if name == None:
self.name = cls.__name__.lower()
else:
self.name = name.lower()

def __set__(self, inst, value):
if inst.__dict__.has_key(self.name):
inst.__dict__[self.name] = self.cls(inst, value, True)
else:
inst.__dict__[self.name] = self.cls(inst, value, False)

class InitAlways(str):
def __new__(cls, rec, value, reset):
if reset:
return str.__new__(cls, value)
if value == Empty:
return str.__new__(cls, '')
if value == Fill or value == None: #if value in (None, Fill,
''):
return str.__new__(cls, cls.fill(rec) or '')
return str.__new__(cls, value or '')
 
B

Ben Finney

Is there a better way to make the subclassing of built-in types
stick?

They stick. Your new classes are available until you get rid of them.
The goal is to have the the fields of a class behave like strings
with extra methods attached. That is, I want the fact that the
fields are not strings to be invisible to the client
programmers. But I always want the extras to be there for the
clients too.

What I'm doing is subclassing str.

Sounds like the right way to do what you're describing. Your subclass
can then be used to instantiate objects that behave like 'str'
objects, except for the different behaviour you define in your class.
Of course, whenever you then set mystr = 'a string'

.... you're instantiating a 'str' object, since that's what the syntax
you use will do.
you loose the extra goodies that I have attached in the
subclass.

Because you haven't created an object of that subclass.
... """ Our groovy extended string class """
... pass
...
>>> foo = "Larry"
>>> bar = str("Curly")
>>> baz = GroovyStr("Moe")
>>> print [type(x) for x in foo, bar, baz]
[<type 'str'>, <type 'str'>, <class '__main__.GroovyStr'>]

The syntax used to make the object assigned to 'foo' is just a
shortcut for the syntax used to assign to 'bar'. If you want to
instantiate anything else, you need to use that explicit syntax, such
as for the object assigned to 'baz'.

If you're hoping that "subclass" means "modify the behaviour of the
original class", you're mistaken. It makes a *new* class that has
behaviour *inherited from* the original class.
 
T

telesphore4

Thanks.

Ben said:
... you're instantiating a 'str' object, since that's what the syntax
you use will do.


Because you haven't created an object of that subclass.

naturally.


The syntax used to make the object assigned to 'foo' is just a
shortcut for the syntax used to assign to 'bar'. If you want to
instantiate anything else, you need to use that explicit syntax, such
as for the object assigned to 'baz'.

If you're hoping that "subclass" means "modify the behaviour of the
original class", you're mistaken. It makes a *new* class that has
behaviour *inherited from* the original class.

Nah. I was hoping that I hadn't muffed the implementation and there was
a more Pythonic way of doing what I wanted.

Sounds like I've gotten things mostly right from the get go. which is
reassuring for a newbie. using __set__ is the correct way to hide the
vectoring to the __new__ assignment... no further shortcuts.

thanks again
t4
 
M

Maric Michaud

Le Mercredi 17 Mai 2006 06:17, (e-mail address removed) a écrit :
I want the fact that the fields are
not strings to be invisible to the client programmers.
You should use properties then.

In [12]: class mystr(str) : pass
....:

In [13]: class myrow(object) :
....: getX = lambda s : s._x
....: setX = lambda s, v : setattr(s, '_x', mystr(v))
....: X = property(getX, setX)
....:
....:

In [14]: r=myrow()

In [15]: r.X = 'toto'

In [16]: r.X
Out[16]: 'toto'

In [17]: type(r.X)
Out[17]: <class '__main__.mystr'>


--
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
 
T

telesphore4

Maric said:
Le Mercredi 17 Mai 2006 06:17, (e-mail address removed) a écrit :
You should use properties then.

I started with that idea, using the recipie 20.2 from the cookbook.
However, this caused a fair amount of code bloat... Err the way I
implemented it did at least. I may be missing a way to regularize the
process and make the whole process cleaner too.

The problem was that I needed to set the properties for all of the
object fields with boilerplate code that looks very much the same. Even
if the boilerplate was small, it was still bigger than the one-line
descriptor definitions at the bottom of the module. Shrinking the
descriptor definitions to a one-liner shrunk the code by a fair bit.
There are many classes (100+ when I'm done) and some of them have a
fair number of fields (up to 50) and all of them have to have the
snazzyStr abilities.

Another problem was esthetics; it forces me to place the main class at
the bottom of the module after the definition of the supporting
classes. Putting the descriptors after the bottom of the module left
the important parts at the top where they should be, IMO.

I wanted to use supporting classes for the field definitions because it
allowed me to use mix-ins. This was the biggest win in the design.

Thanks
t4
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,049
Members
48,769
Latest member
Clifft

Latest Threads

Top