Re: Factory for Struct-like classes

2008-08-20 Thread Dave Benjamin

eliben wrote:

Whaaa? Named tuples are being added to Python? Neat! Is there any
documentation on this? I can't seem to find anything on the web...


It's not easy to find unless you recall where you've seen it:
http://docs.python.org/dev/3.0/library/collections.html#collections.namedtuple


Thanks!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Factory for Struct-like classes

2008-08-20 Thread Dave Benjamin

Christian Heimes wrote:

eliben wrote:

Ruby's 'Scruct' class (http://ruby-doc.org/core/classes/Struct.html)
does this. I suppose it can be done with 'exec', but is there a more
Pythonic way ?


Try named tuple http://code.activestate.com/recipes/500261/

A named tuple implementation is part of Python 2.6 and 3.0. For older 
versions of Python use the recipe from activestate.


Whaaa? Named tuples are being added to Python? Neat! Is there any 
documentation on this? I can't seem to find anything on the web...


Thanks,
Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] minimalist web server

2007-12-01 Thread Dave Benjamin
Daniel Fetchinson wrote:
> The reason I need this is that my current best strategy to avoid ads
> in web pages is putting all ad server names into /etc/hosts and stick
> my local ip number next to them (127.0.0.1) so every ad request goes
> to my machine. I run apache which has an empty page for 404 errors so
> I'll just see that blank page for every ad. Now I guess apache is a
> pretty heavy weight guy so I'm looking for a lightweight alternative.
> Lighttpd, nginx and company are all too complex and "know" too much. I
> even considered just putting netcat into an infinite loop but I'm
> afraid if there is a security hole in netcat I might be screwed.

I don't know if this qualifies as "lightweight", but my current best 
strategy is to block ads using a Squid proxy. My /etc/squid/squid.conf has:

acl ads dstdom_regex -i "/etc/squid/squid.adservers"
http_access deny ads
deny_info javascript:void(0) ads

/etc/squid/squid.adservers came from this site:
http://pgl.yoyo.org/adservers/

Ads completely disappear with no visible errors or unnecessary HTTP 
requests. (Sorry, no Python needed for this one.)

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Resize image NO PIL!!

2007-05-28 Thread Dave Benjamin
cbmeeks wrote:
> I have created an image hosting site and when a user uploads an image,
> I want a service to run on the server to create a few thumbnails while
> the user does other things.
> 
> My stupid host (pair.com) doesn't have PIL installed and I'm too much
> of a stupid newbie to figure out how to get it to work with them
> (access denied while installing it, of course).
> 
> Also, they don't have any python interface setup for GD.
> 
> Anyway, I don't know what my options are.  I'm thinking:
> 
> 1) Find another host with mod_python, PIL, and other Python goodies
> 2) use PHP to create the thumbnails
> 3) Open the images into a buffer and try to do the calculations
> myself

Have you checked to see if Imagemagick is available? You could use the 
"convert" command via os.system or something along those lines...

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading the tilde operator?

2007-02-07 Thread Dave Benjamin
Neil Cerutti wrote:
> There's been only one (or two?) languages in history that
> attempted to provide programmers with the ability to implement
> new infix operators, including defining precedence level and
> associativity (I can't think of the name right now).

You're probably thinking of SML or Haskell. OCaml also allows you to 
define new infix operators, but the associativities are fixed (and 
determined by what punctuation you use).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Partial classes

2006-07-19 Thread Dave Benjamin
On Wed, 18 Jul 2006, Sanjay wrote:

> What is the equivalent in Python? Inheriting is a way, but is not
> working in all scenerios.

Have you tried multiple inheritance? For example:

from GeneratedPerson import GeneratedPerson
from HandcraftedPerson import HandcraftedPerson

class Person(GeneratedPerson, HandcraftedPerson):
 pass

If this doesn't work for you, can you explain why?

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time to bundle PythonWin

2006-05-16 Thread Dave Benjamin
Martin v. Löwis wrote:
> Dave Benjamin wrote:
>> Why is PythonWin (win32all) still a separate download from a third
>> party? Is it legal, technical, or what? I think it's about time it be
>> part of the standard distribution.
> 
> Both legal and technical. The PythonWin author and maintainer (Mark
> Hammond) hasn't contributed this package for inclusion into Python.
> Without him explicitly saying that he wants that to happen, and prefers
> that over maintaining it outside Python himself, there is no way it
> could ever get included. This is a basic rule of politeness in open
> source software: don't fork, not even if you are legally allowed to.
> [of course, forks happen, typically because people don't consider
>  it important enough to be polite to the original author]

Sure. I wasn't proposing that this be done behind Mark's back. I wasn't 
even proposing a fork; rather, just two installers bundled into one. The 
user, upon running the .msi file, would simply be asked if they'd like 
PythonWin also. PythonWin could be automatically combined into the 
installer by downloading the latest version from SourceForge, perhaps.

> Now, if Mark did indeed offer it for inclusion, I would request (and
> also work on if I find the time) that the structure of these libraries
> is revised. I know that the current structure tries to be "natural"
> in some sense, but I find the assignment of API functions to modules
> quite arbitrary. I also think that some of the API functions should
> be replaced with their *Ex versions that Microsoft added over time.

Well, I'm sure the structure could be improved, but there's really 
nothing else quite like PythonWin out there. And I could think of parts 
of Python's standard library that evolved organically (os.popen2 thru 12 
comes to mind ;-) ) which could stand some reorganization. But anyway, I 
digress...

> Coming back to organizational issues: it would surely help if people
> would actively contribute to PythonWin. I believe this still is
> primarily a one-man show, and that Mark does an excellent job should
> not be an excuse for you to not contribute.

If only I had his expertise on the win32 API...

>> There are many useful things that you ought to be able to do without
>> downloading third-party libraries. Terminating a process, for example.
> 
> You can use subprocess.TerminateProcess for that (in some limited way).

Good to know, although this requires Python 2.5. I'm getting rather 
excited about Python 2.5... looks like a lot of useful new tools are in 
the pipeline.

>> Communicating with other applications via a standard, common protocol
>> (COM). We demand these things from our UNIX environments--why do we
>> tolerate their omission on the Windows platform?
> 
> We tolerate them because they aren't omitted. They are readily
> available, and we are all lazy enough to never do more than just
> post to a newsgroup complaining about it.

Well, good, at least I'm not the only lazy complainer around here. =)

>> It's time to bundle PythonWin.
> 
> So go and work on that.

Nah. Sounds like the better option is to wait for ctypes in 2.5...

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time to bundle PythonWin

2006-05-16 Thread Dave Benjamin
[EMAIL PROTECTED] wrote:
> The ctypes.com package is no longer part of ctypes.
> It has been split by Thomas Heller into a separate package comtypes.
> See: http://sourceforge.net/projects/comtypes/
> 
> Still in its childhood but as easy as com can get, I guess, way easier
> and better than pythonWin at least.

What makes you say it's way easier? PythonWin is pretty darn easy, from 
my experience.

If ctypes is going to be standard, and ctypes.com is pure-Python, I 
really have no reason left to complain. I do have to rewrite some 
scripts, but this isn't a big deal.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time to bundle PythonWin

2006-05-16 Thread Dave Benjamin
Ten wrote:
> Respectfully, that sounds like a reason for *you* to bundle pythonwin (and 
> python, to be honest :) ), not a reason for everyone else to have to download 
> an extra 40-50% of potentially superfluous cruft with their standard python 
> setup.

Certainly, I could bundle Python and PythonWin myself. I'll even admit 
that my little office utilities would be better distributed as frozen 
.exe files with all the necessary libraries bundled inside. But my 
original problem as stated was this:

   1. I release a Python script (a .py file)
   2. My user upgrades or switches computers
   3. They (logically) download and install Python
   4. My script still doesn't work
   5. They ask me for help

At this point, I dig through four or five web sites to find where 
PythonWin is hosted these days, and it's obvious that my user never 
would have guessed to download it, or found the right place to retrieve 
it. If the windows installer for Python came with PythonWin, they might 
not have needed my help at all.

I realize that other people's needs aren't the same as mine, but this 
scenario isn't contrived. This has happened numerous times. Bundling 
PythonWin myself wouldn't solve this particular problem as stated.

> In more general terms I can see why it would be useful to some windows people
> to have more winapi stuff available. I can still think of quite a few things 
> I'd rather be spending that extra download time on myself, though, like a 
> sexed-up tkinter or maybe even a new gui toolkit.

I'd happily download a larger installer for any or all of these things. 
In the time it took me to write this, I'd probably already have finished 
the download anyway.

> Still, it's not an either/or choice, I suppose.

Yep. =)

Cheers,
Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time to bundle PythonWin

2006-05-12 Thread Dave Benjamin
On Thu, 11 May 2006, Alex Martelli wrote:

> Dave Benjamin <[EMAIL PROTECTED]> wrote:
>   ...
>> It's time to bundle PythonWin.
>
> No: the Python Standard Distribution, in 2.5, includes instead ctypes,
> which is lower-level than PythonWin but more general (exists for other
> platforms, lets you call other DLLs on Windows and not just those
> wrapped for you by the author).

I didn't realize you could do COM with ctypes. Thanks for the tip! Are 
there any caveats to this approach?

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time to bundle PythonWin

2006-05-11 Thread Dave Benjamin
On Thu, 11 May 2006, Robert Hicks wrote:

> No it isn't. It is a Windows only package. It needs to stay a separate
> download.

The Windows installer for Python is an MSI file. It's already Windows 
only.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Time to bundle PythonWin

2006-05-11 Thread Dave Benjamin
Hey folks,

Why is PythonWin (win32all) still a separate download from a third party? 
Is it legal, technical, or what? I think it's about time it be part of the 
standard distribution.

There are many useful things that you ought to be able to do without 
downloading third-party libraries. Terminating a process, for example. 
Communicating with other applications via a standard, common protocol 
(COM). We demand these things from our UNIX environments--why do we 
tolerate their omission on the Windows platform?

Mac libraries are bundled with Python's *standard library*. I'm not even 
advocating merging the win32 extensions with the standard library. All I'm 
saying is that when you install Python on Windows, it should ask you if 
you want to install PythonWin too, and that this option be selected by 
default.

I write applications that use COM and Tkinter to automate basic office 
tasks. My users are thankfully benevolent enough to download and install 
Python on their own. They don't know what PythonWin is, they aren't 
remembering it, and frankly, I don't think it should be their concern.

It's time to bundle PythonWin.

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
  "we control the sun" - toys that kill
-- 
http://mail.python.org/mailman/listinfo/python-list


OT: Mozart (was Re: perspective on ruby)

2006-04-21 Thread Dave Benjamin
On Thu, 20 Apr 2006, Alex Martelli wrote:

> Edward Elliott <[EMAIL PROTECTED]> wrote:
>   ...
>> course in C++ doesn't cut it, the curriculum should either use different
>> languages fitted to each task or emphasize a single language with broad
>> abilities (picking the best programming model for each task).  Java is
>
> The only "single language" I could see fitting that role is Mozart,
> deliberately designed to be SUPER-multi-paradigm -- not even Lisp and
> Scheme (the only real competition) can compare.

I agree that Mozart/Oz is probably the most ambitiously multi-paradigm 
language out there, and anyone interested in some real mind expansion 
should really check out the excellent book, "Concepts, Techniques, and 
Models of Computer Programming" by Peter Van Roy and Seif Haridi.

However, my impression of Mozart/Oz so far can be summed up like this: 
"You can have any paradigm you want, as long as it's concurrent". The 
degree to which out-parameters are used (in the form of "dataflow 
variables") is very unusual for OO or FP, and this is a source of both 
amazement and confusion for me. It's clearly possible to program in many 
styles, but you still need to adapt your thinking to the Mozart way.

Also worth a mention is Alice ML, which runs on the Mozart system but is 
statically typed, type-inferred, very similar to SML but with concurrency 
support (lazies and futures), typesafe marshalling, and "packages", which 
allow for dynamically-typed interfaces between modules.

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
"one man's constant is another man's variable" - alan perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing csh scripts with python

2006-03-28 Thread Dave Benjamin
On Tue, 28 Mar 2006, David Hirschfield wrote:

> I need to be able to parse the script, modify some variable settings and 
> then write the script back out so that the only changes are the 
> variables I've modified (comments, ordering of statements, etc. must 
> remain the same).
>
> I looked at shlex, but I don't think it will do what I need.

