Re: A replacement for lambda

2005-07-29 Thread Paul Rubin
James Richards <[EMAIL PROTECTED]> writes:
> Personally, I can't recall any decent programmer I know who objects
> to actually writing out a variable name.  In fact, I don't know a
> single "real" programmer (this is one who writes programs he intends
> to look at again in, say, 3 weeks) who doesn't insist on writing
> "real" variable names.

The issue is whether you want to name every intermediate result in
every expression.

   sum = a + b + c + d + e

is a lot nicer than

   x1 = a + b
   x2 = c + d
   x3 = x1 + e
   sum = x2 + x3

the language has nicely kept all those intermediate results anonymous.

Python has first-class functions, which, like recursion, is a powerful
idea that takes some getting used to.  They let you say things like

  def derivative(f, t, h=.1):   # evaluate f'(t) numerically
return (f(t+h) - f(t)) / h
  
  dy_dt = derivative(cos, 0.3) # approx. -sin(0.3)

With anonymous functions, you can also say:

   dy_dt = derivative(lambda x: sin(x)+cos(x), 0.3) # approx. cos(.3)-sin(.3)

Most Python users have experience with recursion before they start
using Python, so they don't see a need for extra keywords to express
it.  Those not used to first-class functions (and maybe some others)
seem to prefer extra baggage.  For many of those used to writing in
the above style, though, there's nothing confusing about using a
lambda there instead of spewing extra verbiage to store that
(lambda x: sin(x)+cos(x)) function in a named variable before
passing it to another function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-cgi or Perl-cgi script doubt

2005-07-29 Thread EP
Prabahar wrote:

>I want to know difference between
> Python-cgi and Perl-cgi and also I want
> to which one is efficient from the performance.


The difference between a cgi program written in Perl and a cgi program written 
in Python is the choice of programming language.  Both work quite well.  You 
probably want to use whichever programming language you like best, and that can 
only be discovered from writing programs in both.

In terms of "efficient"  (efficiency) , are you talking about how much memory 
the program uses, how fast the program executes, or how much time it takes to 
write and debug the program?  There are differences between the two in these 
regards, but I do not have any reliable information that quantifies those 
differences, and the differences are likely to vary greatly depending on the 
nature and length of the program, and how efficiently written the code is.

I think, generally, if you really like programming in Perl, there is probably 
no reason not to use it (at least for typical/short cgi programs) - it has been 
the default choice for years; conversely, if you really like programming in 
Python, you will probably be happy to tackle any challenges associated with 
using it for cgi.


Notes:
Perl cgi execution is generally offered by all hosts that offer cgi; Python cgi 
execution is offered by fewer hosts (but some of those hosts are really great).

With either language, if execution "performance" is a concern, you may want to 
use something along the lines of mod_python or mod_perl which embed a 
persistent interpreter in your web server. This lets you avoid the overhead of 
starting an external interpreter and avoids the penalty of Perl/Python start-up 
time, giving faster time to execution.

Was this at all the information you were looking for?  Why do I think you may 
have intended a very technical question?  If so, you may have to be a little 
more specific about the sort of differences you are interested in understanding.


Eric


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


Re: On fighting fire with fire...

2005-07-29 Thread mustafa
Steven D'Aprano wrote:
> On Thu, 28 Jul 2005 15:23:46 -0500, Rocco Moretti wrote:
> 
> 
>>Professionals (and even decent hobbyists) don't 
>>escalate flame wars, even unintentionally.
> 
> 
> You don't get out much, do you? *wink*
> 
> If your comment is meant to be _prescriptive_ rather than _descriptive_, I
> don't entirely agree.
> 
> Flame wars, like all wars, are unproductive beyond a certain point, but to
> push the combat analogy, punitive raids can be productive at changing
> behaviour.
> 
> It is never pleasant to be on the receiving end of a flaming, but if it is
> deserved, then people should accept it and learn from it, rather than just
> dismiss it as a flaming and therefore meaningless.
> 
> The problem on the Internet is that there is little or no status: the most
> ignorant newbie and the stupidest AOLer think that they are equal in
> status to somebody who has proven their knowledge for ten years. (This
> lack of status on the Internet is not *always* a bad thing, but it can be.)
> 
> If your boss or professor or a judge gave you a tongue-lashing for stupid
> behaviour, sensible people accept it. "I've been bad, I got caught, thank
> goodness I'm suffering nothing worse than being told I'm an idiot." At
> worst they might complain to their friends afterwards. 
> 
> But on the Internet, people who deserve that tongue-lashing think that
> because they can retaliate, they should retaliate -- and that's where the
> risk of escalation from punitive raid to unproductive flame war lies.
> 
> 
> 
your wierd.
i dont mean that in a bad sense but your the first
the person to i have seen who think in internet does not
have a status quo.
i newbie is classified as one from his first post in any mailing list or 
forum.(in fact most forums siply give you that status according to you 
post count.


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


HTML Scraping??

2005-07-29 Thread mustafa
anyone know some good reliable html scraping (with python) tutorials.
i have looked around and found a few.
one uses urllib2 and beautifull soap modules for scraping and parsing
http://www.dalkescientific.com/writings/diary/archive/2005/04/21/screen_scraping.html

and the other uyses mechanize, clientcookie  ,clientform.
http://sig.levillage.org/?p=588

which one should i go with.
i am looking for and html scraping solution
that works with the registrar of a college and return stuff like course 
dtails.

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


Re: A replacement for lambda

2005-07-29 Thread Tim Roberts
Scott David Daniels <[EMAIL PROTECTED]> wrote:
>
>What kind of shenanigans must a parser go through to translate:
> <
>
>this is the comparison of two functions, but it looks like a left-
>shift on a function until the second with is encountered.  Then
>you need to backtrack to the shift and convert it to a pair of
>less-thans before you can successfully translate it.

C++ solves this exact problem quite reasonably by having a greedy
tokenizer.  Thus, that would always be a left shift operator.  To make it
less than and a function, insert a space:
< 
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Aiksaurus interface?

2005-07-29 Thread James Richards
Major big apologies if this has been covered to death before.

It's been a few years since I played with these two technologies.

I seem to recall a python wrapper over aiksaurus.  I can't find it now.
(Or maybe it's just my own stupidity.  That's been known to happen :-/).

Is there a project/wrapper dedicated to this?  I didn't find anything
obvious on google or sourceforge, but that doesn't mean much. I probably
spelled all my search queries wrong, and stuff like that.

Then again, I didn't see anything in PyPI.  Aiksaurus has evolved quite 
a bit in the last few years, and I haven't been following.  Is there a
Python wrapper?  Would anyone be interested in a Python wrapper if there's
not one now?

Regards,
James

-- 
Liberty means responsibility. That is why most men dread it.
- George Bernard Shaw

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


Re: To thread or not to thread

2005-07-29 Thread James Richards
On 2005-07-28, Sidd <[EMAIL PROTECTED]> wrote:
> Hello,
>   I was recently reading an article on threading in python and I
> came across Global Interpreter Lock,now as a novince in python I was
> cusrious about
>
> 1.Is writing a threaded code in python going to perform well than a
> normal python  code.If so on what basis can it performance be measured.

My last "real" experience with python threads was a while back, on a P-2.
That experience suggested that creating "lots" of threads (a few hundred)
caused some serious performance impacts.  I determined, in that instance,
that it was better to write my own implementation to simulate threads.
I had set of classes that pretended to be threads.  I had another class
which actually did all the threading for them.  It was pretty ugly.
>
> 2.Is writing a threaded code in python better than a code written in
> C/C++ using PTHREADS.

I agree with the earlier.  Define "better."  Do you really have a heavily
multi-threaded app?  Are these threads all CPU-intensive, or do you just 
have a bunch of threads which need some arbitrary scheduling?  Is it really
worth re-writing in PTHREADS?  Or could you buy a new server and save a few
months in development time by writing your own scheduling?

It all depends on your situation.

>
> If someone can comment on these questions, it would be great.
>

Heh.  You're on Usenet.  *Anyone* can comment on these questions.  :-)  
You should have asked for *useful* comments.  ;-)


-- 
Liberty means responsibility. That is why most men dread it.
- George Bernard Shaw

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


Python-cgi or Perl-cgi script doubt

2005-07-29 Thread praba kar
Dear All,

   I want to know difference between
Python-cgi and Perl-cgi and also I want
to which one is efficient from the performance.

regards
Prabahar



___
Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for 
FREE! http://in.mail.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A replacement for lambda

2005-07-29 Thread James Richards
On 2005-07-30, Scott David Daniels <[EMAIL PROTECTED]> wrote:
> Christopher Subich wrote:
>> g = 
>> g(1) == 1
>> 
>> Basically, I'd rewrite the Python grammar such that:
>> lambda_form ::= "<" expression "with" parameter_list ">"
>> 
>> Biggest change is that parameter_list is no longer optional, so 
>> zero-argument expr-comps would be written as , which makes 
>> a bit more sense than .
>> 
>> Since "<" and ">" aren't ambiguous inside the "expression" state, this 
>> shouldn't make the grammar ambiguous.  The "with" magic word does 
>> conflict with PEP-343 (semantically, not syntactically), so "for" might 
>> be appropriate if less precise in meaning.
>
> What kind of shenanigans must a parser go through to translate:
>  <
>
> this is the comparison of two functions, but it looks like a left-
> shift on a function until the second with is encountered.  Then
> you need to backtrack to the shift and convert it to a pair of
> less-thans before you can successfully translate it.

I'm just worming my way into learning Lisp, but this seems to be a
perfect example of everything I'm seeing so far.  The compiler should
do all sorts of gymnastics and contortions.  Make the compiler/interpreter
as complex as possible, to handle any freaky thing a programmer can
invent.

Which does not, in the least, imply that the same attitude should apply toward
python.

I read this thread and my brain hurts.  Python code should *never* do this.

Tim Peters (let's all bow down, we're not worthy ) might write some code that
I can't quite follow.  But at least it's obvious.  He doesn't suddenly introduce
an entirely new syntax for the sake of "hey, this would be cool." Or maybe
"It'd be much more simple if we made everyone use more C-like syntax." Or...
wherever you were going with this.  This
>
>  <
is precisely the kind of code that I got into python to avoid.

I happen to like nice, simple, readable code.  Maybe I'm just old and grumpy.  
Looking at that line, I get the same "This is just ugly" feel that I get when 
I at perl.  Some note from other pieces in this thread.  Things about $_ or 
what-not.


Personally, I can't recall any decent programmer I know who objects to actually
writing out a variable name.  In fact, I don't know a single "real" programmer
(this is one who writes programs he intends to look at again in, say, 3 weeks) 
who doesn't insist on writing "real" variable names.

(Heh. I'll probably read through some Guido code next week that totally proves 
me wrong ...such is life).

> --Scott David Daniels
> [EMAIL PROTECTED]


-- 
Liberty means responsibility. That is why most men dread it.
- George Bernard Shaw

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


Selection, picking with PyOpenGL?

2005-07-29 Thread Erik Max Francis
I was interesting in adding selection and hit testing to ZOE, and was 
looking at the PyOpenGL wrappers' handling of selection and picking.  I 
see glSelectBuffer to specify the size of the buffer, and glRenderMode 
properly returns the number of hits when put back into GL_RENDER mode, 
but I don't see any way within PyOpenGL itself to access the select 
buffer to actually process the hits.  Is there any way to do this 
without using OpenGLContext?  (If not, does this make sense, given that 
OpenGLContext is supposed to be an additional helper library for a 
gentle introduction to OpenGL?)

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   I will always remember / This moment
   -- Sade
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Path inherits from basestring again

2005-07-29 Thread Peter Hansen
NickC wrote:
> I'm usually not much of a purist, but C++ has convinced me that
> overloading an operator to mean something entirely unrelated to its
> mathematical meaning can be very unwise.

Me too.  In general.  I've yet to overload a single operator that way in 
years of writing Python code, though I definitely sinned with the rest 
of the C++ crowd (in the early days).

In actual usage with path.py, however, I've found the use of "/" to be 
quite unsurprising and benign relative to what I had expected.  That's 
why (to my surprise) I found myself using and appreciating it.

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


Re: Ten Essential Development Practices

2005-07-29 Thread Jorge Godoy
Michael Hoffman wrote:

> In that case, I think he just wasted a lot of time in the article, and
> would have been better off saying "use Getopt::Long."

This is why I think he was more concerned with design than implementation. 

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

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


Re: Hiding

2005-07-29 Thread Jay
thanks for the great info and urls, i have downloaded the pymedia
module and playing around with it now. Thx alot

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


Re: Ten Essential Development Practices

