Re: Re: Guido's new method definition idea

2008-12-06 Thread acerimusdux

Russ P. wrote:

Python already uses shorthand extensively. How about "def"? For people
who are so worried about self-explanatory symbols, what the heck does
that stand for? Default? Defeat? Defect? Defunct? Defer?


  


I think the difference here is that those other  abbreviations are 
mostly fairly standard. The "def" keyword is the same in Ruby, and 
similar enough to "define" or "defun" in Scheme or LISP. The "!=" 
operator is pretty much standard across nearly all languages. What is 
being proposed with "$" here though, would be different from how it is 
used anywhere else and would be confusing.


Moreover, I especially don't like proposing to eliminate as well in this 
instance the "dot notation", which is standard in nearly all object 
oriented languages. Using something as a substitute for "self" is one 
thing, and you can mostly use what you like there now, as "self" is more 
a convention than a requirement.  But the "dot" that belongs there is 
critical to understanding, you can't hide that to save one keystroke.


Getting back to Guido's suggestion, though, I think it makes some sense. 
Being new to Python, I did find myself occasionally forgetting "self" in 
instance methods. But, I also thought the requirement to include it was 
helpful in reminding me what was really going on there, that I was 
creating an instance method which was really a function that wouldn't 
actually be created until the instance was initiated.  I tend to think 
this may be clearer though using the dot notation rather than passing 
the instance variable as a parameter.


I'm not sure though whether allowing both syntaxes would make things 
more or less confusing. It might actually be helpful in some respects 
for newcomers to realize that self.method(arg) is somewhat the same as 
method(self, arg).  Perhaps I'm wrong on this, I don't fully understand 
yet what is going on under the hood, but it seems to me that that would 
be part of the glue that allows Python to be so multi-paradigm; much of 
the difference between OOP and procedural or functional is just 
different syntax for the same thing.




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


hifriends

2008-12-06 Thread deen . vdm
hi,visit the web for download the latest songs and music by
clickhttp://musicsite-download.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Don't you just love writing this sort of thing :)

2008-12-06 Thread Stefan Behnel
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Arnaud Delobelle wrote:
> 
>>   * you seem to disregard the fact that in 'programming language' there
>> is the word 'language'.  A language is a way to _communicate_
>> information, in the case of a programming language you communicate
>> it to the computer but also to other human beings.
> 
> It was Niklaus Wirth, I think who pointed out that programming languages are
> not properly "languages" but are actually "notations". Like mathematics is
> a notation.
> 
> And mathematics, too, is a predominantly functional, not a procedural,
> notation. Could that be why so many people are frightened of functional
> constructs, like my code example and things like lambdas? Because they look
> too much like mathematics?

That's not the impression I got from reading this thread.

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


Re: Don't you just love writing this sort of thing :)

2008-12-06 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Arnaud Delobelle wrote:

>   * you give the impression of being arrogant;

Oddly enough, I wasn't the one who started by criticizing other people's
code. I have no ego about my code; I gladly accept criticisms. But perhaps
some other people are not so thick-skinned and do not like getting as they
give...
--
http://mail.python.org/mailman/listinfo/python-list


Brain going crazy with recursive functions

2008-12-06 Thread 5lvqbwl02
I'm trying to solve the 9-tile puzzle using as functional an approach
as possible.  I've recently finished reading SICP and am deliberately
avoiding easy python-isms for the more convoluted scheme/functional
methods.  The following function is trivial to do with for loops and
directly accessing arrays with [] syntax.  I'm trying to limit myself
to the types of idioms/semantics one finds in minimal scheme, such as
in SICP.  I want eventually to port this to scheme, but I know python
better, so that's where I'm starting.

My current problem is the following.  The 9-tile puzzle consists of a
list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers
can be jumbled up.  I'm looking for the location of the zero using
*only* recursion and operators that are similar to car/cdr.  The
return value should be the row,col of the zero.  For example above
the
return value would be (2,2).

I'm also trying to define a single "linear_search(...)" function
which
does the search for within the row (an inner list above) and within
the whole list.  linear_search takes as an argument a
"truth_function"
which does the actual work.  What's tricky is that the truth function
for the array-as-a-whole is also the linear_search for a row.  Once
I'm in linear_search for the array, I also call linear_search for
each
row.

The problem is the line where it says acc.insert(0,idx) looks fishy
to
me.  It works fine and returns the row,col of the location of the
zero
tile, but it seems to be mutating a variable, and that's the thing
I'm
trying to avoid.  In a sense, it's not hard enough and python is
making this too easy :)  (although it took a bit of mind-wrenching to
get to this point.  Recursion makes you either dumber or smarter, I'm
not sure which).

How do I accumulate the inner value of the search so it pops out at
the end, without resorting to a mutable variable?  I did a bit of
search and the word "monad" came up, but I'm not sure what that is (I
know it relates to haskell and some other purely functional stuff,
but
I get very lost when trying to read that stuff).




def linear_search(array, truth_func, acc):
# Goes through each element of array and applies truth_func.
# Returns index if found, otherwise returns None
def linear_search_iter(idx, truth_func, arr, acc):
if arr:
tf = truth_func(arr[0])
if tf or type(tf) is int:
acc.insert(0,idx)
return idx, acc+[idx]
else:
return linear_search_iter(idx+1, truth_func, 
arr[1:], acc)
return linear_search_iter(0, truth_func, array, acc)



def locate_zero(p):
# Locates empty tile.  Returns (r,c) tuple
def find_zero_in_row(row):
return linear_search(row, lambda x: x==0, acc)

acc = []
ls = linear_search(p, find_zero_in_row, acc)
print acc
return acc

locate_zero([[5, 3, 4], [2, 0, 1], [8, 6, 7]]) correctly returns (1,1)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Don't you just love writing this sort of thing :)

2008-12-06 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Arnaud Delobelle wrote:

>   * you seem to disregard the fact that in 'programming language' there
> is the word 'language'.  A language is a way to _communicate_
> information, in the case of a programming language you communicate
> it to the computer but also to other human beings.

It was Niklaus Wirth, I think who pointed out that programming languages are
not properly "languages" but are actually "notations". Like mathematics is
a notation.

And mathematics, too, is a predominantly functional, not a procedural,
notation. Could that be why so many people are frightened of functional
constructs, like my code example and things like lambdas? Because they look
too much like mathematics?
--
http://mail.python.org/mailman/listinfo/python-list


Brain going crazy with recursive functions

2008-12-06 Thread 5lvqbwl02
I'm trying to solve the 9-tile puzzle using as functional an approach
as possible.  I've recently finished reading SICP and am deliberately
avoiding easy python-isms for the more convoluted scheme/functional
methods.  The following function is trivial to do with for loops and
directly accessing arrays with [] syntax.  I'm trying to limit myself
to the types of idioms/semantics one finds in minimal scheme, such as
in SICP.  I want eventually to port this to scheme, but I know python
better, so that's where I'm starting.

My current problem is the following.  The 9-tile puzzle consists of a
list of lists like this [[1,2,3],[4,5,6],[7,8,0]], where the numbers
can be jumbled up.  I'm looking for the location of the zero using
*only* recursion and operators that are similar to car/cdr.  The
return value should be the row,col of the zero.  For example above the
return value would be (2,2).

I'm also trying to define a single "linear_search(...)" function which
does the search for within the row (an inner list above) and within
the whole list.  linear_search takes as an argument a "truth_function"
which does the actual work.  What's tricky is that the truth function
for the array-as-a-whole is also the linear_search for a row.  Once
I'm in linear_search for the array, I also call linear_search for each
row.

The problem is the line where it says acc.insert(0,idx) looks fishy to
me.  It works fine and returns the row,col of the location of the zero
tile, but it seems to be mutating a variable, and that's the thing I'm
trying to avoid.  In a sense, it's not hard enough and python is
making this too easy :)  (although it took a bit of mind-wrenching to
get to this point.  Recursion makes you either dumber or smarter, I'm
not sure which).

How do I accumulate the inner value of the search so it pops out at
the end, without resorting to a mutable variable?  I did a bit of
search and the word "monad" came up, but I'm not sure what that is (I
know it relates to haskell and some other purely functional stuff, but
I get very lost when trying to read that stuff).

def linear_search(array, truth_func, acc):
# Goes through each element of array and applies truth_func.
# Returns index if found, otherwise returns None
def linear_search_iter(idx, truth_func, arr, acc):
if arr:
tf = truth_func(arr[0])
if tf or type(tf) is int:
acc.insert(0,idx)
return idx, acc+[idx]
else:
return linear_search_iter(idx+1, truth_func, 
arr[1:], acc)
return linear_search_iter(0, truth_func, array, acc)



def locate_zero(p):
# Locates empty tile.  Returns (r,c) tuple
def find_zero_in_row(row):
return linear_search(row, lambda x: x==0, acc)

acc = []
ls = linear_search(p, find_zero_in_row, acc)
print acc
return acc

locate_zero(def linear_search(array, truth_func, acc):
# Goes through each element of array and applies truth_func.
# Returns index if found, otherwise returns None
def linear_search_iter(idx, truth_func, arr, acc):
if arr:
tf = truth_func(arr[0])
if tf or type(tf) is int:
acc.insert(0,idx)
return idx, acc+[idx]
else:
return linear_search_iter(idx+1, truth_func, 
arr[1:], acc)
return linear_search_iter(0, truth_func, array, acc)



def locate_zero(p):
# Locates empty tile.  Returns (r,c) tuple
def find_zero_in_row(row):
return linear_search(row, lambda x: x==0, acc)

acc = []
ls = linear_search(p, find_zero_in_row, acc)
print acc
return acc

locate_zero([[5, 3, 4], [2, 0, 1], [8, 6, 7]])

returns the correct value of [1,1].

Any suggestions please?

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


Re: Don't you just love writing this sort of thing :)

2008-12-06 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Rhodri
James wrote:

> Yes, it's very pretty, and you're terribly clever.  In six months' time
> when you come back to make some engineering change and have to sit down
> and break it back down into those simple pieces to remind yourself what
> it's doing, "pretty" and "clever" will not be the words you are using. 
> Trust me on this one.

Considering I've been writing and maintaining and debugging code for about
30 years now, I figure I have the hard-earned right to judge what I will be
able to understand in six months and what I won't...

-- 
Lawrence "Been There, Done That" D'Oliveiro
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Lie
On Dec 6, 9:21 am, "Daniel Fetchinson" <[EMAIL PROTECTED]>
wrote:
> Hi folks,
>
> The story of the explicit self in method definitions has been
> discussed to death and we all know it will stay. However, Guido
> himself acknowledged that an alternative syntax makes perfect sense
> and having both (old and new) in a future version of python is a
> possibility since it maintains backward compatibility. The alternative
> syntax will be syntactic sugar for the old one. This blog post of his
> is what I'm talking about:
>
> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay...
>
> The proposal is to allow this:
>
> class C:
>     def self.method( arg ):
>         self.value = arg
>         return self.value
>
> instead of this:
>
> class C:
>     def method( self, arg ):
>         self.value = arg
>         return self.value
>
> I.e. explicit self stays only the syntax is slightly different and may
> seem attractive to some. As pointed out by Guido classmethods would
> work similarly:
>
> class C:
>     @classmethod
>     def cls.method( arg ):
>         cls.val = arg
>         return cls.val

To sum up:

Arguments on Status Quo:
+ Andreas Waldenburger: it works and there just is no need to change
it
+ need no change
+ Andreas Waldenburger: Getting the Python comunity to replace self
with something shorter will never compensate for the time you spent
bullying it through
- Confusion for number of parameters
- The standard 'self' is too long
- Newbie FAQ
- It is ugly

Arguments on "def self.method(" as "def method(self" inside a class:
+ OP: It reduces confusion for number of parameters
+ Patrick Mullen: The symetry of "def self.func(blah)==def func
(self,blah)" and "ob.func(blah)==func(ob.blah)" is kind of neat.
+ OP: Backward compatible
+ OP: It is explicit
- Marc 'Blackjack' Rintsch: they [newcomers] will run into *both*
variants in tutorials, code, and books, so it might be even more
confusing.
- Carl Banks: def ():  ==  = , but def self.method(): return 1 != self.method = lambda: 1
- `self` in this context might be misconstrued as the class object and
thus `def self.foo` might be misunderstood ... as a defining a
classmethod rather than an instance method.
- It is ugly
? Syntax sugar or replacement? Many people prefers this to be
replacement to reduce confusion.

Arguments on variants of $
+ Russ P.: looks like S(elf)
+ Russ P.: more succinct with no loss of readability
- Antoine de Groote: slightly less readable.
- Antoine de Groote: wouldn't require this new syntax (def meth($,
args): $.foo)
- Andreas Waldenburger: "self" is a speaking identifier, "$" isn't
- Obscure symbol
- It is ugly

Unresolved:
? Patrick Mullen: Outside a class definition?

I think we have to test this on newbies. Personally, I think the new
syntax would confuse newbies too, though not as much as the tricky
error message we currently have (code: foo.bar(1, 2, 3, 4); Error:
TypeError: foo() takes exactly 4 arguments (5 given); Newbie: "what
the... 1.. 2.. 3.. 4.., I correctly gave 4 arguments, python counted
the wrong number of arguments").

If this dead horse is revived because of that reason, then I'd go with
changing the error message to something that is less confusing to
newbies[1]. I remember being tripped with the (thinking that python
miscounted the number of argument) when I was new. This has the
advantage of backward compatibility and no syntax change, just less
misleading error message.

[1] anything could work, but I like this one: (c is an instance of
class C)
if the code is: c.foo(...), Error: "TypeError: c.foo() takes exactly 3
argument"
while if the code is: C.foo(...), Error: "C.foo() takes exactly 4
arguments"
You can implement c.foo as a curried C.foo function, catch C.foo's
TypeError exception then reraise it as c.foo exception.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Lie
On Dec 7, 1:02 am, News123 <[EMAIL PROTECTED]> wrote:
> What would be interesting would be some syntactical sugar to get rid of
> the 'self' (at least in the code body).
>
> example:
> class C:
>     class_elements a,b,c,d
>
>     def method(self,arg):
>         global d
>         a,b,c = arg[0..3]
>         d = a + b
>         self.e = a + d
>

Nah, that would make it not explicit. Explicit here also means that to
refer to self's a, we need to explicitly refer to self.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python now coming from Perl

2008-12-06 Thread Aahz
In article <[EMAIL PROTECTED]>,
Bertilo Wennergren  <[EMAIL PROTECTED]> wrote:
>
>The main reason I waited until Python 3000 came out is the new way
>Unicode is handled. The old way seemed really broken to me. Much of
>what I do when I program consists of juggling Unicode text (real
>Unicode text with lots of actual characters outside of Latin 1). So in
>my case learning version 2.x first might not be very convenient.  I'd
>just get bogged down with the strange way 2.x handles such data. I'd
>rather skip that completely and just go with the Unicode handling in
>3.0.

Sounds like you have a good use-case for 3.0 -- go to it!
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: "as" keyword woes

2008-12-06 Thread Mensanator
On Dec 6, 9:09�pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 06 Dec 2008 18:09:07 -0800, Mensanator wrote:
> > On Dec 6, 6:25 pm, Steven D'Aprano <[EMAIL PROTECTED]
> > cybersource.com.au> wrote:
> >> On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote:
> >> > It was extremely simple for me to fix the sympy module where I
> >> > noticed it. I'm not saying it wasn't a problem, I'm saying it wasn't
> >> > BROKEN.
>
> >> If it wasn't broken, why did you need to fix it?
>
> > If my tire is flat, I have to fix it. But it may just need air, in which
> > case it's not broken.
>
> In which case it doesn't need *fixing*,

The state of the tire being flat has to be fixed, but not
necessarily the tire.

> it needs *refilling*. A flat tire
> isn't necessarily broken. It is broken if it has a puncture or a slow
> leak or has been ripped to shreds, but not if somebody merely let the air
> out. "Air comes out if you open the value" is within standard operating
> parameters and the tire is therefore working correctly.

Just as "as" producing a syntax error is working correctly.

>
> >> "Broken" means "not working", not "unfixable".
>
> > So, you're saying that Python is broken and will remain so forever,
> > since "as" will remain a keyword?
>
> I don't think that having "as" be a keyword is broken.

But WS does and you appear to be taking his side.

> I think the OP's
> code is broken for Python 2.6 or better,

So do I. Why are you arguing then? Simply to be pedantic
about the meaning of "broken"?

> and it will remain broken
> forever unless he fixes it or chooses to stay with 2.5.
>
> > Are you advocating that we all switch to Ruby?
>
> Why do you think that?

Because seem to be agreeing that the problem is with Python.
If that's not what you meant, it's not coming across that way.

> Do you imagine that Ruby has no features which are
> inconvenient to users, or backwards incompatibilities, or warts, or that
> it is impossible to write broken Ruby code?

Who knows what you believe if you're agrreing that Python is
permanently broken?

>
> --
> Steven

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


Re: "as" keyword woes

2008-12-06 Thread Warren DeLano
> Date: Sat, 6 Dec 2008 12:13:16 -0800 (PST)
> From: Carl Banks <[EMAIL PROTECTED]>
> Subject: Re: "as" keyword woes
> To: python-list@python.org
> Message-ID:
>
> (snip)
>   
> If you write a PEP, I advise you to try to sound less whiny and than
> you have in this thread.  
>
> (snip)

Ehem, well, such comments notwithstanding, I thank everyone who
responded to my latest post on this topic for taking my inquiry
seriously, and for providing cogent, focused, well-reasoned feedback
while not resorting to name-calling, to false accusations on top of
baseless assumptions, or to explicit personal attacks on my competence,
sincerity, experience, credibility, or form.  

To you especially, I am grateful for your input for your years of
service to the community and to the noble ideals you embody in the
Python project.  May the rest of us (not just myself) be ashamed of our
lesser conduct and learn from you exemplary performance.

So to summarize, having assimilated all responses over the past several
days (python-list as well as python-dev, for the newcomers), I now
accept the following as self-evident:

-> "as", as a Python keyword, is a here to stay:  Love it or leave it.

-> Likewise ditto for the GIL: if you truly need Python concurrency
within a single process, then use a Python implementation other than
CPython.

Season's greetings to all!  Peace.

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


Re: Learning Python now coming from Perl

2008-12-06 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "Python Nutter" <[EMAIL PROTECTED]> wrote:

> At least if you push REs inform the readers where to get the a RE GUI
> builder written in Python so they can build and *test* the complex and
> unwieldy REs to perform anything beyond the basic pattern searches.

Oh, my, I think my brain's about to explode.  A RE GUI builder?  Cough, 
gasp, sputter.  This is literally the first time I've ever heard of such a 
thing, and it's leaving a bad taste in my mouth.

RE is the last bastion of Real Programmers.  Real Programmers don't use GUI 
builders.  Using a GUI to build an RE is like trying to program by pushing 
little UMLish things around with a mouse.  It's Just Wrong.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Cameron Simpson
On 06Dec2008 11:30, Andreas Waldenburger <[EMAIL PROTECTED]> wrote:
| On 6 Dec 2008 09:18:20 GMT Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]>
| wrote:
| > On Sat, 06 Dec 2008 09:56:12 +0100, Antoine De Groote wrote:
| > [snip reference to "preferably only one way to do it"]
| > 
| > The reason why I'm against that change too.  It adds a second, 
| > alternative way to express something that is already in the language.
| > 
| > > I agree that for newcomers to Python, the class method definition
| > > might seem strange.
| > 
| > And after the change it continues to because they will run into
| > *both* variants in tutorials, code, and books, so it might be even
| > more confusing.
| > 
| I agree with that view. Not much to add to it, just increasing the
| weight.

