Re: PATCH: Speed up direct string concatenation by 20+%!

2006-09-30 Thread Steve Holden
Larry Hastings wrote:
> Fredrik Lundh wrote:
> 
>>so what does the benchmark look like if you actually do this ?
> 
> 
> Okay, timing this:
>   x = ""
>   for i in range(10):
> x += "a"
>   t = x[1] # forces the concat object to render
> 
> The result:
>   Python 2.5 release: 30.0s
>   Python 2.5 locally built: 30.2s
>   Python 2.5 concat: 4.3s
>   Improvement: 600% (1/7 of the time)
> 
> 
> /larry/
> 
Interesting. Does a comparison also force it to render? If not, I wonder 
if comparisons might not end up slower. It does sound like memory usage 
might go through the roof with this technique under certain 
circumstances, so the more extensive your tests are the more likely you 
are to see the change actually used (I'm not convinced you'll persuade 
the developers to include this).

Whether or not it does get incorporated I think it's a great 
demonstration of how amenable Python is to experimentation with 
alternate representations, and I think your project might make a very 
interesting PyCon paper for people who were thinking about joining the 
development effort but hadn't yet started.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: File I/O

2006-09-30 Thread MonkeeSage
Diez B. Roggisch wrote:
> Good to know that you can get drunk under any circumstances.

+(++)1 heh!

> I have seen a bazillion bad xml/html parsing-hacks using regexes and the
> like, which stopped working after somehow the xml came all in one line, or
> some other implicit assumption about its layout failed to be met.

Seriously, I fully agree with you. To manipulate X/HT/ML data reliably
you need to use a parser. And usually the parser API is much cleaner
and easier to work with than trying to cobble together regexps anyhow!

Regards,
Jordan

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


Re: retry in exception

2006-09-30 Thread Steve Holden
Sybren Stuvel wrote:
> Antoine De Groote enlightened us with:
> 
>>I hope I don't upset anybody by comparing Python to Ruby (again). Is 
>>there something like Ruby's retry keyword in Python?
> 
> 
> Please don't assume that everybody knows Ruby through and through...
> 
I didn't see any such assumption in that post. *I* don't know much Ruby, 
but it seems like a perfectly reasonable question, as I know many 
readers *are* proficient in that language.

This is one of those cases where not posting at all would have saved 
everyone some time ;-)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: creating a small test server on my local computer

2006-09-30 Thread Ant

Mirco Wahab wrote:
> Thus spoke John Salerno (on 2006-09-29 21:13):
...
> My advice would be (because Apache installations on
> WinXP don't usually support Python (except pulling
> the whole thing into each CGI invocation) - download
> and install a VMWare Player

This sounds a horribly complicated way of doing things. If you read the
OP's post, it seems he is simply trying to serve straight HTML pages
(but with Server Side Includes) locally for testing, rather than having
to pester his operations guys to put them up on the company servers.

If it's just HTML and SSI, then Apache is the easy answer on XP. The
download is a simple .msi installer, and you'll just be able to drop
the html files in the htdocs directory to start serving them.
(http://httpd.apache.org/download.cgi)

If you look at the docs for a majority of the Python webservers, they
recommend putting them behind Apache for production use, and for good
reason, Apache httpd is probably the most mature, stable and feature
rich web server out there.

(Incidentally, adding python support with mod_python is a breeze on XP
- just another installer and uncommenting a couple of lines in the
httpd.conf file. But then for actual python development it may be
simpler to get started using a framework such as TurboGears or Django,
which both have very good introductory tutorials.)

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


why logging re-raise my exception and can't be caught?

2006-09-30 Thread daniel
I use a simple program to illustrate the problem:

import logging

def foo() :
raise ValueError("foo")

if __name__ == "__main__" :
try :
foo()
except ValueError :
logging.exception("caught here")  -- seems re-raise the
exception and can't be caught
print "caught here" --- just works.

I'm expecting the exception to be caught silently, and print the msg to
some place, if I comment out the logging statement, it just works, but
now, the stack trace is printed as if the except statement was not
there!!

how could this happen, just weird.. can I make the logging module
behave as I expected?

tks in advance.

daniel

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


Re: storing variable names in a list before they are used?

2006-09-30 Thread Steve Holden
John Salerno wrote:
> If I want to have a list like this:
> 
> [(first_name, 'First Name:'), (last_name, 'Last Name:').]
> 
> where the first part of each tuple is a variable name and the second 
> part is a label for the user to see, such as a form like this:
> 
> First Name: 
> Last Name:  
> 
> (the variables would store whatever information is entered in the text 
> boxes to the right of each label. I'm doing it this way so I can write a 
> loop to construct my GUI components).
> 
> how would I go about putting these variable names in a list? I know I 
> can't leave them as above, but if I put them in as a string, then how do 
> I later "transform" them into an actual variable for assign, such as:
> 
> first_name = widget.get_text()
> 
> Is there some kind of idiom that does this sort of work?
> 
> Thanks.

There are ways you can do this, but the best advice is "don't". If you 
are putting names into a Python namespace that aren't known in advance 
then you also have to use similarly obscure techniques to access the 
variables, and you are running the risk that your code will collide whit 
a name of a variable already used in that namespace by your code.

What's wring with just using a dict to store the values against the 
names? Dicts and namespaces have a lot of behaviour in common.

regard
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: The Python world tries to be polite [formerly offensive to another language]

2006-09-30 Thread MonkeeSage
Steve Holden wrote:
> Perhaps so, but none the less comp.lang.perl has a demonstrable history
> of newbie-flaming. Don't know what it's like now, as it's years since I
> read that group, but they used to just love the smell of crisply-toasted
> newbie in the morning ;-)

C'mon! No reason why a newbie should be confused by a hyper-fatugly,
err, "hyper-fatarrow" every now and then [1]! What, are newbies totally
dense or something?! ;))

[1] http://www.nntp.perl.org/group/perl.perl6.language/25946

Regards,
Jordan

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


Re: DAT file compilation

2006-09-30 Thread Steve Holden
Jay wrote:
> That cgi idea is really cool, but I don't have any web space to host
> the files.  Plus the bandwidth required would be deadly.  I think I'll
> just have to stick to the zip file idea.  The problem with the
> read-only is that this program is aimed at a Windows audience.

So don't call it something.zip. Since most Windows users rely on the 
registry to discern filetypes from extensions you will probably find in 
practice that very few actually poke about with your ".dat" file that's 
actually a zip.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: why logging re-raise my exception and can't be caught?

2006-09-30 Thread Ben Finney
"daniel" <[EMAIL PROTECTED]> writes:

> I'm expecting the exception to be caught silently, and print the msg to
> some place

Then why not use logging.error() ?

http://docs.python.org/lib/module-logging>
=
error(msg[, *args[, **kwargs]])
Logs a message with level ERROR on the root logger. The arguments
are interpreted as for debug().

exception(msg[, *args])
Logs a message with level ERROR on the root logger. The arguments
are interpreted as for debug(). Exception info is added to the
logging message. This function should only be called from an
exception handler.
=

A 'try ... except' statement is not an exception handler. So, if you
want to log the fact that an error occurred, it seems logging.error()
is the correct choice.