What about regular expressions?

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
"one man's constant is another man's variable" - alan perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function params with **? what do these mean?

2006-03-20 Thread Dave Benjamin
On Mon, 20 Mar 2006, Ben Cartwright wrote:

> Dave Hansen wrote:
>> On 20 Mar 2006 15:45:36 -0800 in comp.lang.python,
>> [EMAIL PROTECTED] (Aahz) wrote:
>>> Personally, I think it's a Good Idea to stick with the semi-standard
>>> names of *args and **kwargs to make searching easier...
>>
>> Agreed (though "kwargs" kinda makes my skin crawl).
>
> Coincidentally, "kwargs" is the sound my cat makes when coughing up a
> hairball.
>
> Fortunately, **kw is also semi-standard.

I prefer the semi-standard **kwds, myself. ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import, from and reload

2006-03-02 Thread Dave Benjamin
On Thu, 2 Mar 2006, John Salerno wrote:

> Dave Benjamin wrote:
>
>> In general, "from X import *" should be avoided anyway, for reasons that 
>> have been discussed many times in the past. The annoyance with reloading is 
>> just one more reason. Better to just use "import X" in the first place.
>
> Thanks. I kind of figured it's better to use import instead of from anyway, 
> but I was following along with some examples that use from (despite the fact 
> that earlier in the book they even say that from is problematic and you 
> should use import instead!)  :)

No problem. I stand by my original advice, but there is one semi-oneliner 
that you might find useful:

reload(__import__('X')); from X import *

You could keep that in your clipboard and paste it into the interpreter 
when you need to reload.

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
"one man's constant is another man's variable" - alan perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import, from and reload

2006-03-02 Thread Dave Benjamin
On Thu, 2 Mar 2006, John Salerno wrote:

> I understand that after you import something once, you can reload it to pick 
> up new changes. But does reload work with from statements? I tried this:
>
> from X import *
>
> and then did my testing. I changed X and tried to reload it, but that didn't 
> seem to work. I figure the reason is because the module itself doesn't exist 
> as an object, only its names do. But I couldn't figure out how to pick up my 
> new changes at this point. I think eventually I did
>
> import X
>
> and that sort of started me back from the beginning, with my changes. But is 
> there a way to continue to use a from statement instead, and then reload your 
> changes?

"reload" is an ordinary procedure that takes a module as an argument. When 
you use a "from X import *" statement, "X" is not imported, so you have no 
module object to pass to "reload". In addition, even if you do import "X" 
and reload it, you won't update your bindings; you'll still have to do 
"from X import *" again to update any names imported from X before.

So, to make a long story short, you have to do something like:

import X
reload(X)
del X # to keep your namespace clean
from X import *

In general, "from X import *" should be avoided anyway, for reasons that 
have been discussed many times in the past. The annoyance with reloading 
is just one more reason. Better to just use "import X" in the first place.

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
"one man's constant is another man's variable" - alan perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it better to use class variables or pass parameters?

2006-03-01 Thread Dave Benjamin
On Wed, 1 Mar 2006, Derek Basch wrote:

> This one has always bugged me. Is it better to just slap a "self" in
> front of any variable that will be used by more than one class method
> or should I pass around variable between the methods?

As a general rule, I only turn a parameter into an instance variable when 
it would otherwise be a parameter of all (or nearly all) methods. Though 
this is perhaps an overly mechanical perspective, I like to think of 
instance variables as implicit parameters to every method. It helps me 
keep scope under control and encourages better cohesion.

-- 
    .:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
"one man's constant is another man's variable" - alan perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about isinstance()

2006-01-26 Thread Dave Benjamin
On Thu, 26 Jan 2006, Dave Benjamin wrote:

> On Thu, 26 Jan 2006, Rocco Moretti wrote:
>
>>> You were better off with what you had before. Equality in this case is 
>>> left completely open-ended, and as a result, there is no way that you can 
>>> guarantee that "a == b" is the same as "b == a" if "a" is a "foo" and "b" 
>>> is of unknown type. This can lead to bizarre and unpredictable behavior.
>> 
>> Mind explaining that better? b == a *always* calls b.__eq__(a), if it 
>> exists. What a.__eq__(b) is doesn't matter at that point. So you have the 
>> same problems either way.
>
> Right, but we don't know what "b.__eq__" does, since "b" could be anything, 
> if it exists at all. So, it's quite possible that "a == b", since "a.__eq__"
   ^^^

By "it" here, I mean "b.__eq__".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about isinstance()

2006-01-26 Thread Dave Benjamin
On Thu, 26 Jan 2006, Rocco Moretti wrote:

>> You were better off with what you had before. Equality in this case is left 
>> completely open-ended, and as a result, there is no way that you can 
>> guarantee that "a == b" is the same as "b == a" if "a" is a "foo" and "b" 
>> is of unknown type. This can lead to bizarre and unpredictable behavior.
>
> Mind explaining that better? b == a *always* calls b.__eq__(a), if it exists. 
> What a.__eq__(b) is doesn't matter at that point. So you have the same 
> problems either way.

Right, but we don't know what "b.__eq__" does, since "b" could be 
anything, if it exists at all. So, it's quite possible that "a == b", 
since "a.__eq__" is defined and only depends on "b" having an 
attribute named "an_attribute", but "b == a" is:

   a) an error
   b) false, even though "a == b" is true

If we control the class of "a" and the class of "b", we can ensure that 
the two "__eq__" methods behave identically. The problem is that, in the 
supposed interest of "polymorphism" we are relaxing the dependency on 
"a.__eq__"'s parameter so that it can be any class with "an_attribute". 
This implies that we would like other classes besides those we control to 
be able to participate in equality tests with the class of "a". However, 
to do this properly, we need to be able to modify *both classes*, or we 
will have inconsistent results depending on whether we say "a == b" or
"b == a". It is reasonable to expect that these two expressions produce 
the same result, isn't it?

> The only difference between the two is in the case where b is of an unrelated 
> class and b.an_attribute exists (1). In this case, the first always returns 
> False, and the second returns (a.an_attribute == b.an_attribute). Which you 
> prefer depends on how strictly you adhere to  duck typing.

I don't think duck typing buys you anything valuable here. The usual 
flexibility of duck typing is lost because of the symmetric nature of 
equality; all participating classes need to be involved to guarantee 
correctness. You *could* have "b.__eq__" just call "a.__eq__", but once 
again this assumes we have control over the implementation of "b".

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.

   "To attain knowledge, add things every day.
To attain wisdom, remove things every day." - Lao Tzu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about isinstance()

2006-01-26 Thread Dave Benjamin
On Thu, 26 Jan 2006, Mr.Rech wrote:

> I've read some thread about isinstance(), why it is considered harmful
> and how you can achieve the same results using a coding style that
> doesn't break polymorphism etc... Since I'm trying to improve my Python
> knowledge, and I'm going to design a class hierarchy from scratch, I'd
> like to have some feedback about this from those of you much more
> experienced than me in OOP.

When trying to write OO code, you should of course always be suspicious of 
any use of "isinstance". However, it is not always "considered harmful", 
and this is one case where it is perfectly reasonable.

> Now, avoiding isinstace() I've written the following code:
>
> class foo(object):
>   ...
>   def __eq__(self, other):
>  try:
> return self.an_attribute == other.an_attribute
>  except AttributeError:
> return False

You were better off with what you had before. Equality in this case is 
left completely open-ended, and as a result, there is no way that you can 
guarantee that "a == b" is the same as "b == a" if "a" is a "foo" and "b" 
is of unknown type. This can lead to bizarre and unpredictable behavior.

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.

   "To attain knowledge, add things every day.
To attain wisdom, remove things every day." - Lao Tzu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ovum quote about Python [OT]

2006-01-26 Thread Dave Benjamin
On Thu, 26 Jan 2006, Pete Forman wrote:

> In an article about the Royal Bank of Scotland working with Zope there
> is this quote from Gary Barnett, a research director at analyst firm
> Ovum:
>
>  "A lot of banks are using applications like Apache and Perl, but
>  it's interesting to see they're using Python and Zope as it's
>  moderately hardcore open source stuff".

Moderately hardcore? Is that like listening to Rage Against the Machine 
with your seatbelt on?

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.

   "To attain knowledge, add things every day.
To attain wisdom, remove things every day." - Lao Tzu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft IronPython?

2006-01-04 Thread Dave Benjamin
On Wed, 4 Jan 2006, Kent Johnson wrote:

> Ray wrote:
>> Kay Schluehr wrote:
>> 
>>> At least for Jython we already know from the Jython homepage that it is
>>> the great hope of the Java platform to survive in future and far
>>> beyond.
>> 
>> Yeah except that it's coming on so slow... we were doing some scripting
>> for our Java app and Groovy won because Jython has been in alpha for
>> YEARS :(
>
> That's a hoot! Of course you can choose what language you like, but to choose 
> Groovy over Jython because it is more developed is mind-boggling!
>
> Jython 2.1 has been released, stable and suitable for production use for many 
> years. The Groovy community was still working on the *language definition* in 
> November 2005 and has yet to deliver a stable final release.

I agree 100% with the above. I've been using Jython in production for two 
years now, and it's been rock-solid. A little bit outdated, yes, but you 
could do a lot worse than Python 2.1, as far as feature set is concerned.
(Of course, this is not to discourage the Jython team from coming through 
with a new stable release. ;)

-- 
  .:[ dave benjamin: ramen/[spoomusic.com] ]:.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Application architecture (long post - sorry)

2006-01-03 Thread Dave Benjamin
On Tue, 3 Jan 2006, Mike Meyer wrote:

> ... Personally, I prefer to Cheetah Templates to PSP - it plays better 
> in the OO world, and I can use intelligent HTML/XML/SGML editors on the 
> files. ...

Thanks for reminding me of Cheetah. I am trying out TurboGears on a 
small project, and haven't gotten to the HTML part yet... I was going to 
try and learn Kid, but I'm in a bit of a hurry, and Cheetah's much closer 
to what I'm used to. So, I decided to search Google for TurboGears and
cheetah, and guess what I found:

TurboGears now supports Cheetah and Stan
http://www.blueskyonmars.com/2006/01/01/turbogears-now-supports-cheetah-and-stan/

Happy New Year!
Dave

-- 
  .:[ dave benjamin: ramen/[spoomusic.com] ]:.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generators in Java?

2006-01-02 Thread Dave Benjamin
On Fri, 30 Dec 2005, Tom Sheffler wrote:

> Does Java have generators?  I am aware of the "Iterator" interface,
> but it seems much more restrictive.  Python generators are useful
> for many more things than simply list enumeration, but the Java
> Iterator seems limited.

What makes you think that Java's Iterators are more restrictive or 
limited? As far as I understand, Java's hasNext/next protocol is 
essentially the same as Python's next/StopIteration protocol. The main 
advantage of the use of generators is that, when converting from a 
callback-style or non-streaming function to one that produces values 
on-demand, you don't have to rewrite your function to save intermediate 
states (which can be a considerable amount of work).

A good explanation of the rationale for generators in Python is in the 
"Motivation" section of PEP 255:

http://www.python.org/peps/pep-0255.html

-- 
  .:[ dave benjamin: ramen/[spoomusic.com] ]:.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTMLGen- Table Align property

2005-12-27 Thread Dave Benjamin
Cappy2112 wrote:
> Table and TableLite are different classes. Tablelite requires a little
> more work, and I will ave to rewrite some code to use it.
> 
> I am using Table a tthe moment

Well, as far as I know, wrapping a DIV align="center" around a TABLE 
should produce the same effect as giving the TABLE an align="center".

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTMLGen- Table Align property

2005-12-27 Thread Dave Benjamin
Cappy2112 wrote:
> Does anyone know if the table align property is available in
> HTMLgen.Table?
> The docs don't show it, but I find it hard to believe that it is not
> available.
> 
> I want to center the table.
> Only the cell align propterty is available

 >>> print HTMLgen.TableLite(align="center")


 >>> print HTMLgen.Div(align="center")

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HTMLGen- Table Align property

2005-12-27 Thread Dave Benjamin
Cappy2112 wrote:
> Does anyone know if the table align property is available in
> HTMLgen.Table?
> The docs don't show it, but I find it hard to believe that it is not
> available.
> 
> I want to center the table.
> Only the cell align propterty is available

I've never used HTMLgen, but you might try wrapping your table in a DIV 
with a "style" attribute (or using the TableLite class, which also 
accepts a "style" attribute), and setting the "text-align" property:

http://www.w3schools.com/css/pr_text_text-align.asp

Hope this helps,
Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Indentation/whitespace

2005-12-23 Thread Dave Benjamin
Alex Martelli wrote:
> The main reason I suggest a general-purpose mechanism for the hooking-up
> of the preprocessor is that such a mechanism might stand a chance to be
> accepted (via the usual PEP procedure), as long as other interesting use
> cases can be found; I suspect that if the only use case was "turn braces
> into indents/dedents", the PEP would stand no chance.

+1 on the preprocessor idea, especially if it would allow us to hook in 
at the AST level as well. (No comment on the curlies. ;)

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


"Humane" programmer interfaces

2005-12-22 Thread Dave Benjamin
useful tool "part of the 
core". I think that, in contrast, Ruby goes a bit overboard.

Note that Stroustrup is willing to budge on this ideal for the sake of 
efficiency: "you might have five or ten member functions that are there 
because they are logically necessary, or for performance reasons". 
Likewise, Python sometimes includes methods in the core classes that could 
be implemented elsewhere, specifically for the sake of performance. 
"dict.setdefault" comes to mind. Another, more debatable reason, is 
convenience, and this is where most disagreement is found. What is 
convenient to one person is added conceptual baggage for another. It is 
difficult to strike a good balance between the two, but erring on the side 
of minimalism is much easier to correct in the long term.

One last comment I'd like to make is regarding the notion that minimalist 
and humane are mutually exclusive. This is a false dichotomy. According to 
Webster:

Main Entry: minimalism
Pronunciation: 'mi-n&-m&-"li-z&m
Function: noun
1 : MINIMAL ART
2 : a style or technique (as in music, literature, or design) that is 
characterized by extreme spareness and simplicity

Main Entry: humane
Pronunciation: hy-'mAn, y-
Function: adjective
Etymology: Middle English humain
1 : marked by compassion, sympathy, or consideration for humans or animals
2 : characterized by or tending to broad humanistic culture : HUMANISTIC 


Accepting both of these definitions as (potentially) ideal, we have humane 
minimalism: a style or technique that is characterized by extreme 
spareness and simplicity, marked by compassion and sympathy, in 
consideration of humans. In a world of increasing software complexity, 
this doesn't sound half bad to me.

-- 
  .:[ dave benjamin: ramen/[sp00] ]:.
   \\ "who will clean out my Inbox after I'm dead[?]" - charles petzold
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which Python web framework is most like Ruby on Rails?

2005-12-19 Thread Dave Benjamin
On Mon, 19 Dec 2005, Paul Rubin wrote:

> "Russell E. Owen" <[EMAIL PROTECTED]> writes:
>> I disagree. Once you've picked a database (not trivial in itself, of
>> course), you typically only have a few options for talking to in in
>> Python. Also, typically either:
>> - One stands out (because others have been abandoned or whatever), so
>> there's an easy answer, or
>
> But none of them stand out, the way the ones in PHP stand out, by
> being included in the standard library.

Well, even with PHP there are several ways to talk to a given database, 
and the library du jour has changed a few times. When I first learned PHP, 
it was pretty standard to use the mysql_* functions (and for another 
database, a set of functions specific to that database). Then, PEAR DB 
came out, which wrapped around these functions and provided some database 
abstraction for portability. This is the direction I went, but I don't 
know many others that followed.

PEAR is distributed with PHP, so it's basically standard, but in the early 
days it wasn't in the library path by default so it didn't stick out as 
the obvious way to talk to a database. Also, ADOdb was around at the time, 
which was (and still is) a pretty popular third-party interface -- maybe 
more popular than PEAR DB. And now there's the new "mysqli" interface, 
which is yet another (this time object-oriented) alternative to the 
mysql_* functions, but once again tied specifically to MySQL.

So, PHP has had the same kind of problems, even with database functions in 
the core. There's more than one way to do it, even with standard 
functions. Same with Java -- should we use the native Type 3 driver or the 
pure-Java Type 4 driver? Scrap JDBC and go with JDO or EJB? Hibernate?

I'm not saying it's necessarily a good thing to have all these options, 
but it's not atypical, especially considering how many database users are 
out there and how different their needs are. In the Java world, commercial 
vendors actually compete to produce better JDBC driver implementations, 
which increases the number of options even more but results in some 
wickedly fast and advanced drivers.

I do agree that the "obsolete" MySQLdb page needs a makeover, or to be 
removed entirely. Also, getting psycopg to install on Windows involves 
hunting around for some magic installers, and I'm afraid to delete them 
off of my hard drive because I'm not sure I'll be able to find them again. 
Perhaps all that is needed is some better organization.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RoR like (was : SPE 0.8.1.b Python IDE...)

2005-12-15 Thread Dave Benjamin
On Thu, 15 Dec 2005, Adrian  Holovaty wrote:

> bruno at modulix wrote:
>> RoR is not an IDE, it's a web framework. The closest things in Python
>> are TurboGears (good Ajax/js support via Mochikit), Subway (never
>> tested), and Django (no Ajax support AFAIK).
>
> Note that "no Ajax support" is misleading. Of course you can use Ajax
> with Django, just as you can use it with *any* Web framework. That's
> because Ajax is a browser-side technology (JavaScript), not a
> server-side technology (Python). Django is just as capable of producing
> JavaScript as it is of producing (X)HTML or whatever else.

I don't think it's misleading. Just because you can do asynchronous 
programming between JavaScript and any given web server technology doesn't 
mean it's going to be easy or effective. For example, both sides need to 
agree on a method for serialization of data. You can use XML or JSON with 
any web server, and any client technology for that matter, but the fact 
remains that code is going to have to exist on both sides to make it fly.

Having common support for data serialization standards, as well as remote 
calling conventions, can reduce the amount of glue code you have to write.

I guess it depends on your definition of "support".

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why and how "there is only one way to do something"?

2005-12-15 Thread Dave Benjamin
On Thu, 15 Dec 2005, Simon Brunning wrote:

> On 12/15/05, Steve Holden <[EMAIL PROTECTED]> wrote:
>> Aahz wrote:
>>> python -c 'import this'
>>
>> Faster:
>>
>>python -m this
>
> So, there's two ways to do it. ;-)

Yes, but which way do you do it if you're Dutch?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why and how "there is only one way to do something"?

2005-12-15 Thread Dave Benjamin
On Thu, 15 Dec 2005, Richie Hindle wrote:

> [Steve]
>> Since Python is Turing-complete
>
> Is there some equivalent of Godwin's Law that we can invoke at this
> point?  8-)

None that I know of, but perhaps there should be. =) Note that in this 
particular thread, we could have invoked the real Godwin's Law already.

Beware of the Turing tar-pit in which everything is possible but nothing 
of interest is easy." -- Alan Perlis, "Epigrams on Programming"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rename files with numbers

2005-10-31 Thread Dave Benjamin
On Mon, 31 Oct 2005, Micah Elliott wrote:

> On Oct 31, Micah Elliott wrote:
>> Now I need to go beautify my collection.  :-)
>
> While a fun exercise, there are probably already dozens (or
> thousands?) of utilities in existence that do this and much more.

Seconded. I initially considered writing a script to rename a huge pile of 
MP3 files, but halfway through, I thought, "there's *got* to be a better 
way". I found this app: http://www.softpointer.com/tr.htm

Bought it the next day. Holy crap, what a gigantic timesaver. It looks up 
albums based on track lengths, downloads titles from freedb and Amazon, 
does ID3 tagging, renaming, moves files into separate directories... I 
busted through about 20 gigs of MP3s in three days. I kid you not.

If this is just a fun toy Python project, don't let me discourage you, but 
if you have more than a handful of albums to rename, trust me. This 
problem has been solved.

Here's a list of apps, including Tag&Rename, that can query freedb:
http://www.freedb.org/freedb_aware_apps.php

-- 
  .:[ dave benjamin: ramen/[sp00] ]:.
   \\ "who will clean out my Inbox after I'm dead[?]" - charles petzold
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yes, this is a python question, and a serious one at that (moving to Win XP)

2005-10-17 Thread dave . benjamin
Jorgen Grahn wrote:
> On Fri, 14 Oct 2005 12:37:25 +0200, Christophe <[EMAIL PROTECTED]> wrote:
> > Kenneth McDonald a Ă©crit :
> >> For unfortunate reasons, I'm considering switching back to Win XP  (from
> >> OS X) as my "main" system. Windows has so many annoyances that  I can
> ...
> >> Yes, I know that Cygwin is out there, but last I looked, they still
> >> went through the Win command-line window, which imposes a lot of
> >> restrictions.
> ...
> > Last time I checked, you could install a native win32gui version of rxvt
> > with cygwin. This would give you a better terminal window than that
> > crappy thing you get in XP.
>
> Last time /I/ checked (two years ago or so) that rxvt looked nice enough,
> but was impossible to use in practice. I cannot remember /what/ the problem
> was -- possibly it was that it could only run CygWin-compiled commands, or
> something vital only worked with CygWin-compiled commands. Google probably
> knows more.

Cygwin comes with a fully-functioning X server, from which you can run
just about any terminal program you like. For awhile, I was using
Konsole, but KDE on Cygwin is a bit slow and buggy. Recently I switched
to "mrxvt", which is like "rxvt" but with tab support and keyboard
shortcuts almost identical to Konsole. It's easy to compile for Cygwin,
and so far I'm really enjoying the improved speed. Here's my .mrxvtrc:

mrxvt*bottomTabbar: true
mrxvt*scrollBar:false
mrxvt*font: neep-alt-bold-14
mrxvt*boldFont: neep-alt-bold-14
mrxvt*foreground:   snow
mrxvt*background:   black
mrxvt*geometry: 80x40
mrxvt*saveLines:65535
mrxvt*hotkey*Dummy: Ctrl+Shift+underscore

I like my tabs at the bottom, Konsole-style, and don't really like
scrollbars on terminals. I use the Neep Alt font, which is nice for
coding because it makes 'l', '|', '1', etc. all look different, and I
like thick console fonts. I was a Fixedsys diehard for a long time. The
"saveLines" variable lets you increase the scrollback buffer
(shift-PgUp/Down) pretty high - I have it maxxed out. And that last
line tells mrxvt to ignore C-_, which is undo in emacs. There are still
a few other keyboard bindings that I'd like to turn off at some point.

One drawback of mrxvt is that it doesn't support UTF-8. I don't do much
multi-language stuff, but on most Linux distributions the manpages are
in UTF-8, so you get garbage characters unless you fiddle with your
LANG/LOCALE settings.

Oh yeah, and to keep this on topic, Cygwin's Python works just fine in
mrxvt, though the native Windows version doesn't work so well. It
doesn't print any output, which I think is due to buffering... however,
I tend to use PythonWin for interactive development, and emacs with M-x
shell to actually test and run (native) Python scripts. I'm pretty
happy with it, overall.

Dave

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Info] PEP 308 accepted - new conditional expressions

2005-09-30 Thread Dave Benjamin
Reinhold Birkenfeld wrote:
> after Guido's pronouncement yesterday, in one of the next versions of Python
> there will be a conditional expression with the following syntax:
> 
> X if C else Y

Hooray! After years of arguing over which syntax to use, and finally 
giving up since nobody could agree, the Benevolent Dictator did what 
only a dictator can do, and just made a damn decision already.