2005-07-29 Thread Michael Hoffman
Jorge Godoy wrote:
> Michael Hoffman wrote:
> 
> 
>>True, but a lot of his point *is* parsing input from the command line.
>>Consider the following points paraphrased from his article:
>>
>>* Don't mix multiple ways of specifying options. (Solved by optparse)
>>* If a flag expects an associated value, allow an optional = between the
>>flag and the value. (Solved by optparse)
>>* Allow single-letter options to be "bundled" after a single dash.
>>(Solved by optparse)
>>* Always allow -- as a file list marker. (Solved by optparse)
>>
>>And a lot of the other points are things that are made much, much,
>>simpler by optparse, to the point that they become somewhat obvious.
> 
> Take a look at the Perl module, then.  You'll see that all of these are also
> solved there "automagically".

In that case, I think he just wasted a lot of time in the article, and 
would have been better off saying "use Getopt::Long."
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyDev 0.9.7 released

2005-07-29 Thread Jorge Godoy
Rocky Burt wrote:

> Installing fresh PyDev 0.9.7 onto eclipse 3.1 (no prior PyDev installed)
> yields the following error when opening a python file.  Seems like a
> simple enough error... the PyEdit class seems to be present.

I had the same problems today.  Then I read the requisites: Java 1.5.0. ;-) 
Installing it made everything work perfectly.

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

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


RE: [path-PEP] Path inherits from basestring again

2005-07-29 Thread Tony Meyer
>> (Those who are offended by sweeping generalisations should 
>> ignore this next bit)
[...generalisation bit snipped...]
> This is not only bullshit, it's elitist bullshit.  "Windows users are
> more clueless than users of posix systems."  Pfui.  Prove it 
> or withdraw it.

Sigh.  I guess you didn't read or understand the first sentence?

>> This (readability without knowing the language/standard
>> libraries) is a huge benefit of using Python.
> 
> It's overrated.  It must be macho to say "I learned Python without
> reading books."

No it is not.  Have you used Python as pseudocode when teaching people how
to program?  Many people have.  That's just one example.

> Then that's your right, but don't try to take / away from 
> people who use it and like it.

People can subclass Path and add it if they really want it.  They can use
Jason's original module.  My position is that the PEP without this use of
__div__ is (a) better as a standard module, and (b) improves the chance of
the PEP being accepted.

=Tony.Meyer

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


Re: [path-PEP] Path inherits from basestring again

2005-07-29 Thread Ivan Van Laningham
Hi All--

Tony Meyer wrote:
> 
> So far, there have been various statements that look like +0 for __div__,
> but no-one with a +1.  (And I've said this a couple of times now, which
> really is just trolling for a +1 from someone).
> 
> > It's not a question of saving characters, but readability which, as
> > you've said, is a matter of opinion.
> 

I like / as a shortcut to joinwith().  I like it a lot.  I like it so
much I'll give you a +2.

> (Those who are offended by sweeping generalisations should ignore this next
> bit)
> 
> I think it's also worth considering that Windows users are more clueless
> than users of posix systems.  The readability of __div__ comes from
> familiarity with posix filesystems; for a Windows user, \ would be the
> natural character.  So we're making things more readable for users that are
> already more likely figure things out, and less readable for users that have
> trouble figuring things out.
> 

This is not only bullshit, it's elitist bullshit.  "Windows users are
more clueless than users of posix systems."  Pfui.  Prove it or withdraw
it.

> 1.  ISTM that standard library modules should be as readable as possible,
> even for those that don't use them.  If I'm reading the source for module X
> and it uses a Path object, then it should be pretty straightforward to
> understand what is happening without also having to read the Path
> source/docs.  This (readability without knowing the language/standard
> libraries) is a huge benefit of using Python.
> 

It's overrated.  It must be macho to say "I learned Python without
reading books."  Next you'll tell me you never ask for directions when
you're lost.

> 2.  If I did use the Path module, then I wouldn't use __div__, because it
> looks less readable to me.  I suppose I might find that I got annoyed typing
> joinpath, but I doubt it.  Also, because I have followed this PEP, I know
> that __div__ means joinwith, so if I read code that used path, I would
> understand it - it's too late for me to try reading code as a 'fresh' user
> and see if it confuses me or not.
> 

Then that's your right, but don't try to take / away from people who use
it and like it.

Metta,
Ivan
--
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writing a web client

2005-07-29 Thread gene tani
Here:
http://diveintopython.org/http_web_services/index.html#oa.divein

Here:
Cookbook rel 2, and:
http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=Web

Here:other really good py intros which cover 2.2 / urllib (maybe 2.3, I
don't have them with me), but examples should all not give deprecation
warnings: Practical Py (Hetland), Text Processing (Mertz).

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


Re: ANN: PyDev 0.9.7 released

2005-07-29 Thread Rocky Burt
Installing fresh PyDev 0.9.7 onto eclipse 3.1 (no prior PyDev installed)
yields the following error when opening a python file.  Seems like a
simple enough error... the PyEdit class seems to be present.

java.lang.ClassNotFoundException: org.python.pydev.editor.PyEdit
at
org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:403)
at
org.eclipse.osgi.framework.internal.core.BundleLoader.findClass(BundleLoader.java:350)
at
org.eclipse.osgi.framework.adaptor.core.AbstractClassLoader.loadClass(AbstractClassLoader.java:78)
at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
at
org.eclipse.osgi.framework.internal.core.BundleLoader.loadClass(BundleLoader.java:275)
at
org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:227)
at
org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1259)
at
org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:152)
at
org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:142)
at
org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:129)
at
org.eclipse.core.internal.registry.ConfigurationElementHandle.createExecutableExtension(ConfigurationElementHandle.java:48)
at org.eclipse.ui.internal.WorkbenchPlugin
$1.run(WorkbenchPlugin.java:240)
at
org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69)
at
org.eclipse.ui.internal.WorkbenchPlugin.createExtension(WorkbenchPlugin.java:236)
at
org.eclipse.ui.internal.registry.EditorDescriptor.createEditor(EditorDescriptor.java:252)
at
org.eclipse.ui.internal.EditorManager.createPart(EditorManager.java:837)
at
org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:543)
at
org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:365)
at
org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:552)
at
org.eclipse.ui.internal.EditorAreaHelper.setVisibleEditor(EditorAreaHelper.java:258)
at
org.eclipse.ui.internal.EditorManager.setVisibleEditor(EditorManager.java:1216)
at org.eclipse.ui.internal.EditorManager$5.run(EditorManager.java:944)
at
org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1044)
at org.eclipse.core.runtime.Platform.run(Platform.java:783)
at
org.eclipse.ui.internal.EditorManager.restoreState(EditorManager.java:939)
at
org.eclipse.ui.internal.WorkbenchPage.restoreState(WorkbenchPage.java:2535)
at
org.eclipse.ui.internal.WorkbenchWindow.restoreState(WorkbenchWindow.java:1819)
at
org.eclipse.ui.internal.Workbench.doRestoreState(Workbench.java:2566)
at org.eclipse.ui.internal.Workbench.access$14(Workbench.java:2515)
at org.eclipse.ui.internal.Workbench$19.run(Workbench.java:1514)
at org.eclipse.ui.internal.Workbench$16.run(Workbench.java:1263)
at
org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:346)
at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:291)
at
org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:447)
at
org.eclipse.ui.internal.Workbench.runStartupWithProgress(Workbench.java:1258)
at org.eclipse.ui.internal.Workbench.restoreState(Workbench.java:1512)
at org.eclipse.ui.internal.Workbench.access$12(Workbench.java:1491)
at org.eclipse.ui.internal.Workbench$17.run(Workbench.java:1374)
at
org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1044)
at org.eclipse.core.runtime.Platform.run(Platform.java:783)
at org.eclipse.ui.internal.Workbench.restoreState(Workbench.java:1318)
at
org.eclipse.ui.internal.WorkbenchConfigurer.restoreState(WorkbenchConfigurer.java:183)
at
org.eclipse.ui.application.WorkbenchAdvisor.openWindows(WorkbenchAdvisor.java:700)
at org.eclipse.ui.internal.Workbench.init(Workbench.java:1034)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1636)
at
org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:367)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:143)
at
org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:103)
at org.eclipse.core.internal.runtime.PlatformActivator
$1.run(PlatformActivator.java:226)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:376)
at
org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:163)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.ja

Re: A replacement for lambda

2005-07-29 Thread Scott David Daniels
Christopher Subich wrote:
> g = 
> g(1) == 1
> 
> Basically, I'd rewrite the Python grammar such that:
> lambda_form ::= "<" expression "with" parameter_list ">"
> 
> Biggest change is that parameter_list is no longer optional, so 
> zero-argument expr-comps would be written as , which makes 
> a bit more sense than .
> 
> Since "<" and ">" aren't ambiguous inside the "expression" state, this 
> shouldn't make the grammar ambiguous.  The "with" magic word does 
> conflict with PEP-343 (semantically, not syntactically), so "for" might 
> be appropriate if less precise in meaning.

What kind of shenanigans must a parser go through to translate:
 <

this is the comparison of two functions, but it looks like a left-
shift on a function until the second with is encountered.  Then
you need to backtrack to the shift and convert it to a pair of
less-thans before you can successfully translate it.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: [path-PEP] Path inherits from basestring again

2005-07-29 Thread Tony Meyer
> We're talking at this point about how Path should work, not 
> whether it's preferable to os.path.join, even though that was
> really the point of Reinhard's original post.

That's not what I'm talking about.  I'm talking about whether __div__ should
be a shortcut to joinwith, or whether users should be forced to use joinwith
explicitly.

So far, there have been various statements that look like +0 for __div__,
but no-one with a +1.  (And I've said this a couple of times now, which
really is just trolling for a +1 from someone).

> It's not a question of saving characters, but readability which, as 
> you've said, is a matter of opinion.

(Those who are offended by sweeping generalisations should ignore this next
bit)

I think it's also worth considering that Windows users are more clueless
than users of posix systems.  The readability of __div__ comes from
familiarity with posix filesystems; for a Windows user, \ would be the
natural character.  So we're making things more readable for users that are
already more likely figure things out, and less readable for users that have
trouble figuring things out.

> I can live with the latter, but as *someone who has used the 
> path module already* I can only say that you might want to try it
> for a few months before condemning the approach using / as being
> unacceptable.

1.  ISTM that standard library modules should be as readable as possible,
even for those that don't use them.  If I'm reading the source for module X
and it uses a Path object, then it should be pretty straightforward to
understand what is happening without also having to read the Path
source/docs.  This (readability without knowing the language/standard
libraries) is a huge benefit of using Python.

2.  If I did use the Path module, then I wouldn't use __div__, because it
looks less readable to me.  I suppose I might find that I got annoyed typing
joinpath, but I doubt it.  Also, because I have followed this PEP, I know
that __div__ means joinwith, so if I read code that used path, I would
understand it - it's too late for me to try reading code as a 'fresh' user
and see if it confuses me or not.

=Tony.Meyer

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


Re: A replacement for lambda

2005-07-29 Thread Paul Rubin
Christopher Subich <[EMAIL PROTECTED]> writes:
> My personal favourite is to replace "lambda" entirely with an
> "expression comprehension", using < and > delimeters.

But how does that let you get more than one expression into the
anonymous function?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A replacement for lambda

2005-07-29 Thread Christopher Subich
Mike Meyer wrote:
> My choice for the non-name token is "@". It's already got magic
> powers, so we'll give it more rather than introducing another token
> with magic powers, as the lesser of two evils.

Doesn't work.  The crux of your change isn't introducing a meaning to @ 
(and honestly, I prefer _), it's that you change the 'define block' from 
a compound_stmt (funcdef) (see 
www.python.org/doc/current/ref/compound.html) to an expression_stmt 
(expresion).  This change would allow some really damn weird things, like:

if def _(x,y):
   return x**2 - y**2
(5,-5): # ?!  How would you immediately call this 'lambda-like'?[1]
print 'true'
else:
print 'false'

[1] -- yes, it's generally stupid to, but I'm just pointing out what has 
to be possible.

Additionally, Python's indenting Just Doesn't Work Like That; mandating 
an indent "after where the def came on the previous line" (as you do in 
your example, I don't know if you intend for it to hold in your actual 
syntax) wouldn't parse right -- the tokenizer generates INDENT and 
DEDENT tokens for whitespace, as I understand it.

My personal favourite is to replace "lambda" entirely with an 
"expression comprehension", using < and > delimeters.  It just looks 
like our existing list and generator comprehensions, and it doesn't use 
'lambda' terminology which will confuse any newcomer to Python that has 
experience in Lisp (at least it did me).

g = 
g(1) == 1

Basically, I'd rewrite the Python grammar such that:
lambda_form ::= "<" expression "with" parameter_list ">"

Biggest change is that parameter_list is no longer optional, so 
zero-argument expr-comps would be written as , which makes 
a bit more sense than .

Since "<" and ">" aren't ambiguous inside the "expression" state, this 
shouldn't make the grammar ambiguous.  The "with" magic word does 
conflict with PEP-343 (semantically, not syntactically), so "for" might 
be appropriate if less precise in meaning.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Path inherits from basestring again