Me too. And it smells like Perl if we let the $ get in there. And it doesn't
add any facility to the language - it's just syntactic lint.

So -1 from me.
-- 
Cameron Simpson <[EMAIL PROTECTED]> DoD#743
http://www.cskk.ezoshosting.com/cs/
--
http://mail.python.org/mailman/listinfo/python-list


Number of Python 3.x packages at the PyPI

2008-12-06 Thread excord80
Is there an easy way to see the number of PyPI packages which have
been ported to Python 3?

Are there any special arrangements necessary for PyPI packages which
have both a Python 2.x version and a Python 3.x version?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Carl Banks
On Dec 6, 6:42 pm, "Russ P." <[EMAIL PROTECTED]> wrote:
> > But it's ugly.  No amount of rationalization will make it not ugly.
>
> The dollar sign is ugly? I beg to differ.

Nope, you're wrong.


Carl Banks

(See where this is going?)
--
http://mail.python.org/mailman/listinfo/python-list


Re: "as" keyword woes

2008-12-06 Thread Carl Banks
On Dec 6, 8:17 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 07 Dec 2008 11:27:56 +1000, Nick Coghlan wrote:
> > Warren DeLano wrote:
> >> In other words we have lost the ability to refer to "as" as the
> >> generalized OOP-compliant/syntax-independent method name for casting:
>
> > Other possible spellings:
>
> > # Use the normal Python idiom for avoiding keyword clashes # and append
> > a trailing underscore
> > new_object = old_object.as_(class_hint) float_obj = int_obj.as_("float")
> > float_obj = int_obj.as_(float_class)
>
> > # Use a different word (such as, oh, "cast" perhaps?) new_object =
> > old_object.cast(class_hint) float_obj = int_obj.cast("float")
> > float_obj = int_obj.cast(float_class)
>
> I don't like "cast", because a cast is an instruction to the compiler to
> treat data as some type other than what it was defined as.
It doesn't
> create a new piece of data. (At least in C-like languages.)

Actually, C-like languages do exactly that.  (float)i doesn't take the
bits of int i and treat them as if they were a float, it creates new
data in the appropriate data type that matches the value of i
semantically, which would have a very different bit pattern.

Pointer-to-int and pointer-to-pointer typecasts are really the only
ones that tend to preserve the bits of the data (which, since they are
the most common kinds of typecast, has misled some people to think
that typecasts in C are all about preserving bits).  However, in
general typecasts preserve the semantic value of the original data.

That's exactly what these methods would be doing, changing the type
while preserving the semantic value as much as possble, so cast is a
perfectly appropriate name for it.

(BTW, in C++, even pointer-to-pointer static casts don't always
preserve the bits.)


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


Re: Python 3.0 automatic decoding of UTF16

2008-12-06 Thread John Machin
On Dec 7, 9:34 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Dec 7, 9:01 am, David Bolen <[EMAIL PROTECTED]> wrote:
>
> > Johannes Bauer <[EMAIL PROTECTED]> writes:
> > > This is very strange - when using "utf16", endianness should be detected
> > > automatically. When I simply truncate the trailing zero byte, I receive:
>
> > Any chance that whatever you used to "simply truncate the trailing
> > zero byte" also removed the BOM at the start of the file?  Without it,
> > utf16 wouldn't be able to detect endianness and would, I believe, fall
> > back to native order.
>
> When I read this, I thought "O no, surely not!". Seems that you are
> correct:
> [Python 2.5.2, Windows XP]
> | >>> nobom = u'abcde'.encode('utf_16_be')
> | >>> nobom
> | '\x00a\x00b\x00c\x00d\x00e'
> | >>> nobom.decode('utf16')
> | u'\u6100\u6200\u6300\u6400\u6500'
>
> This may well explain one of the Python 3.0 problems that the OP's 2
> files exhibit: data appears to have been byte-swapped under some
> conditions. Possibility: it is reading the file a chunk at a time and
> applying the utf_16 encoding independently to each chunk -- only the
> first chunk will have a BOM.

Well, no, on further investigation, we're not byte-swapped, we've
tricked ourselves into decoding on odd-byte boundaries.

Here's the scoop: It's a bug in the newline handling (in io.py, class
IncrementalNewlineDecoder, method decode). It reads text files in 128-
byte chunks. Converting CR LF to \n requires special case handling
when '\r' is detected at the end of the decoded chunk n in case
there's an LF at the start of chunk n+1. Buggy solution: prepend b'\r'
to the chunk n+1 bytes and decode that -- suddenly with a 2-bytes-per-
char encoding like UTF-16 we are 1 byte out of whack. Better (IMVH[1]
O) solution: prepend '\r' to the result of decoding the chunk n+1
bytes. Each of the OP's files have \r on a 64-character boundary.
Note: They would exhibit the same symptoms if encoded in utf-16LE
instead of utf-16BE. With the better solution applied, the first file
[the truncated one] gave the expected error, and the second file [the
apparently OK one] gave sensible looking output.

[1] I thought it best to be Very Humble given what you see when you
do:
   import io
   print(io.__author__)
Hope my surge protector can cope with this :-)
^%!//()
NO CARRIER
--
http://mail.python.org/mailman/listinfo/python-list


Re: operators as variables

2008-12-06 Thread James Stroud

macc_200 wrote:

Hi,
just starting programming and have an elementary question after 
playing around with lists but cannot find the answer with googling.
I have a list of variables and I would like some of those variables to 
be integers and some to be operators so the list would look something 
like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get 
10).  How do you make the interpreter see the operator as that instead 
of a string and just echo the list back to me.


Your specification is ambiguous because you mention lists but wrote an 
evaluable expression inside of brackets. Others have answered the 
question you probably really are asking. For fun, though, I'm going to 
pretend you meant "list" and not whatever [5 * 4 - 4 + 6] is:


import operator

opdict = {'+' : operator.add,
  '-' : operator.sub,
  '*' : operator.mul,
  '/' : operator.div}

def take_two(aniterable):
  assert len(aniterable) % 2 == 0
  aniter = iter(aniterable)
  while True:
try:
  yield aniter.next(), aniter.next()
except StopIteration:
  break

def reductifier(alist):
  value = alist.pop(0)
  for op, operand in take_two(alist):
value = opdict[op](value, operand)
  return value

reductifier([5, "*", 4, "-", 4, "+", 6])
--
http://mail.python.org/mailman/listinfo/python-list


Re: "as" keyword woes

2008-12-06 Thread Steven D'Aprano
On Sat, 06 Dec 2008 18:09:07 -0800, Mensanator wrote:

> On Dec 6, 6:25�pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
>> On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote:
>> > It was extremely simple for me to fix the sympy module where I
>> > noticed it. I'm not saying it wasn't a problem, I'm saying it wasn't
>> > BROKEN.
>>
>> If it wasn't broken, why did you need to fix it?
> 
> If my tire is flat, I have to fix it. But it may just need air, in which
> case it's not broken.

In which case it doesn't need *fixing*, it needs *refilling*. A flat tire 
isn't necessarily broken. It is broken if it has a puncture or a slow 
leak or has been ripped to shreds, but not if somebody merely let the air 
out. "Air comes out if you open the value" is within standard operating 
parameters and the tire is therefore working correctly.



>> "Broken" means "not working", not "unfixable".
> 
> So, you're saying that Python is broken and will remain so forever,
> since "as" will remain a keyword?

I don't think that having "as" be a keyword is broken. I think the OP's 
code is broken for Python 2.6 or better, and it will remain broken 
forever unless he fixes it or chooses to stay with 2.5.

> Are you advocating that we all switch to Ruby?

Why do you think that? Do you imagine that Ruby has no features which are 
inconvenient to users, or backwards incompatibilities, or warts, or that 
it is impossible to write broken Ruby code?



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


Re: Learning Python now coming from Perl

2008-12-06 Thread MRAB

Bertilo Wennergren wrote:

Aahz wrote:


In article <[EMAIL PROTECTED]>,



Bertilo Wennergren  <[EMAIL PROTECTED]> wrote:



I don't suppose there is any introductory material out there that is
based on Python 3000 and that is also geared at people with a Perl
background? Too early for that I guess..



Honestly, the differences between 2.x and 3.0 are small enough that it
doesn't much matter, as long as you're not the kind of person who gets
put off by little problems.  Because so much material is for 2.x, you
may be better off just learning 2.x first and then moving to 3.x.


The main reason I waited until Python 3000 came out is
the new way Unicode is handled. The old way seemed really
broken to me. Much of what I do when I program consists
of juggling Unicode text (real Unicode text with lots of
actual characters outside of Latin 1). So in my case
learning version 2.x first might not be very convenient.
I'd just get bogged down with the strange way 2.x handles
such data. I'd rather skip that completely and just go
with the Unicode handling in 3.0.

I wouldn't have said it was broken, it's just that it was a later 
addition to the language and backwards compatibility is important. 
Tidying things which would break backwards compatibility in a big way 
was deliberately left to a major version, Python 3.

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


Re: [Python-Dev] "as" keyword woes

2008-12-06 Thread Steven D'Aprano
On Sun, 07 Dec 2008 11:27:56 +1000, Nick Coghlan wrote:

> Warren DeLano wrote:
>> In other words we have lost the ability to refer to "as" as the
>> generalized OOP-compliant/syntax-independent method name for casting:
> 
> Other possible spellings:
> 
> # Use the normal Python idiom for avoiding keyword clashes # and append
> a trailing underscore
> new_object = old_object.as_(class_hint) float_obj = int_obj.as_("float")
> float_obj = int_obj.as_(float_class)
> 
> # Use a different word (such as, oh, "cast" perhaps?) new_object =
> old_object.cast(class_hint) float_obj = int_obj.cast("float")
> float_obj = int_obj.cast(float_class)


I don't like "cast", because a cast is an instruction to the compiler to 
treat data as some type other than what it was defined as. It doesn't 
create a new piece of data. (At least in C-like languages.)

I'd prefer a method like obj.make_from(type) or obj.export_as(type) or 
similar. It's more verbose than "as" but its more explicit about what it 
does. obj.as(type) is ambiguous, because it could mean any "return a new 
object of type made from obj", "return obj inside a wrapper that makes it 
behave as if it were type", "convert obj to type in place".


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


Re: "as" keyword woes

2008-12-06 Thread Mensanator
On Dec 6, 6:25�pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote:
> > It was extremely simple for me to fix the sympy module where I noticed
> > it. I'm not saying it wasn't a problem, I'm saying it wasn't BROKEN.
>
> If it wasn't broken, why did you need to fix it?

If my tire is flat, I have to fix it. But it may just need air,
in which case it's not broken.

>
> "Broken" means "not working", not "unfixable".

So, you're saying that Python is broken and will remain so forever,
since "as" will remain a keyword?

Are you advocating that we all switch to Ruby?

>
> --
> Steven

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


Re: Learning Python now coming from Perl

2008-12-06 Thread Bertilo Wennergren

Aahz wrote:


In article <[EMAIL PROTECTED]>,



Bertilo Wennergren  <[EMAIL PROTECTED]> wrote:



I don't suppose there is any introductory material out there that is
based on Python 3000 and that is also geared at people with a Perl
background? Too early for that I guess..



Honestly, the differences between 2.x and 3.0 are small enough that it
doesn't much matter, as long as you're not the kind of person who gets
put off by little problems.  Because so much material is for 2.x, you
may be better off just learning 2.x first and then moving to 3.x.


The main reason I waited until Python 3000 came out is
the new way Unicode is handled. The old way seemed really
broken to me. Much of what I do when I program consists
of juggling Unicode text (real Unicode text with lots of
actual characters outside of Latin 1). So in my case
learning version 2.x first might not be very convenient.
I'd just get bogged down with the strange way 2.x handles
such data. I'd rather skip that completely and just go
with the Unicode handling in 3.0.

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


Re: Guido's new method definition idea

2008-12-06 Thread Jeremiah Dodds
On Fri, Dec 5, 2008 at 9:21 PM, Daniel Fetchinson <[EMAIL PROTECTED]
> wrote:

>
> The proposal is to allow this:
>
> class C:
>def self.method( arg ):
>self.value = arg
>return self.value
>
> instead of this:
>
> class C:
>def method( self, arg ):
>self.value = arg
>return self.value
>
> I.e. explicit self stays only the syntax is slightly different and may
> seem attractive to some. As pointed out by Guido classmethods would
> work similarly:
>
> class C:
>@classmethod
>def cls.method( arg ):
>cls.val = arg
>return cls.val
>
>
-1. It doesn't solve a real problem, just shuffles syntax around with very
little, if any, gain in clarity.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python now coming from Perl

2008-12-06 Thread Python Nutter
> In article <[EMAIL PROTECTED]>,
>  Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>
> Well, as an old-time unix hacker (who learned REs long before Perl
> existed), my question to you would be, "Is there any problem which
> *shouldn't* be solved with an RE?" :-)
>
> One of the reasons REs don't get used in Python as much as in Perl is
> because strings have useful methods like startswith(), endswith(), and
> split(), and also the "in" operator.  These combine to give you easy ways
> to do many things you might otherwise do with REs.