Thank you, Guido! =)

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Duplicating Modules

2005-09-30 Thread Dave Benjamin
Misto . wrote:
> Hi folks!
> 
> Short:
> 
> There is a way to dumplicate a module ?

Here's one way... it doesn't quite work with modules inside of packages, 
unfortunately, but it does avoid defeating module caching and tries to 
keep sys.modules in a predictable state. I don't know what the 
thread-safety implications are for this sort of trickery with sys.modules.

def import_as(newname, oldname):
 """Import a module under a different name.

 This procedure always returns a brand new module, even if
 the original module has always been imported.

 Example::

 try:
 # Reuse this module if it's already been imported
 # as "mymath".
 import mymath
 except ImportError:
 # "mymath" has not yet been imported.
 # Import and customize it.
 mymath = import_as('mymath', 'math')
 mymath.phi = (mymath.sqrt(5.0) - 1.0) / 2.0

 The above code will not reinitialize "mymath" if it executes
 a second time (ie. if the module containing this code is
 reloaded). Whether or not "math" has already been imported,
 it will always be a different object than "mymath".
 """

 import sys
 if sys.modules.has_key(oldname):
 tmp = sys.modules[oldname]
 del sys.modules[oldname]
 result = __import__(oldname)
 sys.modules[newname] = sys.modules[oldname]
 sys.modules[oldname] = tmp
 else:
 result = __import__(oldname)
 sys.modules[newname] = sys.modules[oldname]
 del sys.modules[oldname]
 return result

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where to find python c-sources

2005-09-29 Thread Dave Benjamin
Tor Erik Sønvisen wrote:
> I need to browse the socket-module source-code. I believe it's contained in 
> the file socketmodule.c, but I can't locate this file... Where should I 
> look?

You can browse the Python CVS tree here:
http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/

For example, the file you asked for is viewable here:
http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/socketmodule.c?rev=1.314&view=auto

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about consistency in python language

2005-09-08 Thread Dave Benjamin
Mike Meyer wrote:
> Dave Benjamin <[EMAIL PROTECTED]> writes:
> 
>>Python is actually quite consistent in this regard: methods that
>>modify an object in-place return None;
> 
> Um, no. list.pop comes to mind as an immediate counterexample. It may
> be the only one...

I'm sure there are counterexamples... maybe 95% is too optimistic. 
Anyone want to volunteer to compile some stats? ;)

I've never had to look up the return type of "pop" though. The only 
thing even remotely ambigious about that term (at least, if you've 
learned what a stack is) is whether it mutates the object, but I don't 
think I've ever seen a "pop" that didn't (aside from toy examples in 
formal methods / ADT related classes).

"os.system" might be a better example, since the return value could be 
one of two obvious things: the status code, or the program's output.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about consistency in python language

2005-09-08 Thread Dave Benjamin
[EMAIL PROTECTED] wrote:
> Let's say I define a list of pairs as follows:
> 
>>>l = [('d', 3), ('a', 2), ('b', 1)]
> 
> 
> Can anyone explain why this does not work?
> 
>>>h = {}.update(l)
> 
> 
> and instead I have to go:
> 
>>>h = {}
>>>h.update(l)
> 
> to initialize a dictionary with the given list of pairs?
> 
> when an analagous operation on strings works fine:
> 
>>>s = "".join(["d","o","g"])
> 
> 
> Seems inconsistent. 

Python is actually quite consistent in this regard: methods that modify 
an object in-place return None; methods that do not modify an object 
in-place return a new object instead. Since strings are immutable, they 
cannot be modified in-place, so it makes sense for the "join" method to 
return a new string. On the other hand, Python's dictionaries are 
imperative-style and so most operations on a dictionary modify an 
existing dictionary.

I was initially bothered by the phenomenon of so many methods returning 
None because they could not be chained. But I have come to deeply 
appreciate this style for a couple of reasons. First, it makes it clear 
which methods are side-effecting (like "update") and which are not (like 
"sort").

Second, it is not always clear what a good return value is for a 
mutator. Perhaps {}.update() should return the dictionary, making 
chaining convenient. Perhaps it should return the total number of items 
after updating. Or maybe it should return the number of new keys that 
were added, or a list of those keys. All of these are plausible 
behaviors; the problem is that "update" is not a function. Its job is to 
change something, not return something. Any possible return value would 
be a convenience for certain tasks and useless for other tasks.

It's also hard to remember, in my opinion. For example, JavaScript has a 
"push" method on the Array object which behaves like Python's "append" 
method on lists:

js> var a = [];
js> a.push(5);
1
js> a.push(6);
2

I bet you that almost nobody knows that "push" returns the new length of 
the Array. It could just as easily have returned "a" here. I could 
always write "a.length", if I really needed to know the new length. This 
sort of thing becomes language trivia, and when I write in JavaScript I 
always ignore the result of "push" because, even if *I* know what it 
returns, chances are that my readers don't.

Another reason that Python adopts the convention of returning None for 
mutators is that it discourages the use of side-effecting code in 
expressions. Mixing side-effects with expressions can lead to code that 
is hard to read and understand. This is often debated by those who know 
better and wish to write things like "h.update(a).update(b)" (method 
chaining) or "while (line = file.readline()): ...". Python's decision is 
pretty clear, and it's also evident in the division between statements 
and expressions.

Regardless of whether you like Python's style decision or not, if you 
dig deeper I think you will find that it is pretty consistent, and that 
there are useful benefits to Python's way of handling side effects.

Dave

PS. If mutators had to return a value, I'd have them return "self", 
probably 95% of the time. But then, it wouldn't be Python anymore. It'd 
be Ruby, maybe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: epydoc CLI and many files

2005-09-07 Thread Dave Benjamin
Terry Hancock wrote:
> On Monday 05 September 2005 08:10 am, Laszlo Zsolt Nagy wrote:
> 
>>The problem is that now I have so many modules that the shell (cmd.exe) 
>>cannot interpret this as a one command. 
> 
> In POSIX systems, the shell expands wildcards into multiple files on
> the command line, but under DOS/Windows systems, the expansion normally
> takes place within the program (I think this is still true).  In this
> case, I would guess that the Python interpreter would do the
> expansion. That should avoid any limits on command length that
> cmd.exe is giving you (I'm trusting that Python is much more capable).

Python does not do this translation for you automatically, but it does 
provide the tools to make it easy. See the "glob" module:

http://docs.python.org/lib/module-glob.html

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jython Released

2005-07-19 Thread Dave Benjamin
Ramza Brown wrote:
>>
>> I figured it out. You might want to document this somewhere. ;)
>> java -cp jython_Release_2_2alpha1.jar 
>> org.python.util.install.Installation
> 
> Did you try double clicking on the jar.  That is what most do or at 
> least the last package supported that.

Yeah. It opens in WinRAR. =)

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jython Released

2005-07-19 Thread Dave Benjamin
Dave Benjamin wrote:
> Ramza Brown wrote:
> 
>> This is an update from Brian Zimmer of the Jython group, new release:
> 
> Great news!
> 
>>  - new installer
> 
> How do I use it?

I figured it out. You might want to document this somewhere. ;)
java -cp jython_Release_2_2alpha1.jar org.python.util.install.Installation

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jython Released

2005-07-19 Thread Dave Benjamin
Ramza Brown wrote:
> This is an update from Brian Zimmer of the Jython group, new release:

Great news!

>  - new installer

How do I use it?

Thanks,
Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating anonymous functions using eval

2005-07-12 Thread Dave Benjamin
Joseph Garvin wrote:
> Robert Kern wrote:
> 
>> Not everyone is reading this list in a conveniently threaded form
>>  
>>
> Why not? Just about every modern newsgroup reader and e-mail app has a 
> threaded view option.

My newsreader supports threading, but the first message I see in this 
thread is from Devan L. I didn't notice the "Re:" and assumed his post 
was half in the subject line and half in the body.

Sometimes I only download the 100 most recent posts, so I don't see the 
original (or referred-to) post. Other times the threading doesn't work 
properly, splitting conversations or using the wrong level of 
indentation. Also, this is both a newsgroup and a mailing list, and that 
has adverse effects on threading as well.

So, please quote. =)

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better console for Windows?

2005-07-01 Thread Dave Benjamin
Brett Hoerner wrote:
> Is there a different shell I can use (other than cmd.com) to run Python
> in, where I can full-screen the window (if I pleased), etc?  As it is,
> things that would run far off the right have to be word wrapped after
> very few characters.

I have a pretty exotic setup but I like it a lot. I use Konsole with 
Cygwin and the KDE release for Cygwin (that's the only part of KDE that 
I use). I love Konsole's tabbed virtual terminals. You can also get 
tabbed virtual terminals with mrxvt, which isn't quite so heavyweight, 
but Konsole is the most user-friendly terminal I've ever used.

And on top of that, I run emacs, pull up a shell with M-x shell, and 
then I can run any program I want, including Python and Jython, and 
freely cut and paste between the command line and my editor window.

As far as the beeps go, I go for any "silent bell" option I can find, 
and pick the "No sounds" theme in the "Sounds and Audio Devices" control 
panel.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inheriting from object

2005-06-29 Thread Dave Benjamin
Steven Bethard wrote:
> Guido also suggests that the explicit:
> 
> class C(object):
> pass
> 
> is "much preferred"[2] over:
> 
> __metaclass__ = type
> 
> class C:
> pass

Really? I have been toying with the idea of using the __metaclass__ 
trick, since it results in completely valid Jython 2.1 code, as long as 
you don't use any of the new-style features.

But once Brian Zimmer gets his broadband fixed, we're supposed to get a 
new alpha release. =)

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which kid's beginners programming - Python or Forth?

2005-06-28 Thread Dave Benjamin
BORT wrote:
> I am toying with the idea of teaching my ten year old a little about
> programming.  I started my search with something like "best FREE
> programming language for kids."  After MUCH clicking and high-level
> scanning, I am looking at Python and Forth.  Both have advocates that
> say each is a great approach to learning computers.

Kids your backwards talking like if forth love will they then.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thoughts on Guido's ITC audio interview

2005-06-28 Thread Dave Benjamin
Sakesun Roykiattisak wrote:
> 
>> What's being ignored is that type information is useful for other things
>> than compile type checking. The major case in point is the way IDEs
>> such as IntelliJ and Eclipse use type information to do refactoring, code
>> completion and eventually numerous other things. A Java programmer
>> using IntelliJ or Eclipse can eliminate the advantage that Python
>> used to have, and possibly even pull ahead.
>>  
> 1. Automatic refactoring never solve the readability issue.

True, but with the aid of automatic refactoring, you can make code more 
readable, by splitting up classes and functions, giving things better 
names, etc.

Another readability issue in a similar vein is "intellisense" / 
context-sensitive menus. They allow you to give every class and method 
really long or confusing names without slowing you down, since you can 
just pick it from a menu. But I think this has some negative consequences.

First, as you've stated, you still have to read the code. Second, you 
become reliant on these menus, rather than just "flowing". For instance, 
I almost never have to look up documentation for any of Python's list, 
dictionary, and string methods. They're short and simple, and they're 
easy to memorize. I think this is at least partially a consequence of 
the fact that people type them in, by hand, all the time, so they're 
designed to be friendly and memorable.

> 2. I've never been lucky enough to have enough resource for those IDE.

It's worth noting that IntelliJ IDEA has gotten rather slow and bulky 
with the more recent releases. It used to be pretty quick. Emacs, which 
was at one point considered a total resource hog, is lean and mean in 
comparison, and doesn't seem to be expanding much these days... =)

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Thoughts on Guido's ITC audio interview

2005-06-28 Thread Dave Benjamin
Stephen Kellett wrote:
> In message <[EMAIL PROTECTED]>, Simon 
> Brunning <[EMAIL PROTECTED]> writes
> 
>> Eclipse's refactorings are a great boon, I find. Refectoring is never
>> *fully* automatic, of course, but the ability to, for example, select
>> a chunk of code and have it extracted into a separate method with all
>> needed arguments and the return value worked out for you is very
>> helpful. All you have to do is give the new method a name. And this
>> sort of thing can certainly improve readability.
> 
> This is not an attach on you Simon, but if people are relying on that 
> type of thing for increases in software productivity they are hiring the 
> wrong people.

