Python evangelists unite!
Jason Voegele
jason at jvoegele.com
Wed Dec 5 11:32:06 EST 2001
"Jyrinx" <jyrinx at mindspring dot com> wrote in message news:<9ukbaj$thh$1 at slb0.atl.mindspring.net>...
> Gotcha. Well, at this point I can see the use for singleton methods in an
> object database, but I'm still not convinced of the need in a general
> language. In a more self-contained program, how often do you suddenly find
> yourself with someone else's object at runtime and need to add functionality
> like that?
One example I can think of is in a Web server implementation I was
working on. HTTP requires the line separator to be "CRLF"
(carraige-return line-feed). Ruby's IO methods use either '\n' or a
platform-specific line separator. Part of my application accepted a
socket connection back to the browser as a parameter. This method
generated a response and wrote it to the IO object passed in. Instead
of doing this everywhere:
print("Content-type: text/html \r\n")
I just did this:
def my_method(io)
def io.print(text)
self.print(text << "\r\n")
end
io.print("Content-type: text/html")
end
I changed the print method of the single instance of IO that I was
using, so this change did not affect other IO objects in the system.
Granted, I didn't *need* to do this, since I could have just added the
"\r\n" to the end of each print, but it's a lot easier and less
error-prone to do it OnceAndOnlyOnce.
> Besides, if I may continue stubbornly to stick by my favorite
> contender :-) , I should think it would be trivial to have a Python library
> to add this sort of runtime extension, if it isn't easy already. (Great.
> I've argued myself in a circle - Ruby supports this paradigm too well; well,
> maybe it could be useful; well, it's not hard in Python either :-) ... )
> Anyway, this looks to me like a useful feature best relegated to a standard
> library, more than a major feature of a general-purpose language.
I suppose it's one of those things where if you don't have it you
don't miss it, but once you've gotten used to it you'd be annoyed by
its absence.
> I could be wrong, though ... where else have you guys found singleton
> methods useful?
It happens very frequently in Ruby, since any class method is a
singleton method of the Class object for that class instance :) But
that of course is specific to the Ruby object model. (Maybe it works
like this in Smalltalk to? I don't know.)
In everyday application programming, I admit I don't use it all that
often, but I like to have it there when I need it. But consider that
any use of the Decorator pattern is easily implemented using singleton
methods.
Jason
More information about the Python-list
mailing list