2005-07-29 Thread NickC
[Re: how to get at the base class]

Do you really want to have a "only works for Path" way to get at the
base class, rather than using the canonical Path.__bases__[0]?

How about a new property in the os.path module instead? Something like
os.path.path_type.

Then os.path.path_type is unicode if and only if
os.path.supports_unicode_filenames is True. Otherwise,
os.path.path_type is str.

Then converting a Path to str or unicode is possible using:

as_str_or_unicode = os.path.path_type(some_path)

The other thing is that you can simply make Path inherit from
os.path.path_type.

Regards,
Nick C.

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


Re: Block-structured resource handling via decorators

2005-07-29 Thread Paul Rubin
Mike Meyer <[EMAIL PROTECTED]> writes:
> > When handling resources in Python, where the scope of the resource is
> > known, there seem to be two schools of thought:
> > (1) Explicit: ...
> > (2) Implicit: let the GC handle it.
> 
> The only cases I see the first school of thought is when the resource
> in question is "scarce" in some way. For example, most OS's place a
> limit on the number of open files a process can have, some rather
> tight. CPython's garbage collector will close an open file when it
> leaves scope. Jython's GC will close it when the file is collected,
> but you have no idea of when that will be, and an "open" failing won't
> trigger a GC. So in this case, the first form is less likely to fail
> unexpectedly.

I thought there was a Zen thing somewhere saying that Python is not
Perl.  One of Perl's silliest tenets is that the implementation
defines the language.  There are already 4 different Python
implementations (CPython, Jython, Pypy, IronPython) and probably more
on the way.  We should take the view that the manual, not the
implementation, defines the language.

The manual doesn't specify anything about reference counting or GC
happening as soon as something goes out of scope.  That is a GOOD
thing since requiring CPython-like behavior would eliminate many good
GC techniques, including some that are both more efficient and easier
for extension writers to deal with.  Since reference counting is not
in the manual, it is not part of the language, it's subject to change
at any time in any implementation, and non-throwaway Python apps
should not depend on it.  

On the other hand, the try/finally explicit release is cumbersome and
non-tasty.  

Therefore, the correct solution is a language extension along the
lines of PEP 343.  I haven't studied PEP 343 specifically enough to
say that I think every detail of it is the right thing, but at least
it is the right idea.

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


Re: Block-structured resource handling via decorators

2005-07-29 Thread Mike Meyer
"John Perks and Sarah Mount" <[EMAIL PROTECTED]> writes:

> When handling resources in Python, where the scope of the resource is
> known, there seem to be two schools of thought:
>
> (1) Explicit:
> f = open(fname)
> try:
> # ...
> finally:
> f.close()
>
> (2) Implicit: let the GC handle it.

The only cases I see the first school of thought is when the resource
in question is "scarce" in some way. For example, most OS's place a
limit on the number of open files a process can have, some rather
tight. CPython's garbage collector will close an open file when it
leaves scope. Jython's GC will close it when the file is collected,
but you have no idea of when that will be, and an "open" failing won't
trigger a GC. So in this case, the first form is less likely to fail
unexpectedly.

> I've come up with a third method that uses decorators to achieve a
> useful mix between the two. The scope of the resource is clear when
> reading the code (useful if the resource is only needed in part of a
> function), while one does not have to write an explicit cleanup. A
> couple of examples:
>
> @withFile(fname, 'w')
> def do(f):
> # ... write stuff into file f ...
>
> @withLock(aLock):
> def do():
> # ... whatever you needed to do once the lock was acquired,
> # safe in the knowledge it will be released afterwards ...
>
> The implementation is easily extensible: a handler for a new type of
> resource can be written in as a couple of lines. For the examples above:
>
> class withFile(blockScopedResource):
> init, cleanup = open, 'close'
>
> It's so simple I was wondering why I haven't seen it before. Possibly:
>   it's a stupid idea and I just can't see why;
>   everyone knows about it except me;
>   it's counter-intuitive (that's not the way decorators were intended);
>   it's "writing C# in Python" or in some other way unPythonic;
>   I've actually had an idea that is both Original and non-Dumb.

Well, I'd say that using a string for cleanup and a function for init
is unpythonic. But the general idea seems to be a good one. Making it
easy to deal with resources that must be explicitly released is a good
thing. The question is whether having to turn your scope into a
function to do this is more trouble than it's worth.

I'd certainly be interested in seeing the implementation.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Path inherits from basestring again

2005-07-29 Thread NickC
[Re: alternatives to overloading '/']

Is there a reason the Path constructor is limited to a single argument?
If it allowed multiple arguments, the following would seem very
straightforward:

p = Path(somePath, user.getFolder(), 'archive', oldPath + ".bak")

I'm usually not much of a purist, but C++ has convinced me that
overloading an operator to mean something entirely unrelated to its
mathematical meaning can be very unwise.

Regards,
Nick C.

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


Re: Block-structured resource handling via decorators

2005-07-29 Thread Neil Hodgson
John Perks:

> When handling resources in Python, where the scope of the resource is
> known, there seem to be two schools of thought:
> ...

This is part of what PEP 343 addresses:
http://www.python.org/peps/pep-0343.html

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


Re: xml-object mapping

2005-07-29 Thread uche . ogbuji
"I am looking for an xml-object mapping tool ('XML Data Binding-design
time product') where I can define the mapping rules in 'binding files'
and the parser is generated automatically.

Similar to the solution of Dave Kuhlman
(http://www.rexx.com/~dkuhlman/ generateDS.html) where the mapping is
defined in an xml file (if I am understand well).

But I already have the target object. The xml-tags should not be used
as
a property/member name, but should be mapped to an existing object. "

In generateDS the mapping is not just deined in any old sort of XML
file: it's defined in a W3C XML Schema file, which makes good sense
(except that in my case I dislike WXS).

Amara does not use a mapping specification: it maps automatically, and
it allows you to specify your own classes for the mapping.  This is
discussed in the manual.

http://uche.ogbuji.net/tech/4Suite/amara/

-- 
Uche
http://uche.ogbuji.net

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


Re: Suggestions for Python XML library which can search and insert

2005-07-29 Thread uche . ogbuji
"I'm looking for a library that can search through an XML document
tree,
locate an element by attribute (ideally this can be done through
XPath), and insert an element (as its child).

Simple? Yes? ...but the code I've seen so far which does this uses
'nested for loops' for trees which are relatively shallow compared to
mine. "

Amara can easily do this using XPath (complete with predicates,
functions, etc.), without nested for loops:

http://uche.ogbuji.net/tech/4Suite/amara/

-- 
Uche
http://uche.ogbuji.net

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


Re: On fighting fire with fire...

2005-07-29 Thread Steven D'Aprano
On Thu, 28 Jul 2005 17:24:06 -0400, Asad Habib wrote:

> Well, even if you are a hobbyist, that does not excuse you from being
> civil. After all, we are all humans beings that deserve to be treated with
> respect. Professional, hobbyist, vagabond, ogre, instigator, troll ...
> THERE IS NO EXCUSE ... please treat others with respect.

And yet your earlier angry, aggressive reply to Robert Kern was not very
respectful, don't you think? Your assumption that Robert is wrapped up in
an "academic cocoon" was uncalled for, and viciously aggressive pacifism
like you have displayed is almost as bad as aggressive flaming, and far
worse than Robert's self-depreciating humour.

In any case, I don't agree with you that all people deserve the same
amount of respect. Respect is rare currency, and has to be earned, not
just given away to anyone.



-- 
Steven.

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


Re: On fighting fire with fire...

2005-07-29 Thread Steven D'Aprano
On Thu, 28 Jul 2005 15:23:46 -0500, Rocco Moretti wrote:

> Professionals (and even decent hobbyists) don't 
> escalate flame wars, even unintentionally.

You don't get out much, do you? *wink*

If your comment is meant to be _prescriptive_ rather than _descriptive_, I
don't entirely agree.

Flame wars, like all wars, are unproductive beyond a certain point, but to
push the combat analogy, punitive raids can be productive at changing
behaviour.

It is never pleasant to be on the receiving end of a flaming, but if it is
deserved, then people should accept it and learn from it, rather than just
dismiss it as a flaming and therefore meaningless.

The problem on the Internet is that there is little or no status: the most
ignorant newbie and the stupidest AOLer think that they are equal in
status to somebody who has proven their knowledge for ten years. (This
lack of status on the Internet is not *always* a bad thing, but it can be.)

If your boss or professor or a judge gave you a tongue-lashing for stupid
behaviour, sensible people accept it. "I've been bad, I got caught, thank
goodness I'm suffering nothing worse than being told I'm an idiot." At
worst they might complain to their friends afterwards. 

But on the Internet, people who deserve that tongue-lashing think that
because they can retaliate, they should retaliate -- and that's where the
risk of escalation from punitive raid to unproductive flame war lies.



-- 
Steven.

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


urllib2 bug?

2005-07-29 Thread bob sacamano
Certain pages cause urllib2 to go into an infinite loop when using
readline(), but everything works fine if read() is used instead. Is
this a bug or am I missing something simple?

import urllib2

url = 'http://www.naylamp.com'

f = urllib2.urlopen(url)

i = 0

#this works fine when uncommented
#print f.read()
#print 'finished'

#this never ends
while 1:
line = f.readline()
if not line:
break
print line
print i
i = i + 1
#end while

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


Block-structured resource handling via decorators

2005-07-29 Thread John Perks and Sarah Mount
When handling resources in Python, where the scope of the resource is
known, there seem to be two schools of thought:

(1) Explicit:
f = open(fname)
try:
# ...
finally:
f.close()

(2) Implicit: let the GC handle it.

I've come up with a third method that uses decorators to achieve a
useful mix between the two. The scope of the resource is clear when
reading the code (useful if the resource is only needed in part of a
function), while one does not have to write an explicit cleanup. A
couple of examples:

@withFile(fname, 'w')
def do(f):
# ... write stuff into file f ...

@withLock(aLock):
def do():
# ... whatever you needed to do once the lock was acquired,
# safe in the knowledge it will be released afterwards ...

(The name "do" is arbitrary; this method has the "mostly harmless"
side-effect of assigning None to a local variable with the function
name.)

I find it clear because I come from a C++/C#/Java background, and I
found C#'s using-blocks to very useful, compared to the explicit
finallys of Java. I know that Python's deterministic finalization sort
of achieves the same effect, but I had been led to believe there were
complications in the face of exceptions.

The implementation is easily extensible: a handler for a new type of
resource can be written in as a couple of lines. For the examples above:

class withFile(blockScopedResource):
init, cleanup = open, 'close'

It's so simple I was wondering why I haven't seen it before. Possibly:
  it's a stupid idea and I just can't see why;
  everyone knows about it except me;
  it's counter-intuitive (that's not the way decorators were intended);
  it's "writing C# in Python" or in some other way unPythonic;
  I've actually had an idea that is both Original and non-Dumb.

If the last is the case, can someone let me know, and I'll put up the
code and explain how it all works. On the other hand, if there is
something wrong with it, please can someone tell me what it is?

Thanks

John Perks


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


A replacement for lambda

2005-07-29 Thread Mike Meyer
I know, lambda bashing (and defending) in the group is one of the most
popular ways to avoid writing code. However, while staring at some Oz
code, I noticed a feature that would seem to make both groups happy -
if we can figure out how to avoid the ugly syntax.

This proposal does away with the well-known/obscure "lambda"
keyword. It gives those who want a more functional lambda what they
want. It doesn't add any new keywords. It doesn't add any new magic
characters, though it does add meaning to an existing one. That could
be replaced by a new magic token, or adding magic meaning to a
non-magic token. It breaks no old code either way.

I haven't really worked out all the implications; I just wanted to
throw it out and see what everyone else thought about it. As a
result, the code examples tend to be ugly.

As previously hinted, this feature is lifted from Oz.

Currently, class and functions definitions consist of a keyword -
either "class" or "def" - followed by a name, a header, then code. The
code is compiled into an object, and the name is bound to that object.

The proposal is to allow name to be a non-name (or rare name)
token. In this case, the code is compiled and the resulting object is
used as the value of the class/def expression.

My choice for the non-name token is "@". It's already got magic
powers, so we'll give it more rather than introducing another token
with magic powers, as the lesser of two evils.

Rewriting a canonical abuse of lambda in this idiom gives:

myfunc = def @(*args):
 return sum(x + 1 for x in args)

In other words, this is identical to:

def myfunc(*args):
return sum(x + 1 for x in args)

We can write the same loop with logging information as:

sum(def @(arg):
print "Bumping", arg
return arg + 1
(x)   # '(' at the same indent level as def, to end the definition
for x in stuff)

A more useful example is the ever-popular property creation without
cluttering the class namespace:

class Spam(object):
  myprop = property(fget = def @(self):
   return self._properties['myprop']
   ,
fset = def @(self, value):
   self._properties['myprop'] = value
   ,
fdel = def @(self)
   del self._properties['myprop']
   ,
doc = "Just an example")