I think that the right people to hire are the ones that can make the 
best use of whatever tools are available so they can get their job done 
well and in a reasonable amount of time.

I'm not a big fan of Java programming, but sometimes I have to do it, 
and when I do, I must say that the refactoring capabilities of IDEs like 
IntelliJ IDEA are very helpful. Being able to rename classes, variables 
and functions across multiple files, extract methods with automatic 
naming and typing of parameters and throws-clauses, and move methods 
from one class to another makes it so much easier to reorganize and 
improve large amounts of code. And due to Java's verbosity, there 
usually is a lot of code to manage even for simple changes.

In Python, there's still a need to do these sorts of things. Typically, 
we use "search and replace" and "cut and paste" instead. You could make 
a similar statement about those tools - if you rely on "cut and paste" 
to increase your productivity... gah, it makes me cringe just writing 
that! Nonetheless, I would hate to program without "cut and paste" as a 
tool. In any language.

The need for automatic refactoring tools in Python is smaller; Python 
gives you the opportunity to program at a higher level of abstraction, 
so there is less code to deal with. In addition, since Python doesn't 
have checked exceptions or require type annotation, design changes tend 
to "splatter" less across your code base. Still, Python's dynamic nature 
limits the sort of automatic changes you can make reliably, and we ought 
to recognize that. By using Python, we are making a tradeoff: in 
communicating less information, we are forcing IDEs to do more 
guesswork. Java requires less guesswork for the IDE, but requires 
significantly more communication on behalf of the programmer. I don't 
think it's a cut-and-dry win for either language.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Thoughts on Guido's ITC audio interview

2005-06-25 Thread Dave Benjamin
Guido gave a good, long interview, available at IT Conversations, as was
recently announced by Dr. Dobb's Python-URL! The audio clips are available
here: 

http://www.itconversations.com/shows/detail545.html
http://www.itconversations.com/shows/detail559.html

I'd like to comment on a few parts of that interview.

One thing Guido mentions in his comparison of ABC (Python's predecessor) and
Python is how ABC was inextricably tied to its environment (a la Smalltalk),
where Python, though it supports an interactive mode, follows more of a
UNIX-style "do one thing well" philosophy, and was designed to integrate
with other tools rather than being a whole world to its own.

I find that a similar comparison can be made between Python and Java. Java's
startup time is so long that it is not practical for writing small tools for
use in command-line scripts, and the propensity toward application servers
and integrated development environments suggests a strong preference for a
monolithic, self-contained, single-language environments. On the other hand,
even though internally "there's only one way to do it" in Python, Python
itself is one of many ways to develop software, and does not insist on being
the one perfect way to do it. You can use whatever editor you like, and the
language doesn't go out of its way to make it difficult to use other
programs and processes, including the operating system if so desired.

It is a bit ironic that, according to Guido, the command-line interpreter
interface to Python was more of an afterthought, since my whole experience
with Python has very much centered around the interpreter. Like many, I
think, my first use for Python was as a calculator. =) In fact, since
discovering Python, I've been very resistant toward learning any language
that doesn't have an interpreter. Ruby, Scheme, OCaml and SML/NJ have been
fun to learn because I can tinker with them at the command line. "perl -de
42" is rather frustrating to use, as is Haskell's "hugs" due to the
inability to define new functions at the command line.

Command-line interfaces are a great way to get up to speed on new languages
and libraries. One of the advantages of Python is that it allows you to
graft a CLI onto environments that weren't designed with one. For instance,
Jython gives Java a command-line interface, and this makes working with Java
much more tolerable since you can interact with libraries in real-time and
learn how they behave at runtime. Likewise with PythonWin and COM scripting. 
I am glad to see that IronPython is designed with a command-line interpreter
as well, should I ever need to learn my way around .NET in a hurry.

Guido makes a funny jab at Paul Graham about Graham's nine things that make
Lisp Lisp (available here: http://www.paulgraham.com/icad.html) - I had read
this essay many times but never saw the subtle irony behind claims of
"Greenspunning": in order to claim that a language is approaching Lisp, you
have to define what it is about Lisp that other languages are purportedly
emulating, and this begs the question of why you have the authority to
declare which 9 (or n) attributes of Lisp are most important. I like Paul
Graham and his essays a lot, but I must admit I had to laugh too when I
heard the way Guido framed this argument. I'm not so sure that Python has 8
out of 9, though: the statement/expression dichotomy rules out #6, and the
lack of macros rules out #9. These are arguable, depending on how you define
things, but I think the most obvious thing that Python lacks compared with
Lisp and Scheme (and also Ruby) is a symbol type (#7). I'm in the process of
trying to understand what symbols are good for, outside the context of Lisp
and its nested lists of symbols as executable code. Ruby seems to have come
up with some creative uses for symbols within Python-like syntax, though I
haven't seen anything terribly compelling so far.

Guido briefly summarizes language comparisons with other languages:

  - Perl: similar niche, but Perl is for regexes and text processing, and
Python is for objects, data structures, and more general-purpose
programming. Obligatory TMTOWTDI argument.
  - PHP: very successful at its niche, being a point-solution for adding
bits of script to web pages. Not very useful outside that context, and
lots of language-design gaffes.
  - Java: the usual static vs. dynamic, static analysis vs. unit testing
arguments. Guido says that there's such a small amount of problems that
can be caught at compile time, and even the smallest amount of unit
testing would also catch these problems. "The blindness of that [static]
position... escapes me."
  - C/C++: same arguments as Java, plus most programmers aren't up to the
task of manual memory-management.
  - Lisp: even though there's no code-equals-data in Python, you still have
the compiler available at runtime, and there's a lot you can do to treat
code as data even though they're not syntacticall

Re: FAQ: __str__ vs __repr__

2005-06-15 Thread Dave Benjamin
Jan Danielsson wrote:
>   Sorry, but I Just Don't Get It. I did search the 'net, I did read the
> FAQ, but I'm too dumb to understand.

Say we define a string "s" as follows:

 >>> s = 'hello'

If we print "s", we see its string form (__str__):

 >>> print s
hello

However, if we just examine "s", we see its representation (__repr__):

 >>> s
'hello'

This can be verified by calling str() and repr() on the string:

 >>> str(s)
'hello'
 >>> repr(s)
"'hello'"

So, the result of repr() includes quotes, whereas the result of str() 
does not. This has useful properties when the object is part of a more 
complex structure. For instance, these two expressions print out the same:

 >>> [s, s]
['hello', 'hello']
 >>> print [s, s]
['hello', 'hello']

That's because, in either case, the repr() form is used. If Python only 
had str(), we would probably expect str(s) = s, so we'd instead see 
something like this imaginary snippet:

 >>> [s, s]
[hello, hello]
 >>> repr([s, s])
'[hello, hello]'

So, the convention in Python is that repr() returns a string that, when 
evaluated, returns the original object. This is not always easy or 
possible to do, but if you can do it, your objects will print nicely 
when nested within Python's built-in data structures. Python's actual 
behavior is this:

 >>> repr([s, s])
"['hello', 'hello']"

And therefore:

 >>> eval(repr([s, s]))
['hello', 'hello']

Also worth noting is that if you define __repr__, the default behavior 
of __str__ is to delegate to that definition, so if you only want to 
define one, it's often more convenient to just define __repr__.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying behaviour of the != operator

2005-06-08 Thread Dave Benjamin
Jordan Rastrick wrote:
> Surely the != operator should, if no __ne__ method is present for
> either object, check to see if an __eq__ method is defined, and if so,
> return its negation?
> 
> Actually, that brings me to a wider question - why does __ne__ exist at
> all? Surely its completely inconsistent and unnessecary to have
> seperate equals and not equals methods on an object? a != b should just
> be a short way of writing not (a == b). The fact the two can give a
> different answer seems to me to be utterly unintuitive and a massive
> pitfall for beginners (such as myself).

I agree that it's confusing. I didn't even understand this behavior 
myself until I went and looked it up:

http://docs.python.org/ref/customization.html

The rationale for this behavior is in PEP 207 -- Rich Comparisons:

http://python.fyxm.net/peps/pep-0207.html

Personally, I implement the __cmp__ method when I want my objects to be 
comparable, so I've never run into this problem.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help! File objects and scoping

2005-06-07 Thread Dave Benjamin
bens wrote:
> I'm trying to return an 'mmap' object from a function.  The return
> works, but some of the object's methods crash.  Here are two examples
> 
> doesntwork.py
> ---
> import mmap
> import os
> 
> name="/any/real/file/on/my/hard/drive"
> 
> def getfile(name):
> somefile=file(name, 'r+b')
> mmapped = mmap.mmap(fileno=somefile.fileno(), \
> length=os.path.getsize(name))
> return mmapped

Here's the problem: the "mmap" object doesn't have a reference to 
"somefile", only to its file descriptor number. So, when getfile() goes 
out of scope, there are no references left, and the file gets closed 
automatically.

One way to avoid this problem is to return the file object as well as 
the "mmap" object, ie.:

def getfile(name):
 somefile = file(name, 'r+b')
 mmapped = mmap.mmap(fileno=somefile.fileno(),
 length=os.path.getsize(name))
 return (somefile, mmapped)

(somefile, mmapped) = getfile(name)

# do something with mmapped...

Now, as long as you keep "somefile" in scope, the file won't get closed. 
You could also build an object and make both "somefile" and "mmapped" 
attributes of this object.

Caveat: There may be a better way of doing this. I've never used "mmap".

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing a warnings filter?

2005-06-03 Thread Dave Benjamin
Torsten Bronger wrote:
> When I add a warning filter with warnings.filterwarnings, how can I
> get rid of it?  I've read about resetwarnings(), but it removes all
> filters, even those that I didn't install in a certain function.

I have never used this module, but judging by a quick glance of the 
source to "warnings.py", it appears that warning filters are added to a 
list called "warnings.filters". They are added to the beginning of the 
list unless you pass a true value for the "append" parameter of 
"filterwarnings", in which case they are added to the end. The usual way 
to remove items from a list apply, ie.:

del warnings.filters[0] # if append was false
del warnings.filters[-1] # if append was true

Note that all of these operations modify module data, which could have 
implications in multithreaded programs. If your program is 
multithreaded, you may want to consider using locks.

Hope this helps,
Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO design question / Transform object in place?

2005-05-20 Thread Dave Benjamin
[EMAIL PROTECTED] wrote:
> Dave Benjamin wrote:
> 
>>I think it's much better for simplify() to return a new object
>>and leave the original object unmodified. You can still write:
>>expression2 = expression2.simplify()
> 
> A belated thank-you message for your reply to my posting. I took your
> advice, and made all the simplify methods return new objects and this
> has simplified my code structure a great deal (and any slow down in run
> time just doesn't matter!).

No problem. Glad it helped. =)

> Am I right that to make "expression2.simplify()" return a new object I
> will need use copy.copy a lot, as in:
> 
> def simplify(self):
> newreturnvalue=copy.copy(self)
> #
> #now the code does lots of complicated things
> #to newreturnvalue object...
> #
> return newreturnvalue

You could use copy.copy(), as long as you want a shallow copy and you 
don't want to change from one class to another. However, it may be to 
your advantage to use the constructor of one or more classes to build 
the result; this allows you to conditionally pick the result object's 
class. Also, there may be situations where an object can't be 
simplified, in which case you can just return "self", and avoid copying 
entirely.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple TCP "relay" or "proxy"

2005-05-13 Thread Dave Benjamin
Tomas Christiansen wrote:
> Im trying to make a simple TCP socket "relay" or "proxy", but my skills in 
> Python are not high (yet).

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO design question / Transform object in place?

2005-05-11 Thread Dave Benjamin
[EMAIL PROTECTED] wrote:
> Now suppose I set "expression2 = Sum([a,-a])" and Sum.simplify()
> recognises that the two terms cancel and the Sum has value 0.
> 
> Can I make "expression2.simplify()" transform expression2 from an
> instance of Sum to an instance of Number(0) **in place**? Is that
> possibe, or do I really have to write

I think it's much better for simplify() to return a new object always, 
and leave the original object unmodified. You can still write:

expression2 = expression2.simplify()

if you don't care about the old value.

> expression2 = SimplifyFunction(expression2)

This is another valid solution, but it's not an OO solution (you will 
need to use "isinstance" to write "SimplifyFunction").

> and use the function return to set expression2 to be a Number(0)
> object, which is annoying for a variety of reasons! Have I made a
> mistake in the design?

It's usually considered poor OO style to have an object change its class 
at runtime, although I'm sure you could do it in Python ("__bases__" 
would be a place to start) if you really wanted. For what you're trying 
to do, I don't think it's necessary, though.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reg strip_tags function in Python.