I agree, I'm going through the new book Python for Unix and Linux
Administration now and although in general I like what they say, they
take you through the built in string functions and then introduce REs
and end the chapter leaving the reader with the impression that REs
are the better solution and I only agree with the case of the
problem/program they presented.

However I used the built ins more effectively using the indexes
returned within the string and I've built plenty of scripts that did
not need to move to REs to perform the text/file processing that I
did. This intermediate use of string built-in functions was missing
between the first string-function and RE versions of code and imho it
is not letting the readers see that string-functions are even more
powerful than the reader is lead to believe and that REs are pushed
more towards edge cases than the impression the reader seems to be
left with which is to use REs more.

At least if you push REs inform the readers where to get the a RE GUI
builder written in Python so they can build and *test* the complex and
unwieldy REs to perform anything beyond the basic pattern searches.

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


Re: Learning Python now coming from Perl

2008-12-06 Thread Python Nutter
Perl Cookbook for Python Programmers:
http://pleac.sourceforge.net/pleac_python/index.html

P3K as starting point (slight cringe) as long as you know the caveats.

I'm of the mind as Christopher with regard to how Python 3.0 has been
released on Python.org:

"""I don't think that Python 3.0 is a bad thing. But that it's
displayed so prominently on the Python web site, without any kind of
warning that it's not going to work with 99% of the Python code out
there, scares the hell out of me. People are going to download and
install 3.0 by default, and nothing's going to work. They're going to
complain, and many are going to simply walk away.
- Christopher Lenz"""

Python3 is beautiful, and I am totally with James Bennet
http://www.b-list.org/weblog/2008/dec/05/python-3000/

That said I would suggest you learn the whole history of the Py3K
project and its 19+ years of 20/20 hindsight on what works well and
what doesn't so you can if you want to jump right into Python3 fully
informed on why it is the way it is and why you need to wait for 3rd
party libraries to catch up and release a Python 3 compatible version
and why all the Internal libraries are no worry except for the fact
some of them have disappeared in the cleanup or merged into a single
library. Then you can make sense of all the 2.x books and posts and
know where to start when trying to apply it to Python 3.

Cheers,
PN
(Python 2.5.2, Stackless Python 2.5.2, Python 2.6 and Python 3.0 on my box)

P.S. Look into iPython as your new favourtie shell and virtualenv to
help you keep all your projects straight and you'll be very productive
in no time =)


2008/12/7 Bertilo Wennergren <[EMAIL PROTECTED]>:
> I'm planning to start learning Python now, using Python 3000.
> I have no previous Python skills, but I now Perl pretty well.
> I'm also well experienced with JavaScript.
>
> Any pointers and tips how I should go about getting into
> Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread bearophileHUGS
Erik Max Francis:
> your precise proposal has
> been brought up countless times on comp.lang.python

And something tells me that it will keep coming up many more times in
the following years too.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] "as" keyword woes

2008-12-06 Thread Nick Coghlan
Warren DeLano wrote:
> In other words we have lost the ability to refer to "as" as the
> generalized OOP-compliant/syntax-independent method name for casting:

Other possible spellings:

# Use the normal Python idiom for avoiding keyword clashes
# and append a trailing underscore
new_object = old_object.as_(class_hint)
float_obj = int_obj.as_("float")
float_obj = int_obj.as_(float_class)

# Use a different word (such as, oh, "cast" perhaps?)
new_object = old_object.cast(class_hint)
float_obj = int_obj.cast("float")
float_obj = int_obj.cast(float_class)

You could make a PEP if you really wanted to, but it's going to be rejected.

Cheers,
Nick.

-- 
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Rhodri James
On Sat, 06 Dec 2008 21:51:51 -, Daniel Fetchinson  
<[EMAIL PROTECTED]> wrote:



Did you read the blog post? The advantage is having a less confusing
situation for newbies (confusing the number of arguments to a method
call).


Experience suggests that newbies don't find this confusing, or at
least not more than momentarily.

I'm -0 on this at the moment.  Maybe -0.5.  I don't really like the
potential for hideousness like

  @staticmethod
  def spam.alot(isa, silly, place):
return silly + spam

that's implied by making this a general feature of methods.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Russ P.

> But it's ugly.  No amount of rationalization will make it not ugly.

The dollar sign is ugly? I beg to differ.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Erik Max Francis

Russ P. wrote:

On Dec 6, 4:32 am, Andreas Waldenburger <[EMAIL PROTECTED]> wrote:

But that is not the way Python is meant to work. There are several
tennets in the Zen of Python that don't chime well with this approach.
"self" is a speaking identifier, "$" isn't.


Is "@" a "speaking identifier? How about "#" and "!="? Last I heard,
they were all part of Python.


None of these are identifiers at all.  You might want to read up on the 
language reference to see what an identifier actually is.


--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  There are not fifty ways of fighting, there is only one: to be the
   conqueror. -- Andrew Malraux, 1937
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Erik Max Francis

Russ P. wrote:


Python already uses shorthand extensively. How about "def"? For people
who are so worried about self-explanatory symbols, what the heck does
that stand for? Default? Defeat? Defect? Defunct? Defer?


That's pretty silly; it's pretty obvious that `def` means "define," and 
even if that weren't obvious on its face, in context it's _really_ 
obvious.  `def f(): ...` certainly isn't going to be confused to a 
request to defecate on something called `f`, after all -- which is about 
as plausible as your other suggestions.


`$` as a shortcut for self, on the other hand, gives absolutely no 
mnemonic indication what it stands for, and users would be simply left 
guessing.


P.S. You're beating a long-dead horse here; your precise proposal has 
been brought up countless times on comp.lang.python and shot down every 
single time for the same reason.  It isn't going to happen.


--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  There are not fifty ways of fighting, there is only one: to be the
   conqueror. -- Andrew Malraux, 1937
--
http://mail.python.org/mailman/listinfo/python-list


Re: python book for non technical absolute beginner

2008-12-06 Thread Rhodri James

On Sat, 06 Dec 2008 13:21:45 -, News123 <[EMAIL PROTECTED]> wrote:


No my question does anybody know a nice beginners book (or a learning CD
or on line tutorial)? Ideally it shouldn't be too serious and have a lot
of small nice mini-examples


For just pottering around with, your friend could do worse than the
LiveWires Python Course.  It doesn't go far into general programming
skills, largely because its designed for 12-15 year old kids to get
through in about three days of concentrated effort, but it will help
to learn the basics of Python and programming in general.

Caveat: the worksheets are built around Python 2.x (for small values of
x!), tell your friend not to use Python 3.0.  This is one of the few cases
where it really matters that 'print' is now a function; nothing freaks a
beginner like his output not behaving the way he's been told it should.


--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: "as" keyword woes

2008-12-06 Thread Steven D'Aprano
On Sat, 06 Dec 2008 14:36:07 -0800, Mensanator wrote:

> It was extremely simple for me to fix the sympy module where I noticed
> it. I'm not saying it wasn't a problem, I'm saying it wasn't BROKEN.

If it wasn't broken, why did you need to fix it?

"Broken" means "not working", not "unfixable".



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


Re: Guido's new method definition idea

2008-12-06 Thread Carl Banks
On Dec 6, 4:39 pm, "Russ P." <[EMAIL PROTECTED]> wrote:
> On Dec 6, 1:21 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Dec 6, 9:12 am, "Russ P." <[EMAIL PROTECTED]> wrote:
>
> > > On Dec 6, 1:02 am, Antoine De Groote <[EMAIL PROTECTED]> wrote:
>
> > > > Allowing "$" as a substitute for "self" wouldn't require this new 
> > > > syntax.
>
> > > > class C:
> > > >     def method($, arg):
> > > >         $.value = arg
>
> > > > I'm strongly against this. This looks ugly and reminds me of Perl and
> > > > Ruby. (I don't have anything against these languages, but there's a
> > > > reason I use Python).
>
> > > > Russ P. wrote:
> > > > > On Dec 5, 6:21 pm, "Daniel Fetchinson" <[EMAIL PROTECTED]>
> > > > > wrote:
> > > > >> Hi folks,
>
> > > > >> The story of the explicit self in method definitions has been
> > > > >> discussed to death and we all know it will stay. However, Guido
> > > > >> himself acknowledged that an alternative syntax makes perfect sense
> > > > >> and having both (old and new) in a future version of python is a
> > > > >> possibility since it maintains backward compatibility. The 
> > > > >> alternative
> > > > >> syntax will be syntactic sugar for the old one. This blog post of his
> > > > >> is what I'm talking about:
>
> > > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay...
>
> > > > >> The proposal is to allow this:
>
> > > > >> class C:
> > > > >>     def self.method( arg ):
> > > > >>         self.value = arg
> > > > >>         return self.value
>
> > > > >> instead of this:
>
> > > > >> class C:
> > > > >>     def method( self, arg ):
> > > > >>         self.value = arg
> > > > >>         return self.value
>
> > > > >> I.e. explicit self stays only the syntax is slightly different and 
> > > > >> may
> > > > >> seem attractive to some. As pointed out by Guido classmethods would
> > > > >> work similarly:
>
> > > > >> class C:
> > > > >>     @classmethod
> > > > >>     def cls.method( arg ):
> > > > >>         cls.val = arg
> > > > >>         return cls.val
>
> > > > >> The fact that Guido says,
>
> > > > >> "Now, I'm not saying that I like this better than the status quo. But
> > > > >> I like it a lot better than [...] but it has the great advantage that
> > > > >> it is backward compatible, and can be evolved into a PEP with a
> > > > >> reference implementation without too much effort."
>
> > > > >> shows that the proposal is viable.
>
> > > > >> I'd like this new way of defining methods, what do you guys think?
> > > > >> Anyone ready for writing a PEP?
>
> > > > >> Cheers,
> > > > >> Daniel
>
> > > > >> --
> > > > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown
>
> > > > > I like it.
>
> > > > > I'll even go a step further and suggest that "$" be allowed as a
> > > > > substitute for "self". It looks like a capital "S" (for Self), and it
> > > > > stands out clearly. It also makes code more succinct with no loss of
> > > > > readability. Think of the line wraps that could be avoided.
>
> > > It looks "ugly" simply because it is new to you. Once you get used to
> > > it, I'll bet it will look fine. And resemblance to another language is
> > > not a very good reason to reject it.
>
> > Perl is not new to me and I am familiar with the syntax, such as it
> > is.  I find it unspeakably ugly.  So, no, you would lose your bet if
> > it were me.
>
> > Carl Banks
>
> I don't know much about Perl, but my understanding is that a dollar
> sign must be used every time a variable is dereferenced, as in bash or
> other shell languages. What we are proposing here is something
> entirely different: the dollar sign would simply be a shorthand for
> "self". In Perl, the dollar sign is clutter, but in this case it
> actually reduces clutter.

But it's ugly.  No amount of rationalization will make it not ugly.


> Python already uses shorthand extensively. How about "def"? For people
> who are so worried about self-explanatory symbols, what the heck does
> that stand for? Default? Defeat? Defect? Defunct? Defer?
>
> At some time in the past, a conscious decision was made to save three
> characters in the word "define" by abbreviating it as "def". The
> suggestion to abbreviate "self" as "$" also saves three characters.
> And "self" appears much more often than "def", so an abbreviation is
> equally or more justified in my opinion.

def isn't ugly.


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


Re: Learning Python now coming from Perl

2008-12-06 Thread Steven D'Aprano
On Sat, 06 Dec 2008 14:15:28 -0500, Roy Smith wrote:

> In article <[EMAIL PROTECTED]>,
>  Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> 
>> On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote:
>> 
>> > For your first
>> > project, pick something that's small enough that you think you could
>> > tackle it in under 50 lines of Perl.
>> 
>> Is there anything which *can't* be written in under 50 lines of Perl?
> [...]
>> Also, Perl REs are faster than Python REs, or so I'm told. Between the
>> speed and the convenience, Perl programmers tend to use RE's for
>> everything they can. Python programmers tend to use REs only for
>> problems that *should* be solved with REs rather than *can* be solved
>> with a RE.
> 
> Well, as an old-time unix hacker (who learned REs long before Perl
> existed), my question to you would be, "Is there any problem which
> *shouldn't* be solved with an RE?" :-)


I think you've answered your own question:

> One of the reasons REs don't get used in Python as much as in Perl is
> because strings have useful methods like startswith(), endswith(), and
> split(), and also the "in" operator.  These combine to give you easy
> ways to do many things you might otherwise do with REs.


Also:

* splitting pathnames and file extensions

* dealing with arbitrarily nested parentheses

* any time you need a full-blown parser (e.g. parsing HTML or XML)