-- 
 \"I have one rule to live by: Don't make it worse."  -- Hazel |
  `\  Woodcock |
_o__)  |
Ben Finney

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


Re: Hot new programming languages - according to the TIOBE index

2006-09-30 Thread MonkeeSage
vasudevram wrote:
> Ruby and Python are doing well, according to the latest TIOBE index.

Doing well?? Ruby is up 14 points, relatively...ghea! ruby p0wns!11 ;)

D is an interesting language, though, I must say. Looks like they did
all the things right that C++ did wrong.

Regards,
Jordan

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


Re: Python/UNO/OpenOffice?

2006-09-30 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
> Are then any currently active and reasonably mature Python plugins/
> apis/whatever for programming/scripting OpenOffice? The page I've
> found is http://udk.openoffice.org/python/python-bridge.html, but it
> was last updated more than a year ago.

Aside from what has already been said, it might be nice for you to
read my article about OOo and Python at
http://www.stuvel.eu/ooo-python ;-)

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread Sybren Stuvel
Paul Rubin enlightened us with:
>> height = 0
>> for block in stack:
>> if block.is_marked():
>> print "Lowest marked block is at height", height
>> break
>> height += block.height
>> else:
>> raise SomeError("No marked block")
>
> all_heights = [block.height for block in stack if block.is_marked()]
> if all_heights:
>   height = sum(all_heights)
> else:
>   raise SomeError("No marked block")
>
> Alternatively (lower memory usage for large list):
>
> all_heights = (block.height for block in stack if block.is_marked())
> try:
>   height = all_heights.next()
>   height += sum(all_heights)
> except StopIteration:
>   raise SomeError("No marked block")

I must say that the for/else construct is a LOT more readable than the
rewritten alternatives.

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread MonkeeSage
Sybren Stuvel wrote:
> I must say that the for/else construct is a LOT more readable than the
> rewritten alternatives.

+1

I just wish it had a more intuitive name like "after:" or "then:", as
"else:" seems like a choice between the loop and the other block (but
really the choice is between StopIteration and break).

Regards,
Jordan

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


Re: File I/O

2006-09-30 Thread Ant

Kirt wrote:
...
> i dont wanna parse the xml file..
>
> Just open the file as:
>
> f=open('test.xml','a')
>
> and append a line "abc" before  tag 

The other guys are right - you should look at something like
ElementTree which makes this sort of thing pretty easy, and is robust.
But if you are sure that:

1)  is going to be on its own line (rather than something like
)
2) the ending tag will *definitely* have no extraneous whitespace (e.g.
< / Top >)

then the following will probably be the simplest solution:

f=open('test.xml')
out = []
for line in f:
if "" in line:
out.append("abc")
out.append(line")

f.close()

f_out = open("test.xml", "w")
f.write("".join(out))
f_out.close()

If you're working with XML in any sort of quantity, then look into the
available XML tools - it will be worth your time.

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


Re: Hot new programming languages - according to the TIOBE index

2006-09-30 Thread MonkeeSage
MonkeeSage wrote:
> vasudevram wrote:
> > Ruby and Python are doing well, according to the latest TIOBE index.
>
> Doing well?? Ruby is up 14 points, relatively...ghea! ruby p0wns!11 ;)

Sorry my fellow pythonistas! I didn't see that this was cross-posted. I
was of course being silly, but I wanted to make that clear so as not to
unduely offend!

Regards,
Jordan

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


Re: The Python world tries to be polite [formerly offensive to another language]

2006-09-30 Thread Steve Holden
MonkeeSage wrote:
> Steve Holden wrote:
> 
>>Perhaps so, but none the less comp.lang.perl has a demonstrable history
>>of newbie-flaming. Don't know what it's like now, as it's years since I
>>read that group, but they used to just love the smell of crisply-toasted
>>newbie in the morning ;-)
> 
> 
> C'mon! No reason why a newbie should be confused by a hyper-fatugly,
> err, "hyper-fatarrow" every now and then [1]! What, are newbies totally
> dense or something?! ;))
> 
> [1] http://www.nntp.perl.org/group/perl.perl6.language/25946
> 

My God, Perl 6 is going to be even less comprehensible that Perl 5, 
which was at least usable. Is »=>« really a Perl6 operator? That's too 
funny!

hoping-the-chevrons-were-emphasis-on-ly y'rs  - steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: why logging re-raise my exception and can't be caught?

2006-09-30 Thread Diez B. Roggisch
daniel schrieb:
> I use a simple program to illustrate the problem:
> 
> import logging
> 
> def foo() :
> raise ValueError("foo")
> 
> if __name__ == "__main__" :
> try :
> foo()
> except ValueError :
> logging.exception("caught here")  -- seems re-raise the
> exception and can't be caught
> print "caught here" --- just works.
> 
> I'm expecting the exception to be caught silently, and print the msg to
> some place, if I comment out the logging statement, it just works, but
> now, the stack trace is printed as if the except statement was not
> there!!
> 
> how could this happen, just weird.. can I make the logging module
> behave as I expected?

For starters - reading the documentation. The logging.exception-call 
precisely is for printing the exception as if it was not caught at all.

If you don't want that, don't use it - use one of the error, warn, info 
or debug calls.

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


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread Paul Rubin
Sybren Stuvel <[EMAIL PROTECTED]> writes:
> I must say that the for/else construct is a LOT more readable than the
> rewritten alternatives.

They are all pretty ugly.  I prefer the genexp version with a
hypothetical "is_empty" function:

 all_heights = (block.height for block in stack if block.is_marked())
 if is_empty(all_heights):
raise SomeError("No marked block")
 heights = sum(all_heights)

Python generators don't really work the right way for this though.

I've been fooling around with Haskell, so these kinds of constructions
seems more natural to me than explicit for loops.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb for Python 2.5

2006-09-30 Thread Martin v. Löwis
Harold Trammel schrieb:
> Does anyone know the status of a version of MySQLdb that will work with
> Python 2.5? 

AFAICT, MySQLdb 1.2.1 builds and works just fine.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why logging re-raise my exception and can't be caught?

2006-09-30 Thread Steve Holden
Ben Finney wrote:
[...]
> A 'try ... except' statement is not an exception handler. [...]

Just as a matter of interest, what would your definition of an exception 
handler be, then? Specifically, what's the "except" clause for?

The docs for looging.except should make it explicit that the exception 
will be re-raised.

Of course it might be possible to do something hackish like

 try:
 ...
 except:
 try:
 logging.exception(...)
 except:
 pass

which (although untested) should theoretically allow the catching (for a 
second time) of teh exception reraised by logging.exception().

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: why logging re-raise my exception and can't be caught?

2006-09-30 Thread daniel
thank your so much firstly.

I feel really ashamed...

I think I did read through all examples and docs, but I just took for
granted that all the  info(), warning(), debug() like functions behaves
much alike except the level name.. so the description you listed really
was ignored,, 

tks again for your help.. I do appreciate it.

daniel

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


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread Peter Otten
Sybren Stuvel wrote:

> Paul Rubin enlightened us with:
>>> height = 0
>>> for block in stack:
>>> if block.is_marked():
>>> print "Lowest marked block is at height", height
>>> break
>>> height += block.height
>>> else:
>>> raise SomeError("No marked block")
>>
>> all_heights = [block.height for block in stack if block.is_marked()]
>> if all_heights:
>>   height = sum(all_heights)
>> else:
>>   raise SomeError("No marked block")
>>
>> Alternatively (lower memory usage for large list):
>>
>> all_heights = (block.height for block in stack if block.is_marked())
>> try:
>>   height = all_heights.next()
>>   height += sum(all_heights)
>> except StopIteration:
>>   raise SomeError("No marked block")
> 
> I must say that the for/else construct is a LOT more readable than the
> rewritten alternatives.

I like

def blocks_til_mark(stack):
for block in stack:
if block.is_marked():
return
yield block
raise SomeError
height = sum(block.height for block in blocks_til_mark(stack))

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


Re: why logging re-raise my exception and can't be caught?

2006-09-30 Thread Georg Brandl
Steve Holden wrote:
> Ben Finney wrote:
> [...]
>> A 'try ... except' statement is not an exception handler. [...]
> 
> Just as a matter of interest, what would your definition of an exception 
> handler be, then? Specifically, what's the "except" clause for?
> 
> The docs for looging.except should make it explicit that the exception 
> will be re-raised.
> 
> Of course it might be possible to do something hackish like
> 
>  try:
>  ...
>  except:
>  try:
>  logging.exception(...)
>  except:
>  pass
> 
> which (although untested) should theoretically allow the catching (for a 
> second time) of teh exception reraised by logging.exception().

Use the source, people. The exception is not reraised. The only effect of
exception() versus error() is that exception() passes the "exc_info=1" keyword
argument to error() which means that the stack trace is added to the
logging message.

The default logger prints to stdout, which is why the stack trace is printed
there too.

(In the sense of the logging docs, an except:-clause *IS* an error handler).

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


Re: Automatic methods in new-style classes

2006-09-30 Thread bertgoos
The metaclass approach seems to be the one I was looking for. Thanks!

Bert

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


Re: Leave the putdowns in the Perl community, the Python world does not need them

2006-09-30 Thread Pierre Quentel
I am also shocked by Fredrick Lundh's impoliteness and think he makes
this group less friendly than I expected when I read this on
http://www.python.org/community/lists/:

"Rudeness and personal attacks, even in reaction to blatant flamebait,
are strongly frowned upon. People may strongly disagree on an issue,
but usually discussion remains civil"

This should apply to anyone, from the newbie to the most valuable
contributor to Python

Regards,
Pierre

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


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread Peter Otten
Paul Rubin wrote:

> Sybren Stuvel <[EMAIL PROTECTED]> writes:
>> I must say that the for/else construct is a LOT more readable than the
>> rewritten alternatives.
> 
> They are all pretty ugly.  I prefer the genexp version with a
> hypothetical "is_empty" function:
> 
>  all_heights = (block.height for block in stack if block.is_marked())
>  if is_empty(all_heights):
> raise SomeError("No marked block")

Such a function would have to rebind the generator:

def check_empty(items):
items = iter(items)
try:
first = items.next()
except StopIteration:
return False
return chain([first], items)

all_heights = check_empty(all_heights)
if not all_heights:
raise SomeError

>  heights = sum(all_heights)
> 
> Python generators don't really work the right way for this though.

You can make it work, but the result tends to be messy:

from itertools import chain

def raiseiter(exc, *args):
raise exc(*args)
yield None # unreachable
def stop():
raise StopIteration

height = sum(block.height for block in chain(stack, raiseiter(SomeError)) if
(not block.is_marked()) or stop())

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


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread Paul Rubin
Peter Otten <[EMAIL PROTECTED]> writes:
> I like
> 
> def blocks_til_mark(stack):
> for block in stack:
> if block.is_marked():
> return
> yield block
> raise SomeError
> height = sum(block.height for block in blocks_til_mark(stack))

Oh my, I realize now that I mis-read the original, and my examples
were all wrong.  Shows how the explicit loop isn't necessarily so
clear ;-).  Note that unlike the original, the loop above fails to set
height = 0 in the case where the exception gets raise.

I'd maybe just scan the stack twice.  The rescan is needed only if
there can be blocks with height <= 0.  Otherwise, you can just raise
SomeError if height == 0:

height = sum(b.height for b in 
 itertools.takewhile(lambda: not block.is_marked(), stack))

if height == 0 and True not in (b.is_marked() for b in stack):
 raise SomeError
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread Paul Rubin
Peter Otten <[EMAIL PROTECTED]> writes:
> >  all_heights = (block.height for block in stack if block.is_marked())
> >  if is_empty(all_heights):
> > raise SomeError("No marked block")
> 
> Such a function would have to rebind the generator:

Yeah, that's what I mean about generators not working the right way.

> You can make it work, but the result tends to be messy:

I think it's better underneath, but still syntactically ugly, to just
defer the generator creation:

 all_heights = lambda: 
 (block.height for block in stack if block.is_marked())
 if is_empty(all_heights ()):
 raise SomeError("No marked block")
 height = sum(all_heights ())

Now sum and is_empty see two separate generators, so is_empty is
straightforward:

 def is_empty(gen):
try:
   gen.next()
   return True
except StopIteration:
   return False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ruby %w equivalent

2006-09-30 Thread MonkeeSage
Nick Craig-Wood wrote:
> These are snatched straight from perl.  In perl they are spelt
> slightly differently

Yup, they are; perl had _some_ good ideas; no doubt. ;)

> In perl (and maybe in ruby I don't know) the { } can be replaced with
> any two identical chars, or the matching pair if bracketty, so q/blah/
> or q(blah).

Yes; same thing in ruby.

Regards,
Jordan

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


Escapeism

2006-09-30 Thread Kay Schluehr
Usually I struggle a short while with \ and either succeed or give up.
Today I'm in a different mood and don't give up. So here is my
question:

You have an unknown character string c such as '\n' , '\a' , '\7' etc.

How do you echo them using print?

print_str( c ) prints representation '\a' to stdout for c = '\a'
print_str( c ) prints representation '\n' for c = '\n'
...

It is required that not a beep or a linebreak shall be printed.

First of all it has be remarked that it is impossible to a certain
extent. That's because e.g. c = '\a' and c = '\7' do represent the same
string but this ambiguity doesn't occur for many numbers. But lets
weaken the requirement and fix a canonical representation in case of
ambiguity. I'm still getting stuck here.

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


Filter class

2006-09-30 Thread TheSaint
Hello NG,

Curious to know whether exists a filter class.
I'm doing some rough mail filtering on my own criteria, but I'm very new on
programming and I like to find some clue on passing a config file of rules
which will be regex by Python.

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


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread Peter Otten
Paul Rubin wrote:

> Peter Otten <[EMAIL PROTECTED]> writes:
>> >  all_heights = (block.height for block in stack if
>> >  block.is_marked()) if is_empty(all_heights):
>> > raise SomeError("No marked block")
>> 
>> Such a function would have to rebind the generator:
> 
> Yeah, that's what I mean about generators not working the right way.
> 
>> You can make it work, but the result tends to be messy:
> 
> I think it's better underneath, but still syntactically ugly, to just
> defer the generator creation:
> 
>  all_heights = lambda:
>  (block.height for block in stack if
>  block.is_marked())

You still need the stop() trick to omit the heights after the marked block.

>  if is_empty(all_heights ()):
>  raise SomeError("No marked block")
>  height = sum(all_heights ())
> 
> Now sum and is_empty see two separate generators, so is_empty is
> straightforward:
> 
>  def is_empty(gen):
> try:
>gen.next()
>return True
> except StopIteration:
>return False

Alternatively you can turn all_heights into a list (comprehension) which
makes the test trivial. 

I think it will be interesting to see how Python 3000's emphasis on
iterators will affect overall code complexity.

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


builtin regular expressions?

2006-09-30 Thread Antoine De Groote
Hello,

Can anybody tell me the reason(s) why regular expressions are not built 
into Python like it is the case with Ruby and I believe Perl? Like for 
example in the following Ruby code

line = 'some string'

case line
   when /title=(.*)/
 puts "Title is #$1"
   when /track=(.*)/
 puts "Track is #$1"
   when /artist=(.*)/
 puts "Artist is #$1"
end

I'm sure there are good reasons, but I just don't see them.

Python Culture says: 'Explicit is better than implicit'. May it be 
related to this?

Regards,
antoine
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Escapeism

2006-09-30 Thread Peter Otten
Kay Schluehr wrote:

> Usually I struggle a short while with \ and either succeed or give up.
> Today I'm in a different mood and don't give up. So here is my
> question:
> 
> You have an unknown character string c such as '\n' , '\a' , '\7' etc.
> 
> How do you echo them using print?
> 
> print_str( c ) prints representation '\a' to stdout for c = '\a'
> print_str( c ) prints representation '\n' for c = '\n'
> ...
> 
> It is required that not a beep or a linebreak shall be printed.
> 
> First of all it has be remarked that it is impossible to a certain
> extent. That's because e.g. c = '\a' and c = '\7' do represent the same
> string but this ambiguity doesn't occur for many numbers. But lets
> weaken the requirement and fix a canonical representation in case of
> ambiguity. I'm still getting stuck here.

I don't understand the question. Wouldn't the canonical representation be
repr(c) or repr(c)[1:-1]?

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


Re: builtin regular expressions?

2006-09-30 Thread Sybren Stuvel
Antoine De Groote enlightened us with:
> Can anybody tell me the reason(s) why regular expressions are not built 
> into Python like it is the case with Ruby and I believe Perl?

They _are_ built into Python. Python ships with the 're' module.

> Python Culture says: 'Explicit is better than implicit'. May it be
> related to this?

The creators of Python chose not to include an extention of the Python
syntax for regular expressions. It's a lot simpler to have a
straight-forward syntax, and simply pass the regular expressions to
the appropriate functions.

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Escapeism

2006-09-30 Thread Sybren Stuvel
Kay Schluehr enlightened us with:
> Usually I struggle a short while with \ and either succeed or give up.
> Today I'm in a different mood and don't give up. So here is my
> question:
>
> You have an unknown character string c such as '\n' , '\a' , '\7' etc.
>
> How do you echo them using print?
>
> print_str( c ) prints representation '\a' to stdout for c = '\a'
> print_str( c ) prints representation '\n' for c = '\n'
> ...
>
> It is required that not a beep or a linebreak shall be printed.

try "print repr(c)".

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb for Python 2.5

2006-09-30 Thread James Stroud
Harold Trammel wrote:
> Hi everyone,
> 
> Does anyone know the status of a version of MySQLdb that will work with 
> Python 2.5?  I will accept a workaround if you know one.  Thanks in 
> advance.
> 
> Harold Trammel

I could not find a way around this requirement, but you will want to 
manually add libz to your building with this version. This seems to be 
how to do this when you run setup.py:

  python setup.py -lz [other args] install

This is for mysqldb "MySQL-python-1.2.1_p2" (which I believe is the 
latest).

I built this a few days ago and finally tested today and got this 
terribly annoying (and apparently well documented) error:

[stacktrace clipped]
LookupError: unknown encoding: latin1_swedish_ci

My setup: python 2.5, very old mysql servers (C. 2003?), mysqldb 
1.2.1_p2. It seems the problem is related to mysqldb, but I'm not sure.

I found the only real work-around here:

   http://mail.python.org/pipermail/python-list/2006-July/350408.html

Its ugliness manifests in my code as such:


###
# workaround function for problems with encoding
###
def _csn(*args, **kwargs): return 'utf-8'

###
# init_mysql()
###
def init_mysql(the_db="some_db"):
   adb = MySQLdb.connect(
host="sql.some.institute.edu",
# charset="utf8", # <-- our mysql servers too old for this
user="my_login",
passwd="pa55w0rd",
db=the_db
   )
   adb.character_set_name = instancemethod(_csn, adb, adb.__class__)
   return adb


This fix passes some initial rudimentary tests. No guarantees on proper
handling of unicode. If you are using unicode, you may want to test it 
thoroughly with this fix and report your results (preferably on this 
comp.lang.python).


James

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


Re: ruby %w equivalent

2006-09-30 Thread James Stroud
hg wrote:
> But today ? what is the cost of replacing %w("blah blah") by
> Hi_I_Want_To_Split_The_String_That_Follows( "blah blah")

The latter is beginning to look like the Cocoa/NextStep framework. 
Perhaps we should give up scripting languages for ObjC?

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


Re: another distutils question

2006-09-30 Thread Keith Perkins
Thanks everyone, for your answers.  They've been very helpful.
Keith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: windev vs python SOS

2006-09-30 Thread Wolfgang Keller
>   - python work on multiple platform (linux, mac, windows)
>   A good point but it didn't interest him. Because
>   we want to choose a language for prototyping.
>   So multi platform is not enough.

With Python the prototype _is_ the application. You just need to add a little 
bit of polishing (exception handling etc.) where required, maybe implement a 
speed-critical module in Pyrex, that's it.

And for running a production application, cross-platform-ness _is_ important. 
Or what would you do when your customer wants to run his application not just 
on Windows, but on an embedded OS like VxWorks, QNX, or a _real_ server OS 
such as any proprietary Unix (including MacOS X), Linux, *BSD, OS/400 (or 
whatever it is called now), MVS...
 
Can Windev interface with .net? For Python, there's Python.net (not 
Ironpython, that's a different thing).

Can Windev interface with Java? For Python, there's JPype (not Jython, that's 
a different thing as well).

Does Windev interface with JMS, Java RMI, SAP RFC, mqseries and other 
middleware?

Can you build COM clients and servers in Windev? Can you build Corba clients 
and servers in Windev?

Can Windev interface natively with nearly every relational database on the 
planet?

Can you easily access any C/C++ library from Windev?

Is Windev code as readable as Python for non-computer scientists?

...

>   - windev as a good IDE, python? boa-constructor is ok with wxpython

Python for Windows comes with an IDE (PythonWin) iirc. Otherwise there are 
plenty of development tools for database applications in Python (not all 
mentioned below are free):

Access/Filemaker-like:
- Rekall (Qt)
- Knoda (Qt)
- Kexi (Qt)
- Gemello (GTK)
- Glom (GTK)
...

GUI-Builders:
- Qt Designer
- Glade (GTK)
- Gazpacho (GTK) & Kiwi (application framework)
- wxGlade (wxwidgets)
- DialogBlocks (wxWidgets)
- VisualWx (wxWidgets)
- wxDesigner (wxWidgets)
...

IDEs:
- WingIDE
- Eric3
- SPE
- Komodo
- PyDev (for Eclipse)
- Trustudio (for Eclipse)
- Pythoncard (incl. GUI-Builder)
- Boa Constructor (incl. GUI-Builder)
...

Others:
- GNUe (wxWidgets) (complete framework for enterprise database applications, 
including application server etc.)
- TinyERP (GTK) (complete ERP implemented in Python, but if you strip out all 
the ERP-specific modules, you get a powerful framework inlcuding a workflow 
engine)
- Dabo (wxWidgets) (framework & GUI Builder)
...

>   - python is open source (that's not an argument for my boss, sorry 
> it's  a boss ...)

The point is that with Python you _can_ have commercial support if you 
want/need to. With Windev, as with any other proprietary software, you 
_depend_ on the original developer to continue to exist, fix bugs, implement 
required functionality...

How anyone can bet the existence of a company on proprietary software in a 
time where even multi-billion dollar companys get taken over just to 
"consolidate competition" is beyond my scope of comprehension.

Sincerely,

Wolfgang Keller

-- 
My email-address is correct.
Do NOT remove ".nospam" to reply.

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


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread Paul Rubin
Peter Otten <[EMAIL PROTECTED]> writes:
> >  all_heights = lambda:
> >  (block.height for block in stack if
> >  block.is_marked())
> 
> You still need the stop() trick to omit the heights after the marked block.

Yeah, that code was based on my earlier mis-read of the original post.
How's this:

def blocks_until_mark():
   return itertools.takewhile(lambda block:\
  not block.is_marked(), \
  stack)

height = sum(b.height for b in blocks_until_mark())
if is_empty(blocks_until_mark()):
raise SomeError("No marked block")

> Alternatively you can turn all_heights into a list (comprehension) which
> makes the test trivial. 

Yes, I felt it wasn't in the spirit of the thing to use that memory.

> I think it will be interesting to see how Python 3000's emphasis on
> iterators will affect overall code complexity.

We will need more iterator primitives, which are still evolving.
-- 
http://mail.python.org/mailman/listinfo/python-list


Storing records from a parsed file

2006-09-30 Thread Ben
Apologies if this is te wrong place to post -  I realise the question
is pretty basic...

I have a simple python script that parses a text file and extracts data
from it. Currently
this data is stored in a list by  a function, each element of which is
an instance of a class with
member variables to take the data. So for example I have:

camera_list.append(camera(alpha,beta,gamma))

where

class camera:
 def __init__(self,name,site,address,text):
 self.name=name
 self.site=site
 self.address=address
 self.text=text

Every time I append an item to this list I pass in the constructor
parameters so end up with all my data in the list which can then be
accessed by doing myList[x].name (for example)

This seemed like  a nice solution until I tried to put the entire
parsing program into its own class. I did this so that I could parse
different types of file:

thistype.getdata()
thattype.getdata()
...
thisfile and thatfile would have the same function definitions, but
different implementations as needed.

But now my list generating funtion needs to create inner "camera"
classes when it is itself a member funcition of a class. This seems to
be causing problems - I coudl possibly use nested dictionaries, but
this sounds messy. Ideally I would use structs defined inside the
outer class, but pythn doesn't seem to support these.

I hope I haven't rambled too much here - I'm new to python so have
probably done some silly things :-)

Cheers,

Ben

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


Re: builtin regular expressions?

2006-09-30 Thread Jorge Godoy
Antoine De Groote <[EMAIL PROTECTED]> writes:

> Hello,
>
> Can anybody tell me the reason(s) why regular expressions are not built into
> Python like it is the case with Ruby and I believe Perl? Like for example in
> the following Ruby code
>
> line = 'some string'
>
> case line
>   when /title=(.*)/
> puts "Title is #$1"
>   when /track=(.*)/
> puts "Track is #$1"
>   when /artist=(.*)/
> puts "Artist is #$1"
> end
>
> I'm sure there are good reasons, but I just don't see them.
>
> Python Culture says: 'Explicit is better than implicit'. May it be related to
> this?

See if this isn't better to read:


def print_message(some_str):
if some_str.startswith('track='):
print "Your track is", some_str[6:]
elif some_str.startswith('title='):
print "It's a title of", some_str[6:]
elif some_str.startswith('artist='):
print "It was played by", some_str[7:]
else:
print "Oops, I dunno the pattern for this line..."
return

for line in ['track="My favorite track"', 'title="My favorite song"',
 'artist="Those Dudes"', 'Something else']:
print_message(line)


Expected output:


Your track is "My favorite track"
It's a title of "My favorite song"
It was played by "Those Dudes"
Oops, I dunno the pattern for this line...



I came from Perl and was used to think with regular expressions for
everything.  Now I rarely use them.  They aren't needed to solve most of the
problems. 

-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Typing UTF-8 characters in IDLE

2006-09-30 Thread kazuo fujimoto
Ricky,

I found your message now, because I also would encounter the same
problem.


> A few unicode tutorials on the web show that it's possible to type
> unicode characters into the IDLE gui...
> 
> However, when i type korean (hangul) characters it complains:
> 
> Unsupported Characters in input
> 
> I don't have a great understanding of unicode, but when I use a UTF-8
> source file with korean strings in, and run it as a CGI script it
> works fine.
> 
> I'm using python 2.3.3 on win XP.
> 
> Any tutorials / info anyone could point me to? Thanks...

Now I am using Hangle with Japaese. 

What I did is as follow.

My Python is now 2.4.3

1) open the IOBinding.py in $python/idellib
2) see the block just after line35, and insert one line.

encoding = "ascii"   # line 35
if sys.platform == 'win32':
# On Windows, we could use "mbcs". However, to give the user
# a portable encoding name, we need to find the code page
try:
encoding = locale.getdefaultlocale()[1]
codecs.lookup(encoding)
except LookupError:
pass
encoding = 'utf-8' ## <- this line force the encoding to utf-8.
-
3) save the file and quit Idle and reopen Idle.

I hope my experience will solve your problem.

(It has passed 2 years and more, so you might already solve the problem.
I you know better solution, please inform me.)

kazuo

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


Re: builtin regular expressions?

2006-09-30 Thread John Roth

Antoine De Groote wrote:
> Hello,
>
> Can anybody tell me the reason(s) why regular expressions are not built
> into Python like it is the case with Ruby and I believe Perl? Like for
> example in the following Ruby code
>
> line = 'some string'
>
> case line
>when /title=(.*)/
>  puts "Title is #$1"
>when /track=(.*)/
>  puts "Track is #$1"
>when /artist=(.*)/
>  puts "Artist is #$1"
> end
>
> I'm sure there are good reasons, but I just don't see them.

Partially it's a matter of language design
philosophy, and partially it's a matter of
the early history of the language.

Guido tends toward a very clean, almost mathematical
minimalist approach: things should be put into the core
language that duplicate other things. Larry Wall tends
toward what I think of as a "kitchen sink" approach.
Put it in!

The other is early history. Python started out as the
scripting language for an operating system research
project at a university. Perl started out as a language
for doing text manipulation in a working systems
administration environment.

There's a different issue that, I think, illustrates
this very nicely: text substitution. Python uses
the "%" operator for text substitution. I suspect
that Guido doesn't like it very much, because it
has recently grown a second library for text
substitution, and there's a PEP  for 3.0 for yet
a third library. And guess what? Neither of them
uses an operator.

> Python Culture says: 'Explicit is better than implicit'. May it be
> related to this?

It's more "there should  be one, and preferably
only one, obvious way to do something."

John Roth
> 
> Regards,
> antoine

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


Python pyphone module download

2006-09-30 Thread vedran_dekovic
Hello,
I was install python pyphone,but I can't run it becose I must download
module gtk.Where to I find
module gtk   (gtk.exe)














Thanks

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


Re: Storing records from a parsed file

2006-09-30 Thread Steve Holden
Ben wrote:
> Apologies if this is te wrong place to post -  I realise the question
> is pretty basic...
> 
> I have a simple python script that parses a text file and extracts data
> from it. Currently
> this data is stored in a list by  a function, each element of which is
> an instance of a class with
> member variables to take the data. So for example I have:
> 
> camera_list.append(camera(alpha,beta,gamma))
> 
> where
> 
> class camera:
>  def __init__(self,name,site,address,text):
>  self.name=name
>  self.site=site
>  self.address=address
>  self.text=text
> 
> Every time I append an item to this list I pass in the constructor
> parameters so end up with all my data in the list which can then be
> accessed by doing myList[x].name (for example)
> 
> This seemed like  a nice solution until I tried to put the entire
> parsing program into its own class. I did this so that I could parse
> different types of file:
> 
> thistype.getdata()
> thattype.getdata()
> 
> thisfile and thatfile would have the same function definitions, but
> different implementations as needed.
> 
> But now my list generating funtion needs to create inner "camera"
> classes when it is itself a member funcition of a class. This seems to
> be causing problems - I coudl possibly use nested dictionaries, but
> this sounds messy. Ideally I would use structs defined inside the
> outer class, but pythn doesn't seem to support these.
> 
> I hope I haven't rambled too much here - I'm new to python so have
> probably done some silly things :-)
> 
Sounds like a fairly simple problem, but just the kind to tax a beginner ...

I think you are mistaken in your belief that the camera classes have to 
be declared inside the file-handler classes: it's quite possible to 
declare them independently and use them anyway. Here's a class whose 
method creates an instance of another class and returns it (though it 
could of course just as easily return a list of such objects):

In [9]: class Camera1:
...: def __init__(self, p1, p2):
...: self.p1 = p1
...: self.p2 = p2
...:

In [10]: class Camera2:
: def __init__(self, p1, p2):
: self.p1 = p1
: self.p2 = p2
:

In [11]: class factory:
: def CreateCamera(self, x):
: if x == 1:
: return Camera1("a", "b")
: else:
: return Camera2("x", "y")
:

In [12]: f = factory()

In [13]: c1 = f.CreateCamera(1)

In [14]: c2 = f.CreateCamera("something else")

In [15]: c1
Out[15]: 

In [16]: c2
Out[16]: 

Does this help?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Storing records from a parsed file

2006-09-30 Thread Ben
Ah I see. So istead of creating the classes diectly I use a facroty
class as a buffer - I tell it what I want and it makes the appropriate
instances. I am not enitely sure that applies here though (I may be
wrong)

Currently I have:

camera_list[]

class camera:
 def __init__(self,alpha,beta,gamma...):
 self.alpha=alpha
 self.beta=beta
 self.gamma=gamma
 ...

for (some conditions)
camera_list.append(camera(alpha,beta,gamma...)

the append command creates an instance of the camera class and shoves
it at the end of a list for each itteration of the loop.

However, I want to recover various types of information from the text
file I am parsing - not just (as in the example above) camera data.
However I am trying to keep the interface the same.

so I can have collectSomeData.getData() as well as
collectSomeOtherData.getData()

In each case the getData impementation will be different to suit the
required task.

So something like:

class camera:
 def __init__(self,alpha,beta,gamma...):
 self.alpha=alpha
 self.beta=beta
 self.gamma=gamma
 ...

class list_type1
def createList() :
for (some conditions)
camera_list.append(camera(alpha,beta,gamma...)

class list_type2
def createList() :
for (some other conditions)
camera_list.append(camera(alpha,beta,gamma...)



data1=list_type1()
data2=list_type2()


data1.createList()
data2.createList()

The only change above is that I have taken the list appending loop and
put it into a class of its own.

However, wheras when the method list_type_2 was not in a class tings
worked fine, when put into a class as above and the method attempts to
create an instance of the camera class to append to its list it
complains.

I'm pretty sure there is a solution, and I think I will kick myself
when I work it out (or have it pointed out)!

Cheers,

Ben

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


cx_Freeze and Python

2006-09-30 Thread BM
Hi.
Does somebody used cx_Freeze, especially on Mac? I have a trouble to
make *standalone* program. If I use dynamically compiled Python as it
done by default, I always have an "hardcoded" URL inside the Python
binary something like /usr/local/Python2.5/lib/libpython so after I
freeze stuff and put to another machine, it fails with exactly the
error: Library /usr/local/Python2.5/blah-blah/... is missing. Means,
not a standalone App so far.

Then I tried to build Python statically. I success editing
Modules/Setup and I got fat binary with no such a path inside the VM.
However, when I try to Freeze, it barks with the following:

Traceback (most recent call last):
  File "/Users/bm/cx_Freeze-3.0.3/initscripts/ConsoleKeepPath.py", line
15, in 
exec code in m.__dict__
  File "FreezePython.py", line 7, in 
import Freezer
  File "Freezer.py", line 9, in 
import zipfile
  File "/Users/bm/Python2.5-static/lib/python2.5/zipfile.py", line 5,
in 
import binascii, cStringIO
ImportError:
dlopen(/Users/bm/Python2.5-static/lib/python2.5/lib-dynload/binascii.so,
2): Symbol not found: _PyModule_GetDict
  Referenced from:
/Users/bm/Python2.5-static/lib/python2.5/lib-dynload/binascii.so
  Expected in: dynamic lookup

Well, traceback usually differs - depends of what module it wants to
load. If you make it ./configure --disable-shared, then it fails
loading _struct.so or similar. What I am missing in the very principle?

Thanks for any advice.

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


Re: Storing records from a parsed file

2006-09-30 Thread Ben
Ah - I think I've sorted it out.

I can now have data1.function()

or

data2.function()


etc


However, I can still call function() directly:

function()

 which seems very odd Indeed. The only instances of function are within
classes data1 and data2, and these definitions are different, so I
don't see why I can get away with calling it without reference to a
base class - for a start how does it know whivh one to call... will
investigate :-p

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


Re: builtin regular expressions?

2006-09-30 Thread Mirco Wahab
Thus spoke Antoine De Groote (on 2006-09-30 11:24):

> Can anybody tell me the reason(s) why regular expressions are not built 
> into Python like it is the case with Ruby and I believe Perl? Like for 
> example in the following Ruby code
> I'm sure there are good reasons, but I just don't see them.
> Python Culture says: 'Explicit is better than implicit'. May it be 
> related to this?

I think it is exactly because the /\b(\d+)\s+\/\//
together with $_ and $whatever=~/\/\/(?=\d+)/ are
seen as the 'line noise' everybody talks about ;-)

Regex as part of the core language expressions
makes code very very hard to understand for
newcomers, and because Python is ...

To invoke an additional cost in using Regexes,
the language simply prevents them in a lot of
situations. Thats it. You have to think three
times before you use them once. In the end,
you solve the problem 'elsewise' because of
the pain invoked ;-)

Regards

Mirco

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


Re: builtin regular expressions?

2006-09-30 Thread Mirco Wahab
Thus spoke Jorge Godoy (on 2006-09-30 14:37):
> Antoine De Groote <[EMAIL PROTECTED]> writes:
>> I'm sure there are good reasons, but I just don't see them.
>> Python Culture says: 'Explicit is better than implicit'. May it be related to
>> this?
> 
> See if this isn't better to read:
> 
> def print_message(some_str):
> if some_str.startswith('track='):
> print "Your track is", some_str[6:]
> elif some_str.startswith('title='):
> print "It's a title of", some_str[6:]
> elif some_str.startswith('artist='):
> print "It was played by", some_str[7:]
> else:
> print "Oops, I dunno the pattern for this line..."
> return
> 
> for line in ['track="My favorite track"', 'title="My favorite song"',
>  'artist="Those Dudes"', 'Something else']:
> print_message(line)

I don't see the point here, this example can be
translated amost 1:1 to Perl and gets much more
readable in the end, consider:


sub print_message {
   if   (/^(track=)/ ){ print 'Your track is '   .substr($_, length $1)."\n" }
   elsif(/^(title=)/ ){ print 'It\'s a title of '.substr($_, length $1)."\n" }
   elsif(/^(artist=)/){ print 'It was played by '.substr($_, length $1)."\n" }
   else   { print "Oops, I dunno the pattern for this line...\n" }
}

print_message for ( 'track="My favorite track"', 'title="My favorite song"',
'artist="Those Dudes"',  'Something else' );


Now one could argue if simple Regexes like
   /^track=/ are much worse compared to
more explicit formulations, like
   str.startswith('track=')

> I came from Perl and was used to think with regular expressions for
> everything.  Now I rarely use them.  They aren't needed to solve 
> most of the problems. 

OK, I do Perl and Python side by side and didn't reach
that point so far, maybe beause I read the Friedel-Book
 ( http://www.oreilly.com/catalog/regex2/reviews.html )
sometimes and actually *like* the concept of regular expressions.


Regards

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


Re: builtin regular expressions?

2006-09-30 Thread Duncan Booth
Jorge Godoy <[EMAIL PROTECTED]> wrote:

> See if this isn't better to read:
> 
>
> 
> def print_message(some_str):
> if some_str.startswith('track='):
> print "Your track is", some_str[6:]
> elif some_str.startswith('title='):
> print "It's a title of", some_str[6:]
> elif some_str.startswith('artist='):
> print "It was played by", some_str[7:]
> else:
> print "Oops, I dunno the pattern for this line..."
> return
> 
> for line in ['track="My favorite track"', 'title="My favorite song"',
>  'artist="Those Dudes"', 'Something else']:
> print_message(line)
>
> 
> 
> Expected output:

Or you could make it even clearer by using a loop:

messages = [
('track=', 'Your track is'),
('title=', "It's a title of"),
('artist=', "It was played by"),
]

def print_message(s):
for key, msg in messages:
if s.startswith(key):
print msg,s[len(key):]
break
else:
print "Oops, I dunno the pattern for this line..."


for line in ['track="My favorite track"', 'title="My favorite song"',
 'artist="Those Dudes"', 'Something else']:
print_message(line)

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


Re: builtin regular expressions?

2006-09-30 Thread Steve Holden
Mirco Wahab wrote:
> Thus spoke Antoine De Groote (on 2006-09-30 11:24):
> 
> 
>>Can anybody tell me the reason(s) why regular expressions are not built 
>>into Python like it is the case with Ruby and I believe Perl? Like for 
>>example in the following Ruby code
>>I'm sure there are good reasons, but I just don't see them.
>>Python Culture says: 'Explicit is better than implicit'. May it be 
>>related to this?
> 
> 
> I think it is exactly because the /\b(\d+)\s+\/\//
> together with $_ and $whatever=~/\/\/(?=\d+)/ are
> seen as the 'line noise' everybody talks about ;-)
> 
> Regex as part of the core language expressions
> makes code very very hard to understand for
> newcomers, and because Python is ...
> 
> To invoke an additional cost in using Regexes,
> the language simply prevents them in a lot of
> situations. Thats it. You have to think three
> times before you use them once. In the end,
> you solve the problem 'elsewise' because of
> the pain invoked ;-)
> 
Tim Peters frequently says something along the lines of "If you have a 
problem and you try to solve it with regexes, then you have TWO 
problems". This isn't because the Python use of regexes is more 
difficult than Perl's: it's because regexes themselves are inherently 
difficult when the patterns get at all sophisticated.

If you think Perl gives better text-handing features nobody is going to 
mind if you use Perl - appropriate choice of language is a sign of 
maturity. Personally I tend to favour the way Python does it, but I 
don't require that anyone else does.

The real answer to "why doesn't Python do it like Perl?" is "Because 
Python's not like Perl".

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: builtin regular expressions?

2006-09-30 Thread Jorge Godoy
Mirco Wahab <[EMAIL PROTECTED]> writes:

> I don't see the point here, this example can be
> translated amost 1:1 to Perl and gets much more
> readable in the end, consider:

I could make it shorter in Python as well.  But for a newbie that haven't seen
the docs for strings in Python I thought the terse version would be more
interesting. 

At least he'll see that there are methods to do what he wants already builtin
with the language.

> sub print_message {
>if   (/^(track=)/ ){ print 'Your track is '   .substr($_, length $1)."\n" }
>elsif(/^(title=)/ ){ print 'It\'s a title of '.substr($_, length $1)."\n" }
>elsif(/^(artist=)/){ print 'It was played by '.substr($_, length $1)."\n" }
>else   { print "Oops, I dunno the pattern for this line...\n" }
> }
>
> print_message for ( 'track="My favorite track"', 'title="My favorite song"',
> 'artist="Those Dudes"',  'Something else' );

If I were writing in Perl I'd not use substr like this and would write code
similar to the one the OP posted (i.e., /^track=(.*)/).

> OK, I do Perl and Python side by side and didn't reach
> that point so far, maybe beause I read the Friedel-Book
>  ( http://www.oreilly.com/catalog/regex2/reviews.html )
> sometimes and actually *like* the concept of regular expressions.

I like them as well.  I just don't see the need to use them everywhere. :-) 


-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: builtin regular expressions?

2006-09-30 Thread Jorge Godoy
Duncan Booth <[EMAIL PROTECTED]> writes:

> Or you could make it even clearer by using a loop:

Oops.  Should have read your message before replying to Mirco.  But again,
since the OP didn't read the docs for string operations I tried the terse
approach so that he actually sees the correspondence from Perl to Python. 

Dictionaries (and hashes in Perl) are very powerful and solve very interesting
problems (specially when one is looking for something like a "case"
implementation in Python). 


-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing records from a parsed file

2006-09-30 Thread Ben
Finally got it all sorted :-)

I got slightly confused because it seems that if you refer to class
variables from methods within that class you need to explicitly state
that they are self, otherwise, since class variables are all public in
python, things could get quite confusing.

Ben


Ben wrote:
> Ah - I think I've sorted it out.
>
> I can now have data1.function()
>
> or
>
> data2.function()
>
>
> etc
>
>
> However, I can still call function() directly:
>
> function()
>
>  which seems very odd Indeed. The only instances of function are within
> classes data1 and data2, and these definitions are different, so I
> don't see why I can get away with calling it without reference to a
> base class - for a start how does it know whivh one to call... will
> investigate :-p

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


_gtk

2006-09-30 Thread vedran_dekovic
Hello,
Where to I download module:  _gtk

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


Re: builtin regular expressions?

2006-09-30 Thread Mirco Wahab
Thus spoke Jorge Godoy (on 2006-09-30 17:50):
> Mirco Wahab <[EMAIL PROTECTED]> writes:
> 
> I could make it shorter in Python as well.  But for a newbie that haven't seen
> the docs for strings in Python I thought the terse version would be more
> interesting. 

OK

> At least he'll see that there are methods to do what he wants already builtin
> with the language.

OK

>> sub print_message {
>>if   (/^(track=)/ ){ print 'Your track is '   .substr($_, length $1)."\n" 
>> }
...
> If I were writing in Perl I'd not use substr like this and would write code
> similar to the one the OP posted (i.e., /^track=(.*)/).

Right, I actually tried to match your example as close as I could
get and to use only *simple* Regexes (as stated below). What one
really would do (as you probably meant above) is sth. like:

  sub print_message {
 if   (/^track="(.+?)"/ ){ print "Your track is $1\n" }
 ...

which has a "more complicated" regex that is usually
not understood easily by newbies.

>> OK, I do Perl and Python side by side and didn't reach
>> that point so far, maybe beause I read the Friedel-Book
>>  ( http://www.oreilly.com/catalog/regex2/reviews.html )
>> sometimes and actually *like* the concept of regular expressions.
> 
> I like them as well.  I just don't see the need to use them everywhere. :-) 

I like Python for its radically plain look, my
underlying feeling of Python is: "Pascal", whereas
Perl feels and tastes like "C" to me ;-)

Regards

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


Re: _gtk

2006-09-30 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Hello,
> Where to I download module:  _gtk

is google dead today?

google: python module gtk download windows

something like the fifth link.

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


Re: windev vs python SOS

2006-09-30 Thread Amanda
> Can Windev interface with .net?  YES
> Can Windev interface with Java?  YES
> Can Windev interface natively with nearly every relational database on the
> planet?  YES
> Does Windev interface with JMS, Java RMI, SAP RFC, mqseries and other
> middleware?>> YES
> Can you easily access any C/C++ library from Windev?  YES
> Is Windev code as readable as Python for non-computer scientists?>>> I don't 
> know Python but Wlangage is as readable as free text

I am always amazed when I meet fanatics!!
Links abour Windev for those who like facts :

http://www.windev.com/pcsoft/testimonials/index.html
http://www.pcsoft.fr/annonce10/photos.html
http://www.pcsoft.fr/pcsoft/120pages/index.html
Be cool !!!
A.


Wolfgang Keller wrote:
> >   - python work on multiple platform (linux, mac, windows)
> > A good point but it didn't interest him. Because
> > we want to choose a language for prototyping.
> > So multi platform is not enough.
>
> With Python the prototype _is_ the application. You just need to add a little
> bit of polishing (exception handling etc.) where required, maybe implement a
> speed-critical module in Pyrex, that's it.
>
> And for running a production application, cross-platform-ness _is_ important.
> Or what would you do when your customer wants to run his application not just
> on Windows, but on an embedded OS like VxWorks, QNX, or a _real_ server OS
> such as any proprietary Unix (including MacOS X), Linux, *BSD, OS/400 (or
> whatever it is called now), MVS...
>
> Can Windev interface with .net? For Python, there's Python.net (not
> Ironpython, that's a different thing).
>
> Can Windev interface with Java? For Python, there's JPype (not Jython, that's
> a different thing as well).
>
> Does Windev interface with JMS, Java RMI, SAP RFC, mqseries and other
> middleware?
>
> Can you build COM clients and servers in Windev? Can you build Corba clients
> and servers in Windev?
>
> Can Windev interface natively with nearly every relational database on the
> planet?
>
> Can you easily access any C/C++ library from Windev?
>
> Is Windev code as readable as Python for non-computer scientists?
>
> ...
>
> >   - windev as a good IDE, python? boa-constructor is ok with wxpython
>
> Python for Windows comes with an IDE (PythonWin) iirc. Otherwise there are
> plenty of development tools for database applications in Python (not all
> mentioned below are free):
>
> Access/Filemaker-like:
> - Rekall (Qt)
> - Knoda (Qt)
> - Kexi (Qt)
> - Gemello (GTK)
> - Glom (GTK)
> ...
>
> GUI-Builders:
> - Qt Designer
> - Glade (GTK)
> - Gazpacho (GTK) & Kiwi (application framework)
> - wxGlade (wxwidgets)
> - DialogBlocks (wxWidgets)
> - VisualWx (wxWidgets)
> - wxDesigner (wxWidgets)
> ...
>
> IDEs:
> - WingIDE
> - Eric3
> - SPE
> - Komodo
> - PyDev (for Eclipse)
> - Trustudio (for Eclipse)
> - Pythoncard (incl. GUI-Builder)
> - Boa Constructor (incl. GUI-Builder)
> ...
>
> Others:
> - GNUe (wxWidgets) (complete framework for enterprise database applications,
> including application server etc.)
> - TinyERP (GTK) (complete ERP implemented in Python, but if you strip out all
> the ERP-specific modules, you get a powerful framework inlcuding a workflow
> engine)
> - Dabo (wxWidgets) (framework & GUI Builder)
> ...
>
> >   - python is open source (that's not an argument for my boss, sorry
> > it'sa boss ...)
>
> The point is that with Python you _can_ have commercial support if you
> want/need to. With Windev, as with any other proprietary software, you
> _depend_ on the original developer to continue to exist, fix bugs, implement
> required functionality...
>
> How anyone can bet the existence of a company on proprietary software in a
> time where even multi-billion dollar companys get taken over just to
> "consolidate competition" is beyond my scope of comprehension.
>
> Sincerely,
>
> Wolfgang Keller
>
> -- 
> My email-address is correct.
> Do NOT remove ".nospam" to reply.

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


Re: _gtk

2006-09-30 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> Hello,
> Where to I download module:  _gtk

I would suggest starting here:

http://www.pygtk.org/downloads.html

It looks like you need the PyGTK package.

Paul

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


Re: creating a small test server on my local computer

2006-09-30 Thread John Salerno
Ant wrote:
> Mirco Wahab wrote:
>> Thus spoke John Salerno (on 2006-09-29 21:13):
> ...
>> My advice would be (because Apache installations on
>> WinXP don't usually support Python (except pulling
>> the whole thing into each CGI invocation) - download
>> and install a VMWare Player
> 
> This sounds a horribly complicated way of doing things. If you read the
> OP's post, it seems he is simply trying to serve straight HTML pages
> (but with Server Side Includes) locally for testing, rather than having
> to pester his operations guys to put them up on the company servers.
> 
> If it's just HTML and SSI, then Apache is the easy answer on XP. The
> download is a simple .msi installer, and you'll just be able to drop
> the html files in the htdocs directory to start serving them.
> (http://httpd.apache.org/download.cgi)

Thanks! I'll look into this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mark Lutz Python interview

2006-09-30 Thread John Salerno
Fuzzyman wrote:
> Mark Lutz wrote:
>> Python author and trainer Mark Lutz will be interviewed
>> on the radio show Tech Talk this Sunday, October 1st,
>> at 6PM Eastern time.  He'll be answering questions about
>> Python, his books, and his Python training services.
>>
> 
> Does he always talk in the third person ? ;-)

We'll have to listen to the interview to find out. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread Carl Banks
[EMAIL PROTECTED] wrote:
> I'm wondering if anyone has ever found a practical use for the else
> branch?

Say you have code that looks like this:

if command.startswith("set"):
do_set_action(command)
elif command.startswith("input"):
do_input_action(command)
elif command.startswith("print"):
do_print_action()
else:
do_general_action()

Now, during refactoring, we note that there's a lot of similarity in
all those if clauses that we can exploit to simplify the code.  Let's
ignore the final else clause for now, since it's not similar to the if
and elif clauses (it has no test).  We define a mapping of prefixes to
actions, and rewrite the if...elif as a for loop:

command_map = (
("set",do_set_action),
("input",do_input_action),
("print",do_print_action)
)

for keyword,action in command_map:
if command.startswith(keyword):
action(command)
break

Ok, this works great.  Now let's come back to that else clause: how do
we translate default case to the for loop?  Well, I guess we could set
some sort of flag indicating we got a match  But wait!  We don''t
have to!  We can just leave the else clause there as-is, and it'll
work.  The for loop here is quite literally a drop-in replacement for
the if...elif...elif, even going so far as to allow the same else
clause.

for keyword,action in command_list:
if command.startswith(keyword):
action(command)
break
else:
do_general_action()


Moral of the story: there are two ways to do a linear search (or linear
sequence of tests): either an unrolled sequence of if...elif...elif
clauses, or a rolled up for loop with a break.  Either way you do it,
you can tack on an else clause for when you don't find anything.


Carl Banks

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


Re: does anybody earn a living programming in python?

2006-09-30 Thread Brad Allen
I'll attest that we have a shortage of Python developers in the Dallas
area; in the DFW Python user group (dfwpython.org) we occasionally
encounter local employers who have trouble finding local Python
developers who can take on new work. Most of the group members are
already employed, so the standard answer to the employer is to
recommend hiring experienced developers and train them in Python.
Unfortunately we've seen a few cases where the employer decided to
choose a different technology due to the lack of available Python
talent.  Hopefully this will abate as more programmers understand this
problem and become attracted to Python.

BTW, are some Python-specific job sites:

http://www.python.org/community/jobs/

http://blog.gmane.org/gmane.comp.python.jobs

http://python.jobmart.com/

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


Re: storing variable names in a list before they are used?

2006-09-30 Thread John Salerno
John Salerno wrote:

> (the variables would store whatever information is entered in the text 
> boxes to the right of each label. I'm doing it this way so I can write a 
> loop to construct my GUI components).

Thanks very much for the responses guys. I actually tried something 
similar with a dictionary already, but then I discovered the obvious: I 
need them in a certain order! :)

Here is what I want to do more specifically: I am creating a single 
frame (wxPython terminology for a window) and the user will be able to 
click a "New" button which will open a new tab in that frame (using the 
wx.Notebook class). Each time a new tab is opened, it will contain a 
form to fill out, with a label widget on the left ("First Name:") and a 
text box control on the right (the underlines), like this:

First Name: 
Last Name:  
Job Title:  
etc.
etc.



In wxPython, you can use "sizers" for layout control, and in this case 
the FlexGridSizer is ideal. You just assign the above widgets to it in 
this order: first label, first textbox, second label, second textbox, etc.

Instead of manually creating these widgets and adding all of them to the 
sizer (and having to add or delete code later in case something changes) 
I wanted to use some type of for loop to do it for me. This is easy for 
creating and adding the labels, because I need no reference for them 
later. But I will need a reference for the textboxes so I can later get 
the data that is in them.

So my original question involved finding a way to assign a variable name 
to the textboxes while they are being automatically created in a for 
loop. This seems like something that is probably done quite often and 
maybe I'm just not thinking of the proper idiom that is used.

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


Re: DAT file compilation

2006-09-30 Thread Roger Upole
On Windows NTFS file systems, you can add data to a file using named streams.
The extra streams aren't visible from Explorer so the average end-user won't
even know they're there.

Roger


"Jay" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> That cgi idea is really cool, but I don't have any web space to host
> the files.  Plus the bandwidth required would be deadly.  I think I'll
> just have to stick to the zip file idea.  The problem with the
> read-only is that this program is aimed at a Windows audience.
>
> James Stroud wrote:
>> Jay wrote:
>> > That's one solution, but I'd rather a file format the end-user can't
>> > easily mess around with.
>>
>> Require the program to be installed as root and installation to be in a
>> read-only directory--or serve the resources to your program from a cgi
>> script somewhere, only to be downloaded when needed. This way, the user
>> would at least have to reverse engineer your program to see where the
>> resources were coming from so they could plug the appropriate query in
>> their web browser.
>>
>> James
>>
>>
>> --
>> James Stroud
>> UCLA-DOE Institute for Genomics and Proteomics
>> Box 951570
>> Los Angeles, CA 90095
>>
>> http://www.jamesstroud.com/
> 




== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 
Newsgroups
---= East/West-Coast Server Farms - Total Privacy via Encryption =---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb for Python 2.5

2006-09-30 Thread Jan Dries
Martin v. Löwis wrote:
> Harold Trammel schrieb:
>> Does anyone know the status of a version of MySQLdb that will work with
>> Python 2.5? 
> 
> AFAICT, MySQLdb 1.2.1 builds and works just fine.
> 

Does anyone know if Windows binaries for 2.5 are available somewhere?

Regards,
Jan

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


PyCon 2007: What talks/tutorials/panels do you want to see?

2006-09-30 Thread Brad Allen
This thread is for posting ideas and general brainstorming about what
kinds
of talks folks would be interested in seeing at PyCon 2007. The idea is
to
inspire volunteer speakers to propose talks that they might not
otherwise
realize would be popular, and to give PyCon organizers a whiff of fresh
community feedback.

So, what do you want to see? What will attract you to travel to PyCon?
Or for that matter, what does your boss need to see on the schedule
to allow you to expense the conference?

The deadline for talks proposals is October 31.

http://us.pycon.org/TX2007/CallForProposals

The deadline for tutorial proposals is November 15.

http://us.pycon.org/TX2007/CallForTutorials

Remember, tutorials are half-day events on the day prior to the main
PyCon days, and have a separate admission price. The tutorial teachers
do receive some financial compensation for their time and preparation.

Also, consider the possibility of panel discussions, which would
compete for time with normal talks but might not require the same
kind of speaker preparation or proposal. Who in the Python community
would you like to see in a panel discussion or "town-hall" style event?

Btw, there is also a wiki for consolidating ideas on talks:

http://us.pycon.org/TX2007/TalkIdeas

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


Re: Escapeism

2006-09-30 Thread Kay Schluehr
Sybren Stuvel wrote:
> Kay Schluehr enlightened us with:
> > Usually I struggle a short while with \ and either succeed or give up.
> > Today I'm in a different mood and don't give up. So here is my
> > question:
> >
> > You have an unknown character string c such as '\n' , '\a' , '\7' etc.
> >
> > How do you echo them using print?
> >
> > print_str( c ) prints representation '\a' to stdout for c = '\a'
> > print_str( c ) prints representation '\n' for c = '\n'
> > ...
> >
> > It is required that not a beep or a linebreak shall be printed.
>
> try "print repr(c)".

This yields the hexadecimal representation of the ASCII character and
does not simply echo the keystrokes '\' and 'a' for '\a' ignoring the
escape semantics. One way to achieve this naturally is by prefixing
'\a' with r where r'\a' indicates a "raw" string. But unfortunately
"rawrification" applies only to string literals and not to string
objects ( such as c ). I consider creating a table consisting of pairs
{'\0': r'\0','\1': r'\1',...}  i.e. a handcrafted mapping but maybe
I've overlooked some simple function or trick that does the same for
me.

Kay

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


Re: builtin regular expressions?

2006-09-30 Thread Jorge Godoy
Mirco Wahab <[EMAIL PROTECTED]> writes:

>   sub print_message {
>  if   (/^track="(.+?)"/ ){ print "Your track is $1\n" }
>  ...
>
> which has a "more complicated" regex that is usually
> not understood easily by newbies.

Specially the non-greedy part. :-) I don't believe that non-greedyness would
be adequate here since I believe he's willing to process the whole line.

===
$line = "track='My favorite track'";
if ($line =~ /^track=(.+?)/) { print "My track is $1\n"};
===

outputs

===
My track is '
===

While

===
$line = "track='My favorite track'";
if ($line =~ /^track=(.+)/) { print "My track is $1\n"};
===

outputs

===
My track is 'My favorite track'
===

and what I'd use

===
$line = "track='My favorite track'";
if ($line =~ /^track=(.*)/) { print "My track is $1\n"};
===

has the same output.  ;-)

All this running perl 5.8.8.


Be seeing you,
-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: builtin regular expressions?

2006-09-30 Thread Antoine De Groote
Just to get it clear at the beginning, I started this thread. I'm not a 
newbie (don't get me wrong, I don't see this as an insult whatsoever, 
after all, you couldn't know, and I appreciate it being so nice to 
newbies anyway). I'm not an expert either, but I'm quite comfortable 
with the language by now. It's just that, when I started Python I loved 
it for its simplicity and for the small amount of code it takes to get 
something done. So the idea behind my original post was that the 
Perl/Ruby way takes even less to type (for the regex topic of this 
discussion, I'm not generalizing), and that I like a lot. To me (and I 
may be alone) the Perl/Ruby way is more "beautiful" (Python  culture: 
Beautiful is better than ugly) than the Python way (in this particular 
case) and therefore I couldn't see the reasons.

Some of you say that this regex stuff is used rarely enough so that 
being verbose (and therefore more readable ?) is in these few cases the 
better choice. To me this a perfectly reasonable and maybe it is just 
true (as far as one can talk about true/false for something subjective 
as this). I dont' know (yet) ;-)

I just have to learn accept the fact that Python is more verbose more 
often than Ruby (I don't know Perl really). Don't get me wrong though, I 
know the benefits of this (at least in some cases) and I can understand 
that one opts for it. Hopefully I will end up some day preferring the 
Python way.

Thanks for your explanations.

Regards,
antoine

Mirco Wahab wrote:
> Thus spoke Jorge Godoy (on 2006-09-30 17:50):
>> Mirco Wahab <[EMAIL PROTECTED]> writes:
>>
>> I could make it shorter in Python as well.  But for a newbie that haven't 
>> seen
>> the docs for strings in Python I thought the terse version would be more
>> interesting. 
> 
> OK
> 
>> At least he'll see that there are methods to do what he wants already builtin
>> with the language.
> 
> OK
> 
>>> sub print_message {
>>>if   (/^(track=)/ ){ print 'Your track is '   .substr($_, length 
>>> $1)."\n" }
> ...
>> If I were writing in Perl I'd not use substr like this and would write code
>> similar to the one the OP posted (i.e., /^track=(.*)/).
> 
> Right, I actually tried to match your example as close as I could
> get and to use only *simple* Regexes (as stated below). What one
> really would do (as you probably meant above) is sth. like:
> 
>   sub print_message {
>  if   (/^track="(.+?)"/ ){ print "Your track is $1\n" }
>  ...
> 
> which has a "more complicated" regex that is usually
> not understood easily by newbies.
> 
>>> OK, I do Perl and Python side by side and didn't reach
>>> that point so far, maybe beause I read the Friedel-Book
>>>  ( http://www.oreilly.com/catalog/regex2/reviews.html )
>>> sometimes and actually *like* the concept of regular expressions.
>> I like them as well.  I just don't see the need to use them everywhere. :-) 
> 
> I like Python for its radically plain look, my
> underlying feeling of Python is: "Pascal", whereas
> Perl feels and tastes like "C" to me ;-)
> 
> Regards
> 
> Mirco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Escapeism

2006-09-30 Thread Duncan Booth
"Kay Schluehr" <[EMAIL PROTECTED]> wrote:

>> try "print repr(c)".
> 
> This yields the hexadecimal representation of the ASCII character and
> does not simply echo the keystrokes '\' and 'a' for '\a' ignoring the
> escape semantics.

But you yourself noted earlier that '\a' and '\x07' are the same string
and said: 

> But lets weaken the requirement and fix a canonical representation in
> case of ambiguity.

That's exactly what repr(c) does, it uses a canonical representation
with '\t', '\r', '\n', '\\', (and when it has to "\'", '\"') using the 
short escape form (because they are so commonly used), and the all the 
other (more obscure) escape sequences using the hexadecimal form.

BTW, c.encode('string_escape') is another way to convert a string to almost 
the same escaped form (except for a minor difference in the treatment of 
quote characters).

> But unfortunately "rawrification" applies only to string literals and
> not to string objects ( such as c ).

Oh dear, the fact that you could even consider writing that sentence seems 
to show a fundamental misunderstanding of what a raw string literal means.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Python world tries to be polite [formerly offensive to another language]

2006-09-30 Thread A.M. Kuchling
On Sat, 30 Sep 2006 09:10:14 +0100, 
Steve Holden <[EMAIL PROTECTED]> wrote:
> My God, Perl 6 is going to be even less comprehensible that Perl 5, 
> which was at least usable. Is »=>« really a Perl6 operator? That's too 
> funny!

While we poor Python people have to cope with writing:
d = dict(zip(k, v))
instead of Perl 6's 
%h = @k >>=><< @v;

But at least the Perl solution is 4 non-whitespace characters
shorter... unless you don't write the source in Unicode, in which you
have to put >> and << instead of the chevrons -- that makes it only 2
characters shorter.

> hoping-the-chevrons-were-emphasis-on-ly y'rs  - steve

Nope; they turn the operator into a hyper operator that iterates over
its operands.  See
.  Perl 6:
the PL/1 of scripting languages.

--amk

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


Re: builtin regular expressions?

2006-09-30 Thread Jorge Godoy
Antoine De Groote <[EMAIL PROTECTED]> writes:

> Just to get it clear at the beginning, I started this thread. I'm not a newbie

Sorry :-)  I got to this wrong conclusion because of the way I read your
message.

> an expert either, but I'm quite comfortable with the language by now. It's
> just that, when I started Python I loved it for its simplicity and for the
> small amount of code it takes to get something done. So the idea behind my

See that being "small" is not all that important.  From the Zen of Python:

Explicit is better than implicit.

> original post was that the Perl/Ruby way takes even less to type (for the
> regex topic of this discussion, I'm not generalizing), and that I like a
> lot. To me (and I may be alone) the Perl/Ruby way is more "beautiful" (Python
> culture: Beautiful is better than ugly) than the Python way (in this
> particular case) and therefore I couldn't see the reasons.

You can import the re module and use regular expressions in Python, but you
probably know that.

> Some of you say that this regex stuff is used rarely enough so that being
> verbose (and therefore more readable ?) is in these few cases the better
> choice. To me this a perfectly reasonable and maybe it is just true (as far as
> one can talk about true/false for something subjective as this). I dont' know
> (yet) ;-)

It is to me. :-)  If you're parsing simple structures then it might not be to
you (for complex structures you'd end up with some sort of parser).

> I just have to learn accept the fact that Python is more verbose more often
> than Ruby (I don't know Perl really). Don't get me wrong though, I know the
> benefits of this (at least in some cases) and I can understand that one opts
> for it. Hopefully I will end up some day preferring the Python way.

One thing that is also interesting: code completion.  One editor can help you
write "startswith" but it can't help with "/^".  The same goes for "endswith"
compared to "$/".  

I just mentioned this because in the argument of "less code to write leads to
less bugs" doesn't mean that we have typed all what is written :-)

-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating a small test server on my local computer

2006-09-30 Thread Steve Holden
John Salerno wrote:
> Ant wrote:
> 
>>Mirco Wahab wrote:
>>
>>>Thus spoke John Salerno (on 2006-09-29 21:13):
>>
>>...
>>
>>>My advice would be (because Apache installations on
>>>WinXP don't usually support Python (except pulling
>>>the whole thing into each CGI invocation) - download
>>>and install a VMWare Player
>>
>>This sounds a horribly complicated way of doing things. If you read the
>>OP's post, it seems he is simply trying to serve straight HTML pages
>>(but with Server Side Includes) locally for testing, rather than having
>>to pester his operations guys to put them up on the company servers.
>>
>>If it's just HTML and SSI, then Apache is the easy answer on XP. The
>>download is a simple .msi installer, and you'll just be able to drop
>>the html files in the htdocs directory to start serving them.
>>(http://httpd.apache.org/download.cgi)
> 
> 
> Thanks! I'll look into this.

Yup, I'd second that as an approach. I have Apache on my XP system, with 
mod_python and all the trimmings.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


loop over list and modify in place

2006-09-30 Thread Daniel Nogradi
Is looping over a list of objects and modifying (adding an attribute
to) each item only possible like this?

mylist = [ obj1, obj2, obj3 ]

for i in xrange( len( mylist ) ):
mylist[i].newattribute = 'new value'


I'm guessing there is a way to do this without introducing the (in
principle unnecessary) index i, so what I'm really looking for is a
looping method which doesn't pass references to the values of the
items but to the items themselves.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DAT file compilation

2006-09-30 Thread Steve Holden
Roger Upole wrote:
> On Windows NTFS file systems, you can add data to a file using named streams.
> The extra streams aren't visible from Explorer so the average end-user won't
> even know they're there.
> 
I hadn't realised how easy it is to access alternate data streams from 
Python. A filename of the right form ("basefile.ext:alternatename") 
works just fine, it appears.

Unfortunately you then have the problem of how to create it, since there 
is no way to carry it around outside an NTFS filesystem, so some sort of 
post-install script would be required.

There's also the issue that alternate data stream of any significant 
size will be regarded with great suspicion by forensic examinations and 
similar tests.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Python/UNO/OpenOffice?

2006-09-30 Thread wesley chun
as others have said, that project provides a working interface to OOo
(OpenOffice 2 on Ubuntu Breezy and Dapper).  i've made several posts
to this regard over the summer here on CLP.  i was mostly using it to
"mess around" with documents in StarWriter.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Escapeism

2006-09-30 Thread Steve Holden
Kay Schluehr wrote:
> Sybren Stuvel wrote:
> 
>>Kay Schluehr enlightened us with:
>>
>>>Usually I struggle a short while with \ and either succeed or give up.
>>>Today I'm in a different mood and don't give up. So here is my
>>>question:
>>>
>>>You have an unknown character string c such as '\n' , '\a' , '\7' etc.
>>>
>>>How do you echo them using print?
>>>
>>>print_str( c ) prints representation '\a' to stdout for c = '\a'
>>>print_str( c ) prints representation '\n' for c = '\n'
>>>...
>>>
>>>It is required that not a beep or a linebreak shall be printed.
>>
>>try "print repr(c)".
> 
> 
> This yields the hexadecimal representation of the ASCII character and
> does not simply echo the keystrokes '\' and 'a' for '\a' ignoring the
> escape semantics. One way to achieve this naturally is by prefixing
> '\a' with r where r'\a' indicates a "raw" string. But unfortunately
> "rawrification" applies only to string literals and not to string
> objects ( such as c ). I consider creating a table consisting of pairs
> {'\0': r'\0','\1': r'\1',...}  i.e. a handcrafted mapping but maybe
> I've overlooked some simple function or trick that does the same for
> me.
> 
No, you've overlooked the fact that if you print the string containing 
the two characters "backslash" and "lower case a" then it will print 
exactly those two characters. See:

In [30]: c = "\\a"

In [31]: len(c)
Out[31]: 2

In [32]: print c
\a

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: loop over list and modify in place

2006-09-30 Thread Daniel Nogradi
> Is looping over a list of objects and modifying (adding an attribute
> to) each item only possible like this?
>
> mylist = [ obj1, obj2, obj3 ]
>
> for i in xrange( len( mylist ) ):
> mylist[i].newattribute = 'new value'
>
>
> I'm guessing there is a way to do this without introducing the (in
> principle unnecessary) index i, so what I'm really looking for is a
> looping method which doesn't pass references to the values of the
> items but to the items themselves.

Please consider the previous question as an arbitrary random brain
cell fluctuation whose probability of occurence is around once per
month and before sending the question it hasn't yet happened to me in
September.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: builtin regular expressions?

2006-09-30 Thread Antoine De Groote
Jorge Godoy wrote:
> Antoine De Groote <[EMAIL PROTECTED]> writes:
> 
>> Just to get it clear at the beginning, I started this thread. I'm not a 
>> newbie
> 
> Sorry :-)  I got to this wrong conclusion because of the way I read your
> message.

no problem ;-) maybe my formulation was a bit naive, too...

> 
>> an expert either, but I'm quite comfortable with the language by now. It's
>> just that, when I started Python I loved it for its simplicity and for the
>> small amount of code it takes to get something done. So the idea behind my
> 
> See that being "small" is not all that important.  From the Zen of Python:
> 
> Explicit is better than implicit.
> 
>> original post was that the Perl/Ruby way takes even less to type (for the
>> regex topic of this discussion, I'm not generalizing), and that I like a
>> lot. To me (and I may be alone) the Perl/Ruby way is more "beautiful" (Python
>> culture: Beautiful is better than ugly) than the Python way (in this
>> particular case) and therefore I couldn't see the reasons.
> 
> You can import the re module and use regular expressions in Python, but you
> probably know that.

yes I know that ...   ;-) again

> 
>> Some of you say that this regex stuff is used rarely enough so that being
>> verbose (and therefore more readable ?) is in these few cases the better
>> choice. To me this a perfectly reasonable and maybe it is just true (as far 
>> as
>> one can talk about true/false for something subjective as this). I dont' know
>> (yet) ;-)
> 
> It is to me. :-)  If you're parsing simple structures then it might not be to
> you (for complex structures you'd end up with some sort of parser).
> 
>> I just have to learn accept the fact that Python is more verbose more often
>> than Ruby (I don't know Perl really). Don't get me wrong though, I know the
>> benefits of this (at least in some cases) and I can understand that one opts
>> for it. Hopefully I will end up some day preferring the Python way.
> 
> One thing that is also interesting: code completion.  One editor can help you
> write "startswith" but it can't help with "/^".  The same goes for "endswith"
> compared to "$/".  
> 
> I just mentioned this because in the argument of "less code to write leads to
> less bugs" doesn't mean that we have typed all what is written :-)
> 

Excellent point! Love it :-) Helps me overcome it.

Regards,
antoine
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DAT file compilation

2006-09-30 Thread Roger Upole

"Steve Holden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Roger Upole wrote:
>> On Windows NTFS file systems, you can add data to a file using named streams.
>> The extra streams aren't visible from Explorer so the average end-user won't
>> even know they're there.
>>
> I hadn't realised how easy it is to access alternate data streams from 
> Python. A filename of the right form 
> ("basefile.ext:alternatename") works just fine, it appears.
>
> Unfortunately you then have the problem of how to create it, since there is 
> no way to carry it around outside an NTFS 
> filesystem, so some sort of post-install script would be required.
>
> There's also the issue that alternate data stream of any significant size 
> will be regarded with great suspicion by forensic 
> examinations and similar tests.
>
> regards
>  Steve
> -- 

Another drawback is that you have to be careful how you move the files
around.  shutil.copyfile doesn't pick up alternate streams.  Also, there's
no way from stock python to enumerate the streams. (but that could be a
plus for the OP)

  Roger




== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 
Newsgroups
---= East/West-Coast Server Farms - Total Privacy via Encryption =---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: storing variable names in a list before they are used?

2006-09-30 Thread John Salerno
John Salerno wrote:

> Here is what I want to do more specifically:

Ok, I'm sure you all get the idea by now, but here's a simpler way to 
look at it:

Instead of

first_name = wx.TextCtrl(self)
last_name = wx.TextCtrl(self)
job_title = wx.TextCtrl(self)
etc.

and subsequently:

sizer.Add(first_name)
sizer.Add(last_name)
sizer.Add(job_title)
etc.

I want to do something like this:

for name in names:
 name = wx.TextCtrl(self)
 sizer.Add(name)

It's just that I don't know how to handle the "name" variable in the 
"names" list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: builtin regular expressions?

2006-09-30 Thread MRAB

Antoine De Groote wrote:
> Just to get it clear at the beginning, I started this thread. I'm not a
> newbie (don't get me wrong, I don't see this as an insult whatsoever,
> after all, you couldn't know, and I appreciate it being so nice to
> newbies anyway). I'm not an expert either, but I'm quite comfortable
> with the language by now. It's just that, when I started Python I loved
> it for its simplicity and for the small amount of code it takes to get
> something done. So the idea behind my original post was that the
> Perl/Ruby way takes even less to type (for the regex topic of this
> discussion, I'm not generalizing), and that I like a lot. To me (and I
> may be alone) the Perl/Ruby way is more "beautiful" (Python  culture:
> Beautiful is better than ugly) than the Python way (in this particular
> case) and therefore I couldn't see the reasons.
>
> Some of you say that this regex stuff is used rarely enough so that
> being verbose (and therefore more readable ?) is in these few cases the
> better choice. To me this a perfectly reasonable and maybe it is just
> true (as far as one can talk about true/false for something subjective
> as this). I dont' know (yet) ;-)
>
> I just have to learn accept the fact that Python is more verbose more
> often than Ruby (I don't know Perl really). Don't get me wrong though, I
> know the benefits of this (at least in some cases) and I can understand
> that one opts for it. Hopefully I will end up some day preferring the
> Python way.
>
One of the differences between the Python way and the Perl way is that
the Perl way has a side-effect: Perl assigns to the variables $1, $2,
etc. each time you execute a regular expression whereas Python just
returns a match object for each, so it's not overwriting the results of
the previous one. I find the Python way cleaner.

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


Native MP3 Decoder?

2006-09-30 Thread floguy
I've been working on a simple cross-platform alarm clock application in
Python.  I took the time to learn wxPython for the frontend, and
figured there would be some backend for decoding mp3s to play at alarm
time.  So far, I have found 3 viable options.

1) pyMedia, which works great, but only works on Windows XP and Linux,
and not MacOSX
2) pyGame, which seems to lack the needed SDL_mixer support for
pygame.music
3) wx.MediaCtrl, which supposedly works on Windows and MacOSX, but not
Linux

So, I began to look for a pure Python MP3 decoder.  To my surprise,
there was not one implementation to be found.  Is Python too slow for a
pure Python MP3 decoder?  I would like to help in getting something
like this started.  Unfortunately, I have almost no knowledge of the
underlying MP3 algorithm. I know that there is a MP3 decoder written in
pure Java, called javazoom, which could be drawn from heavily.

I have begun taking that code and porting it to Python, but what I
really need is an someone who is experienced who can help me out with
some of the implementation details.

If anyone knows of another project like this, an alternative that I
haven't found yet, or has experience in mp3 decoding, please respond
with your thoughts.

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


Re: Escapeism

2006-09-30 Thread Kay Schluehr
Steve Holden wrote:
> Kay Schluehr wrote:
> > Sybren Stuvel wrote:
> >
> >>Kay Schluehr enlightened us with:
> >>
> >>>Usually I struggle a short while with \ and either succeed or give up.
> >>>Today I'm in a different mood and don't give up. So here is my
> >>>question:
> >>>
> >>>You have an unknown character string c such as '\n' , '\a' , '\7' etc.
> >>>
> >>>How do you echo them using print?
> >>>
> >>>print_str( c ) prints representation '\a' to stdout for c = '\a'
> >>>print_str( c ) prints representation '\n' for c = '\n'
> >>>...
> >>>
> >>>It is required that not a beep or a linebreak shall be printed.
> >>
> >>try "print repr(c)".
> >
> >
> > This yields the hexadecimal representation of the ASCII character and
> > does not simply echo the keystrokes '\' and 'a' for '\a' ignoring the
> > escape semantics. One way to achieve this naturally is by prefixing
> > '\a' with r where r'\a' indicates a "raw" string. But unfortunately
> > "rawrification" applies only to string literals and not to string
> > objects ( such as c ). I consider creating a table consisting of pairs
> > {'\0': r'\0','\1': r'\1',...}  i.e. a handcrafted mapping but maybe
> > I've overlooked some simple function or trick that does the same for
> > me.
> >
> No, you've overlooked the fact that if you print the string containing
> the two characters "backslash" and "lower case a" then it will print
> exactly those two characters. See:
>
> In [30]: c = "\\a"
>
> In [31]: len(c)
> Out[31]: 2
>
> In [32]: print c
> \a

I'm interested in the transition between two literals from which one is
a string literal containing \ as a "meta character" s.t. '\a' has
actually length 1 and is beep when printed to stdout and its "raw" form
without a meta character interpretation of \ that leads to the result
you described. Using the string prefix r to '\a' indicates the raw form
to the compiler. But there seems to be no runtime counterpart. I've
suggested a naive implementation such as

def rawform(c):
 return {'\a': r'\a'}[c]

Here the function returns for the single input character '\a' the two
character raw form by means of escaping \ ( and raises a KeyError
exception otherwise ).

>>> c = '\a'
>>> print rawform(c)
\a

This has the same effect as writing:
>>> c = r'\a'
>>> print c
\a

But there is some ambiguity due to the the fact that applying '\7' to
rawform() yields r'\a' and not r'\7'. So one needs more specification
for disambiguation using e.g. an extra parameter.

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


Re: builtin regular expressions?

2006-09-30 Thread Thorsten Kampe
* Steve Holden (Sat, 30 Sep 2006 17:46:03 +0100)
> Mirco Wahab wrote:
> > Thus spoke Antoine De Groote (on 2006-09-30 11:24):
> Tim Peters frequently says something along the lines of "If you have a 
> problem and you try to solve it with regexes, then you have TWO 
> problems". 

It's originally from Jamie Zawinski:
'Some people, when confronted with a problem, think "I know, I'll use 
regular expressions." Now they have two problems.'

And the simple reason why Regular Expressions are not a part of the 
core Python language is that Regular Expressions are overrated. They 
are simply not the preferred tool for every kind of text manipulation 
and extraction.

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


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread BJörn Lindqvist
> How do you transform this?
>
> height = 0
> for block in stack:
>if block.is_marked():
>print "Lowest marked block is at height", height
>break
>height += block.height
> else:
>raise SomeError("No marked block")

def get_height_of_first_marked_bock(stack):
height = 0
for block in stack:
if block.is_marked():
return height
height += block.height
raise SomeError("No marked block")

height = get_height_of_first_marked_block(stack)
print "Lowest marked block is at height", height

Yes, this transformation is one line longer, but the control flow is
much easier to understand. In general, using the for/else clause mixes
the retrieval and the usage of the element. Consider this:

for item in list:
if somecond(item):
A) do something with item
break
else:
B) exceptional code when somecond() doesnt match anything in list

The code that you write in the positions A and B really are misplaced.
They arent part of the iteration of list. The two tasks, find item and
do something with item should be separated.

def find_item(list):
for item in list:
if somecond(item):
return item
return None # OR raise an exception

item = find_item(list)
if item:
A) do something with item
else:
B) exceptional code

This is, IMHO, much better style.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: builtin regular expressions?

2006-09-30 Thread Mirco Wahab
Thus spoke Jorge Godoy (on 2006-09-30 19:04):
> Mirco Wahab <[EMAIL PROTECTED]> writes:
>>   sub print_message {
>>  if   (/^track="(.+?)"/ ){ print "Your track is $1\n" }
>>  ...
> 
> Specially the non-greedy part. :-) I don't believe that non-greedyness would
> be adequate here since I believe he's willing to process the whole line.

Ohh, but I think it really is, my intention was
to get the quotet text out of the quotes, if
there is any, eg.:


   sub print_message {
  if   (/^track="(.+?)"/ ){ print "Your track is $1\n" }
  ...
   }

   print_message for 'track="My favorite track"', 'title="My favorite song"',
 'artist="Those Dudes"', 'Something else' ;

(... our quoting chars are just inverted.)

> $line = "track='My favorite track'";
> if ($line =~ /^track=(.+?)/) { print "My track is $1\n"};
> 
> outputs
> My track is '

Of course, you can't have the nongreedy thing
without a following item, in the case mentioned,
a second \" (which would have been consumed
in the 'greedy' mode).

> and what I'd use
> 
> $line = "track='My favorite track'";
> if ($line =~ /^track=(.*)/) { print "My track is $1\n"};

OK, but to pull the quoted text alone, you'd
need the non-greedy thing, as in

   ...
   if   ( /^track='(.+?)'/ ){ print "Your track is $1\n" }
   ...

Alternatively, you could use the negated character class
for that:

  if   ( /^track='([^']+)/ ){ print "Your track is $1\n" }

which has exactly the same character count (so taste matters here) ...

Regards

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


Re: Mark Lutz Python interview

2006-09-30 Thread Mark Lutz

Fuzzyman wrote:
> Mark Lutz wrote:
> > Python author and trainer Mark Lutz will be interviewed
> > on the radio show Tech Talk this Sunday, October 1st,
> > at 6PM Eastern time.  He'll be answering questions about
> > Python, his books, and his Python training services.
> >
>
> Does he always talk in the third person ? ;-)

Yes, I've heard that he does. :-)

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


Re: loop over list and modify in place

2006-09-30 Thread James Stroud
Daniel Nogradi wrote:
> Is looping over a list of objects and modifying (adding an attribute
> to) each item only possible like this?
> 
> mylist = [ obj1, obj2, obj3 ]
> 
> for i in xrange( len( mylist ) ):
>mylist[i].newattribute = 'new value'
> 
> 
> I'm guessing there is a way to do this without introducing the (in
> principle unnecessary) index i, so what I'm really looking for is a
> looping method which doesn't pass references to the values of the
> items but to the items themselves.

You can use map, or if you don't map, like list comprehension:

py> class B(object):
...   def __repr__(self):
... return ': %s' % self.value
...   def __init__(self):
... self.value = None
...
py> alist = [B() for i in xrange(5)]
py> alist
[: None, : None, : None, : None, : None]
py> [setattr(b,'value',v+5) for (v,b) in enumerate(alist)]
[None, None, None, None, None]
py> alist
[: 5, : 6, : 7, : 8, : 9]
py> map(setattr, alist, ['value']*5, xrange(5))
[None, None, None, None, None]
py> alist
[: 0, : 1, : 2, : 3, : 4]

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Typing UTF-8 characters in IDLE

2006-09-30 Thread [EMAIL PROTECTED]
thanks, it is useful.

but ,why this line "encoding = locale.getdefaultlocale()[1]" in
original file"IOBinding.py " ,
don't work?

it should be work



kazuo fujimoto wrote:
> Ricky,
>
> I found your message now, because I also would encounter the same
> problem.
>
>
> > A few unicode tutorials on the web show that it's possible to type
> > unicode characters into the IDLE gui...
> >
> > However, when i type korean (hangul) characters it complains:
> >
> > Unsupported Characters in input
> >
> > I don't have a great understanding of unicode, but when I use a UTF-8
> > source file with korean strings in, and run it as a CGI script it
> > works fine.
> >
> > I'm using python 2.3.3 on win XP.
> >
> > Any tutorials / info anyone could point me to? Thanks...
>
> Now I am using Hangle with Japaese.
>
> What I did is as follow.
>
> My Python is now 2.4.3
>
> 1) open the IOBinding.py in $python/idellib
> 2) see the block just after line35, and insert one line.
> 
> encoding = "ascii"   # line 35
> if sys.platform == 'win32':
> # On Windows, we could use "mbcs". However, to give the user
> # a portable encoding name, we need to find the code page
> try:
> encoding = locale.getdefaultlocale()[1]
> codecs.lookup(encoding)
> except LookupError:
> pass
> encoding = 'utf-8' ## <- this line force the encoding to utf-8.
> -
> 3) save the file and quit Idle and reopen Idle.
>
> I hope my experience will solve your problem.
>
> (It has passed 2 years and more, so you might already solve the problem.
> I you know better solution, please inform me.)
> 
> kazuo

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


Re: Native MP3 Decoder?

2006-09-30 Thread MonkeeSage
[EMAIL PROTECTED] wrote:
> If anyone knows of another project like this, an alternative that I
> haven't found yet, or has experience in mp3 decoding, please respond
> with your thoughts.

There's pymad ( http://spacepants.org/src/pymad/ ); haven't tried but
it should work everywhere libmad does.

Regards,
Jordan

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


Re: builtin regular expressions?

2006-09-30 Thread Mirco Wahab
Thus spoke MRAB (on 2006-09-30 20:54):
> Antoine De Groote wrote:
>> I just have to learn accept the fact that Python is more verbose more
>> often than Ruby (I don't know Perl really). 
>
> One of the differences between the Python way and the Perl way is that
> the Perl way has a side-effect: Perl assigns to the variables $1, $2,
> etc. each time you execute a regular expression whereas Python just
> returns a match object for each, so it's not overwriting the results of
> the previous one. I find the Python way cleaner.

This statement reduces to the fact, that

 - in Python you keep the matches if you want,
   but drop them if you don't

   import re
   text = "this is 5 some 89 stuff 12 with numbers 21 interspersed"
   matches =  re.split('\D+', text)

 - in Perl you keep the matches if you want,
   but drop them if you don't

   $text = "this is 5 some 89 stuff 12 with numbers 21 interspersed";
   @matches = $text=~/(\d+)/g;

I fail to see the benefit of a re-object, I consider these to
be just there because regexes aren't in the core language.

Regards

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


Re: Computer Language Popularity Trend

2006-09-30 Thread Arne Vajhøj
Danno wrote:
> Xah Lee wrote:
>> This page gives a visual report of computer languages's popularity, as
>> indicated by their traffic level in newsgroups. This is not a
>> comprehensive or fair survey, but does give some indications of
>> popularity trends.
>>
>> http://xahlee.org/lang_traf/index.html
> 
> Wow, java is a low level industrial language? ;)

Compared to Python, Ruby etc. - yes.

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


PyXML not supported, what to use next?

2006-09-30 Thread Paul Watson
It would appear that xml.dom.minidom or xml.sax.* might be the best 
thing to use since PyXML is going without support.  Best of all it is 
included in the base Python distribution, so no addition hunting required.

Is this right thinking?  Is there a better solution?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Native MP3 Decoder?

2006-09-30 Thread floguy
I did see that, but that seems to only work on Lin/Unix.  In fact, the
only way that I can see to install that package is using distutils and
the config_unix.py script, which indicates to me that it works only on
Lin/Unix.

If I'm mistaken, please let me know.

MonkeeSage wrote:
> [EMAIL PROTECTED] wrote:
> > If anyone knows of another project like this, an alternative that I
> > haven't found yet, or has experience in mp3 decoding, please respond
> > with your thoughts.
>
> There's pymad ( http://spacepants.org/src/pymad/ ); haven't tried but
> it should work everywhere libmad does.
> 
> Regards,
> Jordan

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


Upgrading Problems

2006-09-30 Thread Javier Subervi
Hi;I have python 2.3.5 and I'd like to upgrade to 2.5.0. I've tried installing from FreeBSD ports and the oldfashioned way from source code, with the "configure && make && make install" dance, and still when I call up my python interpreter it tells me I'm in 2.3.5! Why? I didn't do "altinstall"! What gives?TIA,Javier2 
		Do you Yahoo!? 
Get on board. You're invited to try the new Yahoo! Mail.-- 
http://mail.python.org/mailman/listinfo/python-list

  1   2   >