2005-05-07 Thread Dave Benjamin
praba kar wrote:
> In Php I can use strip_tags() function to strip out
> all html tags. I want to know that strip_tags()
> equivalent function in Python.

Here's a simple function based on Python's HTMLParser class. If you need 
to reject only certain tags, you'll probably want to subclass 
HTMLParser, but for simply stripping all tags, this works:

from HTMLParser import HTMLParser
def strip_tags(html):
 result = []
 parser = HTMLParser()
 parser.handle_data = result.append
 parser.feed(html)
 parser.close()
 return ''.join(result)

See the docs for more details on HTMLParser:
http://docs.python.org/lib/module-HTMLParser.html

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: annonymous functions -- how to

2005-05-06 Thread Dave Benjamin
Peter Hansen wrote:
> Dave Benjamin wrote:
> 
>> def add_thingy():
>> def func(thingy_id):
>> print 'got thingy id:', thingy_id
>> def funnc(doodad_id):
>> print 'got doodad id:', doodad_id
>> def func(thingy_doodad):
>> print 'thingy doodad created, froobling...'
>> frooble(thingy_doodad)
>> print 'froobling complete'
>> with_new_thingy_doodad(thingy_id, doodad_id, func)
>> with_next_doodad_id(func)
>> with_next_thingy_id(func)
>>
>> This function now has an infinite loop. Can you spot the reason?
> 
> Not offhand, and to be completely honest, the original with the longer 
> names was equally unreadable.  I doubt this is the best way to do 
> whatever the heck it is that this is supposed to do.

I agree. I think both are difficult to read. I find the first version 
that I originally posted (using an imaginary anonymous function syntax) 
much easier to understand.

I think I've made it pretty clear what this is supposed to do in my 
earlier post to Fredrik, delineating each step of the communication 
process. If you have a better way to do this, I'd certainly like to see it.

> Oh, and while I was typing my eyes fell on "funnc" misspelled above. 
> Presumably that's your loop...

Yes, precisely. And because of a typo, the wrong callback gets passed, 
causing it to use the same callback over and over. With anonymous 
functions, there would be nothing to name, and therefore, nothing to 
misspell.

> Spelling "func" as "_" would tend to avoid this as well, unless you have 
> a keyboard that repeats keys accidentally.

Hrmmm. Well, it is less to type.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32: structured storage

2005-05-06 Thread Dave Benjamin
Dave Benjamin wrote:
> Steve Holden wrote:
> 
>> tlviewer wrote:
>>
>>  > CHM is supposed to be structured storage (ITSF). If a given CHM
>>  > file is infected it most likely has an embedded EXE file -- mine
>>  > had one called [Open.exe].
>>  >
>> Ironic, really, since Microsoft insist that the browser must be 
>> fully-integrated with the operating system I suppose that measn we had 
>> better all start using Linux.
> 
> Even more ironically, it would seem that in effort to kill Netscape they 
> are killing Windows.

Or perhaps I'm just restating your point. ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32: structured storage

2005-05-06 Thread Dave Benjamin
Steve Holden wrote:
> tlviewer wrote:
> 
>  > CHM is supposed to be structured storage (ITSF). If a given CHM
>  > file is infected it most likely has an embedded EXE file -- mine
>  > had one called [Open.exe].
>  >
> Ironic, really, since Microsoft insist that the browser must be 
> fully-integrated with the operating system I suppose that measn we had 
> better all start using Linux.

Even more ironically, it would seem that in effort to kill Netscape they 
are killing Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: annonymous functions -- how to

2005-05-06 Thread Dave Benjamin
Fredrik Lundh wrote:
> Dave Benjamin wrote:
> 
>>>so name them all "func" or "next" or something, so you don't have
>>>to think.  once the object is bound, the name is irrlevant.
>>
>>Sure, you could do this, but then you'd have multiple functions at
>>different nesting levels with the same name, which would be confusing.
> 
> "I don't wanna try that", you mean.

No, I mean, "I have an imagination". But for the sake of argument, here, 
I'll try that:

def add_thingy():
 def func(thingy_id):
 print 'got thingy id:', thingy_id
 def funnc(doodad_id):
 print 'got doodad id:', doodad_id
 def func(thingy_doodad):
 print 'thingy doodad created, froobling...'
 frooble(thingy_doodad)
 print 'froobling complete'
 with_new_thingy_doodad(thingy_id, doodad_id, func)
 with_next_doodad_id(func)
 with_next_thingy_id(func)

This function now has an infinite loop. Can you spot the reason?

> because if you had done so, you would have noticed that "multiple
> functions with the same name" doesn't have to be any more confusing
> than "multiple print statements" or "multiple if statements" (as long as
> you're not using bad names on purpose, of course).

I have noticed. It is more confusing. That's the whole point.

>>>there's also:
>>>
>>>def add_thingy(self):
>>
>>What object is "self"? Are we defining a method at this point?
> 
> if you have a problem with methods, you shouldn't use Python.

No, I was asking you to clarify, are we rewriting "add_thingy" to be a 
method, and if so, what class is it a method of, and what are its 
responsibilities? Because it seems like this example now shares data 
through an instance, but this data is not required for any other method, 
so it will add clutter to the instance namespace. If anything, it seems 
that "add_thingy" should be moved into another class at this point, in 
which case it follows that every method that needs to do this sort of 
asynchronous communication would likewise be moved to a new class. This 
is fine, I suppose, but it's a lot more verbose.

>>>yield get_new_thingy_id; thingy_id = self.result
>>
>>What is "get_new_thingy_id"? A function? To whom are we yielding here?
> 
> I could have sworn that you mentioned event-driven programming
> in your original post.  if that's still what you're doing, the answers
> are "a token" and "the event source".

I am just trying to make sense of your example. I am still talking about 
event-programming. Here are the events:

1. Program A sends program B a message, saying, "I need a thingy ID".
2. B sends A a message, "Here's a thingy ID: 42".
3. A sends B a message, "I need a doodad ID".
4. B sends A a message, "Here's a doodad ID: 43".
5. A sends B a message, "Make a thingy doodad with IDs 42 and 43".
6. B sends A a message, "Thingy doodad created".
7. A sends B a message, "Now, frooble the thingy doodad".

I don't know what parts of this transcript you would consider "tokens". 
And I'm also not sure how generators can provide an alternative solution 
to this problem. I am genuinely interested.

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: annonymous functions -- how to

2005-05-06 Thread Dave Benjamin
Fredrik Lundh wrote:
> Dave Benjamin wrote:
> 
>>In this case, having to name these callback functions is tiring and
>>awkward, and (IMHO) disrupts the flow of my function:
> 
> so name them all "func" or "next" or something, so you don't have
> to think.  once the object is bound, the name is irrlevant.

Sure, you could do this, but then you'd have multiple functions at 
different nesting levels with the same name, which would be confusing. 
You could call them "func1", "func2", "func3", and so on, but at this 
point it becomes painfully obvious that you really don't care what the 
names are; you're only naming them because you have to. As Paul Graham 
would say, it's "the human compiler at work".

> there's also:
> 
> def add_thingy(self):

What object is "self"? Are we defining a method at this point?

> yield get_new_thingy_id; thingy_id = self.result

What is "get_new_thingy_id"? A function? To whom are we yielding here?

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: annonymous functions -- how to

2005-05-05 Thread Dave Benjamin
Peter Hansen wrote:
> I doubt there's a valid usecase for a "anonymous" function that has more 
> than a line or two.  Personally, I don't think there's a good usecase 
> for an anonymous function longer than one line...

The case that I keep running into regards event-driven programming. I 
need to do a series of operations that are tied together asynchronously 
via callback functions, but I still want the actions to read in-order. 
With anonymous functions (and I mean the ones that you can use within 
expressions, Bengt ;) ), I could write something like the following:

def add_thingy():
 with_next_thingy_id(def(thingy_id):
 print 'got thingy id:', thingy_id
 with_next_doodad_id(def(doodad_id):
 pring 'got doodad id:', doodad_id
 with_new_thingy_doodad(thingy_id, doodad_id,
def(thingy_doodad):
 print 'thingy doodad created, froobling...'
 frooble(thingy_doodad)
 print 'froobling complete'
 )
 )
 )

In this case, having to name these callback functions is tiring and 
awkward, and (IMHO) disrupts the flow of my function:

def add_thingy():
 def next_thingy_id_func(thingy_id):
 print 'got thingy id:', thingy_id
 def next_doodad_id_func(doodad_id):
 print 'got doodad id:', doodad_id
 def new_thingy_doodad_func(thingy_doodad):
 print 'thingy doodad created, froobling...'
 frooble(thingy_doodad)
 print 'froobling complete'
 with_new_thingy_doodad(thingy_id, doodad_id,
new_thingy_doodad_func)
 with_next_doodad_id(next_doodad_id_func)
 with_next_thingy_id(next_thingy_id_func)

There is no reason why these callbacks would necessarily be one-liners 
or ten-liners. I suppose this problem could be solved by defining all 
the functions at the top-level (or by using bound methods of an object), 
but to me this is harder to maintain and doesn't read as well.

Not life or death, but there's at least one use case that I would at 
least consider "valid". Your definition of "valid" may differ, of course. =)

Dave
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Dave Benjamin
Cameron Laird wrote:
In article <[EMAIL PROTECTED]>,
Peter Hansen  <[EMAIL PROTECTED]> wrote:
This meets your requirements as stated:
def temp():
  foo.var = 1
bind('a', temp)
def temp():
  foo.var = 2
bind('b', temp)
del temp
Ewww!  *When* is lambda going bye-bye?  I apparently
haven't been paying close enough attention.  Among other
considerations, I still instruct people to use lambda for
plenty of specific cases.
Well, IMNSHO, it's an empty threat that's been looming on the horizon 
for several years now. ;) Most recently, Guido mentioned his desire to 
remove the keyword in his post on Artima, which resulted in a huge debate:

http://www.artima.com/weblogs/viewpost.jsp?thread=98196
Note that in the OP's question, as with Peter's example above, you still 
can't do it with lambda alone, since you can't mix expressions with 
assignment. Nonetheless, lambda is nice for delaying binding, and 
combined with a helper function that sets attributes, it can produce the 
most concise solution:

bind('a', lambda: setattr(foo, 'var', 1))
bind('b', lambda: setattr(foo, 'var', 2))
The usual response is that you probably want to make a class anyway, and 
use bound methods for this type of stuff. But I find that in GUI/async 
programming, often you need a little dab of glue to connect events 
between objects, and lambda provides a nice way to avoid 
over-abstracting the problem.

We'll see how this all pans out in the next few years. I'm not too fond 
of removing features from a language for purely aesthetic reasons, but 
lambda's really stuck in a syntactic quandry due to the 
statement/expression dichotomy, so I can understand to some extent 
Guido's desire to remove it.

Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Dave Benjamin
Dave Benjamin wrote:
You could use a combination of bound methods and the "curry" function 
defined in the Python Cookbook:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
The examples in the discussion do just that.
Also, in the CVS version of Python, there's a new module called 
"functional" with a function called "partial" that does the same thing 
as far as I can tell. So, in the future, this function will probably be 
available in the standard library.

Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Dave Benjamin
Paul Miller wrote:
Michael Hoffman wrote:
Dave Benjamin wrote:
I think you meant to write something like this:
def attrsetter(obj, name, value):
def _return_func():
return setattr(obj, name, value)
return _return_func