This looks like the abuse of lambda case, but these aren't
assignments, they're keyword arguments. You could leave off the
keywords, but it's not noticably prettier. fget can be done with a
lambda, but the the others can't.

Giving clases the same functionality seems to be the reasonable thing
to do. It's symmetric. And if anonymous function objects are good,
then anonymous class objects ought to be good as well.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Async PySerial (was Re: pySerial Windows write problem)

2005-07-29 Thread Peter Hansen
phil wrote:
> I use PySerial in a 16 line data collection system
> with LOTS of threads, and yes am frustrated by read().
> This sounds excellent, keep us updated.
> 
> BTW, haven't done any event driven Python except Tkinter.
> Would this a class library  which would let you
> define an event and a handler?

Roughly speaking, yes.  The primary parent class happens to be called 
Handler, and is a threading.Thread subclass which in its run() method 
basically sits in a win32 WaitForMultipleObjects() call for various 
things to happen, then calls handler routines based on which event fires.

> Do you have a one line code example?

One line?  No way... this isn't Perl. ;-)


from bent.serial import Driver

class MyDriver(Driver):
 def __init__(self, port, baud=9600):
 Driver.__init__(self, port, baud=baud, name='iodriver')
 self.start()   # start the thread

 def handleSerialRead(self, data):
 print 'read %r' % data

 def handleSerialDsr(self, level):
 print 'DSR', level

 def handleSerialBreak(self):
 print 'break detected, ho hum'


Usage for this would be simply:  d = MyDriver('COM3') and then sit back 
and watch the, uh, fireworks... or at least the print statements.

Anything interesting represents a much more sophisticated subclass which 
parses the data as it arrives, of course, and at least in my case then 
calls a handlePacket() routine where the fun really begins.

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


Re: multiple inheritance super()

2005-07-29 Thread Mike Meyer
"Michele Simionato" <[EMAIL PROTECTED]> writes:

> adding methods on the fly and metaclasses could live pretty well
> without
> multiple inheritance. There would be no real loss
> of power and hopefully less monstruosities such
> a Zope 2. But maybe this is just wishful thinking ...

Um, no real loss of power? Well, in the sense that all languages are
turing-equivalent, maybe.

My current project includes a small set of classes that all deal with
web pages. The classes exist in three layers: the first layer is very
abstract, and provides a general mechanism. The second layer adapts
the general mechanasm to a specific case. The last layer provides
application-specific functionality. The classes intercommunicate, but
are generally completely unrelated to each other except for the more
concrete classes inheriting from the layer above.

So far, so good - it's all simple single inheritance.

Now, I have a class Utility that collects utility methods that are
useful for dealing with web pages: extracting data, filling out forms,
etc. These are provided as a mixin. The classes that need this
functionality inherits from it as well as their parent. The classes
that don't need it don't. This makes use of multiple inheritance.

Without multiple inheritance, I would have had to make the Utility
class a parent of all the most abstract classes. Some of the those
classes don't need that functionality - but their children do, so they
have to inherit from it. Children's needs shouldn't influence the
implementation of the child - that's simply ugly. Also, it creates an
apparent relationship between all the most abstract classes that
doesn't really exist.

Do you have a proposed solution that doesn't have these problems?

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can list comprehensions replace map?

2005-07-29 Thread Andrew Dalke
Peter Otten wrote:
> Seems my description didn't convince you. So here's an example:

Got it.  In my test case the longest element happened to be the last
one, which is why it didn't catch the problem.

Thanks.

Andrew
[EMAIL PROTECTED]

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


Re: writing a web client

2005-07-29 Thread Mike Meyer
"Fuzzyman" <[EMAIL PROTECTED]> writes:

> Ajar wrote:
>> I want to write a program which will automatically login to my ISPs
>> website, retrieve data and do some processing. Can this be done? Can
>> you point me to any example python programs which do similar things?
>>
>> Regards,
>> Ajar
>
> Very easily. Have a look at my article on the ``urllib2`` module.
>
> http://www.voidspace.org.uk/python/articles.shtml#http
>
> You may need to use ClientCookie/cookielib to handle cookies and may
> have to cope with BASIC authentication. There are also articles about
> both of these as well.
>
> If you want to handle filling in forms programattically then the module
> ClientForm is useful (allegedly).

The last piece of the puzzle is BeautifulSoup. That's what you use to
extract data from the web page.

For instance a lot of web pages listing data have something like this
on it:


...
Item:Value
...


You can extract value from such with BeautifulSoup by doing something like:

soup.fetchText('Item:')[0].findParent(['td', 'th']).nextSibling.string

Where this checks works for the item being in either a td or th tag.

Of course, I recommend doing things a little bit more verbosely. In my
case, I'm writing code that's expected to work on a large number of
web pages with different formats, so I put in a lot of error checking,
along with informative errors.

links = table.fetchText(name)
if not links:
raise BadTableMatch, "%s not found in table" % name
td = links[0].findParent(['td', 'th'])
if not td:
raise BadmatchTable, "td/th not a parent of %s" % name
next = td.nextSibling
if not next:
raise BadTableMatch, "td for %s has no sibling" % name
out = get_contents(next)
if not out:
raise BadTableMatch, "no value string found for %s" % name
return out

BeautifulSoup would raise exceptions if the conditions I check for are
true and I didn't check them - but the error messages wouldn't be as
informative.

Oh yeah - get_contents isn't from BeautifulSoup. I ran into cases
where the  tag held other tags, and wanted the flat text
extracted. Couldn't find a BeautifulSoup method to do that, so I wrote:

def get_contents(ele):
"""Utility function to return all the text in a tag."""

if ele.string:
return ele.string   # We only have one string. Done
return ''.join(get_contents(x) for x in ele)



  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding code and methods to a class dynamically

2005-07-29 Thread Peter Hansen
Sarir Khamsi wrote:
> Peter Hansen <[EMAIL PROTECTED]> writes:
>>I'm not sure what "completion" means in this case, and I'm not aware
>>of any "command-line completion" support in cmd.Cmd though it may well
>>be there, so I can't say.  Certainly there is nothing in any way
>>different about the new attribute created by the alias code, as both
>>it and the original attribute are bound to exactly the same method.
> 
> If you have the readline module, you get TAB command completion for
> free (a la bash, emacs, etc)...or maybe readline only gives you
> emacs-style command history editing, or both...not sure.

Cool.  The answer to whether a particular approach preserves command 
completion ability then, unfortunately, depends on how it's implemented. 
  If it's totally dynamic, then the aliases my approach created will be 
supported, but if it's done at Cmd creation time, or in some other 
static manner, the dynamically created aliases won't be found.

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


Re: Hiding

2005-07-29 Thread Peter Hansen
Jason Drew wrote:
> Also, I think
> using file("C:\file.txt") is now preferred to open("C:\file.txt").

As others have noted, "open" is preferred as the method for opening 
files, while "file" is the _type_ involved, for testing or subclassing 
or what-have-you.

But neither file("C:\file.txt") nor open("C:\file.txt") is actually 
correct at all, unless you have strange files whose names start with 
ASCII FF characters.  '\f' is an escape sequence, equivalent to '\x0c'.

Always use forward slashes ("C:/file.txt") in path names unless you are 
passing them to the shell, or use raw strings (r"C:\file.txt") to avoid 
mysterious problems with escape sequences.

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


Re: Ten Essential Development Practices

2005-07-29 Thread Peter Hansen
Dan Sommers wrote:
> [EMAIL PROTECTED] (Aahz) wrote:
>>Dan Sommers  <[EMAIL PROTECTED]> wrote:
>>>Was Tim writing about developing Python itself, or about developing
>>>other programs with Python?
> 
>>Yes.
> 
> It was a rhetorical question.  :-)

That's all right...  Aahz gave a rhetorical answer.  ;-)

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


Re: Advanced concurrancy

2005-07-29 Thread Michael Sparks
Peter Tillotson wrote:

> Hi,
> 
> I'm looking for an advanced concurrency module for python and don't seem
> to be able to find anything suitable. Does anyone know where I might
> find one? I know that there is CSP like functionality built into
> Stackless but i'd like students to be able to use a standard python build.

Please take a look at Kamaelia* - it /probably/ has what you're after by the
sounds of things. Currently the unit for sequential process can be either
generators or threads, and is single CPU, single process, however we do
expect to make the system multi-process and multi-system.
   * http://kamaelia.sourceforge.net/

Currently it runs on Linux, Mac OS X, Windows and a subset works nicely on
Series 60 mobiles. (That has separate packaging) It works with standard
Python versions 2.2 and upwards.

The basic idea in Kamaelia is you have a class that represents a concurrent
unit that communicates with local interfaces only which are essentially
queues. The specific metaphor we use is that of an office worker with
inboxes and outboxes with deliveries made between outboxes to inboxes.
There also exists a simple environmental/service lookup facility which acts
like an assistant in the above metaphor, and has natural similarities to a
Linda type system.

(The actual rationale for the assistant facility though is based on
biological systems. We have communicating linked concurrent components -
which is much like many biological systems. However in addition to that
most biological systems also have a hormonal system - which is part of the
thinking behind the assistant system)

Generators (when embedded in a class) lend themselves very nicely to this
sort of model in our experience /because/ they are limited to a single
level (with regard to yield).

It's probably suitable for your students because we've tested the system on
pre-university trainees, and vacation trainees, and found they're able to
pick up the system, learn the basic ideas within a week or so (I have some
exercises on how to build a mini- version if that helps), and build
interesting systems. 

For example we had a pre-university trainee start with us at the beginning
of the year, learn python, Kamaelia, and build a simple streaming system
taking a video file, taking snapshots and sending those to mobile phones
and PC's - this was over a period of 3 months. He'd only done a little bit
of access in the past, and a little bit of VB. Well that as well as a
simple learning system simulating a digital TV decode chain, but taking a
script instead of a transport stream.

We recently made a 0.2.0 release of the system (not announced on c.l.p yet)
that includes (basic) support for a wide range of multimedia/networked apps
which might help people getting started. Some interesting new additions in
the release are an IPython integration - allowing you to build Kamaelia
systems on the fly using a shell, much like you can build unix pipelines,
as well as a visual introspection tool (and network graph visualiser) which
allows you to see inside systems as they are running. (This has turned out
to be extremely useful - as you can expect with any CSP-type system)

The specific use cases you mention are also very closed aligned with our
aims for the project. 

We're essentially working on making concurrency easy and natural to use,
(starting from the domain of networked multimedia). You can do incremental
development and transformation in exactly the way it sounds like you want,
and build interesting systems. We're also working on the assumption that if
you do that you can get performance later by specific optimisations (eg
more CPUs).
   * Example of incremental component development here:
 http://tinyurl.com/dp8n7