* sanitizing untrusted user input
  ("I bet I can think of *every* bad input and detect them all 
  with this regex!")

* validating email addresses
  
http://northernplanets.blogspot.com/2007/03/how-not-to-validate-email-addresses.html

* testing prime numbers
  http://jtauber.com/blog/2007/03/18/python_primality_regex/

* doing maths
  http://blog.stevenlevithan.com/archives/algebra-with-regexes
  http://weblogs.asp.net/rosherove/archive/2004/11/08/253992.aspx



There's probably more.


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


Re: Rich Comparisons Gotcha

2008-12-06 Thread Robert Kern

Terry Reedy wrote:

Rasmus Fogh wrote:

Dear All,

For the first time I have come across a Python feature that seems
completely wrong. After the introduction of rich comparisons, equality
comparison does not have to return a truth value, and may indeed return
nothing at all and throw an error instead. As a result, code like
  if foo == bar:
or
  foo in alist
cannot be relied on to work.

This is clearly no accident. According to the documentation all 
comparison
operators are allowed to return non-booleans, or to throw errors. 
There is

explicitly no guarantee that x == x is True.


You have touched on a real and known issue that accompanies dynamic 
typing and the design of Python.  *Every* Python function can return any 
Python object and may raise any exception either actively, by design, or 
passively, by not catching exceptions raised in the functions *it* calls.



Personally I would like to get these [EMAIL PROTECTED]&* misfeatures removed,


What you are calling a misfeature is an absence, not a presence that can 
be removed.


That's not quite true. Rich comparisons explicitly allow non-boolean return 
values. Breaking up __cmp__ into multiple __special__ methods was not the sole 
purpose of rich comparisons. One of the prime examples at the time was numpy 
(well, Numeric at the time). We wanted to use == to be able to return an array 
with boolean values where the two operand arrays were equal. E.g.


In [1]: from numpy import *

In [2]: array([1, 2, 3]) == array([4, 2, 3])
Out[2]: array([False,  True,  True], dtype=bool)

SQLAlchemy uses these operators to build up objects that will be turned into SQL 
expressions.


>>> print users.c.id==addresses.c.user_id
users.id = addresses.user_id

Basically, the idea was to turn these operators into full-fledged operators like 
+-/*. Returning a non-boolean violates neither the letter, nor the spirit of the 
feature.


Unfortunately, if you do overload __eq__ to build up expressions or whatnot, the 
other places where users of __eq__ are implicitly expecting a boolean break. 
While I was (and am) a supporter of rich comparisons, I feel Rasmus's pain from 
time to time. It would be nice to have an alternate method to express the 
boolean "yes, this thing is equal in value to that other thing". Unfortunately, 
I haven't figured out a good way to fit it in now without sacrificing rich 
comparisons entirely.



and constrain the __eq__ function to always return a truth value.


It is impossible to do that with certainty by any mechanical 
creation-time checking.  So the implementation of operator.eq would have 
to check the return value of the ob.__eq__ function it calls *every 
time*.  That would slow down the speed of the 99.xx% of cases where the 
check is not needed and would still not prevent exceptions.  And if the 
return value was bad, all operator.eq could do is raise and exception 
anyway.


Sure, but then it would be a bug to return a non-boolean from __eq__ and 
friends. It is not a bug today. I think that's what Rasmus is proposing.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Guido's new method definition idea

2008-12-06 Thread Steven D'Aprano
On Sat, 06 Dec 2008 08:01:40 -0800, Russ P. wrote:

>> -2 on this proposal.
> 
> Did you get two votes in the Presidential election too? 8^)

You know, occasionally you stumble across people on the Internet who 
aren't from the USA. Some of us even speak English almost as good as 
native speakers *wink*

In any case, in this context -2 refers to the strength of feeling, not 
the number of votes. Python is not a democracy, and our Beloved BDFL 
Guido graciously takes our needs and wants into account before making 
decisions.


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


Re: how to get a beep, OS independent ?

2008-12-06 Thread Rainy
On Dec 6, 3:40 pm, Stef Mientki <[EMAIL PROTECTED]> wrote:
> hello,
>
> I want to give a small beep,
> for windows there's message-beep,
> and there seems to be something like " curses" ,
> but that package seems to be totally broken in P2.5 for windows.
>
> Any other suggestions ?
>
> thanks,
> Stef Mientki

For win there's winsound, you have to check sys.platform and do
what's necessary for the platform in question. In linux I think
you can just print '\a' (or does that only work in terminals?).
If you know that ext. speakers are always on, you can do a nicer
beep by using some wav file, in linux it's probably easiest to
use an external program to play it, like wavplay. Basically,
there is no single answer, it depends on circumstances.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a beep, OS independent ?

2008-12-06 Thread MRAB

Stef Mientki wrote:

hello,

I want to give a small beep,
for windows there's message-beep,
and there seems to be something like " curses" ,
but that package seems to be totally broken in P2.5 for windows.

Any other suggestions ?


print chr(7)?
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a beep, OS independent ?

2008-12-06 Thread Chris Rebert
On Sat, Dec 6, 2008 at 3:40 PM, Stef Mientki <[EMAIL PROTECTED]> wrote:
> hello,
>
> I want to give a small beep,
> for windows there's message-beep,
> and there seems to be something like " curses" ,
> but that package seems to be totally broken in P2.5 for windows.
>
> Any other suggestions ?

Printing the http://en.wikipedia.org/wiki/Bell_character ("\a") to the
terminal produces a beep from the internal speaker.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com

>
> thanks,
> Stef Mientki
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


how to get a beep, OS independent ?

2008-12-06 Thread Stef Mientki

hello,

I want to give a small beep,
for windows there's message-beep,
and there seems to be something like " curses" ,
but that package seems to be totally broken in P2.5 for windows.

Any other suggestions ?

thanks,
Stef Mientki
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Andreas Waldenburger
On Sat, 6 Dec 2008 14:39:34 -0800 (PST) "Russ P."
<[EMAIL PROTECTED]> wrote:

> I don't know much about Perl, but my understanding is that a dollar
> sign must be used every time a variable is dereferenced, as in bash or
> other shell languages. What we are proposing here is something
> entirely different: the dollar sign would simply be a shorthand for
> "self". In Perl, the dollar sign is clutter, but in this case it
> actually reduces clutter.
> 
This is the weirdest thing. Not a month seems to go by that this old
hat isn't dug up again. You're fighting windmills. Why do you think
self has been around so long? Because it's the best choice? No, because
it works and there just is no need to change it (where "need" is
defined by the desires of the majority).

Getting the Python comunity to replace self with something shorter will
never compensate for the time you spent bullying it through. I'd much
rather spend time coding than complaining, but that might be just me.
(BTW: I have my editor set up so that "s" is expanded to "self" and "."
is expanded to "self."; I virtually lose no time at all with self and
would gain nothing from a change to it.

And regarding line-lengths: My code lines tend to be shorter than my
comments explaining them, but that may again be just me.


Excuse my being stubborn. :)
/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Don't you just love writing this sort of thing :)

2008-12-06 Thread Rhodri James
On Sat, 06 Dec 2008 01:20:55 -, Lawrence D'Oliveiro  
<[EMAIL PROTECTED]> wrote:



Do you find this
   (open, gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir,  
Entry), "r")

complicated or hard to understand? It's made up of very simple pieces,
combined according to very simple rules, viz:-


Yes, it's very pretty, and you're terribly clever.  In six months' time
when you come back to make some engineering change and have to sit down and
break it back down into those simple pieces to remind yourself what it's
doing, "pretty" and "clever" will not be the words you are using.  Trust
me on this one.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Source code generation using Python

2008-12-06 Thread ats
On Dec 6, 11:19 pm, Philip Semanchuk <[EMAIL PROTECTED]> wrote:
> On Dec 6, 2008, at 4:47 PM, ats wrote:
>
>
>
> > Hello,
>
> > This is my first posting to a Python group (and I'm starting with
> > Python seriously only now) , so bear with me if I make some mistakes.
>
> > I want to generate 3 different versions of a C++ source code,
> > basically injecting different flavours of inline assembler depending
> > on target compiler/CPU.
>
> > Code generation should be integrated into a 'master source file' which
> > is the processed and generates the right code for GCC / MSVC or other
> > cases. Something like:
>
> >  int FastAdd( int t1, int t2 ){
> >    int r;
> >    ##if USE_INLINE_ASM
> >      #ARG( eax, "t1")
> >      #ARG( ebx, "t2")
> >      #ASM( "add", ebx, eax )
> >      #RES( eax, "r" )
> >    ##else
> >      r = t1+t2;
> >    ##endif
> >    return r;
> >  }
>
> > On processing, given constant USE_INLINE_ASM (or not) the right code
> > is generated to a target file, which goes into the build process.
>
> > I was looking for packages that can do this and came up with some
> > candidates:
>
> > - "empy" -http://www.alcyone.com/pyos/empy/- It looks like it could
> > do the job, but appears non-maintained since 2003.
> > - "Cheetah" - Looks like more of a tool to do fix replacements of code
> > snippets.
>
> > There is some logic going on in the "ARG", "ASM" and "RES" sections,
> > so I need to link code generation with true Python functions.
>
> Hi Arne,
> There are *lots* of packages for Python that replace chunks of  
> predefined templates. Most are HTML-focused, some more so than others.  
> I've used Mako (http://www.makotemplates.org/) to generate both HTML  
> and Apache config files. It could certainly do C++. Some alternatives  
> to Mako are mentioned in the documentation -- Kid, Genshi and Cheetah.
>
> Rather than invite a flame war as to which is a better templating  
> engine, I'll just say that I'm happy with how Mako addresses *my*  
> needs. =) Good luck finding something that addresses yours.
>
> Cheers
> Philip
>
>
>
> > The situation is really quite similar to HTML/PHP except, here we
> > would have C++/Python.
>
> > Any suggestions?
>
> > Thanks,
> > //Arne S.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>

Thanks, Mako looks neat.

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


Re: [Python-Dev] "as" keyword woes

2008-12-06 Thread Virgil Dupras

On 06 Dec 2008, at 20:38, Warren DeLano wrote:




Date: Fri, 05 Dec 2008 22:22:38 -0800
From: Dennis Lee Bieber <[EMAIL PROTECTED]>
Subject: Re: "as" keyword woes
To: python-list@python.org
Message-ID: <[EMAIL PROTECTED]>

I'm still in the dark as to what type of data could
even inspire the
use of "as" as an object name... A collection of "a" objects? In  
which

case, what are the "a"s? 


Please let me clarify.  It is not "as" as a standalone object that we
specifically miss in 2.6/3, but rather, the ability to use ".as"  
used as

a method or attribute name.

In other words we have lost the ability to refer to "as" as the
generalized OOP-compliant/syntax-independent method name for casting:

new_object = old_object.as(class_hint)

# For example:

float_obj = int_obj.as("float")

# or

float_obj = int_obj.as(float_class)

# as opposed to something like

float_obj = int_obj.asFloat()

# which requires a separate method for each cast, or

float_obj = (float)int_obj

# which required syntax-dependent casting [language-based rather than
object-based].

Of course, use of explicit casting syntax "(float)" is fine if you're
restricting yourself to Python and other languages which support
casting, but that solution is unavailable inside of a pure OOP
message-passing paradigm where object.method(argument) invocations are
all you have to work with.

Please note that use of object.asClassname(...) is a ubiqitous
convention for casting objects to specific classes (seen in  
ObjectiveC,

Java, SmallTalk, etc.).

There, I assert that 'object.as(class_reference)' is the simplest and
most elegant generalization of this widely-used convention.  Indeed,  
it
is the only obvious concise answer, if you are limited to using  
methods

for casting.

Although there are other valid domain-specific uses for "as" as  
either a
local variable or attribute names (e.g. systematic naming: as, bs,  
cs),
those aren't nearly as important compared to "as" being available as  
the
name of a generalized casting method -- one that is now strictly  
denied

to users of Python 2.6 and 3.

As someone somewhat knowledgable of how parsers work, I do not
understand why a method/attribute name "object_name.as(...)" must
necessarily conflict with a standalone keyword " as ".  It seems to me
that it should be possible to unambiguously separate the two without
ambiguity or undue complication of the parser.

So, assuming I now wish to propose a corrective PEP to remedy this
situation for Python 3.1 and beyond, what is the best way to get  
started

on such a proposal?

Cheers,
Warren



As long as "as" is widely known as a keyword, I don't see the problem.  
Every python developer knows that the convention is to add a trailing  
underscore when you want to use a reserved word in your code. Besides,  
your examples are quite abstract. I'm sure it's possible to find good  
examples for "while", "with", "import", "from" (I often use "from_")  
or "try" as well. Or perhaps that the python keywords should be "as_"  
so we leave "as" free for eventual methods?


As for the implicit proposition of allowing keywords only for methods,  
I agree with Guido about it being a slippery slope. So we would end up  
with a language where it is allowed to name methods after keywords,  
but not functions (they can be declared in the local scope)? Yikes! Oh  
well, maybe it's possible for an intelligent parser to distinguish  
between keywords and function references, but think of the poor  
grammar highlighters in all source editors! What a nightmare it will  
be for them. Anyway, is there any language that does this, allowing  
keywords as method names? I don't know, but if not, there's probably a  
reason for it.


Your views on code elegance are also rather Javaish. I'd go for  
"class_reference(object)" (and why the heck would you "be limited to  
using method for casting"?).


Ciao,
Virgil
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Benjamin Kaplan
On Sat, Dec 6, 2008 at 4:51 PM, Daniel Fetchinson <[EMAIL PROTECTED]
> wrote:

> >> Hi folks,
> >>
> >> The story of the explicit self in method definitions has been
> >> discussed to death and we all know it will stay. However, Guido
> >> himself acknowledged that an alternative syntax makes perfect sense
> >> and having both (old and new) in a future version of python is a
> >> possibility since it maintains backward compatibility. The alternative
> >> syntax will be syntactic sugar for the old one. This blog post of his
> >> is what I'm talking about:
> >>
> >>
> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
> >>
> >> The proposal is to allow this:
> >>
> >> class C:
> >> def self.method( arg ):
> >> self.value = arg
> >> return self.value
> >>
> >> instead of this:
> >>
> >> class C:
> >> def method( self, arg ):
> >> self.value = arg
> >> return self.value
> >>
> >> I.e. explicit self stays only the syntax is slightly different and may
> >> seem attractive to some. As pointed out by Guido classmethods would
> >> work similarly:
> >>
> >> class C:
> >> @classmethod
> >> def cls.method( arg ):
> >> cls.val = arg
> >> return cls.val
> >>
> >> The fact that Guido says,
> >>
> >> "Now, I'm not saying that I like this better than the status quo. But
> >> I like it a lot better than [...] but it has the great advantage that
> >> it is backward compatible, and can be evolved into a PEP with a
> >> reference implementation without too much effort."
> >>
> >> shows that the proposal is viable.
> >>
> >> I'd like this new way of defining methods, what do you guys think?
> >> Anyone ready for writing a PEP?
> >>
> > What's the advantage?  If there is not a good reason, I would strongly
> > opposed polluting the language.
>
> Did you read the blog post? The advantage is having a less confusing
> situation for newbies (confusing the number of arguments to a method
> call).
>

2 points about this:

1) You'd confuse newbies about the fact that self.foo() is just syntax sugar
for cls.foo(self). The problem with newbies getting argument numbers still
exists, just in the other case. This could also get confusing when you call
methods for the super class


class Foo :
 def self.bar() :
...
class OtherFoo(Foo) ;
def self.bar() :
...

b = OtherFoo()
cls = Foo
cls.bar(b)

2) You'd have to allow this at the module level too (or else it violates the
special cases part of the Zen). That would really confuse newbies.
--
http://mail.python.org/mailman/listinfo/python-list


Re: operators as variables

2008-12-06 Thread Mark Tolonen


"macc_200" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Hi,
just starting programming and have an elementary question
after playing around with lists but cannot find >the answer
with googling.
I have a list of variables and I would like some of those
 variables to be integers and some to be operators so the
 list would look something like [5 * 4 - 4 + 6] and then be
 able to evaluate the result (i.e. get 10).  How do you make
 the interpreter see the operator as that instead of a string
 and just echo the list back to me.
thanks,
Andy
(and suggestions for a decent Python book would be appreciated)


See the operator module, and then check out pyparsing.

-Mark


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


Re: RELEASED Python 3.0 final

2008-12-06 Thread William McBrine
On Fri, 05 Dec 2008 12:16:47 -0800, Fernando H. Sanches wrote:

> I agree that the tab/space thing should be changed. Would it be too hard
> to make the parser see if the indentation is consistent in the whole
> file?

*Something* has changed. I had a piece of code where, without realizing 
it, I had a tab mixed in with the spaces at the start of one line in a 
block. In 2.5, it worked, silently. In 3.0, I got an indentation error.

-- 
09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Russ P.
On Dec 6, 1:21 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Dec 6, 9:12 am, "Russ P." <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Dec 6, 1:02 am, Antoine De Groote <[EMAIL PROTECTED]> wrote:
>
> > > Allowing "$" as a substitute for "self" wouldn't require this new syntax.
>
> > > class C:
> > >     def method($, arg):
> > >         $.value = arg
>
> > > I'm strongly against this. This looks ugly and reminds me of Perl and
> > > Ruby. (I don't have anything against these languages, but there's a
> > > reason I use Python).
>
> > > Russ P. wrote:
> > > > On Dec 5, 6:21 pm, "Daniel Fetchinson" <[EMAIL PROTECTED]>
> > > > wrote:
> > > >> Hi folks,
>
> > > >> The story of the explicit self in method definitions has been
> > > >> discussed to death and we all know it will stay. However, Guido
> > > >> himself acknowledged that an alternative syntax makes perfect sense
> > > >> and having both (old and new) in a future version of python is a
> > > >> possibility since it maintains backward compatibility. The alternative
> > > >> syntax will be syntactic sugar for the old one. This blog post of his
> > > >> is what I'm talking about:
>
> > > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay...
>
> > > >> The proposal is to allow this:
>
> > > >> class C:
> > > >>     def self.method( arg ):
> > > >>         self.value = arg
> > > >>         return self.value
>
> > > >> instead of this:
>
> > > >> class C:
> > > >>     def method( self, arg ):
> > > >>         self.value = arg
> > > >>         return self.value
>
> > > >> I.e. explicit self stays only the syntax is slightly different and may
> > > >> seem attractive to some. As pointed out by Guido classmethods would
> > > >> work similarly:
>
> > > >> class C:
> > > >>     @classmethod
> > > >>     def cls.method( arg ):
> > > >>         cls.val = arg
> > > >>         return cls.val
>
> > > >> The fact that Guido says,
>
> > > >> "Now, I'm not saying that I like this better than the status quo. But
> > > >> I like it a lot better than [...] but it has the great advantage that
> > > >> it is backward compatible, and can be evolved into a PEP with a
> > > >> reference implementation without too much effort."
>
> > > >> shows that the proposal is viable.
>
> > > >> I'd like this new way of defining methods, what do you guys think?
> > > >> Anyone ready for writing a PEP?
>
> > > >> Cheers,
> > > >> Daniel
>
> > > >> --
> > > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown
>
> > > > I like it.
>
> > > > I'll even go a step further and suggest that "$" be allowed as a
> > > > substitute for "self". It looks like a capital "S" (for Self), and it
> > > > stands out clearly. It also makes code more succinct with no loss of
> > > > readability. Think of the line wraps that could be avoided.
>
> > It looks "ugly" simply because it is new to you. Once you get used to
> > it, I'll bet it will look fine. And resemblance to another language is
> > not a very good reason to reject it.
>
> Perl is not new to me and I am familiar with the syntax, such as it
> is.  I find it unspeakably ugly.  So, no, you would lose your bet if
> it were me.
>
> Carl Banks

I don't know much about Perl, but my understanding is that a dollar
sign must be used every time a variable is dereferenced, as in bash or
other shell languages. What we are proposing here is something
entirely different: the dollar sign would simply be a shorthand for
"self". In Perl, the dollar sign is clutter, but in this case it
actually reduces clutter.

Python already uses shorthand extensively. How about "def"? For people
who are so worried about self-explanatory symbols, what the heck does
that stand for? Default? Defeat? Defect? Defunct? Defer?

At some time in the past, a conscious decision was made to save three
characters in the word "define" by abbreviating it as "def". The
suggestion to abbreviate "self" as "$" also saves three characters.
And "self" appears much more often than "def", so an abbreviation is
equally or more justified in my opinion.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "as" keyword woes

2008-12-06 Thread Mensanator
On Dec 6, 2:09�pm, Wolfgang Strobl <[EMAIL PROTECTED]> wrote:
> Mensanator <[EMAIL PROTECTED]>:
>
>
>
>
>
> >On Dec 6, 8:16?am, Wolfgang Strobl <[EMAIL PROTECTED]> wrote:
> >> Dennis Lee Bieber <[EMAIL PROTECTED]>:
>
> >> >On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano
> >> ><[EMAIL PROTECTED]> declaimed the following in
> >> >comp.lang.python:
>
> >> >> On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote:
>
> >> >> > The point was that there
> >> >> > is that new releases don't _break_ anything.
>
> >> >> But that's clearly not true, because the OP is pointing out that the new
> >> >> release from 2.5 to 2.6 *does* break his code.
>
> >> > ? ?One now has to ask what "break" really meant... For this example,
> >> >the change did not break Python SYNTAX -- just a complaint about using
> >> >what is now a reserved word as an object name.
>
> >> Of course it does:
>
> >> C:\Python26>python
> >> Python 2.6 (r26:66721, Oct ?2 2008, 11:35:03) [MSC v.1500 32 bit
> >> (Intel)] on win 32
> >> Type "help", "copyright", "credits" or "license" for more information.>>> 
> >> as=2
>
> >> ? File "", line 1
> >> ? ? as=2
> >> ? ? ?^
> >> SyntaxError: invalid syntax
>
> >I disagree. "Broken" is something you can't work
> >around.
>
> Well, that language change _did_ break the OPs code, and he already
> explained why it isn't as simple to work around as you obviously happen
> to believe.

It was extremely simple for me to fix the sympy
module where I noticed it. I'm not saying it
wasn't a problem, I'm saying it wasn't BROKEN.
And no, I couldn't use sympy after the fix
because apparently there is some change the way
2.6 hashes which truly breaks the sympy code, so
no using sympy with 2.6 until a corrected version
is released. And the real problem is that the
latest version was released without ever testing it
under 2.6. Hopefully, that won't happen again.

> � Calling it "not a SYNTAX error" is not only mistaken, it's
> weaseling around the problem too.

It's not weaseling around the problem, it's rating
the seriousness of the problem. Right now if I need
sympy, I HAVE to use 2.5, if I need itertools.permutations
I HAVE to use 2.6. But I canot use both in the same
program which is a tad more serious than having to
rename a variable I had business using in the first place.

>
> >In this case, simply saying as_=2 works fine.
>
> Certainly not, for example when that name is already used outside your
> control. In addition, you'll have to find all places, where the now
> syntactically illegal name is or might be used. This can get arbitrarily
> hard in generated �or foreign code.

The difficulty of fixing it isn't the issue, it's
whether it can be fixed at all.

>
>
>
> >A better example of broken was when the gmpy module
> >wouldn't solve a certain linear congruence problem
> >because the problem was not invertible.
>
> What does that have to to with anything?

It's an example of what it means to be BROKEN,
and yes, nothing at all to do with SYNTAX.

> We're disussing a language
> change on the syntax level which breaks existing legal code, not how a
> numerical library behaves for borderline cases.

And yet, you don't consider this a case of "weasel words".

Strange.

>
> [...]
>
> >> Making a former syntactically valid ?two letter name a reserved word in
> >> 2.6 was a mistake, IMHO.
>
> >I think you're in the minority there.
>
> Perhaps. Does that matter?

Yeah, if you think it will be resolved in your favor.

>
> >> What's next? What about making i,j,k, x and y
> >> reserved words in 2.7? =:-/
>
> >Yeah, right. That'll happen.
>
> Certainly not. �On the other hand, I was quite flabbergasted by the
> change in question, likewise. Wasn't that something �reserved for 3.0:
> breaking code mercilessly? �

Mercilessly? If there were no deprecation warnings,
you might have a case there. You act as if the failure
to display such warnings was deliberate, but that was due
to a BUG, not merciless behaviour on the part of the
developers.

> What is 3.0 good for, when we have to bear
> such breakage in a minor release, already?

You're making a mountain out of a molehill.

>
> >You ought to be more
> >concerned about real problems.
>
> It is a real problem for the OP.

Who gave him permission to use 2.6? Is 2.5 suddenly
unavailable? Assholes like Microsoft pull stunts
like that, but Python.org doesn't.

If it's his code, he can easily fix it.

If it's someone else's code, he should be using
a version guaranteed to work in 2.6.

>
> --
> Thank you for observing all safety precautions
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 automatic decoding of UTF16

2008-12-06 Thread John Machin
On Dec 7, 9:01 am, David Bolen <[EMAIL PROTECTED]> wrote:
> Johannes Bauer <[EMAIL PROTECTED]> writes:
> > This is very strange - when using "utf16", endianness should be detected
> > automatically. When I simply truncate the trailing zero byte, I receive:
>
> Any chance that whatever you used to "simply truncate the trailing
> zero byte" also removed the BOM at the start of the file?  Without it,
> utf16 wouldn't be able to detect endianness and would, I believe, fall
> back to native order.

When I read this, I thought "O no, surely not!". Seems that you are
correct:
[Python 2.5.2, Windows XP]
| >>> nobom = u'abcde'.encode('utf_16_be')
| >>> nobom
| '\x00a\x00b\x00c\x00d\x00e'
| >>> nobom.decode('utf16')
| u'\u6100\u6200\u6300\u6400\u6500'

This may well explain one of the Python 3.0 problems that the OP's 2
files exhibit: data appears to have been byte-swapped under some
conditions. Possibility: it is reading the file a chunk at a time and
applying the utf_16 encoding independently to each chunk -- only the
first chunk will have a BOM.

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


Re: Source code generation using Python

2008-12-06 Thread Philip Semanchuk


On Dec 6, 2008, at 4:47 PM, ats wrote:


Hello,

This is my first posting to a Python group (and I'm starting with
Python seriously only now) , so bear with me if I make some mistakes.

I want to generate 3 different versions of a C++ source code,
basically injecting different flavours of inline assembler depending
on target compiler/CPU.

Code generation should be integrated into a 'master source file' which
is the processed and generates the right code for GCC / MSVC or other
cases. Something like:

 int FastAdd( int t1, int t2 ){
   int r;
   ##if USE_INLINE_ASM
 #ARG( eax, "t1")
 #ARG( ebx, "t2")
 #ASM( "add", ebx, eax )
 #RES( eax, "r" )
   ##else
 r = t1+t2;
   ##endif
   return r;
 }

On processing, given constant USE_INLINE_ASM (or not) the right code
is generated to a target file, which goes into the build process.

I was looking for packages that can do this and came up with some
candidates:

- "empy" - http://www.alcyone.com/pyos/empy/ - It looks like it could
do the job, but appears non-maintained since 2003.
- "Cheetah" - Looks like more of a tool to do fix replacements of code
snippets.


There is some logic going on in the "ARG", "ASM" and "RES" sections,
so I need to link code generation with true Python functions.


Hi Arne,
There are *lots* of packages for Python that replace chunks of  
predefined templates. Most are HTML-focused, some more so than others.  
I've used Mako (http://www.makotemplates.org/) to generate both HTML  
and Apache config files. It could certainly do C++. Some alternatives  
to Mako are mentioned in the documentation -- Kid, Genshi and Cheetah.


Rather than invite a flame war as to which is a better templating  
engine, I'll just say that I'm happy with how Mako addresses *my*  
needs. =) Good luck finding something that addresses yours.


Cheers
Philip





The situation is really quite similar to HTML/PHP except, here we
would have C++/Python.

Any suggestions?

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


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


Re: operators as variables

2008-12-06 Thread News123
Terry Reedy wrote:
> macc_200 wrote:
>> Hi,
>> just starting programming and have an elementary question after
>> playing around with lists but cannot find the answer with googling.
>> I have a list of variables and I would like some of those variables to
>> be integers and some to be operators so the list would look something
>> like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get
>> 10).  How do you make the interpreter see the operator as that instead
>> of a string and just echo the list back to me.
> 

Without sanity checking following would work:

a= [ '1' , '+' , '3' ]
txt= ' '.join(a)
rslt = eval(txt)


bye

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


Re: Python 3.0 automatic decoding of UTF16

2008-12-06 Thread David Bolen
Johannes Bauer <[EMAIL PROTECTED]> writes:

> This is very strange - when using "utf16", endianness should be detected
> automatically. When I simply truncate the trailing zero byte, I receive:

Any chance that whatever you used to "simply truncate the trailing
zero byte" also removed the BOM at the start of the file?  Without it,
utf16 wouldn't be able to detect endianness and would, I believe, fall
back to native order.

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


Re: Guido's new method definition idea

2008-12-06 Thread Chris Rebert
On Sat, Dec 6, 2008 at 1:33 PM, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Dec 5, 8:21 pm, "Daniel Fetchinson" <[EMAIL PROTECTED]>
> wrote:
>> Hi folks,
>>
>> The story of the explicit self in method definitions has been
>> discussed to death and we all know it will stay. However, Guido
>> himself acknowledged that an alternative syntax makes perfect sense
>> and having both (old and new) in a future version of python is a
>> possibility since it maintains backward compatibility. The alternative
>> syntax will be syntactic sugar for the old one. This blog post of his
>> is what I'm talking about:
>>
>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay...
>>
>> The proposal is to allow this:
>>
>> class C:
>> def self.method( arg ):
>> self.value = arg
>> return self.value
>>
>> instead of this:
>>
>> class C:
>> def method( self, arg ):
>> self.value = arg
>> return self.value
>
>
>
> -1
>
> I explained why deep in the thread but I'll elaborate more here.  When
> I see a def statement, I mentally equate that to an assigment to the
> thing being def'ed.  So for instance, when I see this:
>
>  def ():
>
> I think of it like this:
>
>   = 
>
>
> Thus, if I were to see a function definition like this
>
>  def foo.bar(): return 1
>
> I would think you were defining a function and assigning it to
> foo.bar.  IOW, it would be mostly equivalent to this:
>
>  foo.bar = lambda: 1
>
>
> (Analogously, I would expect a definition like this:
>
>  def baz[10](): return 1
>
> to be equivalent to this:
>
>  baz[10] = lambda: 1  )
>
>
> So, if, inside a class definition, I were to see this:
>
>  def self.method(): return 1
>
> Well, I'd understand that is was a method assigment, of course, but it
> would conflict with what I would expect the natural meaning of
> something like def a.b() would be.  The above statement is not
> equivalent to:
>
>  self.method = lambda: 1
>
> but I think that's what it ought to be, in general.

Similarly, to those coming from Ruby or those operating under the
frequent misunderstanding that the `def`s are happening in the context
of a class object (which in reality has yet to be created), `self` in
this context might be misconstrued as the class object and thus `def
self.foo` might be misunderstood (through the intuitive equivalence
you mention) as a defining a classmethod rather than an instance
method.

I also strongly echo the TOOWTDI arguments against adding this
duplicative syntax. It's a minor gain but costs much more than it's
worth for violating The Zen.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com

>
>
>
> Carl Banks
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Daniel Fetchinson
>> Hi folks,
>>
>> The story of the explicit self in method definitions has been
>> discussed to death and we all know it will stay. However, Guido
>> himself acknowledged that an alternative syntax makes perfect sense
>> and having both (old and new) in a future version of python is a
>> possibility since it maintains backward compatibility. The alternative
>> syntax will be syntactic sugar for the old one. This blog post of his
>> is what I'm talking about:
>>
>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
>>
>> The proposal is to allow this:
>>
>> class C:
>> def self.method( arg ):
>> self.value = arg
>> return self.value
>>
>> instead of this:
>>
>> class C:
>> def method( self, arg ):
>> self.value = arg
>> return self.value
>>
>> I.e. explicit self stays only the syntax is slightly different and may
>> seem attractive to some. As pointed out by Guido classmethods would
>> work similarly:
>>
>> class C:
>> @classmethod
>> def cls.method( arg ):
>> cls.val = arg
>> return cls.val
>>
>> The fact that Guido says,
>>
>> "Now, I'm not saying that I like this better than the status quo. But
>> I like it a lot better than [...] but it has the great advantage that
>> it is backward compatible, and can be evolved into a PEP with a
>> reference implementation without too much effort."
>>
>> shows that the proposal is viable.
>>
>> I'd like this new way of defining methods, what do you guys think?
>> Anyone ready for writing a PEP?
>>
> What's the advantage?  If there is not a good reason, I would strongly
> opposed polluting the language.

Did you read the blog post? The advantage is having a less confusing
situation for newbies (confusing the number of arguments to a method
call).

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


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Daniel Fetchinson
> Bad idea having two ways to do this. Pick one or the other!

Maybe only this alternative syntax for python 4000?

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Source code generation using Python

2008-12-06 Thread ats
Hello,

This is my first posting to a Python group (and I'm starting with
Python seriously only now) , so bear with me if I make some mistakes.

I want to generate 3 different versions of a C++ source code,
basically injecting different flavours of inline assembler depending
on target compiler/CPU.

Code generation should be integrated into a 'master source file' which
is the processed and generates the right code for GCC / MSVC or other
cases. Something like:

  int FastAdd( int t1, int t2 ){
int r;
##if USE_INLINE_ASM
  #ARG( eax, "t1")
  #ARG( ebx, "t2")
  #ASM( "add", ebx, eax )
  #RES( eax, "r" )
##else
  r = t1+t2;
##endif
return r;
  }

On processing, given constant USE_INLINE_ASM (or not) the right code
is generated to a target file, which goes into the build process.

I was looking for packages that can do this and came up with some
candidates:

 - "empy" - http://www.alcyone.com/pyos/empy/ - It looks like it could
do the job, but appears non-maintained since 2003.
- "Cheetah" - Looks like more of a tool to do fix replacements of code
snippets.

There is some logic going on in the "ARG", "ASM" and "RES" sections,
so I need to link code generation with true Python functions.

The situation is really quite similar to HTML/PHP except, here we
would have C++/Python.

Any suggestions?

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


Re: Guido's new method definition idea

2008-12-06 Thread Daniel Fetchinson
>> Hi folks,
>>
>> The story of the explicit self in method definitions has been
>> discussed to death and we all know it will stay. However, Guido
>> himself acknowledged that an alternative syntax makes perfect sense
>> and having both (old and new) in a future version of python is a
>> possibility since it maintains backward compatibility. The alternative
>> syntax will be syntactic sugar for the old one. This blog post of his
>> is what I'm talking about:
>>
>> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
>>
>> The proposal is to allow this:
>>
>> class C:
>> def self.method( arg ):
>> self.value = arg
>> return self.value
>>
>> instead of this:
>>
>> class C:
>> def method( self, arg ):
>> self.value = arg
>> return self.value
>>
> (snip)
>> I'd like this new way of defining methods, what do you guys think?
>
> -1
>
> As far as I'm concerned, it doesn't add anything to the language, nor
> doesn't save any typing, so I just don't see the point. And having it
> co-existing with the normal syntax will only add more confusion.

It doesn't add anything but makes something that exists a bit clearer
and friendlier to newbies. Saving typing was never the intention.

> NB : FWIW, I would eventually have voted -0 if it had been proposed for
> Python 3, and as a _replacement_ (not _alternative_) to the current
> syntax. But Python 3 is now released, so...

There will be python 4000 eventually :)

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: "as" keyword woes

2008-12-06 Thread Terry Reedy

Warren DeLano wrote:


As someone somewhat knowledgable of how parsers work, I do not
understand why a method/attribute name "object_name.as(...)" must
necessarily conflict with a standalone keyword " as ".  It seems to me
that it should be possible to unambiguously separate the two without
ambiguity or undue complication of the parser.


The lexer, which preceeds the parser, has separate KEYWORD and 
IDENTIFIER categories.  For example, 'if a ...' is lexed as (KEYWORD, 
'if'), (IDENTIFIER, 'a'), ... .  Leaving 'as' as an identifier 
identified by the parser as a contextual keyword in import statements 
was a kludge.  When 'as' was reused in "with  as " in 2.5 
(with __future__ import), it was planned and announced that *both* 
'with' and 'as' would become full-time keywords in 2.6, just as 'yield' 
did in 2.3 after its introduction (with required __future__) in 2.2.


Making 'yield' a keyword of course impacted people who used the word in 
financial calculations, but they adjusted.


> So, assuming I now wish to propose a corrective PEP

Working with people trying to improve threading would be more productive.

Terry Jan Reedy

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


Re: Python 3.0 automatic decoding of UTF16

2008-12-06 Thread John Machin
On Dec 7, 6:20 am, "Mark Tolonen" <[EMAIL PROTECTED]> wrote:
> "Johannes Bauer" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
>
>
> >John Machin schrieb:
> >> On Dec 6, 5:36 am, Johannes Bauer <[EMAIL PROTECTED]> wrote:
> >>> So UTF-16 has an explicit EOF marker within the text? I cannot find one
> >>> in original file, only some kind of starting sequence I suppose
> >>> (0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a,
> >>> simple \r\n line ending.
>
> >> Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes
> >> long, an ODD number, which shouldn't happen with utf16.  The file is
> >> stuffed. Python 3.0 has a bug; it should give a meaningful error
> >> message.
>
> >Yes, you are right. I fixed the file, yet another error pops up
> >(http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.t...
>
> >Traceback (most recent call last):
> >  File "./modify.py", line 12, in 
> >    a = AddressBook("2008_12_05_Handy_Backup.txt")
> >  File "./modify.py", line 7, in __init__
> >    line = f.readline()
> >  File "/usr/local/lib/python3.0/io.py", line 1807, in readline
> >    while self._read_chunk():
> >  File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk
> >    self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
> >  File "/usr/local/lib/python3.0/io.py", line 1293, in decode
> >    output = self.decoder.decode(input, final=final)
> >  File "/usr/local/lib/python3.0/codecs.py", line 300, in decode
> >    (result, consumed) = self._buffer_decode(data, self.errors, final)
> >  File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in
> >_buffer_decode
> >    return self.decoder(input, self.errors, final)
> >UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0:
> >truncated data
>
> >File size is 1630 bytes - so this clearly cannot be.
>
> How about posting your code?

He did. Ugly stuff using readline() :-) Should still work, though.
There are definite problems with readline() and readlines(),
including:

First file: silently ignores error *and* the last line returned is
garbage [consists of multiple actual lines, and the trailing
codepoints have been byte-swapped]

Second file: as he has just reported. I've reproduced it with f.open
('second_file.txt', encoding='utf16')
followed by each of:
(1) f.readlines()
(2) list(f)
(3) for line in f:
print(repr(line))
With the last one, the error happens after printing the last actual
line in his file.

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


Re: Can't get exclusive file lock when safely renaming a file

2008-12-06 Thread Jeffrey Straszheim

Steven D'Aprano wrote:
I'm trying to safely rename a file without over-writing any existing 
files, and I've run into a problem with file locks. Here's a naive way of 
renaming without over-writing
By default on a Linux filesystem, flock() gives you an _advisory_ lock.  
Other processes can touch the file unless they explicitly check the lock.


Try

 man mount  (see under the -o mand)

and

 man fcntl (see under file locking)

Jeffrey Straszheim

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


Re: Guido's new method definition idea

2008-12-06 Thread Carl Banks
On Dec 5, 8:21 pm, "Daniel Fetchinson" <[EMAIL PROTECTED]>
wrote:
> Hi folks,
>
> The story of the explicit self in method definitions has been
> discussed to death and we all know it will stay. However, Guido
> himself acknowledged that an alternative syntax makes perfect sense
> and having both (old and new) in a future version of python is a
> possibility since it maintains backward compatibility. The alternative
> syntax will be syntactic sugar for the old one. This blog post of his
> is what I'm talking about:
>
> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay...
>
> The proposal is to allow this:
>
> class C:
>     def self.method( arg ):
>         self.value = arg
>         return self.value
>
> instead of this:
>
> class C:
>     def method( self, arg ):
>         self.value = arg
>         return self.value



-1

I explained why deep in the thread but I'll elaborate more here.  When
I see a def statement, I mentally equate that to an assigment to the
thing being def'ed.  So for instance, when I see this:

  def ():

I think of it like this:

   = 


Thus, if I were to see a function definition like this

  def foo.bar(): return 1

I would think you were defining a function and assigning it to
foo.bar.  IOW, it would be mostly equivalent to this:

  foo.bar = lambda: 1


(Analogously, I would expect a definition like this:

  def baz[10](): return 1

to be equivalent to this:

  baz[10] = lambda: 1  )


So, if, inside a class definition, I were to see this:

  def self.method(): return 1

Well, I'd understand that is was a method assigment, of course, but it
would conflict with what I would expect the natural meaning of
something like def a.b() would be.  The above statement is not
equivalent to:

  self.method = lambda: 1

but I think that's what it ought to be, in general.



Carl Banks


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


Re: Guido's new method definition idea

2008-12-06 Thread Carl Banks
On Dec 6, 9:12 am, "Russ P." <[EMAIL PROTECTED]> wrote:
> On Dec 6, 1:02 am, Antoine De Groote <[EMAIL PROTECTED]> wrote:
>
>
>
> > Allowing "$" as a substitute for "self" wouldn't require this new syntax.
>
> > class C:
> >     def method($, arg):
> >         $.value = arg
>
> > I'm strongly against this. This looks ugly and reminds me of Perl and
> > Ruby. (I don't have anything against these languages, but there's a
> > reason I use Python).
>
> > Russ P. wrote:
> > > On Dec 5, 6:21 pm, "Daniel Fetchinson" <[EMAIL PROTECTED]>
> > > wrote:
> > >> Hi folks,
>
> > >> The story of the explicit self in method definitions has been
> > >> discussed to death and we all know it will stay. However, Guido
> > >> himself acknowledged that an alternative syntax makes perfect sense
> > >> and having both (old and new) in a future version of python is a
> > >> possibility since it maintains backward compatibility. The alternative
> > >> syntax will be syntactic sugar for the old one. This blog post of his
> > >> is what I'm talking about:
>
> > >>http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay...
>
> > >> The proposal is to allow this:
>
> > >> class C:
> > >>     def self.method( arg ):
> > >>         self.value = arg
> > >>         return self.value
>
> > >> instead of this:
>
> > >> class C:
> > >>     def method( self, arg ):
> > >>         self.value = arg
> > >>         return self.value
>
> > >> I.e. explicit self stays only the syntax is slightly different and may
> > >> seem attractive to some. As pointed out by Guido classmethods would
> > >> work similarly:
>
> > >> class C:
> > >>     @classmethod
> > >>     def cls.method( arg ):
> > >>         cls.val = arg
> > >>         return cls.val
>
> > >> The fact that Guido says,
>
> > >> "Now, I'm not saying that I like this better than the status quo. But
> > >> I like it a lot better than [...] but it has the great advantage that
> > >> it is backward compatible, and can be evolved into a PEP with a
> > >> reference implementation without too much effort."
>
> > >> shows that the proposal is viable.
>
> > >> I'd like this new way of defining methods, what do you guys think?
> > >> Anyone ready for writing a PEP?
>
> > >> Cheers,
> > >> Daniel
>
> > >> --
> > >> Psss, psss, put it down! -http://www.cafepress.com/putitdown
>
> > > I like it.
>
> > > I'll even go a step further and suggest that "$" be allowed as a
> > > substitute for "self". It looks like a capital "S" (for Self), and it
> > > stands out clearly. It also makes code more succinct with no loss of
> > > readability. Think of the line wraps that could be avoided.
>
> It looks "ugly" simply because it is new to you. Once you get used to
> it, I'll bet it will look fine. And resemblance to another language is
> not a very good reason to reject it.

Perl is not new to me and I am familiar with the syntax, such as it
is.  I find it unspeakably ugly.  So, no, you would lose your bet if
it were me.


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


first time in the internet history a huge collection of funny pictures and videos over 10000 funny pics and videos download free on mobile format www.funreality.com

2008-12-06 Thread philips
first time in the internet history a huge collection of funny pictures
and videos
 over 1 funny pics and videos download free on mobile format
www.funreality.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Carl Banks
On Dec 6, 9:15 am, "Russ P." <[EMAIL PROTECTED]> wrote:
> On Dec 6, 4:32 am, Andreas Waldenburger <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Sat, 6 Dec 2008 04:02:54 -0800 (PST) [EMAIL PROTECTED] wrote:
>
> > > class C:
> > >     def $method(arg):
> > >         $value = arg
>
> > > (Note there's no point after $, it's not currently possible).
> > > Ruby uses @ and @@ for similar purposes.
> > > I agree that the code looks worse, but also shorter to read and write,
> > > so in lines of code that use many instance attributes, that short $
> > > syntax helps keep the line shorter. So I may grow to accept this
> > > sugar...
>
> > But that is not the way Python is meant to work. There are several
> > tennets in the Zen of Python that don't chime well with this approach.
> > "self" is a speaking identifier, "$" isn't.
>
> Is "@" a "speaking identifier? How about "#" and "!="? Last I heard,
> they were all part of Python.

None of them are identifiers.  $, used as proposed, would be.

(Then again, _ is an identifier.)

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


Re: Guido's new method definition idea

2008-12-06 Thread Carl Banks
On Dec 6, 12:47 am, "Patrick Mullen" <[EMAIL PROTECTED]> wrote:
> Could I do something like this:
>
> def a.add(b): return a+b
>
> Outside of a class?  Of course then that makes you think you could do
> 5.add(6) or something crzy like that.  (I mean, you can do
> (5).__add__(6) but that's something else entirely)


I'd be inclined to think that this defines an instancemethod on an
existing object a.  In other word, I'd read the following two lines as
more or less equivalent.

def a.add(b): return a+b

a.add = lambda b: a+b


Just as the following are equivalent:

def foo(): return bar

foo = lambda: bar


I had been -0 on this, but now I think I'm -1.


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


Re: slow Python 3.0 write performance?

2008-12-06 Thread Terry Reedy

Christian Heimes wrote:

Istvan Albert wrote:

A previous poster suggested that in this case the slowdown is caused
by the new io code being written in python rather than C.


For text mode Python 3's write() method is slower than Python 2.x's 
method because all text is encoded. The slowdown is mostly caused by 
additional code for line ending detection and decoding/encoding. The new 
io library does more than the old file object


So far the new io library hasn't been optimized yet, too. Please give it 
some time and report speed issues at http://bugs.python.org/.


On WinXP, tests 3 times each
---
3.0
---

import time
line = 'a'*99 + '\n'
text = line*50

start=time.time()
open('wtest', 'w').write(text)
print(time.time()-start)

# 3.4 to 4.0

import time
line = 'a'*99 + '\n'
text = line*50

start=time.time()
text = bytes(line,'ascii')*50
print(time.time()-start)

# 1.1 to 1.25

start=time.time()
open('wtest', 'wb').write(text) # note wb
print(time.time()-start)

# 1.5 to 1.8
--
2.5
---

import time
line = 'a'*99 + '\n'
text = line*50

start=time.time()
open('wtest', 'w').write(text)
print(time.time()-start)

# 3.3 to 4.1

import time
line = 'a'*99 + '\n'
text = line*50

start=time.time()
open('wtest', 'wb').write(text) # note wb
print(time.time()-start)

# 1.0 to 1.6
-

Conclusion:
1. on WinXP, writing with 3.0 has no slowdown versus 2.5
2. on WinXP, binary mode writing is about 3 times faster that text mode 
writing with its line-ending expansion. If that is not needed, binary 
mode and explicit bytes-text conversion is about twice as fast.


Terry Jan Reedy

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


Re: Learning Python now coming from Perl

2008-12-06 Thread Carl Banks
On Dec 6, 12:30 pm, Roy Smith <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Aahz)
> wrote:
>
> > In article <[EMAIL PROTECTED]>,
> > Bertilo Wennergren  <[EMAIL PROTECTED]> wrote:
>
> > >I don't suppose there is any introductory material out there that is
> > >based on Python 3000 and that is also geared at people with a Perl
> > >background? Too early for that I guess..
>
> > Honestly, the differences between 2.x and 3.0 are small enough that it
> > doesn't much matter, as long as you're not the kind of person who gets
> > put off by little problems.  Because so much material is for 2.x, you
> > may be better off just learning 2.x first and then moving to 3.x.
>
> I'm not sure I agree.  If you're starting out, you might as well learn the
> new stuff.  Then there's no need to unlearn the old way.

One disadvantage of learning Python 3 first is the availability of
third-party libraries (especially extension libraries), most of which
will not be updated for Python 3.x for quite a while.

Also, I don't think it's really advisable to be completely ignorant of
the 2.x difference even if one intends to start with 3.0.  There is a
lot of code and material out there for 2.x, and until these start to
be widely available for 3.x, people will sometimes have to make do
with the 2.x stuff.


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


Select, interrupted system call, log rotation?

2008-12-06 Thread Rainy
I got an interrupted system call exception in select and I don't know
what could have caused it. Here's the error:

select.select(inputs, [], [], 9)
error: (4, 'Interrupted system call')
Caught an exception, shutting down...

It's py2.3, on mach architecture.

I'm trying to figure out what caused it, and the only idea I have so
far is that it could be that I have python's logging system log
rotation thing running and I think I've seen a reference somewhere
that it uses SIGALRM when log file reaches set size to stop and switch
the files. The program was running for about a week without any
problem and then I got this exception and after I restarted it it's
been running for a few days and I only got the exception once in all
that time.

Am I going in a completely wrong direction here? I'm thinking of just
putting select in try: except: , is that a good idea here?

I don't understand signals all that well. Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python now coming from Perl

2008-12-06 Thread Rainy
On Dec 6, 5:00 am, Bertilo Wennergren <[EMAIL PROTECTED]> wrote:
> I'm planning to start learning Python now, using Python 3000.
> I have no previous Python skills, but I now Perl pretty well.
> I'm also well experienced with JavaScript.
>
> Any pointers and tips how I should go about getting into
> Python?
>
> --
> Bertilo Wennergren 

There's a lot of hoopla about Py3k being different, incompatible
with Py2.x. However, you have to keep in mind that this matters
most of all to old, large programs, which will need to be changed
if one would like to run them on Py3k. For learning the differences
don't matter much. If you learn to code in py2.x for half a year,
you will be able to pick up on most of the differences and transfer
to py3k in a few days. If you find good docs on py2.x go ahead and
use them and don't worry.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] "as" keyword woes

2008-12-06 Thread Guido van Rossum
On Sat, Dec 6, 2008 at 11:38 AM, Warren DeLano <[EMAIL PROTECTED]> wrote:
[...]
> There, I assert that 'object.as(class_reference)' is the simplest and
> most elegant generalization of this widely-used convention.  Indeed, it
> is the only obvious concise answer, if you are limited to using methods
> for casting.

Well, that's too bad, as 'as' is now a reserved word.

> Although there are other valid domain-specific uses for "as" as either a
> local variable or attribute names (e.g. systematic naming: as, bs, cs),
> those aren't nearly as important compared to "as" being available as the
> name of a generalized casting method -- one that is now strictly denied
> to users of Python 2.6 and 3.

If you had brought this up 5-10 years ago when we first introduced
'as' as a semi-keyword (in the import statement) we might have been
able to avert this disaster. As it was, nobody ever brought this up
AFICR, so I don't think it's *that* obvious.

> As someone somewhat knowledgable of how parsers work, I do not
> understand why a method/attribute name "object_name.as(...)" must
> necessarily conflict with a standalone keyword " as ".  It seems to me
> that it should be possible to unambiguously separate the two without
> ambiguity or undue complication of the parser.

That's possible with sufficiently powerful parser technology, but
that's not how the Python parser (and most parsers, in my experience)
treat reserved words. Reserved words are reserved in all contexts,
regardless of whether ambiguity could arise. Otherwise *every*
reserved word would have to be allowed right after a '.', and many
keywords would have to be allowed as identifiers in other contexts.
That way lies PL/1...

Furthermore, how would you define the 'as' method? Would you also want
to be allowed to write

def as(self, target): ...

??? Trust me, it's a slippery slope, and you don't want to start going
down there.

> So, assuming I now wish to propose a corrective PEP to remedy this
> situation for Python 3.1 and beyond, what is the best way to get started
> on such a proposal?

Don't bother writing a PEP to make 'as' available as an attribute
again. It has no chance of being accepted. Instead, think of a
different word you could use.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)
--
http://mail.python.org/mailman/listinfo/python-list


Re: python book for non technical absolute beginner

2008-12-06 Thread Terry Reedy

News123 wrote:


One of my 'non technical' friends complained about knowing nothing at
all about programming (though using computers regularly for mails / web
browsing / googling and downloading / cropping photos )

He wants to play a little with programming to stimulate parts of his
otehrwise idle brain cells. ;-) Normally it's more the social science /
linguistic parts being exercised,

I thought python might be a nice language for this

No my question does anybody know a nice beginners book (or a learning CD
or on line tutorial)? Ideally it shouldn't be too serious and have a lot
of small nice mini-examples

thanks in advance for any suggestions hints


I started with the 1.3 version of
http://docs.python.org/tutorial/index.html
(but had lots of previous experience).

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


Re: "as" keyword woes

2008-12-06 Thread Lie
On Dec 7, 2:38 am, "Warren DeLano" <[EMAIL PROTECTED]> wrote:
> > Date: Fri, 05 Dec 2008 22:22:38 -0800
> > From: Dennis Lee Bieber <[EMAIL PROTECTED]>
> > Subject: Re: "as" keyword woes
> > To: [EMAIL PROTECTED]
> > Message-ID: <[EMAIL PROTECTED]>
>
> >    I'm still in the dark as to what type of data could
> > even inspire the
> > use of "as" as an object name... A collection of "a" objects? In which
> > case, what are the "a"s? 
>
> Please let me clarify.  It is not "as" as a standalone object that we
> specifically miss in 2.6/3, but rather, the ability to use ".as" used as
> a method or attribute name.  
>
> In other words we have lost the ability to refer to "as" as the
> generalized OOP-compliant/syntax-independent method name for casting:
>
> new_object = old_object.as(class_hint)
>
> # For example:
>
> float_obj = int_obj.as("float")
>
> # or
>
> float_obj = int_obj.as(float_class)
>
> # as opposed to something like
>
> float_obj = int_obj.asFloat()
>
> # which requires a separate method for each cast, or
>
> float_obj = (float)int_obj  
>
> # which required syntax-dependent casting [language-based rather than
> object-based].
>
> Of course, use of explicit casting syntax "(float)" is fine if you're
> restricting yourself to Python and other languages which support
> casting, but that solution is unavailable inside of a pure OOP
> message-passing paradigm where object.method(argument) invocations are
> all you have to work with.  
>
> Please note that use of object.asClassname(...) is a ubiqitous
> convention for casting objects to specific classes (seen in ObjectiveC,
> Java, SmallTalk, etc.).  
>
> There, I assert that 'object.as(class_reference)' is the simplest and
> most elegant generalization of this widely-used convention.  Indeed, it
> is the only obvious concise answer, if you are limited to using methods
> for casting.
>
> Although there are other valid domain-specific uses for "as" as either a
> local variable or attribute names (e.g. systematic naming: as, bs, cs),
> those aren't nearly as important compared to "as" being available as the
> name of a generalized casting method -- one that is now strictly denied
> to users of Python 2.6 and 3.
>
> As someone somewhat knowledgable of how parsers work, I do not
> understand why a method/attribute name "object_name.as(...)" must
> necessarily conflict with a standalone keyword " as ".  It seems to me
> that it should be possible to unambiguously separate the two without
> ambiguity or undue complication of the parser.
>
> So, assuming I now wish to propose a corrective PEP to remedy this
> situation for Python 3.1 and beyond, what is the best way to get started
> on such a proposal?  
>
> Cheers,
> Warren

And let things like:

filelike.print('lpt') # python 2.6
zipper.with('7z')
failure.try(alternative)
executecodeobject.if(True)
onfailure.break()

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


Re: "as" keyword woes

2008-12-06 Thread Carl Banks
On Dec 6, 1:38 pm, "Warren DeLano" <[EMAIL PROTECTED]> wrote:
> There, I assert that 'object.as(class_reference)' is the simplest and
> most elegant generalization of this widely-used convention.  Indeed, it
> is the only obvious concise answer, if you are limited to using methods
> for casting.

I don't agree with your assertion.

object.as_type(class_reference)
object.cast(class_reference)

These are both concise and obvious.


> As someone somewhat knowledgable of how parsers work, I do not
> understand why a method/attribute name "object_name.as(...)" must
> necessarily conflict with a standalone keyword " as ".  It seems to me
> that it should be possible to unambiguously separate the two without
> ambiguity or undue complication of the parser.

It's possible, and they've been doing it for years, and they could
have continued doing it if they wanted to.

You'll notice that nowhere the Python grammar can two identifiers be
separated by whitespace.  So if you have two identifiers separated by
whitespace, and the second one is "as", you know it has to be keyword
"as".

Well, they made it a keyword anyway.  It was never a question of
whether they could do it.


> So, assuming I now wish to propose a corrective PEP to remedy this
> situation for Python 3.1 and beyond, what is the best way to get started
> on such a proposal?  

I think you'd be wasting your time, but the general procedure is
outlined in PEP 1.

Basically, you write a pre-PEP (aka PEP XXX) according to the
guidelines in PEP 1, which you would post here and request comments on
it.  Then, if you can muster some support for it, you would send it to
PEP maintainer (the email is listed somewhere on the PEPs page, dig
for it), and get a number assigned, upon which time Guido van Rossum
will read it and any comments in python-dev, and make a pronouncement
of some sort.

If you write a PEP, I advise you to try to sound less whiny and than
you have in this thread.  Saying "object.as(class_reference) is highly
convenient because it mirrors textually the Java convention of
object.asFloat" will go over a lot better than "object.as
(class_reference) is the only obvious concise answer".


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


Re: "as" keyword woes

2008-12-06 Thread Terry Reedy

In my opinion, this thread is a crock of balony.

Python *occasionally* adds keywords after giving a warning or requiring 
a future import in previous versions.


In 2.2, one had to 'from __future__ import generators' to make a 
generator because doing so required the new 'yield' keyword.

In 2.3, yield became a keyword without the import.

In 2.5, one had to 'from __future__ import with_statement' to make a 
'with' statement.  In 2.6, with because a keyword without the import.

And no one seems to have noticed.  No '"with" keyword woes.

In 2.6, 'as' also because a full-time keyword after several releases of 
being an anomalous part-time contextual keyword.


tjr

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


Re: Detaching e-mail attachments?

2008-12-06 Thread Terry Reedy

Ken D'Ambrosio wrote:

Hi, all.  I've done some poking around, and can find roughly two million
different ways to attach attachments to an e-mail... but darn few to
detach them.  Any suggestions?  I'm assuming I'm just missing looking in
The Right Place, but thus-far, my Googling has been for naught.


Try the email package doc in the Lib Manual.

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


Re: Rich Comparisons Gotcha

2008-12-06 Thread Terry Reedy

Rasmus Fogh wrote:

Dear All,

For the first time I have come across a Python feature that seems
completely wrong. After the introduction of rich comparisons, equality
comparison does not have to return a truth value, and may indeed return
nothing at all and throw an error instead. As a result, code like
  if foo == bar:
or
  foo in alist
cannot be relied on to work.

This is clearly no accident. According to the documentation all comparison
operators are allowed to return non-booleans, or to throw errors. There is
explicitly no guarantee that x == x is True.


You have touched on a real and known issue that accompanies dynamic 
typing and the design of Python.  *Every* Python function can return any 
Python object and may raise any exception either actively, by design, or 
passively, by not catching exceptions raised in the functions *it* calls.



Personally I would like to get these [EMAIL PROTECTED]&* misfeatures removed,


What you are calling a misfeature is an absence, not a presence that can 
be removed.



and constrain the __eq__ function to always return a truth value.


It is impossible to do that with certainty by any mechanical 
creation-time checking.  So the implementation of operator.eq would have 
to check the return value of the ob.__eq__ function it calls *every 
time*.  That would slow down the speed of the 99.xx% of cases where the 
check is not needed and would still not prevent exceptions.  And if the 
return value was bad, all operator.eq could do is raise and exception 
anyway.



That is clearly not likely to happen. Unless I have misunderstood something, 
could
somebody explain to me.


a. See above.
b. Python programmers are allowed to define 'weird' but possibly 
useful-in-context behaviors, such as try out 3-value logic, or to 
operate on collections element by element (as with numpy).



1) Why was this introduced?


The 6 comparisons were previously done with one __cmp__ function that 
was supposed to return -1, 0, or 1 and which worked with negative, 0, or 
positive response, but which could return anything or raise an 
exception.  The compare functions could mask but not prevent weird returns.


 I can understand relaxing the restrictions on

'<', '<=' etc. - after all you cannot define an ordering for all types of
object. But surely you can define an equal/unequal classification for all
types of object, if you want to? Is it just the numpy people wanting to
type 'a == b' instead of 'equals(a,b)', or is there a better reason?

2) If I want to write generic code, can I somehow work around the fact
that
  if foo == bar:
or
  foo in alist
does not work for arbitrary objects?


Every Python function is 'generic' unless restrained by type tests. 
However, even 'generic' functions can only work as expected with objects 
that meet the assumptions embodied in the function.  In my Python-based 
algorithm book-in-progess, I am stating this explicitly.  In particular, 
I say taht the book only applies to objects for which '==' gives a 
boolean result that is reflexive, symmetric, and transitive.  This 
exludes float('nan'), for instance (as I see you discovered), which 
follows the IEEE mandate to act otherwise.



CCPN has a table display class that maintains a list of arbitrary objects,
one per line in the table. The table class is completely generic,


but only for the objects that meet the implied assumption.  This is true 
for *all* Python code.  If you want to apply the function to other 
objects, you must either adapt the function or adapt or wrap the objects 
to give them an interface that does meet the assumptions.


> and subclassed for individual cases. It contains the code:


  if foo in tbllist:
...
  else:
...
tbllist.append(foo)
...

One day the 'if' statement gave this rather obscure error:
"ValueError:
 The truth value of an array with more than one element is ambiguous.
 Use a.any() or a.all()"
A subclass had used objects passed in from some third party code, and as
it turned out foo happened to be a tuple containing a tuple containing a
numpy array.


Right.  'in' calls '==' and assumes a boolean return.  Assumption 
violated, exception raised.  Completely normal.  The error message even 
suggests a solution: wrap the offending objects in an adaptor class that 
gives them a normal interface with .all (or perhaps the all() builtin).


Terry Jan Reedy


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


Re: python book for non technical absolute beginner

2008-12-06 Thread Pekka Klärck
2008/12/6 News123 <[EMAIL PROTECTED]>:
> No my question does anybody know a nice beginners book (or a learning CD
> or on line tutorial)? Ideally it shouldn't be too serious and have a lot
> of small nice mini-examples

How to Think Like a Computer Scientist - Learning with Python is a
good book for beginners and it is available for free under the GNU
license.

http://www.greenteapress.com/thinkpython/thinkCSpy/

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


Re: "as" keyword woes

2008-12-06 Thread Warren DeLano
 
> Date: Fri, 05 Dec 2008 22:22:38 -0800
> From: Dennis Lee Bieber <[EMAIL PROTECTED]>
> Subject: Re: "as" keyword woes
> To: python-list@python.org
> Message-ID: <[EMAIL PROTECTED]>
> 
>   I'm still in the dark as to what type of data could 
> even inspire the
> use of "as" as an object name... A collection of "a" objects? In which
> case, what are the "a"s? 

Please let me clarify.  It is not "as" as a standalone object that we
specifically miss in 2.6/3, but rather, the ability to use ".as" used as
a method or attribute name.  

In other words we have lost the ability to refer to "as" as the
generalized OOP-compliant/syntax-independent method name for casting:

new_object = old_object.as(class_hint)

# For example:

float_obj = int_obj.as("float")

# or 

float_obj = int_obj.as(float_class)

# as opposed to something like

float_obj = int_obj.asFloat()

# which requires a separate method for each cast, or

float_obj = (float)int_obj  

# which required syntax-dependent casting [language-based rather than
object-based].

Of course, use of explicit casting syntax "(float)" is fine if you're
restricting yourself to Python and other languages which support
casting, but that solution is unavailable inside of a pure OOP
message-passing paradigm where object.method(argument) invocations are
all you have to work with.  

Please note that use of object.asClassname(...) is a ubiqitous
convention for casting objects to specific classes (seen in ObjectiveC,
Java, SmallTalk, etc.).  

There, I assert that 'object.as(class_reference)' is the simplest and
most elegant generalization of this widely-used convention.  Indeed, it
is the only obvious concise answer, if you are limited to using methods
for casting.

Although there are other valid domain-specific uses for "as" as either a
local variable or attribute names (e.g. systematic naming: as, bs, cs),
those aren't nearly as important compared to "as" being available as the
name of a generalized casting method -- one that is now strictly denied
to users of Python 2.6 and 3.

As someone somewhat knowledgable of how parsers work, I do not
understand why a method/attribute name "object_name.as(...)" must
necessarily conflict with a standalone keyword " as ".  It seems to me
that it should be possible to unambiguously separate the two without
ambiguity or undue complication of the parser.

So, assuming I now wish to propose a corrective PEP to remedy this
situation for Python 3.1 and beyond, what is the best way to get started
on such a proposal?  

Cheers,
Warren







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


Re: Profiling Python

2008-12-06 Thread Dieter Maurer
[EMAIL PROTECTED] writes on Wed, 3 Dec 2008 07:13:14 -0800 (PST):
> To clarify again,
> Is there some function like profile.PrintStats() which dynamically
> shows the stats before stopping the Profiler?

Try to (deep) copy the profiler instance and than call "PrintStats()"
on the copy.

Of course, you will then profile also the "PrintStats" in the running
profiler.


Dieter

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


Re: Python 3.0 automatic decoding of UTF16

2008-12-06 Thread Mark Tolonen
"Johannes Bauer" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

John Machin schrieb:

On Dec 6, 5:36 am, Johannes Bauer <[EMAIL PROTECTED]> wrote:

So UTF-16 has an explicit EOF marker within the text? I cannot find one
in original file, only some kind of starting sequence I suppose
(0xfeff). The last characters of the file are 0x00 0x0d 0x00 0x0a,
simple \r\n line ending.


Sorry, *WRONG*. It ends in 00 0d 00 0a 00. The file is 1559 bytes
long, an ODD number, which shouldn't happen with utf16.  The file is
stuffed. Python 3.0 has a bug; it should give a meaningful error
message.


Yes, you are right. I fixed the file, yet another error pops up
(http://www.file-upload.net/download-1299688/2008_12_05_Handy_Backup.txt.html):

Traceback (most recent call last):
 File "./modify.py", line 12, in 
   a = AddressBook("2008_12_05_Handy_Backup.txt")
 File "./modify.py", line 7, in __init__
   line = f.readline()
 File "/usr/local/lib/python3.0/io.py", line 1807, in readline
   while self._read_chunk():
 File "/usr/local/lib/python3.0/io.py", line 1556, in _read_chunk
   self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
 File "/usr/local/lib/python3.0/io.py", line 1293, in decode
   output = self.decoder.decode(input, final=final)
 File "/usr/local/lib/python3.0/codecs.py", line 300, in decode
   (result, consumed) = self._buffer_decode(data, self.errors, final)
 File "/usr/local/lib/python3.0/encodings/utf_16.py", line 69, in
_buffer_decode
   return self.decoder(input, self.errors, final)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x0a in position 0:
truncated data

File size is 1630 bytes - so this clearly cannot be.


How about posting your code?  The first file is incorrect.  It contains an 
extra 0x00 byte at the end of the file, but is otherwise correctly encoded 
with a big-endian UTF16 BOM and data.  The second file is a correct UTF16-BE 
file as well.


This code (Python 2.6) decodes the first file, removing the trailing extra 
byte:


   raw = open('2008_11_05_Handy_Backup.txt').read()
   data = raw[:-1].decode('utf16')

and this code (Python 2.6) decodes the second:

   raw = open('2008_12_05_Handy_Backup.txt').read()
   data = raw.decode('utf16')

Python 3.0 also has no problems with decoding or accurate error messages:


data = open('2008_12_05_Handy_Backup.txt',encoding='utf16').read()
data = open('2008_11_05_Handy_Backup.txt',encoding='utf16').read()

Traceback (most recent call last):
 File "", line 1, in 
 File "C:\dev\python30\lib\io.py", line 1724, in read
   decoder.decode(self.buffer.read(), final=True))
 File "C:\dev\python30\lib\io.py", line 1295, in decode
   output = self.decoder.decode(input, final=final)
 File "C:\dev\python30\lib\codecs.py", line 300, in decode
   (result, consumed) = self._buffer_decode(data, self.errors, final)
 File "c:\dev\python30\lib\encodings\utf_16.py", line 61, in _buffer_decode
   codecs.utf_16_ex_decode(input, errors, 0, final)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x00 in position 1558: 
trunc

ated data

-Mark


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


Re: Learning Python now coming from Perl

2008-12-06 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> On Sat, 06 Dec 2008 08:50:20 -0500, Roy Smith wrote:
> 
> > For your first
> > project, pick something that's small enough that you think you could
> > tackle it in under 50 lines of Perl.
> 
> Is there anything which *can't* be written in under 50 lines of Perl?
[...]
> Also, Perl REs are faster than Python REs, or so I'm told. Between the 
> speed and the convenience, Perl programmers tend to use RE's for 
> everything they can. Python programmers tend to use REs only for problems 
> that *should* be solved with REs rather than *can* be solved with a RE.

Well, as an old-time unix hacker (who learned REs long before Perl 
existed), my question to you would be, "Is there any problem which 
*shouldn't* be solved with an RE?" :-)

It's easy to go nuts with REs, and create write-only code. On the other 
hand, they are an extremely powerful tool.  If you are wise in the ways of 
RE-fu, they can not only be the most compact way to write something, but 
also the most efficient and even the most comprehensible.  Unfortunately, 
REs seem to be regarded as some kind of monster these days and few people 
take the time to master them fully.  Which is a shame.

One really nice feature of REs in Python is the VERBOSE flag.  It lets you 
write some way-complicated REs in a way which is still easy for somebody to 
read and understand.  Python's raw strings, and triple-quoted strings, also 
help reduce the sea of backslashes which often make REs seem much worse 
than they really are.

One of the reasons REs don't get used in Python as much as in Perl is 
because strings have useful methods like startswith(), endswith(), and 
split(), and also the "in" operator.  These combine to give you easy ways 
to do many things you might otherwise do with REs.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python now coming from Perl

2008-12-06 Thread Martin P. Hellwig

News123 wrote:


What's more painful is to learn which functianilty is in which library
and which library exists.



Yes and one mistake I still often find myself doing is, when confronted 
with a particular problem, that I write some helper code to deal with 
it. Of course later on I discover that there is a standard module or 
built-in that does exactly what I want and better. :-)


Somehow in the heat of the moment my mind is not thinking 'there must be 
something out there which does what I want' but rather 'hmmm I think I 
can do it this way, clicker-di-click'.


In my opinion it is a positive attribute to the language that it makes 
solving problems so easy that you forget about searching for solutions. 
Maybe python should prompt every 10 lines of code a message saying 'Are 
you sure this can not be done with a built-in?' Most of the time it will 
be right anyway :-)


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


Re: operators as variables

2008-12-06 Thread Terry Reedy

macc_200 wrote:

Hi,
just starting programming and have an elementary question after playing 
around with lists but cannot find the answer with googling.
I have a list of variables and I would like some of those variables to 
be integers and some to be operators so the list would look something 
like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get 
10).  How do you make the interpreter see the operator as that instead 
of a string and just echo the list back to me.


I am not sure what you actually want to do, but the following may help:

1. Strings can be evaluated.
2. Operators are syntax sugar for functions.  The functions are 
available in the operator module.


IDLE 3.0
>>> eval('5 * 4 - 4 + 6')
22
>>> import operator as op
>>> op.add(2,3)
5

tjr

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


Re: Python calling COM compliant .dll

2008-12-06 Thread Gabriel Genellina
En Wed, 03 Dec 2008 16:20:27 -0200, David Shi <[EMAIL PROTECTED]>  
escribió:


I am looking for a concise working example of Python script calling COM  
compliant .dll.


The best source of information is Mark Hammond's book "Python Programming  
in Win32".

The sample chapters available are about using COM objects, AFAIR.

--
Gabriel Genellina

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


Re: Learning Python now coming from Perl

2008-12-06 Thread Roy Smith
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Aahz) 
wrote:

> In article <[EMAIL PROTECTED]>,
> Bertilo Wennergren  <[EMAIL PROTECTED]> wrote:
> >
> >I don't suppose there is any introductory material out there that is
> >based on Python 3000 and that is also geared at people with a Perl
> >background? Too early for that I guess..
> 
> Honestly, the differences between 2.x and 3.0 are small enough that it
> doesn't much matter, as long as you're not the kind of person who gets
> put off by little problems.  Because so much material is for 2.x, you
> may be better off just learning 2.x first and then moving to 3.x.

I'm not sure I agree.  If you're starting out, you might as well learn the 
new stuff.  Then there's no need to unlearn the old way.

Using material meant for 2.x is likely to lead to confusion.  If you don't 
know either, you'll never know if something isn't working as described 
because you're doing it wrong or if it's just not the same as it used to 
be.  When everything is new, what seem like little stumbling blocks to 
experts become total blockers to people starting from zero.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python now coming from Perl

2008-12-06 Thread News123
I fully agree with Roy's answer.

COding small tasks is a good starting point. For quite some time you'll
be of course less efficient than with your previous language, but that's
part of the learning curve, isn't it.

I guess you'll learn the syntax rather quickly.
What's more painful is to learn which functianilty is in which library
and which library exists.

There's of course a lot of online documentation, but often you find
answers to trivial python questions fastest with Google:
for example:  search for something like "python string reverse example"

And there's of course this newsgroup whenever you're stuck with a
'missing' feature, (though mostly the features aren't missing, but just
a little different)


bye

N


Roy Smith wrote:
> In article <[EMAIL PROTECTED]>,
>  Bertilo Wennergren <[EMAIL PROTECTED]> wrote:
> 
>> I'm planning to start learning Python now, using Python 3000.
>> I have no previous Python skills,
>> . . . 
> 
> I assume you use Perl to solve real problems in whatever job you do.  My 
> recommendation would be the next time some problem comes up that you would 
> normally solve with Perl, try doing it in Python.  Having a real task that 
> you need to accomplish is a great way to focus the mind.  For your first 
> project, pick something that's small enough that you think you could tackle 
> it in under 50 lines of Perl.
> 
> One of the very first things you'll probably discover that's different 
> between Perl and Python is how they handle string pattern matching.  In 
> Perl, it's a built in part of the language syntax.  In Python, you use the 
> re module.  The regular expressions themselves are the same, but the 
> mechanism you use to apply them to input text is quite different.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread MRAB

Neal Becker wrote:

Daniel Fetchinson wrote:


Hi folks,

The story of the explicit self in method definitions has been
discussed to death and we all know it will stay. However, Guido
himself acknowledged that an alternative syntax makes perfect sense
and having both (old and new) in a future version of python is a
possibility since it maintains backward compatibility. The alternative
syntax will be syntactic sugar for the old one. This blog post of his
is what I'm talking about:

http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html

The proposal is to allow this:

class C:
def self.method( arg ):
self.value = arg
return self.value

instead of this:

class C:
def method( self, arg ):
self.value = arg
return self.value

I.e. explicit self stays only the syntax is slightly different and may
seem attractive to some. As pointed out by Guido classmethods would
work similarly:

class C:
@classmethod
def cls.method( arg ):
cls.val = arg
return cls.val

The fact that Guido says,

"Now, I'm not saying that I like this better than the status quo. But
I like it a lot better than [...] but it has the great advantage that
it is backward compatible, and can be evolved into a PEP with a
reference implementation without too much effort."

shows that the proposal is viable.

I'd like this new way of defining methods, what do you guys think?
Anyone ready for writing a PEP?


What's the advantage?  If there is not a good reason, I would strongly opposed 
polluting the language.


I wouldn't want to see $ for "self." and ¢ (cent) for "cls." either...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread News123
Daniel Fetchinson wrote:
> The proposal is to allow this:
> 
> class C:
> def self.method( arg ):
> self.value = arg
> return self.value
>
> instead of this:
>
> class C:
> def method( self, arg ):
> self.value = arg
> return self.value

Hmm,


I'd give the proposal a -1. Perhaps I'm missing something though.

Does this really justify an enhancement?
Whether the implicit parameter is prepended with a dot or whether it's
the first parameter with the parantheses doesn't save me any typing and
the benefit of 'visualizing' how the function should be called seems
minor to me.

What would be interesting would be some syntactical sugar to get rid of
the 'self' (at least in the code body).

example:
class C:
class_elements a,b,c,d

def method(self,arg):
global d
a,b,c = arg[0..3]
d = a + b
self.e = a + d

instead of
class C:
def method(self,arg):
self.a,self.b,self.c,self.d = arg[0..4]
self.e = self.a + self.b



As far as I understood (I never really followed any of these threads),
getting rid of self has already been discussed and rejected many times.



bye


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


Re: Guido's new method definition idea

2008-12-06 Thread Neal Becker
Daniel Fetchinson wrote:

> Hi folks,
> 
> The story of the explicit self in method definitions has been
> discussed to death and we all know it will stay. However, Guido
> himself acknowledged that an alternative syntax makes perfect sense
> and having both (old and new) in a future version of python is a
> possibility since it maintains backward compatibility. The alternative
> syntax will be syntactic sugar for the old one. This blog post of his
> is what I'm talking about:
> 
> http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
> 
> The proposal is to allow this:
> 
> class C:
> def self.method( arg ):
> self.value = arg
> return self.value
> 
> instead of this:
> 
> class C:
> def method( self, arg ):
> self.value = arg
> return self.value
> 
> I.e. explicit self stays only the syntax is slightly different and may
> seem attractive to some. As pointed out by Guido classmethods would
> work similarly:
> 
> class C:
> @classmethod
> def cls.method( arg ):
> cls.val = arg
> return cls.val
> 
> The fact that Guido says,
> 
> "Now, I'm not saying that I like this better than the status quo. But
> I like it a lot better than [...] but it has the great advantage that
> it is backward compatible, and can be evolved into a PEP with a
> reference implementation without too much effort."
> 
> shows that the proposal is viable.
> 
> I'd like this new way of defining methods, what do you guys think?
> Anyone ready for writing a PEP?
> 
What's the advantage?  If there is not a good reason, I would strongly opposed 
polluting the language.


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


Re: RELEASED Python 3.0 final

2008-12-06 Thread MRAB

Mensanator wrote:

On Dec 5, 12:29 pm, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:

"Ben Finney" <[EMAIL PROTECTED]> wrote:

I hereby recommend “pish and tosh” for use by anyone who wants to
counter someone's point. It beats by a country furlong the invective
that has become regrettably common here in recent months.

I second the motion to use pish and tosh for a first level of disagreement.

I recommend the rather archaic "Balderdash" as the next step in the
escalation of disagreement...


As a W.C. Fields fan, I love his "non-swearing"
vocabulary:

- Drat

- Dag nab it

- Holy Mother of Pearl!

etc.


Holy Zarquon's Singing Fish! (Hitch-hiker's Guide to the Galaxy)

But don't say B*m. :-)
http://www.bbc.co.uk/cult/hitchhikers/guide/belgium.shtml
--
http://mail.python.org/mailman/listinfo/python-list


Re: "as" keyword woes

2008-12-06 Thread MRAB

Mensanator wrote:

On Dec 6, 8:16�am, Wolfgang Strobl <[EMAIL PROTECTED]> wrote:

Dennis Lee Bieber <[EMAIL PROTECTED]>:


On 05 Dec 2008 05:21:25 GMT, Steven D'Aprano
<[EMAIL PROTECTED]> declaimed the following in
comp.lang.python:

On Thu, 04 Dec 2008 08:44:19 -0800, Matimus wrote:

The point was that there
is that new releases don't _break_ anything.

But that's clearly not true, because the OP is pointing out that the new
release from 2.5 to 2.6 *does* break his code.

� �One now has to ask what "break" really meant... For this example,
the change did not break Python SYNTAX -- just a complaint about using
what is now a reserved word as an object name.

Of course it does:

C:\Python26>python
Python 2.6 (r26:66721, Oct �2 2008, 11:35:03) [MSC v.1500 32 bit
(Intel)] on win 32
Type "help", "copyright", "credits" or "license" for more information.>>> as=2

� File "", line 1
� � as=2
� � �^
SyntaxError: invalid syntax


I disagree. "Broken" is something you can't work
around. In this case, simply saying as_=2 works fine.

A better example of broken was when the gmpy module
wouldn't solve a certain linear congruence problem
because the problem was not invertible. But
mathematically, solving a linear congruence does
NOT depend on the problem being invertible. It was
the ALGORITHM that depended on the problem being
invertible and there was nothing the user could do
to make the algorithm behave properly. The algorithm
had to be altered to fix the special case of a
solvable linear congruence not being invertible.




Making a former syntactically valid �two letter name a reserved word in
2.6 was a mistake, IMHO.


I think you're in the minority there.

I think that its special use is clear from the syntax, so IMHO it 
could've been left for Python 3, but I'm not going to lose any sleep 
over it.



What's next? What about making i,j,k, x and y
reserved words in 2.7? =:-/


Yeah, right. That'll happen. You ought to be more
concerned about real problems.


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


operators as variables

2008-12-06 Thread macc_200
Hi,
just starting programming and have an elementary question after playing around 
with lists but cannot find the answer with googling.
I have a list of variables and I would like some of those variables to be 
integers and some to be operators so the list would look something like [5 * 
4 - 4 + 6] and then be able to evaluate the result (i.e. get 10).  How do you 
make the interpreter see the operator as that instead of a string and just echo 
the list back to me.
thanks,
Andy
(and suggestions for a decent Python book would be appreciated)



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


Re: Learning Python now coming from Perl

2008-12-06 Thread Aahz
In article <[EMAIL PROTECTED]>,
Bertilo Wennergren  <[EMAIL PROTECTED]> wrote:
>
>I don't suppose there is any introductory material out there that is
>based on Python 3000 and that is also geared at people with a Perl
>background? Too early for that I guess..

Honestly, the differences between 2.x and 3.0 are small enough that it
doesn't much matter, as long as you're not the kind of person who gets
put off by little problems.  Because so much material is for 2.x, you
may be better off just learning 2.x first and then moving to 3.x.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-06 Thread Tommy Grav


On Dec 6, 2008, at 11:42 AM, [EMAIL PROTECTED] wrote:

class ThisIsAClass:
   def $some_method(arg1, arg2):
   $value = arg1 + $foo + $bar + $baz * arg2
   ...


I think my biggest problem with this is what got me off Perl.
Add $, together with already used @ and maybe some other
identifiers and I start loosing track of what each of the character
means. It is fine when you are used to the language, but
learning it becomes a harder proposition. self.foo is self-explanatory
(no pun intended) to me, $foo is not.

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


Re: RELEASED Python 3.0 final

2008-12-06 Thread Mensanator
On Dec 5, 12:29 pm, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
> "Ben Finney" <[EMAIL PROTECTED]> wrote:
> >I hereby recommend “pish and tosh” for use by anyone who wants to
> >counter someone's point. It beats by a country furlong the invective
> >that has become regrettably common here in recent months.
>
> I second the motion to use pish and tosh for a first level of disagreement.
>
> I recommend the rather archaic "Balderdash" as the next step in the
> escalation of disagreement...

As a W.C. Fields fan, I love his "non-swearing"
vocabulary:

- Drat

- Dag nab it

- Holy Mother of Pearl!

etc.

>
> - hendrik

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


  1   2   >