Sure did. Sorry.

You guys have been very helpful!
While on the subject, is there an equivalent for "methodcaller"?
ie. if I want to bind a function which calls a specific method of an 
object with a specific parameter?
You could use a combination of bound methods and the "curry" function 
defined in the Python Cookbook:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
The examples in the discussion do just that.
Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Dave Benjamin
Michael Hoffman wrote:
Paul Miller wrote:
 > I see lambda is "going away", so I want to use something that will be 
 > around for awhile.
 >
 > All I want to do is provide an "inline function" as an argument to
 > another function.

That's what lambda does. But it's going away, you'll have to use def 
when it does, unless the language designers come up with something better.

For example, let's say I have a function which binds a key to a 
function call. I want to do something "simple" in this function call, 
and I have a lot of bindings, so I don't want to have a ton of tiny 
little functions scattered around:

def setVarTo1():
foo.var = 1
def setVarTo2():
foo.var = 2
bind('a', setVarTo1)
bind('b', setVarTo2)

If a lot of the bindings are actually setting variables, you could do 
something like this:

def attrsetter(obj, name, 1):
def _return_func(value):
return setattr(obj, name, value)
return _return_func
I think you meant to write something like this:
def attrsetter(obj, name, value):
def _return_func():
return setattr(obj, name, value)
return _return_func
Or, if you want to delay binding of the "value" parameter:
def attrsetter(obj, name):
def _return_func(value):
return setattr(obj, name, value)
return _return_func
Cheers,
Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: (PHP or Python) Developing something like www.tribe.net

2005-04-26 Thread Dave Benjamin
In article <[EMAIL PROTECTED]>, Mir Nazim wrote:
> I agree Zope2/Plone are really mature. But I think you missed my point.
> It is not neccessary that I may be using all the functionality of Plone
> etc. More over zope3 seems to have got a few great features like better
> support for building filesystem based products, easier learning curve
> etc.

I played around with Plone a couple of years ago, and it was rather slow. It
seemed to have a very solid design and a lot of intelligence put into it,
but I couldn't use it in any productions because I just couldn't squeeze
enough juice out of it, and also, for some reason I needed to restart the
entire Zope process when I made even small changes to templates/skins.

Can anyone who's worked with Plone recently comment as to whether these
issues have been improved since then? I notice that Plone has been popping
up quite a bit lately, and they don't seem unreasonably slow to me. (CPUs
have of course exploded in speed in the past few years.)

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making things more functional in Python

2005-03-04 Thread Dave Benjamin
On Sat, 2005-03-05 at 00:00 -0700, Dave Benjamin wrote:
> On Fri, 2005-03-04 at 08:36 -0800, gf gf wrote:
> > Is there a better, more FP style, more Pythonic way to
> > write this:
> > 
> > def compute_vectors(samples, dset):
> > vectors = {}
> > for d in dset:
> > vectors[d] = [sample.get_val(d) for sample in
> > samples]
> > return vectors
> 
> You could use reduce:
> 
> def compute_vectors(samples, dset):
> def add_entry(vectors, d):
> vectors[d] = [sample.get_val(d) for sample in samples]
> return vectors
> return reduce(add_entry, dset, {})

This could be further generalized:

def compute(xs, ys, f):
def add_entry(result, y):
result[y] = [f(x, y) for x in xs]
return result
return reduce(add_entry, ys, {})

Now, compute_vectors is just:

compute(samples, dset, lambda x, y: x.get_val(y))

You could even abstract the method call:

def method(name):
def _method(obj, *args, **kwds):
return getattr(obj, name)(*args, **kwds)
return _method

compute(samples, dset, method('get_val'))

Dave


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making things more functional in Python

2005-03-04 Thread Dave Benjamin
On Fri, 2005-03-04 at 08:36 -0800, gf gf wrote:
> Is there a better, more FP style, more Pythonic way to
> write this:
> 
> def compute_vectors(samples, dset):
>   vectors = {}
>   for d in dset:
>   vectors[d] = [sample.get_val(d) for sample in
> samples]
>   return vectors

You could use reduce:

def compute_vectors(samples, dset):
def add_entry(vectors, d):
vectors[d] = [sample.get_val(d) for sample in samples]
return vectors
return reduce(add_entry, dset, {})

Dave


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to wrap a class's methods?

2005-02-17 Thread Dave Benjamin
Michael Spencer wrote:
Grant Edwards wrote:
Thanks.  The stuff provided by the "new" module is what I was
missing.
No magic in the 'new' module - new.instancemethod is just a synonym for 
the method type:

 >>> import new, types
 >>> new.instancemethod is types.MethodType
True
(Assuming you're using Python 2.3 or newer)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't join() call str() on its arguments?

2005-02-17 Thread Dave Benjamin
Jeremy Bowers wrote:
I'd point out that the Zen that can be comprehended by checking off items
in a list is not the true Zen.
The Zen that can be imported is not the eternal Zen. =)
--
http://mail.python.org/mailman/listinfo/python-list


Re: namespace collisions

2005-02-17 Thread Dave Benjamin
Will McGugan wrote:
I'm accumulating a number of small functions, which I have sensibly put 
in a single file called 'util.py'. But it occurs to me that with such a 
generic name it could cause problems with other modules not written by 
myself. Whats the best way of handling this? If I put it in a common 
location in my Python path, should I call it willsutil.py?
I find that it's beneficial in the long run to create a package for your 
project. This will insure you against name collisions in general, should 
you later need to combine projects::

  import myproject.util
  myproject.util.myhandyfunction()
  etc.
The potential downside is that if you really need to reuse util.py in 
multiple projects, you'll have to copy the file to each package, or 
create a central package that the other projects' packages link to. But 
it's been my experience that the type of stuff that goes in "util" 
modules is pretty miscellaneous in nature, and not as reusable as it 
seems. Not worth creating additional dependencies, anyway.

There's really no one right answer to your question, but I've been 
(mildly) bitten by naming collisions, and as a result I use packages for 
every project now.

Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: Nested scopes and class variables

2005-02-03 Thread Dave Benjamin
Thanks, Nick and Alex, for the nice, detailed explanations. My understanding
of Python bytecode is not deep enough to comment at this time. ;)

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
-- 
http://mail.python.org/mailman/listinfo/python-list


Type inference, lessons learned from Vyper

2005-02-03 Thread Dave Benjamin
Hey all,

I came across a fascinating thread on the Caml mailing list this morning.
It's about writing an interpreter for Python that can do type inference, and
John Skaller shares a lot of his experiences with the Vyper project:

http://groups-beta.google.com/group/fa.caml/browse_frm/thread/4f65d0484529848e/

As you may recall, Vyper was an implementation of Python written in OCaml.
The source code has apparently gone to bit-heaven, but Skaller's analysis
gives some illuminating insight into the kinds of problems we might run into
if Python is to become more statically verifiable.

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
-- 
http://mail.python.org/mailman/listinfo/python-list


Nested scopes and class variables

2005-01-30 Thread Dave Benjamin
I ran into an odd little edge case while experimenting with functions that
create classes on the fly (don't ask me why):

  >>> def f(x):
  ...   class C(object):
  ... x = x
  ...   print C.x
  ...
  >>> f(5)
  Traceback (most recent call last):
File "", line 1, in ?
File "", line 2, in f
File "", line 3, in C
  NameError: name 'x' is not defined

"x" clearly is defined, but apparently Python is not looking at the nested
variable scope to find it. What's stranger is that if I rename the parameter
"x" to "y", the error goes away:

  >>> def f(y):
  ...   class C(object):
  ... x = y
  ...   print C.x
  ...
  >>> f(5)
  5

So, it's not like nested scopes aren't supported in the class block. Rather,
when it sees "x = x", it seems like Python is determining at that point that
"x" is a class variable, and refuses to search any further.

At the top-level, it works as expected:

  >>> x = 5
  >>> class C(object):
  ...   x = x
  ...
  >>> C.x
  5

Any implementation gurus have some insight into what's going on here?

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python without OO

2005-01-27 Thread Dave Benjamin
Davor wrote:
Is it possible to write purely procedural code in Python, or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them? Also, is anyone aware of
any scripting language that could be considered as "Python minus OO
stuff"? (As you can see I'm completely new to Python and initially
believed it's a nice&simple scripting language before seeing all this
OO stuff that was added in over time)
Many people have answered your question already, but I thought I would 
share my opinion as well, since I think I understand where you are 
coming from.

What attracted me to Python was not OO at all but the fact that it was 
somewhat similar to PHP (which I was using heavily at the time) but 
allowed me to encode certain higher-order programming techniques that 
PHP simply could not express. In short, I had become interested in 
functional programming after reading David Mertz's "Charming Python" 
tutorials, and after x attempts at trying to port the ideas to PHP, I 
finally gave up in frustration and started learning Python.

At the time, I was decidedly anti-OO. I grew up around a very liberal, 
punk-rock, nonconformist culture, and the amount of hype around OO made 
it too easy to hate (and, I suppose, it still does). PHP at the time was 
90% procedural; the prevaling attitude (which seems to have changed with 
the advent of PHP5) was that procedural code is all you need to solve 
most problems. With web scripting, it kind of makes sense, because 
(IMHO) objects really don't have much value unless you can hold onto 
them long enough for them to be useful, and many web scripts just pipe 
data from one place to another. Packing the data into objects is kind of 
like putting your possessions into boxes so that you can move them from 
one room to another and immediately unpack.

So, I guess you could say, I learned Python in spite of its rich support 
for OO. =)

It wasn't until I had to implement a large (to me), complex, graphical 
user interface, that I finally had to get off of my soapbox and realize 
that I had no better way to create sophisticated GUIs than OO. There are 
surely non-OO ways to build fancy GUIs, like functional-reactive 
programming, but a) I don't understand them, and b) I had to get my 
project done, and used the tools I had and the techniques I knew.

At that time, I started learning about Smalltalk and Alan Kay's emphasis 
on the "messaging" aspect of OO, and it started making a lot more sense. 
One of the most difficult tasks sometimes is getting various parts of 
the screen to update when the user changes a field or clicks a 
button--in a way that is manageable and doesn't devolve into spaghetti.

Aside from GUIs, however, I am rarely confronted with a task where I 
*need* OO. As a method for encoding abstract data types, it works, but 
it seems like more fashion than substance. As many have pointed out, the 
difference between "method(obj, args)" and "obj.method(args)" is subtle, 
and often inconsequential. In Python, you can program with just modules 
and functions/procedures, and never bother with the fact that you are 
using objects. Sure, a module is an object, and so is a procedure, but 
it's not all up in your face like, say, Java's arcane restriction that 
everything belong to some class.

It has been said of Perl programmers that they often dislike 
abstraction. Sometimes, I really sympathize with this viewpoint. I hate 
having to use a class that offers no value to the problem whatsoever, 
merely because an API is hard-wired to use instances of that class. No 
abstraction can often be better than a bad abstraction, and when it 
comes to debugging, the last thing you want is a bunch of black boxes.

These days, I do use classes and objects in Python, but mainly as a code 
organization technique, and only when I actually want my code organized 
that way. I tend to start with the problem at hand, building procedures 
to remove redundancy and keep my code small and simple. If I start 
noticing that a lot of procedures revolve around a particular data 
structure, I refactor them into a class. This way, I avoid creating 
abstractions that don't fit. It's much more mechanical than any feigned 
attempt at "modeling the real world".

I think that functional programming (FP) is a very powerful methodology 
that can solve a lot of the same problems as OO, and does some things a 
lot better. FP and OO can live in harmony to some extent, but there are 
some places where they contradict each other. For instance, FP offers a 
mind-blowingly powerful tool called pattern matching, which is like a 
switch/case statement on steroids. OO dogma insists that this "violates 
encapsulation", and that any form of switch/case is evil... replace 
conditional with polymorphism... replace conditional with 
polymorphism... replace conditional with polymorphism... repl On 
the other hand, implementing something as seemingly simple as a 
"__str__" me