By the time we reach a 1.0 release (of Kamaelia) we're also aiming to be
able to integrate cleanly with Twisted (on Twisted's grounds), but it is
highly usable already - especially in your area. (In CVS we have tools for
building game type systems easily & Tk integration as well. Tk based CSP
systems are particularly fun to work with (as in fun, not "fun" :). One
project we are seriously looking at is a visual editor for these CSP-type
systems, since that appears now to be low hanging fruit.

We've got a white paper about Kamaelia here:
   * http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml

This is "textualisation" of a presentation I gave at ACCU earlier in the
year and is an overview of the core areas of the system - hopefully enough
to let you know whether to look further!

I also gave an updated talk at Europython - the presentation for which can
be downloaded from here:
   * http://www.python-in-business.org/ep2005/talk.chtml?talk=2589&track=692

Last week I also gave a more pragmatic, shorter talk at Open Tech which is
an introduction to Kamaelia, it's goals, and several examples of CSP type
systems ranging from simple audio clients/servers through to presentation
tools. That presentation can be downloaded from here:
   * http:/

Re: Adding code and methods to a class dynamically

2005-07-29 Thread Sarir Khamsi
Peter Hansen <[EMAIL PROTECTED]> writes:

> I'm not sure what "completion" means in this case, and I'm not aware
> of any "command-line completion" support in cmd.Cmd though it may well
> be there, so I can't say.  Certainly there is nothing in any way
> different about the new attribute created by the alias code, as both
> it and the original attribute are bound to exactly the same method.

If you have the readline module, you get TAB command completion for
free (a la bash, emacs, etc)...or maybe readline only gives you
emacs-style command history editing, or both...not sure.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP on path module for standard library

2005-07-29 Thread Mike Orr
Michael Hoffman wrote:
> I use path in more of my modules and scripts than any other third-party
> module, and I know it will be very helpful when I no longer have to
> worry about deploying it.

Same here.  An object-oriented path module is extremely useful, and
makes one's code much less cluttered.  I've written an enhpath module
that I used in my projects, with several convenience methods and some
magic behavior.  It's too
ambitious for the standard library, but I'd like if people could at
least look at the docstring and see whether some features might be
useful in Path.  I'd also like to see Path made subclass-friendly so I
could implement this as a subclass, and others could make other
subclasses.  The docstring itself could also be ported to Path.  The
source and test suite (py.test) are here:
http://cafepy.com/quixote_extras/rex/path/enhpath.py
http://cafepy.com/quixote_extras/rex/path/enhpath_test.py
append "?download=1" for download-friendly format.
I sent an earlier version to Jason Orendorff and he liked some of the
changes and had some ideas of his own, but said he was too busy to do
much implementation work, and then my further letters never got a
reply.

The main changes I'd like to see in Path (some of these have been made
in Python CVS at nondist/sandbox/path/path.py) are:

- When methods create path objects, use self.__class__() instead of
Path().
  This makes it possible to subclass Path.  Otherwise you
  have to rewrite the whole thing due to the hardcoded name.

- Path.cwd() should be a class method instead of a static method, for
the same
  reason.

- The constructor behavior in CVS is good.  Path(''), Path.cwd(),
  Path() => Path.cwd().

- Need .chdir() method, otherwise you have to import os for it.

- Some way to pretty-print paths embedded in lists/dicts as strings.  I
have a
  .repr_as_str class attribute that toggles this.

- .ancestor(3) is the same as .parent.parent.parent, but more concise.

- I saw in a thread that .name and .parent were removed.  I use them
very
  frequently, along with .ext and .namebase.  I don't want to call
methods for
  these.

- '/' vs .joinpath(), no big deal.  I've been using '/' because it's
there.
  .joinpath must take multiple *args, to prevent .joinpath().joinpath()
.

- .joinancestor(N, *components) is a combination of .ancestor and
.joinpath.
  If curdir is /home/joe/Webware/www, Path.cwd().joinancestor(1, 'lib')
is
  /home/joe/Webware/lib.

- Keep .lisdir() as in CVS; it acts like os.listdir().  This is useful
even
  with paths, when you're just going to use the string basename anyway.

- Who needs .open()?  open(myPath) is fine.  But it can stay for
backward
  compatibility.



Less important but non-controversial:

- Path.tempfile(), Path.tempdir():
  Create a temporary file using tempfile.mkstemp, tempfile.mkdtemp

- Path.tempfileobject():
  Create a temporary file object using tempfile.TemporaryFile.
  (Static method.)

Controversial:

- Delete methods and mkdir should succeed silently if the operation is
  already done.  Otherwise you always have to put them in an if:
  'if foo.exists(): foo.remove()'.

- .delete_dammit() recursively deletes it, whatever it is, without you
  having to do the if file/if directory dance.  I suppose it would need
a
  politically correct name.
  which you really have to do every time you delete.

- All .dirs*, .files*, .walk* methods have a symlinks flag, default
True.
  If false, don't yield symlinks.  Add .symlinks and .walksymlinks
methods.
  This eliminates an 'if' for programs that want to treat symlinks
specially.

- I have a .move method that combines .rename, .renames, and .move; and
a .copy
  method that combines .copy, .copy2, and .copytree .

I'd appreciate a Cc on replies if your newsreader allows it.

-- Mike Orr <[EMAIL PROTECTED]>

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


Re: Hiding

2005-07-29 Thread Benji York
Steven Bethard wrote:
> So open("C:\file.txt") is still fine

I think it is more like it is recommended, not just OK.
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hiding

2005-07-29 Thread Steven Bethard
Jason Drew wrote:
> Also, I think using file("C:\file.txt") is now preferred
> to open("C:\file.txt").

Guido has said he wants to keep open() around as the way to open a 
file-like object, with the theory that in the future open might also 
support opening non-files (e.g. urls).  So open("C:\file.txt") is still 
fine, though isinstance(f, open) is probably not. ;)

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


Re: Filtering out non-readable characters

2005-07-29 Thread Steven Bethard
Steve Holden wrote:
>  >>> tt = "".join([chr(i) for i in range(256)])

Or:

tt = string.maketrans('', '')

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


Re: Ten Essential Development Practices

2005-07-29 Thread Jorge Godoy
Michael Hoffman wrote:

> True, but a lot of his point *is* parsing input from the command line.
> Consider the following points paraphrased from his article:
> 
> * Don't mix multiple ways of specifying options. (Solved by optparse)
> * If a flag expects an associated value, allow an optional = between the
> flag and the value. (Solved by optparse)
> * Allow single-letter options to be "bundled" after a single dash.
> (Solved by optparse)
> * Always allow -- as a file list marker. (Solved by optparse)
> 
> And a lot of the other points are things that are made much, much,
> simpler by optparse, to the point that they become somewhat obvious.

Take a look at the Perl module, then.  You'll see that all of these are also
solved there "automagically".  I've stoped coding Perl almost 3 years ago,
and even then I never had to write anything to parse command line input by
hand.

I suggest you take a look at Getopt::Long, at CPAN. 

http://search.cpan.org/~jv/Getopt-Long-2.34/
http://search.cpan.org/src/JV/Getopt-Long-2.34/README


Be seeing you,
-- 
Jorge Godoy  <[EMAIL PROTECTED]>

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


Help with Asyncore

2005-07-29 Thread Seth Nielson
Hello,

I am using Asyncore.dispatcher around a socket (well call the wrapped
version a channel). This channel is passed around to other objects.
These objects call "send" on the channel.

My question is, what do you do for "writable" and "handle_write"?
Those seemed designed for channel-internal buffers. Should I also
overwrite "send" and have the data appended to a buffer? If not, how
should writable and handle_write be implemented? I'm not sure what to
do here...

Thank you in advance,

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


Re: Filtering terminal commands on linux

2005-07-29 Thread Lonnie Princehouse
Firstly, there's probably a better way to do whatever you're trying to
do w.r.t cd/dvd burning.  I'm not familiar with gear, but its webpage
lists "Batch file scripting capability" as a feature, which suggests
that you might be able to do what you want without parsing output
intended for humans.  There are also a multitude of command-line cd and
dvd utilities for Linux which might be better for scripting.

That said, it shouldn't be too hard to craft a regular expression that
matches ANSI control sequences. Using
http://www.dee.ufcg.edu.br/~rrbrandt/tools/ansi.html as a reference,
here's how to do this for the first few control sequences...

esc = '\x1B'
start_control_sequence = esc + '['

Pn = r'\d+' # Numeric parameter
Ps = '%s(;%s)*' % (Pn,Pn)   # Selective parameter
PL = Pn
Pc = Pn

control_sequences = [
PL + ';' + Pc + '[Hf]', # Cursor position
Pn + '[ABCD]',  # Cursor up|down|forward|backward
's',# Save cursor position
'u',# Restore cursor position
'2J',   # Erase display
'K',# Erase line
Ps + 'm',   # Set graphics mode
'=' + Pn + '[hl]',  # Set|Reset mode
# ... etc
]

match_ansi = re.compile(start_control_sequence +
'(' + '|'.join(control_sequences) + ')')

def strip_ansi(text):
return match_ansi.sub('',text)


(note: code is untested.. may contain typos)

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


Re: Hiding

2005-07-29 Thread Larry Bates
I can say with some certainty that opening a "music file" with open
won't launch media player.  If rather, you do os.system('musicfile.mp3')
it will launch whatever application is associated with the file type
.mp3.  You can either automate Windows Media player or use pymedia
to play such files.

Here are some links that might be of interest:

http://www.win32com.de/index.php?option=com_content&task=view&id=141&Itemid=259

http://pymedia.org/tut/

Larry Bates


Jay wrote:
> Well, im not no expert on the python programming language but i just
> wanted to know if there was a quick way to hide certain things when
> programming in python. Such as, i wanted some music or sound effects
> with my python program. So, i type...
> 
> print "Music is by blah blah"
> music-file = open(file containing the music"
> hide(music-file)
> 
> thats wat im looking for, something i can hide the opening of files
> because if i open that file, Windows Media Player will open and i would
> like to hide that. And advise
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hiding

2005-07-29 Thread Jason Drew
Well, using the open function in Python doesn't launch any application
associated with the file (such as Media Player). It just makes the
contents of the file accessible to your Python code. Also, I think
using file("C:\file.txt") is now preferred to open("C:\file.txt").

To answer the specific question of how to play a music file in Python,
search Google Groups for: pygame.mixer.music.load("music.mp3")
That will bring up a useful thread. Note that you will need to install
a module such as pygame or pymedia; they are not in the standard
library.

In general, I would also recommend some of the many good Python
tutorials. Some are listed here:
http://wiki.python.org/moin/BeginnersGuide

Good luck!

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


Seeking Python expertise...

2005-07-29 Thread Amanda Arnett




Hi, 
I found out about your Python community and thought you may be able to help me out.  
I am supporting an elite group of traders (more like the Who's Who on Wall Street).  We are building algorithmic trading models to analyze market movements, economic indicators, and various factors to predict and automate trade executions.  We have quite a bit of success thus far and are expanding into other electronic markets.  Our core technology team wants to add 5-6 talented software engineers in the next few months that know Python well – as we believe it’s a fast and elegant language.  They also said that people with a strong background in math, statistics, modeling, chess, or video game development will find what we are doing to be very fascinating.  Everything is real-time, and you get to apply what you know and see the results of your software models making money in the market immediately.   
Are you the person we seek?  Do you know anyone we can talk to about this?  I am more than happy to forward a job description.
We pay very well for top talents - attractive salary and triple digit percentage in bonuses for top contributors.  And, we will relocate people to Beverly Hill, CA (USA) from anywhere in the world.  
Also, the technology team also has a number of positions open for people with strong experience in concurrency, multi-threading, I/O, NIO, networking, operating systems internals, and performance optimization to work on our core trading platform (where we execute trades directly with the Exchange).  People with experience building servers that can handle thousands of simultaneous connections / concurrent users will be very helpful.  Performance of our platform is very important for us as we profit from even very small fluctuations in price.  I don't know if people in this Python community also know these technologies but I guess it doesn't hurt to ask.
If you have a resume, I'd love to see it.  If you can pass this to the right people, I'd really appreciate it.  If you have any questions, you can call me at 415-503-3998 or email me at [EMAIL PROTECTED] .
Thanks so much for your help.  
Amanda Arnett-- 
http://mail.python.org/mailman/listinfo/python-list

Re: can list comprehensions replace map?

2005-07-29 Thread Peter Otten
Scott David Daniels wrote:

> Can I play too? 

Not unless you buy the expensive but good-looking c.l.py gaming license
which is only available trough me :)

> How about: 
>  import itertools
> 
>  def fillzip(*seqs):
>  def Nones(countactive=[len(seqs)]):
>  countactive[0] -= 1
>  while countactive[0]:
>  yield None
>  seqs = [itertools.chain(seq, Nones()) for seq in seqs]
>  return itertools.izip(*seqs)

You may be introducing a lot of extra tests in the while loop with the
non-constant condition -- which in practice is fairly cheap, though. 
I'm willing to take the performance hit for the introduction of sane
variable names alone...

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


Re: can list comprehensions replace map?

2005-07-29 Thread Peter Otten
Andrew Dalke wrote:

> Me:
>>> Could make it one line shorter with
>>  
>>> from itertools import chain, izip, repeat
>>> def fillzip(*seqs):
>>> def done_iter(done=[len(seqs)]):
>>> done[0] -= 1
>>> if not done[0]:
>>> return []
>>> return repeat(None)
>>> seqs = [chain(seq, done_iter()) for seq in seqs]
>>> return izip(*seqs)
> 
> Peter Otten:
>> that won't work because done_iter() is now no longer a generator.
>> In effect you just say
>> 
>> seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1],
>> [])]
> 
> It does work - I tested it.  The trick is that izip takes iter()
> of the terms passed into it.  iter([]) -> an empty iterator and
> iter(repeat(None)) -> the repeat(None) itself.

Seems my description didn't convince you. So here's an example:

>>> from itertools import chain, izip, repeat
>>> def fillzip(*seqs):
... def done_iter(done=[len(seqs)]):
... done[0] -= 1
... if not done[0]:
... return []
... return repeat(None)
... seqs = [chain(seq, done_iter()) for seq in seqs]
... return izip(*seqs)
...
>>> list(fillzip(range(6), range(3)))
[(0, 0), (1, 1), (2, 2)]
>>>

versus

>>> map(None, range(6), range(3))
[(0, 0), (1, 1), (2, 2), (3, None), (4, None), (5, None)]

Now where's the typo?

> 'Course then the name should be changed.

My variable names where ill-chosen to begin with.

Peter


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


Dr. Dobb's Python-URL! - weekly Python news and links (Jul 29)

2005-07-29 Thread Simon Brunning
QOTW: "Guido has marked the trail; don't ignore the signs unless you really
know where you're going." - Raymond Hettinger

'Proverbs 28:14 JPS "Happy is the man that feareth alway; but he that
hardeneth his heart shall fall into evil." Obviously an exhortation to not
ignore raised exceptions with "except: pass".' - Robert Kern


