473,397 Members | 1,961 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

subclassing str

Hi,

first of all, cheers to everyone, this is my first clp posting.

For an application, I need a special string-like object. It has some
specific semantics and behaves almost like a string, the only difference
being that it's string representation should be somewhat fancy. I want
to implement it as a subclass of str:

class SpecialString(str):
whatever

Using instances

x = SpecialString('foo')
y = SpecialString(x)

I want to get this behaviour:

str(x) => '(foo)'
str(y) => '(foo)'

That is, I want to be able to make a SpecialString from anything that has
a string representation, but at the same time leave a SpecialString
untouched in the process. After all, it already is and gets formatted as a
SpecialString.

I tried the following:

class SpecialString(str):
def __str__(self):
return "(" + self + ")"

This makes for str(x) => '(foo)' but str(y) => '((foo))' - as expected.

Does this accumulation of braces happen in the string itself, or does the
formatting routine get called several times at each str() call? How to fix
it, depending on the answer?

I tried reimplementing __init__() in order to treat the case that a
SpecialString is given to the constructor, but with little success. I
guess that something like

def __init__(self, obj):
if isinstance(obj, SpecialString):
self = raw(obj)
else:
self = obj

is needed, with raw() giving me the string without added parentheses,
bypassing the string representation. If this approach is sensible, what
would raw() look like?

Or is it best not to mess with __str__() at all, and introduce a render()
method?

Thanks & greetings,
Thomas

Jul 18 '05 #1
4 1914
"Thomas Lotze" <th**********@gmx.net> wrote in message
news:pa****************************@ID-174572.user.uni-berlin.de...
For an application, I need a special string-like object. It has some
specific semantics and behaves almost like a string, the only difference
being that it's string representation should be somewhat fancy. I want
to implement it as a subclass of str: .... That is, I want to be able to make a SpecialString from anything that has
a string representation, but at the same time leave a SpecialString
untouched in the process. After all, it already is and gets formatted as a
SpecialString.

I tried the following:

class SpecialString(str):
def __str__(self):
return "(" + self + ")"

This makes for str(x) => '(foo)' but str(y) => '((foo))' - as expected.

Does this accumulation of braces happen in the string itself, or does the
formatting routine get called several times at each str() call? How to fix
it, depending on the answer?

I tried reimplementing __init__() in order to treat the case that a
SpecialString is given to the constructor, but with little success.


I think you need to use __new__() instead of __init__(), like so:
class SpecialString(str): def __new__(cls, seq):
if isinstance(seq, SpecialString):
return str.__new__(cls, str(seq)[1:-1])
else:
return str.__new__(cls, seq)
def __str__(self):
return "(" + self + ")"
x = SpecialString("foo")
y = SpecialString(x)
print x (foo) print y

(foo)

For more info, see http://www.python.org/2.2.1/descrintro.html#__new__
--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.
Jul 18 '05 #2
Thomas Lotze wrote:
Using instances

x = SpecialString('foo')
y = SpecialString(x)

I want to get this behaviour:

str(x) => '(foo)'
str(y) => '(foo)'

That is, I want to be able to make a SpecialString from anything that
has a string representation, but at the same time leave a
SpecialString untouched in the process. After all, it already is and
gets formatted as a SpecialString.

Try this:
class SpecialString(str): def __new__(cls, s):
if isinstance(s, SpecialString):
s = s._raw()
return str.__new__(cls, s)
def __str__(self):
return "(" + self._raw() +")"
def _raw(self):
return str.__str__(self)

x = SpecialString('foo')
y = SpecialString(x)
print x (foo) print y

(foo)

You have to override __new__ as the default constructor for str calls the
__str__ method on its argument (which is where your extra parens appear).

Having added a method to bypass the formatting it makes sense to use it
inside __str__ as well otherwise the code is very sensitive to minor edits
e.g. changing it to:
return "(%s)" % self
would cause an infinite loop.
Jul 18 '05 #3
On Tue, 14 Sep 2004 09:30:43 -0400, Russell Blau wrote:
I think you need to use __new__() instead of __init__(), like so:
Thanks, that did the trick.
class SpecialString(str):

def __new__(cls, seq):
if isinstance(seq, SpecialString):
return str.__new__(cls, str(seq)[1:-1])
else:
return str.__new__(cls, seq)


I found it's actually possible to say seq[:] instead of str(seq)[1:-1],
which is less dependent on the exact format of the fancy representation.

So seq[:] seems to be a "trick" for getting at a sequence as it is,
without honouring its (string) representation. Thinking further, I wonder
what to do on non-sequence types, and whether there isn't a way to get to
an object's core that doesn't look like a trick. Or is it not all that
tricky after all?
For more info, see http://www.python.org/2.2.1/descrintro.html#__new__


Thanks for the pointer.

--
Viele Grüße,
Thomas

Jul 18 '05 #4
On Tue, 14 Sep 2004 13:49:08 +0000, Duncan Booth wrote:
class SpecialString(str):
def __new__(cls, s):
if isinstance(s, SpecialString):
s = s._raw()
return str.__new__(cls, s)

[...] def _raw(self):
return str.__str__(self)
Thanks a lot.
You have to override __new__ as the default constructor for str calls
the __str__ method on its argument (which is where your extra parens
appear).
Ah, good to have that piece of information.
Having added a method to bypass the formatting it makes sense to use it
inside __str__ as well otherwise the code is very sensitive to minor
edits e.g. changing it to:
return "(%s)" % self
would cause an infinite loop.


Yes, of course.

--
Viele Grüße,
Thomas

Jul 18 '05 #5

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

Similar topics

6
by: WhiteRavenEye | last post by:
Why can't I subclass any window except mine in VB? Do I have to write dll for this? I've tried to subclass it with SetWindowLong but without success... Does anyone know how to subclass window...
4
by: GrelEns | last post by:
hello, i wonder if this possible to subclass a list or a tuple and add more attributes ? also does someone have a link to how well define is own iterable object ? what i was expecting was...
2
by: David Vaughan | last post by:
I'm using v2.3, and trying to write to text files, but with a maximum line length. So, if a line is getting too long, a suitable ' ' character is replaced by a new line. I'm subclassing the file...
2
by: BJörn Lindqvist | last post by:
A problem I have occured recently is that I want to subclass builtin types. Especially subclassing list is very troublesome to me. But I can't find the right syntax to use. Take for example this...
3
by: Peter Olsen | last post by:
I want to define a class "point" as a subclass of complex. When I create an instance sample = point(<arglist>) I want "sample" to "be" a complex number, but with its real and imaginary...
11
by: Brent | last post by:
I'd like to subclass the built-in str type. For example: -- class MyString(str): def __init__(self, txt, data): super(MyString,self).__init__(txt) self.data = data
3
by: alotcode | last post by:
Hello: What is 'interprocess subclassing'? To give more context, I am writing in reference to the following remark: With the advent of the Microsoft Win32 API, interprocess subclassing was...
5
by: Pieter Linden | last post by:
Hi, This question refers sort of to Rebecca Riordan's article on Access web about subclassing entities: http://www.mvps.org/access/tables/tbl0013.htm How practical is this? I am writing a...
16
by: manatlan | last post by:
I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance "b". I know it's possible by hacking "b" with setattr() methods. But i'd like to do...
5
by: Ray | last post by:
Hi all, I am thinking of subclassing the standard string class so I can do something like: mystring str; .... str.toLower (); A quick search on this newsgroup has found messages by others
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
Oralloy
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,...
0
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...

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.