Re: Zen of Python

2005-01-21 Thread Dave Benjamin
Paul Rubin wrote:
Tim Peters <[EMAIL PROTECTED]> writes:
But at that time, Python didn't have lexical scoping, and it wasn't
clear that it ever would.  So what's the bigger wart?  Making
listcomps exactly equivalent to an easily-explained Python for-loop
nest, or introducing a notion of lexical scope unique to listcomps,
hard to explain in terms of the way the rest of the language worked? 
Oops, I'd gotten confused and thought lexical scope came first and
listcomps afterwards.  If lexical scope came afterwards, then
implementing listcomps as a for-loop at that time makes more sense.
Of course in that case, since the absence of lexical scope was a wart
in its own right, fixing it had to have been on the radar.  So turning
the persistent listcomp loop var into a documented feature, instead of
describing it in the docs as a wart that shouldn't be relied on,
wasn't such a hot idea.  Adding lexical scope and listcomps at the
same time might have also been a good way to solve the issue.
Can we get a show of hands for all of those who have written or are 
currently maintaining code that uses the leaky listcomp "feature"?

I guess I've been peripherally aware of it, but I almost always use 
names like "x" for my loop variables, and never refer to them 
afterwards. If Python were to change in this regard, I don't think it 
would break any Python code that I've ever written or maintained...

Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: delay and force in Python

2005-01-19 Thread Dave Benjamin
Will Stuyvesant wrote:
. def delay(exp): return lambda: exp
If you look at the definition of "delay" in SICP, you'll notice that 
it's defined as "syntax sugar", in other words, a macro. Since Python 
does not have macros, you'll have to just use "lambda", because by 
defining "delay" as a function, you're forcing the expression "exp" to 
evaluate immediately. In other words, theres a crucial difference between::

  delay(sys.stdout.write('evaluated\n'))
and::
  lambda: sys.stdout.write('evaluated\n')
If you type in those two snippets, you'll see what I mean.
Coincidentally, I attempted a similar experiment just a couple of days 
ago, and here's what I came up with::

   # Stream.py - Stream class inspired by SICP
class Stream(object):
pass
class EndOfStream(Exception):
pass
class Item(Stream):
def __init__(self, current, nextf):
self.current = current
self.nextf = nextf
next = property(lambda self: self.nextf())
def fold(self, f, init):
return f(self.current, self.next.fold(f, init))
def __getitem__(self, n):
if n == 0:
return self.current
else:
return self.next[n - 1]
def __str__(self):
return '' % self.current
__repr__ = __str__
class End(Stream):
def fold(self, f, init):
return init
def __getitem__(self, n):
raise EndOfStream()
def _fail(self):
raise EndOfStream()
current = property(_fail)
next = property(_fail)
def __str__(self):
return ''
__repr__ = __str__
Here's how it works::
Python 2.4 (#1, Dec  4 2004, 20:10:33)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import Stream
>>> s = Stream.Item(1, lambda: Stream.Item(2, lambda: Stream.End()))
>>> s

>>> s.current
1
>>> s.next

>>> s.next.current
2
>>> s.next.next

>>> s.next.next.next
Traceback (most recent call last):
  File "", line 1, in ?
  File "Stream.py", line 37, in _fail
raise EndOfStream()
Stream.EndOfStream
>>> def evens(n=0):
... return Stream.Item(n, lambda: evens(n + 2))
...
>>> s = evens()
>>> s.current
0
>>> s.next.current
2
>>> s.next.next.current
4
I don't know if this is useful or not, but it was an interesting 
exercise nonetheless.

Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: One-Shot Property?

2005-01-18 Thread Dave Benjamin
Kevin Smith wrote:
I have many cases in my code where I use a property for calculating a 
value on-demand.  Quite a few of these only need to be called once.  
After that the value is always the same.  In these properties, I set a 
variable in the instance as a cached value and return that value on 
subsequent calls.  It would be nice if there was a descriptor that would 
do this automatically.  Actually, what would be really nice is if I 
could replace the property altogether and put the calculated value in 
its place after the first call, but the property itself prevents me from 
doing that.  Is this possible?
I was going to recommend taking a look at the "memoize" example on the 
Python wiki, but it seems to be missing at the moment. In any case, 
here's the URL:

http://www.python.org/moin/PythonDecoratorLibrary
There are also a few examples on the Cookbook, like this one:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325205
It shouldn't be too difficult to adapt this technique so that it can be 
used to create properties. I wouldn't bother replacing the property with 
an attribute unless you have a specific reason to do so (performance, 
perhaps).

HTH,
Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda as declarative idiom (was RE: what is lambda used for in real code?)

2005-01-03 Thread Dave Benjamin
Roman Suzi wrote:
I wish lambdas will not be deprecated in Python but the key to that is
dropping the keyword (lambda). If anybody could think of a better syntax for
lambdas _with_ arguments, we could develop PEP 312 further.
Well, my vote is still with Ruby-style codeblock syntax, but as a 
compromise, what about the following:

  fun(a, b): a + b
as a replacement for:
  lambda a, b: a + b
Advantages:
  - Doesn't use the l-word
  - Uses parentheses always
  - "fun" is shorter and self-describing
  - Makes Python code more "fun" ;)
Disadvantages:
  - Requires a new keyword, breaking backward compatibility
(I'm assuming we're still talking about Py3k here)
  - (Still) doesn't interface statements with expressions
Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why no list heritable type?

2004-12-22 Thread Dave Benjamin
Mike Meyer wrote:
"Robert Brewer" <[EMAIL PROTECTED]> writes:
Why aren't built 
in lists and dictionaries real heritable types that can save 
this kind of patchwork?
They are since Python 2.2 (IIRC):
And before Python 2.2 there was the UserList class in the standard
library. Which is still there in 2.4. Shouldn't it be depreciated by
this point?
Please keep in mind that the latest stable version of Jython is 2.1, 
which does not support subclassing "list", and "dict" does not exist at all:

Jython 2.1 on java1.4.2_01 (JIT: null)
Type "copyright", "credits" or "license" for more information.
.>>> class C(list): pass
...
Traceback (innermost last):
  File "", line 1, in ?
TypeError: base is not a class object: instance of 
'org.python.core.BuiltinFunctions'
.>>> class D(dict): pass
...
Traceback (innermost last):
  File "", line 1, in ?
NameError: dict

I'm sure there are workarounds that will make the above code work in 
both CPython and Jython, but until there is a stable release of Jython 
that natively supports subclassing "list" and "dict", I'd appreciate it 
if we didn't deprecate (or depreciate =) UserList/Dict just yet. I 
maintain several modules that are portable to both implementations.

Dave
--
http://mail.python.org/mailman/listinfo/python-list


Re: A rational proposal

2004-12-19 Thread Dave Benjamin
Hi Mike - Thanks for taking the time to put this together.

In article <[EMAIL PROTECTED]>, Mike Meyer wrote:
> - max(*args): return the largest of a list of numbers and self.
> - min(*args): return the smallest of a list of numbers and self.

I would strongly prefer either adapting the already built-in min/max
functions to support this type or creating functions in a module rather than
using the method approach. My reason is the assymetry; I would much prefer:

rational.max(rat1, rat2, rat3)

over:

rat1.max(rat2, rat3)

for the simple reason that the latter looks unbalanced and empbasizes "rat1"
when there is really no reason to do so.

> Rationals will mix with all other numeric types.  When combined with an
> integer type, that integer will be converted to a rational before the
> operation.  When combined with a floating type - either complex or
> float - the rational will be converted to a floating approximation
> before the operation, and a float or complex will be returned.  The
> reason for this is that floating point numbers - including complex -
> are already imprecise.  To convert them to rational would give an
> incorrect impression that the results of the operation are
> precise.  Decimals will be converted to rationals before the
> operation.  [Open question: is this the right thing to do?]

Sounds right to me.

Cheers,
Dave

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lies about OOP

2004-12-15 Thread Dave Benjamin
In article <[EMAIL PROTECTED]>, Adam DePrince wrote:
> On Tue, 2004-12-14 at 18:27, Roy Smith wrote:
>> Terry Reedy <[EMAIL PROTECTED]> wrote:
>> > I did not really 'get' OOP until after learning Python.  The
>> > relatively simple but powerful user class model made more sense to
>> > me than C++.  So introducing someone to Python, where OOP is a
>> > choice, not a mandate, is how *I* would introduce a procedural
>> > programmer to the subject.  YMMV.
>> 
>> OOP is a choice in C++ too.  You can write procedural C++ code; no
>> need to use classes at all if you don't want to.  Something like Java
>> is a different story.  Java *forces* you to use classes.  Nothing
>> exists in Java that's not part of some class.
> 
> Static methods act like C functions.  Sure, they are members of classes,
> but in name only.  Besides, just as you can use a procedural language in
> an OO fashion with enough programmer discipline, you can write in a
> procedural style with an OOP language with sufficient rebellion.  Just
> use one class, put everything in it and create one instance on startup.

Maybe I'm reading this wrong, but it seems like you're implying that
procedural code is inherently unmodular. Why would just one class/instance
suffice to represent a procedural program? I think of namespacing and code
organization as broad concepts that cut across all styles of programming.

Interestingly, Python's main unit of modularity is the "module", not the
"class". A direct translation of a typical Python module to Java would look
something like a Java class containing only static methods and inner classes.
Even this would be considered rebellious within the context of ordinary Java
programming.

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Audio interviews of Guido or other Python advocates?

2004-12-04 Thread Dave Benjamin
In article <[EMAIL PROTECTED]>, Jimmy Retzlaff wrote:
> Dave Benjamin wrote:
>> I looked around for recordings of Guido, but couldn't find any. Does
>> anyone know of any streamable audio (or video) interviews or speeches
>> featuring Guido, the bots, or any other interesting people in the
> Python
>> community?
> 
> There's a video with a few folks in it at:
> 
> http://www.ibiblio.org/obp/pyBiblio/pythonvideo.php

Ohh, man, the geek love story was almost too much to bear. =)
Cool, so that covers Guido, Tim Peters, Eric Raymond, Jim Fulton...

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Audio interviews of Guido or other Python advocates?

2004-12-04 Thread Dave Benjamin
In article <[EMAIL PROTECTED]>, Fredrik Lundh wrote:
> Dave Benjamin wrote:
> 
>> I looked around for recordings of Guido, but couldn't find any.
> 
> http://www.python.org/~guido/guido.au

I found a few--slightly longer--video interviews here today:
http://technetcast.ddj.com/tnc_catalog.html?item_id=90

But thanks, the woodpecker was inspiring.

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
-- 
http://mail.python.org/mailman/listinfo/python-list


Audio interviews of Guido or other Python advocates?

2004-12-04 Thread Dave Benjamin
Ever since I heard Paul Graham's OSCON speech as audio, I've been somewhat
interested in hearing what all these voices of computer culture sound like,
and what they talk about. I enjoyed a few of Larry Wall's speeches as well
as Tim O'Reilly's, here: http://technetcast.ddj.com/

I looked around for recordings of Guido, but couldn't find any. Does anyone
know of any streamable audio (or video) interviews or speeches featuring
Guido, the bots, or any other interesting people in the Python community?
I've seen a video of a Bruce Eckels presentation; that's about the closest
I've found so far.

-- 
 .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
"talking about music is like dancing about architecture."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 and "Python Regrets"

2004-12-01 Thread Dave Benjamin
Steve Holden wrote:
Brad Tilley wrote:
Matt Gerrans wrote:
Anyway, what's to worry about?When the time comes just whip out a 
little script that converts Python 1.6 (or whatever you like) to 
Python3K; it will only take seven lines of P3K code.

How about 'import classic'

... or
from __past__ import __mistakes__
LOL! Better yet:
import __past__
del __past__.__mistakes__
Boy, what a load off!
Merry Christmas in advance,
Dave
--
http://mail.python.org/mailman/listinfo/python-list