Jason Orendorff's path module is a popular alternative to the build
in os.path and shutil modules. Michael Hoffman and Reinhold Birkenfeld
are working on a PEP suggesting that it be included in the standard
library:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1f5bcb67c4c73f15

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/df1b647a0f103640

Java has nearly as many web frameworks as Python, but you can run any
of them on any of the Java web application servers because they are
all built on the Java Servlet specification. PEP 333, the Python Web
Server Gateway Interface, aims to bring something similar to the world
of Python:
http://www.python.org/peps/pep-0333.html

A short but sweet day-of-the-month suffix generator from John Machin:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/904fa627890c85dd

Thanos Tsouanas wants access to an object's namespace dictionary:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d5cc509d138e1701

David Isaac wants to avoid map(), but he wants a zip() function that
runs to the length of the longest sequence. It's suggested that zip()
should be able to do this, but Raymond Hettinger channels Guido and
thinks that this would be a bad idea:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/265675b50fee8ec1

Tiny.be release four open source enterprise applications:
http://lwn.net/Articles/145209/

Who needs "Ten Essential Development Practices"? We've got The Zen of
Python:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c52d3c17f1ea9ec5



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort

Re: can list comprehensions replace map?

2005-07-29 Thread Andrew Dalke
Scott David Daniels wrote:
> Can I play too? How about:

Sweet!


Andrew
[EMAIL PROTECTED]

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


Re: can list comprehensions replace map?

2005-07-29 Thread Andrew Dalke
Me:
>> Could make it one line shorter with
>  
>> from itertools import chain, izip, repeat
>> def fillzip(*seqs):
>> def done_iter(done=[len(seqs)]):
>> done[0] -= 1
>> if not done[0]:
>> return []
>> return repeat(None)
>> seqs = [chain(seq, done_iter()) for seq in seqs]
>> return izip(*seqs)

Peter Otten:
> that won't work because done_iter() is now no longer a generator.
> In effect you just say
> 
> seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1],
> [])]

It does work - I tested it.  The trick is that izip takes iter()
of the terms passed into it.  iter([]) -> an empty iterator and
iter(repeat(None)) -> the repeat(None) itself.

'Course then the name should be changed.

Andrew
[EMAIL PROTECTED]

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


Hiding

2005-07-29 Thread Jay
Well, im not no expert on the python programming language but i just
wanted to know if there was a quick way to hide certain things when
programming in python. Such as, i wanted some music or sound effects
with my python program. So, i type...

print "Music is by blah blah"
music-file = open(file containing the music"
hide(music-file)

thats wat im looking for, something i can hide the opening of files
because if i open that file, Windows Media Player will open and i would
like to hide that. And advise

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


Re: writing a web client

2005-07-29 Thread Jay
thats pretty cool, could someone post a example program of a python
web-based program?

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


Re: writing a web client

2005-07-29 Thread Jay
thats pretty cool, could someone post a example program of a python
web-based program?

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


Re: Ten Essential Development Practices

2005-07-29 Thread Michael Hoffman
Jorge Godoy wrote:
> Michael Hoffman wrote:
> 
> 
>>He spends so much space on "Create Consistent Command-Line Interfaces,"
>>a section that, in Python, could be replaced with a simple "Use optparse."
> 
> 
> In Perl there's also the equivalent of optparse, but where does it guarantee
> that you'll use consistent name options and design a good interface?  I
> think he's point is much broader than parsing input from the command line.

True, but a lot of his point *is* parsing input from the command line. 
Consider the following points paraphrased from his article:

* Don't mix multiple ways of specifying options. (Solved by optparse)
* If a flag expects an associated value, allow an optional = between the 
flag and the value. (Solved by optparse)
* Allow single-letter options to be "bundled" after a single dash. 
(Solved by optparse)
* Always allow -- as a file list marker. (Solved by optparse)

And a lot of the other points are things that are made much, much, 
simpler by optparse, to the point that they become somewhat obvious.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wheel-reinvention with Python (was: Ten Essential DevelopmentPractices)

2005-07-29 Thread en.karpachov
On Fri, Jul 29, 2005 at 01:18:10PM -0400, Jeremy Moles wrote:
> On Fri, 2005-07-29 at 17:59 +0200, Torsten Bronger wrote:
> > one thinks "well, perfect, I have the choice between four 
> 
> Four?
> 
> 1. wx
> 2. PyGTK
> 3. Tk (Are you including this one even?)
> 4. ???

Well, QT at least. And sure there is Tk.

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


Re: Wheel-reinvention with Python (was: Ten Essential Development Practices)

2005-07-29 Thread Jeremy Moles
On Fri, 2005-07-29 at 14:19 -0300, Jorge Godoy wrote:
> Jeremy Moles wrote:
> 
> > Four?
> > 
> > 1. wx
> > 2. PyGTK
> > 3. Tk (Are you including this one even?)
> > 4. ???
> 
> PyQt / PyKDE.

Ah! Can't believe I forgot that one! :)

> > Of the few I can think of, only one would qualify as great. :)
> 
> The fourth one? ;-)

Hehe. :) I was going to say PyGTK... but in all honesty I'm just a GTK
fanboy who hasn't really even TRIED anything else. I remember
experimenting a few years back with compiled Qt apps in C/C++, but the
whole notion of a MOC just scared me--not that I knew enough back then
to really label it as "a bad thing", nor do I now. :)

> -- 
> Jorge Godoy  <[EMAIL PROTECTED]>
> 

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


Re: Ten Essential Development Practices

2005-07-29 Thread Dan Sommers
On 29 Jul 2005 07:45:33 -0700,
[EMAIL PROTECTED] (Aahz) wrote:

> In article <[EMAIL PROTECTED]>,
> Dan Sommers  <[EMAIL PROTECTED]> wrote:
>> 
>> Was Tim writing about developing Python itself, or about developing
>> other programs with Python?

> Yes.

> (C'mon, didja really expect any other answer?)

It was a rhetorical question.  :-)

Regards,
Dan

-- 
Dan Sommers

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


Re: Wheel-reinvention with Python (was: Ten Essential Development Practices)

2005-07-29 Thread Jorge Godoy
Jeremy Moles wrote:

> Four?
> 
> 1. wx
> 2. PyGTK
> 3. Tk (Are you including this one even?)
> 4. ???

PyQt / PyKDE.

> Of the few I can think of, only one would qualify as great. :)

The fourth one? ;-)

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

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


Re: Ten Essential Development Practices

2005-07-29 Thread Jorge Godoy
Michael Hoffman wrote:

> He spends so much space on "Create Consistent Command-Line Interfaces,"
> a section that, in Python, could be replaced with a simple "Use optparse."

In Perl there's also the equivalent of optparse, but where does it guarantee
that you'll use consistent name options and design a good interface?  I
think he's point is much broader than parsing input from the command line.

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

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


Re: can list comprehensions replace map?

2005-07-29 Thread Peter Otten
Andrew Dalke wrote:

> Peter Otten wrote:
>> Combining your "clever" and your "elegant" approach to something fast
>> (though I'm not entirely confident it's correct):
>> 
>> def fillzip(*seqs):
>> def done_iter(done=[len(seqs)]):
>> done[0] -= 1
>> if not done[0]:
>> return
>> while 1:
>> yield None
>> seqs = [chain(seq, done_iter()) for seq in seqs]
>> return izip(*seqs)
> 
> Ohh, that's pretty neat passing in 'done' via a mutable default argument.
> 
> It took me a bit to even realize why it does work.  :)

Though I would never have come up with it, were it not for the juxtaposition
of your two variants (I initially disliked the first and tried to improve
on the second), it is an unobvious merger :) 
It's a bit fragile, too, as
 
> Could make it one line shorter with
 
> from itertools import chain, izip, repeat
> def fillzip(*seqs):
> def done_iter(done=[len(seqs)]):
> done[0] -= 1
> if not done[0]:
> return []
> return repeat(None)
> seqs = [chain(seq, done_iter()) for seq in seqs]
> return izip(*seqs)

that won't work because done_iter() is now no longer a generator.
In effect you just say

seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1],
[])]

I tried

class Done(Exception):
pass

pad = repeat(None)
def fillzip(*seqs):
def check(active=[len(seqs)]):
active[0] -= 1
if not active[0]:
raise Done
# just to turn check() into a generator
if 0: yield None 
seqs = [chain(seq, check(), pad) for seq in seqs]
try
for item in izip(*seqs):
yield item
except Done:
pass

to be able to use the faster repeat() instead of the while loop, and then
stared at it for a while -- in vain -- to eliminate the for item... loop.
If there were a lazy ichain(iter_of_iters) you could tweak check() to decide
whether a repeat(None) should follow it, but I'd rather not ask Raymond for
that particular addition to the itertools.

> Now add the performance tweak
> 
>   def done_iter(done=[len(seqs)], forever=forever, table=table)
> 
> Okay, I'm over it.  :)

Me too. I think. For now...

Peter

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


Re: Wheel-reinvention with Python (was: Ten Essential Development Practices)

2005-07-29 Thread Jeremy Moles
On Fri, 2005-07-29 at 17:59 +0200, Torsten Bronger wrote:
> Hallöchen!
> 
> Michael Hoffman <[EMAIL PROTECTED]> writes:
> 
> > Dark Cowherd wrote:
> >
> >> GUI, Web development, Application Framework - it is shambles.
> >
> > Yeah, I agree. When I finally make that GUI application I still
> > don't know whether I am going to use wx or PyGTK.
> 
> I agree, too, although I can only talk about GUI toolkits.  At first
> one thinks "well, perfect, I have the choice between four 

Four?

1. wx
2. PyGTK
3. Tk (Are you including this one even?)
4. ???

Of the few I can think of, only one would qualify as great. :)

>>wink<<

> great GUI
> systems".  However, except for very special demands, there is no
> clear winner.  You start learning one, and immediately wonder
> whether the other might be better.  Although it sounds paradoxical,
> this can be quite frustrating.  After all, most of us don't have the
> energy or motivation to test all candidates thoroughly.
> 
> Besides, development resources are shared between all projects.
> This is especially sad with regard to IDEs.  There are even more
> IDEs/dialog editors/widget builders than Toolkits, none of them
> being mature.
> 
> >> Is there some place to discuss topics like this? Is this the right place?
> >
> > Sure, although you might want to start a new thread. ;)
> 
> At least a new subject ...
> 
> Tschö,
> Torsten.
> 
> -- 
> Torsten Bronger, aquisgrana, europa vetus
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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

Re: can list comprehensions replace map?

2005-07-29 Thread Scott David Daniels
Peter Otten wrote:
> def fillzip(*seqs):
> def done_iter(done=[len(seqs)]):
> done[0] -= 1
> if not done[0]:
> return
> while 1:
> yield None
> seqs = [chain(seq, done_iter()) for seq in seqs]
> return izip(*seqs)

Can I play too? How about:
 import itertools

 def fillzip(*seqs):
 def Nones(countactive=[len(seqs)]):
 countactive[0] -= 1
 while countactive[0]:
 yield None
 seqs = [itertools.chain(seq, Nones()) for seq in seqs]
 return itertools.izip(*seqs)

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten Essential Development Practices

2005-07-29 Thread Calvin Spealman
On 7/29/05, Dark Cowherd <[EMAIL PROTECTED]> wrote:
> I am new to Python. I tried it out and think it is fantastic.

Congrats and have fun learning all there is to learn.

> I really loved this from import this statements:
>
> There should be one-- and preferably only one --obvious way to do it.
>
> But this not true of Python.
> GUI, Web development, Application Framework - it is shambles. It is so
> frustrating for a person who comes from a well designed environment /
> framework like Delphi.

Well, consider also that all these frameworks and similar such
projects are not Python the Language, and as such are allowed to have
a few more ways to do it. There is movement toward convergence on many
fronts, with efforts such as WSGI and the anygui package. I don't
believe there should be only one way to do a thing at the beginning,
and in many ways we are still at the beginning of many areas, but we
need to spread our collective tentacles into many ideas and try what
works.

What is great about Python is that after some time with works being
quite seperate, such as the many implementations of interfaces and
adaptation systems, we are able to converge them, as is currently
proposed and likely to occure soon. We need to test out many things
and get a feel for the use of something before we can decide what the
one way to do it should be. Python makes it easy to test all the
different waters, and then to combine them into the best solution,
when the community is ready to do so.

> My organisation writes products for Small and Medium Enterprises. We
> are using Delphi, we want to do more web based and Linux solutions, so
> I was evaluating Python, but even though I love the language and will
> probably do hobby programming using the language, I wouldnt really
> recommend our organisation to plan and execute a tranisition.

Thats a shame, really.

> We have been around a while and we have planned and done transitions
> from Clipper to FoxproW to VB to Delphi.
>
> >From what I understand Database access was in similar shambles in
> Python but a SIG took up the task and made some decisions which has
> now streamlined database access in Python.
>
> I really would love to have a Python where TOOWTDI
>
> Is there some place to discuss topics like this? Is this the right place?
> --
> DarkCowherd
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wheel-reinvention with Python (was: Ten Essential Development Practices)

2005-07-29 Thread Calvin Spealman
The choice is GUI toolkits is largely seperate from Python. Consider
that they are just bindings to libraries that are developed completely
seperate of the language. GUI is should be seperate from the language,
and thus not bound to same expectations and desires as elements of the
language itself. Unless, of course, you're VB or Java..

On 7/29/05, Torsten Bronger <[EMAIL PROTECTED]> wrote:
> Hallöchen!
> 
> Michael Hoffman <[EMAIL PROTECTED]> writes:
> 
> > Dark Cowherd wrote:
> >
> >> GUI, Web development, Application Framework - it is shambles.
> >
> > Yeah, I agree. When I finally make that GUI application I still
> > don't know whether I am going to use wx or PyGTK.
> 
> I agree, too, although I can only talk about GUI toolkits.  At first
> one thinks "well, perfect, I have the choice between four great GUI
> systems".  However, except for very special demands, there is no
> clear winner.  You start learning one, and immediately wonder
> whether the other might be better.  Although it sounds paradoxical,
> this can be quite frustrating.  After all, most of us don't have the
> energy or motivation to test all candidates thoroughly.
> 
> Besides, development resources are shared between all projects.
> This is especially sad with regard to IDEs.  There are even more
> IDEs/dialog editors/widget builders than Toolkits, none of them
> being mature.
> 
> >> Is there some place to discuss topics like this? Is this the right place?
> >
> > Sure, although you might want to start a new thread. ;)
> 
> At least a new subject ...
> 
> Tschö,
> Torsten.
> 
> --
> Torsten Bronger, aquisgrana, europa vetus
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wheel-reinvention with Python

2005-07-29 Thread Michael Hoffman
Torsten Bronger wrote:
> Hallöchen!
> 
> Michael Hoffman <[EMAIL PROTECTED]> writes:
> 
> 
>>Dark Cowherd wrote:
>>
>>
>>>GUI, Web development, Application Framework - it is shambles.
>>
>>Yeah, I agree. When I finally make that GUI application I still
>>don't know whether I am going to use wx or PyGTK.
> 
> I agree, too, although I can only talk about GUI toolkits.  At first
> one thinks "well, perfect, I have the choice between four great GUI
> systems".  However, except for very special demands, there is no
> clear winner.  You start learning one, and immediately wonder
> whether the other might be better.  Although it sounds paradoxical,
> this can be quite frustrating.  After all, most of us don't have the
> energy or motivation to test all candidates thoroughly.

The PEP process can be quite good for whittling this down and getting 
the best of all worlds. For example, the current stdlib csv module was 
based on three previous modules[1]. We only really need one.

However, since GUI toolkits are so complicated, I wonder if they will 
ever be subject to this process.

[1] http://www.python.org/peps/pep-0305.html#existing-modules
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: multiple inheritance super()

2005-07-29 Thread Michele Simionato
Sion Arrowsmith
> That way lies Java

well, no, a dynamic language such as Python with the possibility of
adding methods on the fly and metaclasses could live pretty well
without
multiple inheritance. There would be no real loss
of power and hopefully less monstruosities such
a Zope 2. But maybe this is just wishful thinking ...

 Michele Simionato

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


Re: On fighting fire with fire...

2005-07-29 Thread Dr. Who
I was explaining the difference between irony and sarcasm to my
daughter just the other day.  It was nice of Asad to provide us with
such a besutiful example.  Not that I'm sure that was his intent...

Jeff

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


Wheel-reinvention with Python (was: Ten Essential Development Practices)

2005-07-29 Thread Torsten Bronger
Hallöchen!

Michael Hoffman <[EMAIL PROTECTED]> writes:

> Dark Cowherd wrote:
>
>> GUI, Web development, Application Framework - it is shambles.
>
> Yeah, I agree. When I finally make that GUI application I still
> don't know whether I am going to use wx or PyGTK.

I agree, too, although I can only talk about GUI toolkits.  At first
one thinks "well, perfect, I have the choice between four great GUI
systems".  However, except for very special demands, there is no
clear winner.  You start learning one, and immediately wonder
whether the other might be better.  Although it sounds paradoxical,
this can be quite frustrating.  After all, most of us don't have the
energy or motivation to test all candidates thoroughly.

Besides, development resources are shared between all projects.
This is especially sad with regard to IDEs.  There are even more
IDEs/dialog editors/widget builders than Toolkits, none of them
being mature.

>> Is there some place to discuss topics like this? Is this the right place?
>
> Sure, although you might want to start a new thread. ;)

At least a new subject ...

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Ten Essential Development Practices

2005-07-29 Thread Daniel Dittmar
Dark Cowherd wrote:
> There should be one-- and preferably only one --obvious way to do it.
> 
> But this not true of Python. 
> GUI, Web development, Application Framework - it is shambles. It is so

That's because there is no *obvious* way to do these.

> -Quote - Phillip J. Eby from dirtsimple.org
> Python as a community is plagued by massive amounts of
> wheel-reinvention. The infamous web framework proliferation problem is
> just the most egregious example.

In stark contrast to Java, where everybody uses standard components like 
JSP, Struts, Tapestry, JSF, Spring, ...

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


Re: can list comprehensions replace map?

2005-07-29 Thread Andrew Dalke
Peter Otten wrote:
> Combining your "clever" and your "elegant" approach to something fast
> (though I'm not entirely confident it's correct):
> 
> def fillzip(*seqs):
> def done_iter(done=[len(seqs)]):
> done[0] -= 1
> if not done[0]:
> return
> while 1:
> yield None
> seqs = [chain(seq, done_iter()) for seq in seqs]
> return izip(*seqs)

Ohh, that's pretty neat passing in 'done' via a mutable default argument.

It took me a bit to even realize why it does work.  :)

Could make it one line shorter with

from itertools import chain, izip, repeat
def fillzip(*seqs):
def done_iter(done=[len(seqs)]):
done[0] -= 1
if not done[0]:
return []
return repeat(None)
seqs = [chain(seq, done_iter()) for seq in seqs]
return izip(*seqs)

Go too far on that path and the code starts looking likg

from itertools import chain, izip, repeat
forever, table = repeat(None), {0: []}.get
def fillzip(*seqs):
def done_iter(done=[len(seqs)]):
done[0] -= 1
return table(done[0], forever)
return izip(*[chain(seq, done_iter()) for seq in seqs])

Now add the performance tweak

  def done_iter(done=[len(seqs)], forever=forever, table=table)

Okay, I'm over it.  :)

Andrew
[EMAIL PROTECTED]

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


Re: Ten Essential Development Practices

2005-07-29 Thread Michael Hoffman
Dark Cowherd wrote:

> GUI, Web development, Application Framework - it is shambles.

Yeah, I agree. When I finally make that GUI application I still don't 
know whether I am going to use wx or PyGTK.

> Is there some place to discuss topics like this? Is this the right place?

Sure, although you might want to start a new thread. ;)
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten Essential Development Practices

2005-07-29 Thread Dark Cowherd
I am new to Python. I tried it out and think it is fantastic.

I really loved this from import this statements:

There should be one-- and preferably only one --obvious way to do it.

But this not true of Python. 
GUI, Web development, Application Framework - it is shambles. It is so
frustrating for a person who comes from a well designed environment /
framework like Delphi.


-Quote - Phillip J. Eby from dirtsimple.org
Python as a community is plagued by massive amounts of
wheel-reinvention. The infamous web framework proliferation problem is
just the most egregious example.

Why is Python "blessed" with so much reinvention? Because it's often
cheaper to rewrite than to reuse. Python code is easy to write, but
hard to depend on. You pretty much have to:

   1. limit yourself to platforms with a suitable packaging system,
   2. bundle all your dependencies into your distribution, or
   3. make your users do all the work themselves

Ouch. No wonder rewriting looks easier. The only way to stop this
trend is to make it easier to reuse than to rewrite, which has been my
mission with setuptools and EasyInstall
-UnQuote

My organisation writes products for Small and Medium Enterprises. We
are using Delphi, we want to do more web based and Linux solutions, so
I was evaluating Python, but even though I love the language and will
probably do hobby programming using the language, I wouldnt really
recommend our organisation to plan and execute a tranisition.

We have been around a while and we have planned and done transitions
from Clipper to FoxproW to VB to Delphi.

>From what I understand Database access was in similar shambles in
Python but a SIG took up the task and made some decisions which has
now streamlined database access in Python.

I really would love to have a Python where TOOWTDI

Is there some place to discuss topics like this? Is this the right place?
-- 
DarkCowherd
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten Essential Development Practices

2005-07-29 Thread Bill Mill

> although, as some argue, it's
> possible [GvR] thinks in base 9.5, that just doesn't seem Pythonic to me.

+1 QOTW

Peace
Bill Mill
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten Essential Development Practices

2005-07-29 Thread Aahz
In article <[EMAIL PROTECTED]>,
Dan Sommers  <[EMAIL PROTECTED]> wrote:
>
>Was Tim writing about developing Python itself, or about developing
>other programs with Python?

Yes.

(C'mon, didja really expect any other answer?)
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

The way to build large Python applications is to componentize and
loosely-couple the hell out of everything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On fighting fire with fire...

2005-07-29 Thread Rocco Moretti
Asad Habib wrote:
> Well, even if you are a hobbyist, that does not excuse you from being
> civil. After all, we are all humans beings that deserve to be treated with
> respect. Professional, hobbyist, vagabond, ogre, instigator, troll ...
> THERE IS NO EXCUSE ... please treat others with respect.

I really don't think we're disagreeing.

I agree that it is inappropriate, regardless of position or experience, 
  to be rude, hostile, or vitriolic on this newsgroup. And it should be 
made clear to people who are, that it isn't appropriate. However, in 
doing so, it is also inappropriate to become rude, hostile, or vitriolic 
oneself - as Skip mentioned in the post that started all this, the 
appropriate way of handling it is by demonstrating proper behavior yourself.

If, for whatever reason, you do find the desire to be rude, hostile, or 
vitriolic, you can satisfy your urge by writing out your rant and then 
deleting it. You'll feel better by getting it off your chest, and you 
won't have escalated anything.

The reason I point out the hobbyist issue is to disabuse people of the 
misperception that everyone on this list is adhering to some 
professional code of conduct that they should be ostracized for 
breaching. This isn't to excuse their behavior - I'm just pointing out 
that people are coming from different backgrounds, and that we should 
treat them with consideration and respect, even when they aren't showing 
us any.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten Essential Development Practices

2005-07-29 Thread Tim Peters
[Dan Sommers]
> Ok, not universal.  But as usual, Zen is not easily nailed to a tree.
> 
> Was Tim writing about developing Python itself, or about developing
> other programs with Python?

Tim was channeling Guido, and that's as far as our certain knowledge
can go.  It _seems_ reasonable to believe that since Guido's mind is,
by definition, perfectly Pythonic, any truth channeled from it
necessarily applies to all things Pythonic.

nevertheless-we-interpret-the-gods-at-our-peril-ly y'rs  - tim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: poplib.POP3.list() returns extra value?

2005-07-29 Thread Steve Greenland
According to Jeff Epler  <[EMAIL PROTECTED]>:
> I'd consider it a doc bug too.  If you feel comfortable doing it, dive
> in and improve the documentation of poplib.  Submitting a patch to the
> patch tracker on sf.net/projects/python is probably the best way to do
> this, if you have the necessary knowledge of cvs to produce a patch.

Knowledge: yes; Time: maybe. If someone else gets there first, I won't
be offended :-)

Thanks for confirming...

Steve

-- 
Steve Greenland
The irony is that Bill Gates claims to be making a stable operating
system and Linus Torvalds claims to be trying to take over the
world.   -- seen on the net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten Essential Development Practices

2005-07-29 Thread Tim Peters
[Steve Holden]
>> If I canpoint out the obvious, the output from "import this" *is*
>> headed "The Zen of Python", so clearly it isn;t intended to be
>> universal in its applicability.

[Michael Hudson]
> It's also mistitled there, given that it was originally posted as '19
> Pythonic Theses' and nailed to, erm, something.

'Twas actually posted as "20 Pythonic Theses", although most times I
count them I find19.  Nevertheless, that there are in fact 20 was
channeled directly from Guido's perfectly Pythonic mind, so 20 there
must be.  I suspect he withheld one -- although, as some argue, it's
possible he thinks in base 9.5, that just doesn't seem Pythonic to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Filtering out non-readable characters

2005-07-29 Thread Steve Holden
Adriaan Renting wrote:
> def StripNoPrint(self, S):
> from string import printable
> return "".join([ ch for ch in S if ch in printable ])
> 
> 
> Adriaan Renting| Email: [EMAIL PROTECTED]
> ASTRON | Phone: +31 521 595 217
> P.O. Box 2 | GSM:   +31 6 24 25 17 28
> NL-7990 AA Dwingeloo   | FAX:   +31 521 597 332
> The Netherlands| Web: http://www.astron.nl/~renting/
> 
"MKoool" <[EMAIL PROTECTED]> 07/16/05 2:33 AM >>>
> 
> I have a file with binary and ascii characters in it.  I massage the
> data and convert it to a more readable format, however it still comes
> up with some binary characters mixed in.  I'd like to write something
> to just replace all non-printable characters with '' (I want to delete
> non-printable characters).
> 
> I am having trouble figuring out an easy python way to do this... is
> the easiest way to just write some regular expression that does
> something like replace [^\p] with ''?
> 
> Or is it better to go through every character and do ord(character),
> check the ascii values?
> 
> What's the easiest way to do something like this?
> 
> thanks
> 
I'd consider using the string's translate() method for this. Provide it 
with two arguments: the first should be a string of the 256 ordinals 
from 0 to 255 (because you won't be changing any characters, so you need 
a translate table that effects the null transformation) and the second 
argument should a string containing all the characters you want to remove.

So

  >>> tt = "".join([chr(i) for i in range(256)])

generates the null translate table quite easily. Then

  >>> import string
  >>> ds = tt.translate(tt, string.printable)

sets ds to be all the non-printable characters (according to the string 
module, anyway).

Now you should be able to remove the non-printable characters from s by 
writing

 s = s.translate(tt, ds)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Re: Friend wants to learn python

2005-07-29 Thread Ron Stephens
EnderLocke wrote:
> I have a friend who wants to learn python programming. I learned off
> the internet and have never used a book to learn it. What books do you
> recommend?
>
> Any suggestions would be appreciated.

I have just uploaded a podcast specifically about which tutorials and
books might be best for newbies to Python, depending on their
background. It can be reached at
http://www.awaretek.com/python/index.html

Ron

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


Re: functions without parentheses

2005-07-29 Thread Josef Meile
Steven D'Aprano wrote:
> On Fri, 29 Jul 2005 06:37:52 +, Bengt Richter wrote:
> 
> 
>>I suggested in a previous thread that one could support such a syntax by
>>supporting an invisible binary operator between two expressions, so that
>>examine "string" translates to examine.__invisbinop__("string") if
>>examine as an expression evaluates to an object that has a __invisbinop__ 
>>method.
> 
> 
> Why would you want to?
> 
My best guest is that the OP uses VB, where you can do that. I
personally hate this feature because it just makes me do a lot of
mistakes. ie: In VB you can do:

fooFunction fooParameter

but if you want to assign this to a variable you **must** use this:

fooVer = fooFunction(fooParaMeter)

I really get confused because I automatically use the braces.

Regards,
Josef

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


Re: writing a web client

2005-07-29 Thread gene tani
fuzzy's urllib2 info is excellent.  The other way peopel snarf stuff
over HTTP and FTP is using 'wget' or 'libcurl'.  THere's

http://pycurl.sourceforge.net/

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


ANN: python-ldap-2.0.9

2005-07-29 Thread Michael Ströder
Find a new release of python-ldap:

  http://python-ldap.sourceforge.net/

python-ldap provides an object-oriented API to access LDAP directory
servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for
that purpose. Additionally it contains modules for other LDAP-related
stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema).


Released 2.0.9 2005-07-28

Changes since 2.0.8:

Modules/
* Removed __doc__ strings from ldapcontrol.c to "fix"
  build problems with Python versions 2.2 and earlier.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why functions in modules need 'global foo' for integer foo but not dictionary foo?

2005-07-29 Thread John Roth
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> At top of a module I have an integer like so...
>
> foo = 4
>
> In a function in that module I know I need to do 'global foo' to get at
> the value 4.

Actually, you don't need a "global foo" statement to
_access_ the value. You do need a "global foo" to
_rebind_ the value.

> ...
>
> IIRC, for dictionaries you DO NOT have this issue?
>
> Why this scope problem with integers but not dictionaries?

Telling an object to mutate itself doesn't rebind the object.
so, if you wanted to say:

foo = 5

and have it work at the module level, you'd need a global foo
statement, while

foo["bar"] = "spam"

doesn't. The dictionary "foo" isn't rebound, all that's happening
is that its state is being changed (that is, the key and value is
being added to the dictionary).

HTH

John Roth

>
> Chris
> 

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


Re: Async PySerial (was Re: pySerial Windows write problem)

2005-07-29 Thread phil
I use PySerial in a 16 line data collection system
with LOTS of threads, and yes am frustrated by read().
This sounds excellent, keep us updated.

BTW, haven't done any event driven Python except Tkinter.
Would this a class library  which would let you
define an event and a handler?

Do you have a one line code example?

Thanks.

Peter Hansen wrote:

> Neil Benn wrote:
> 
>>PySerial doesn;t have any kind of event firing to notify you when data 
>>is available.  The way I get round this is to have a loop polling (in a 
>>seperate thread) to see if any data is available (it's a method on the 
>>interface), then read all the data in and fire this off to my 
>>listeners/observers with the read data.  
>>
> 
> On that note, I've got a preliminary version of something I call "Bent" 
> (think "slightly Twisted") which is focused for now on providing an 
> asynchronous version of PySerial which is designed around the 
> event-driven model instead of its current polled scheme.
> 
> It shares a number of features with the Twisted-based PySerial port 
> (also done by Chris Liechti, for the Twisted team, judging by the code 
> comments) but doesn't require one to adopt the whole Twisted framework. 
>   Basically it provides you with the equivalent of one "reactor" per 
> thread for PySerial stuff.  On Win32 only for now.  There are other 
> limitations too.  Not ready for prime time.
> 
> On the plus side, it's been letting me convert my serial stuff to be 
> fully event-driven and with the resulting much lower latencies and 
> better CPU efficiency, while keeping my code more "traditional" instead 
> of having to force it entirely into the Twisted point of view.
> 
> Just an FYI.  And, obviously, to hear back from those interested.  I 
> don't know if this is something that should be contributed to the 
> PySerial project (it's more of a rewrite than an add-on), or set up as a 
> new project, or passed around quietly behind the scenes for a while.
> No docs yet, no contrived examples (but various pieces of working code 
> in real daily use).  Did I mention it wasn't ready for prime time?
> 
> If you've ever been annoyed having to do .read(1) to get characters one 
> at a time in PySerial, or .read(100) with a timeout, or whatever, this 
> might be of interest to you...
> 
> -Peter
> 



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


Re: writing a web client

2005-07-29 Thread Fuzzyman

Ajar wrote:
> I want to write a program which will automatically login to my ISPs
> website, retrieve data and do some processing. Can this be done? Can
> you point me to any example python programs which do similar things?
>
> Regards,
> Ajar

Very easily. Have a look at my article on the ``urllib2`` module.

http://www.voidspace.org.uk/python/articles.shtml#http

You may need to use ClientCookie/cookielib to handle cookies and may
have to cope with BASIC authentication. There are also articles about
both of these as well.

If you want to handle filling in forms programattically then the module
ClientForm is useful (allegedly).

Best Regards,

Fuzzyman
http://www.voidspace.org.uk/python

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


Re: os._exit vs. sys.exit

2005-07-29 Thread Peter Hansen
Bryan wrote:
> Thanks for the clarifications.  One more question, can I catch this 
> exception in my main thread and then do another sys.exit() to kill the whole 
> process?

Not as such.  Exceptions can be caught only in the thread in which they 
are raised.  There are tricky techniques to change this, but they would 
have to rely on things which are themselves sufficient for what you are 
trying to do.

> Apparently sys.exit() allows the program to clean up resources and exit 
> gracefully, while os._exit() is rather abrupt.

What does the main thread do while the other thread is running?  If it's 
just waiting for it and other threads to finish/fail, then you need to 
have some kind of loop that waits for all other threads to not respond 
True to .isAlive(), and/or you need to add a threading.Event or 
something like it which the main thread can wait on or poll to see 
whether a thread has caught an exception, *and* you need to make all 
those other threads catch their own exceptions at the top levels of 
their run() method, and to set that Event object if SystemExit is 
caught.  Or related techniques.

If that's not enough ideas for you to figure something out, please 
provide more detail and we can come up with something more specific and 
appropriate.  For example, do you want to exit the app only if a thread 
raises SystemExit, or would other exceptions result in the same effect?

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


Async PySerial (was Re: pySerial Windows write problem)

2005-07-29 Thread Peter Hansen
Neil Benn wrote:
> PySerial doesn;t have any kind of event firing to notify you when data 
> is available.  The way I get round this is to have a loop polling (in a 
> seperate thread) to see if any data is available (it's a method on the 
> interface), then read all the data in and fire this off to my 
> listeners/observers with the read data.  

On that note, I've got a preliminary version of something I call "Bent" 
(think "slightly Twisted") which is focused for now on providing an 
asynchronous version of PySerial which is designed around the 
event-driven model instead of its current polled scheme.

It shares a number of features with the Twisted-based PySerial port 
(also done by Chris Liechti, for the Twisted team, judging by the code 
comments) but doesn't require one to adopt the whole Twisted framework. 
  Basically it provides you with the equivalent of one "reactor" per 
thread for PySerial stuff.  On Win32 only for now.  There are other 
limitations too.  Not ready for prime time.

On the plus side, it's been letting me convert my serial stuff to be 
fully event-driven and with the resulting much lower latencies and 
better CPU efficiency, while keeping my code more "traditional" instead 
of having to force it entirely into the Twisted point of view.

Just an FYI.  And, obviously, to hear back from those interested.  I 
don't know if this is something that should be contributed to the 
PySerial project (it's more of a rewrite than an add-on), or set up as a 
new project, or passed around quietly behind the scenes for a while.
No docs yet, no contrived examples (but various pieces of working code 
in real daily use).  Did I mention it wasn't ready for prime time?

If you've ever been annoyed having to do .read(1) to get characters one 
at a time in PySerial, or .read(100) with a timeout, or whatever, this 
might be of interest to you...

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


writing a web client

2005-07-29 Thread Ajar
I want to write a program which will automatically login to my ISPs
website, retrieve data and do some processing. Can this be done? Can
you point me to any example python programs which do similar things?

Regards,
Ajar

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


Re: os._exit vs. sys.exit

2005-07-29 Thread Bryan

"Peter Hansen" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Andrew Dalke wrote:
>> sys.exit() is identical to "raise SystemExit()".  It raises a Python
>> exception which may be caught at a higher level in the program stack.
>
> And which *is* caught at the highest levels of threading.Thread objects 
> (which Timer is based on).  Exceptions raised (and caught or not) in a 
> Thread do not have any effect on the main thread, and thus don't affect 
> the interpreter as a whole.
>
> -Peter

Thanks for the clarifications.  One more question, can I catch this 
exception in my main thread and then do another sys.exit() to kill the whole 
process?

Apparently sys.exit() allows the program to clean up resources and exit 
gracefully, while os._exit() is rather abrupt.

Bryan 


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


Re: pySerial Windows write problem

2005-07-29 Thread Peter Hansen
Bob Greschke wrote:
> "Peter Hansen" <[EMAIL PROTECTED]> wrote in message >
>>I'd call it very unusual 
>>(in my experience) to have a program open and close a serial port 
>>repeatedly.  
> 
> One of the serial ports (there are actually two) is used to read some NMEA 
> sentences from a GPS.  It is only rarely read.  If it is also opened when 
> the program starts and kept open would you just dump the buffer and then 
> read to get the most current info?  What happens when the buffer fills up? 
> The "main" port is just commands sent, responses received kind of traffic.

Generally, yes, you just dump data received up to the point you are 
about to send a new request (if this is a request/response type of 
thing).  PySerial has a .flush() method of some kind I believe, or you 
can just loop as long as inWaiting() isn't False.

If you aren't using hardware or software handshaking, then the buffer 
filling up is a non-issue for you or the sender.  If you're using 
handshaking, then you do have to keep the buffer from filling.  Pretty 
much all my interesting code runs the PySerial stuff in a separate 
thread, reading whenever data is available, and (this is a 
simplification) posting it to a Queue which the main thread can read 
from as required.  In that scenario, you could just have a flag that 
causes the receive thread to stop posting stuff to the Queue where you 
currently have close the port to prevent data being seen.

I don't recall: is NMEA 0183 asynchronous?  Messages can be sent by the 
GPS even when you didn't ask for one explicitly?  If so, then it's 
possible there are problems even with your current approach: what if you 
open the port halfway through a packet, and receive only the last few 
bytes?  If it's synchronous (data sent only in response to your 
requests), then none of this is an issue since there will be no traffic 
unless you ask for it, so the serial port will be idle between uses.

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


  1   2   >