Re: The worth of comments

2011-05-27 Thread Tim Roberts
Roy Smith  wrote:
>
>Over the years, my use of comments has evolved.  I was taught, "You 
>should comment your code".  Eventually, I came to realize that the real 
>mandate is, "You should make it easy to understand your code".  Comments 
>are just one possible tool to help achieve that goal.

Absolutely correct.  In my view, this is one of the strongest attributes of
Python -- its syntax is such that much of the code can be read out loud
like prose.  That's a HUGE benefit.  Code is read a lot more often than it
is written.

Ruby has a lot of followers, and I am trying to get excited about it, but
it has succumbed to the same special-characters-as-syntax disease that
killed Perl.  Much Ruby code is just unreadable.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Link errors embedding Python 3.2

2011-05-27 Thread Chris Angelico
On Fri, May 27, 2011 at 12:45 PM, Ned Deily  wrote:
>
> The discussion in http://bugs.python.org/issue4434 might be of some help.

Thanks Ned! That was most helpful. I'm still not sure exactly what I
changed, but between building with --enable-shared and some fiddling
with how I link my program, I've managed to get it all to work. Now to
start clean on a different box and try to deploy it... if I can do
that, then it's definitely working.

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


Re: Python's super() considered super!

2011-05-27 Thread Raymond Hettinger
On May 26, 6:39 pm, Ben Finney  wrote:
> We also, though, need *real* URLs. Blind URLs through obfuscation
> services have their uses, but surely not in a forum like this. The real
> URL is http://news.ycombinator.com/item?id=2588262>.

Fair enough.  I had copied the link from Jesse's tweet (where shorter
is better).

Hope you enjoyed the post.


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


Re: Why did Quora choose Python for its development?

2011-05-27 Thread Thorsten Kampe
* Steven D'Aprano (27 May 2011 03:07:30 GMT)
> Okay, I've stayed silent while people criticize me long enough. What 
> exactly did I say that was impolite? 

Nothing.

> John threw down a distinct challenge:
> 
> if Python is really so much better than Python [sic] 
> readability wise, why do I have such a hard time dropping
> Perl and moving on?
> [...]
> If I got it wrong about John, oh well, I said it was a guess, and
> trying to get inside someone else's head is always a chancy business.

Why were you trying to speculate in response to such a - sorry - dumb[1] 
question? What do his personal failures to switch to Python (why did he 
even try?) have to do with whether a) Python is more readable than Perl 
and b) whether readability counts towards productivity?

/Maybe/ it is simply because he "somehow like[s] Perl more" but 
definitely that is not really relevant to the question about 
readibility.

> Or maybe I just ran into him on a bad day.

"Bad argument day". His other "Python vs Perl is like Latin vs 
Devanagari" argument is not really better. The problem with Perl is that 
it does /not/ use (Latin) alphabetic characters (like a, b, c) to form 
words but symbols ($, %, @. |, *) and re-combines them to give them new 
and special meaning.

So this is exactly /not/ a alphabet vs alphabet thing but a word(s) vs 
symbols.

Thorsten
[1] Sorry for being impolite. But "why do I...?" kind of rhetorical 
questions (as arguments) are just dumb.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Ben Finney
Raymond Hettinger  writes:

> Hope you enjoyed the post.

I certainly did.

But I'm not better enlightened on why ‘super’ is a good thing. The
exquisite care that you describe programmers needing to maintain is IMO
just as much a deterrent as the super-is-harmful essay.

-- 
 \“If you continue running Windows, your system may become |
  `\unstable.” —Microsoft, Windows 95 bluescreen error message |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Michele Simionato
On Friday, May 27, 2011 10:49:52 AM UTC+2, Ben Finney wrote:
> The exquisite care that you describe programmers needing to maintain is IMO
> just as much a deterrent as the super-is-harmful essay.

Worth quoting. Also I think this article may encourage naive programmers along 
the dark path of cooperative multiple inheritance, when they could instead use 
better designs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of WindowsError error codes and meanings

2011-05-27 Thread Andrew Berg
On 2011.05.26 10:02 AM, Thomas Heller wrote:
> On Windows, you can use ctypes.FormatError(code) to map error codes
> to strings:
>
>  >>> import ctypes
>  >>> ctypes.FormatError(32)
> 'Der Prozess kann nicht auf die Datei zugreifen, da sie von einem 
> anderen Prozess verwendet wird.'
>  >>>
>
> For HRESULT codes, you (unfortunately) have to subtract 2**32-1 from
> the error code:
>
>  >>> ctypes.FormatError(0x80040005)
> Traceback (most recent call last):
>File "", line 1, in 
> OverflowError: long int too large to convert to int
>  >>> ctypes.FormatError(0x80040005 - (2**32-1))
> 'Kein Cache zum Verarbeiten vorhanden.'
>  >>>
I could get that with str(sys.exc_info()[1]), though. If something
raises a WindowsError, str(sys.exc_info()[1]) contains something like:
[Error 183] Cannot create a file when that file already exists:


sys.exc_info() is how I get the error code from inside an except clause
in the first place. Or is there something I'm missing here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-27 Thread Steven D'Aprano
On Fri, 27 May 2011 10:10:55 +0200, Thorsten Kampe wrote:

> * Steven D'Aprano (27 May 2011 03:07:30 GMT)
[...]
>> If I got it wrong about John, oh well, I said it was a guess, and
>> trying to get inside someone else's head is always a chancy business.
> 
> Why were you trying to speculate in response to such a - sorry - dumb[1]
> question?

Because someone was WRONG on the INTERNET!!!

*wink*


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


Re: bug in str.startswith() and str.endswith()

2011-05-27 Thread Duncan Booth
Carl Banks  wrote:

> The end parameter looks pretty useless for
> .startswith() and is probably only present for consistency with other
> string search methods like .index().

No, the end parameter could be useful if the slice ends up shorter than the 
prefix string:

>>> 'abcd'.startswith('abc', 0, 2)
False

Likewise the start parameter for endswith.

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Steven D'Aprano
On Fri, 27 May 2011 18:49:52 +1000, Ben Finney wrote:

> Raymond Hettinger  writes:
> 
>> Hope you enjoyed the post.
> 
> I certainly did.
> 
> But I'm not better enlightened on why ‘super’ is a good thing. 

Perhaps Raymond assumed that by now everybody knows that multiple 
inheritance in Python that doesn't use super is buggy. super() was 
introduced in version 2.2 in order to overcome bugs in MI, making it 
about 8 years old now.

(Technically, it's only MI with diamond-shaped inheritance, but that 
applies to *all* new-style classes. If you're writing multiple 
inheritance in Python 3 without using super, your code is a land-mine 
waiting to go off. If you're writing single inheritance, it's *still* a 
land-mine, just waiting for some poor caller to use it in a MI context.)

But I do agree with you in that I expected to see at least some 
discussion of why super should be actively preferred over calling the 
parent class directly.


> The
> exquisite care that you describe programmers needing to maintain is IMO
> just as much a deterrent as the super-is-harmful essay.

I don't see that Raymond describes anything needing "exquisite care". 
It's more common sense really: ensure that your method signature and that 
of your parents' match, plus good work-arounds for when they don't. 
Anyone using inheritance is almost certainly 98% of the way there, unless 
they're writing classes like this and wondering why they don't work :)

class MyBrokenList(list):
def __len__(self):
n = list.__len__(self, extra=42)
return n + 1
def __getitem__(self, i):
return list.__getitem__(self) + 1
def last_item(self):
return list.last_item(self) + 1


I was thrilled to learn a new trick, popping keyword arguments before 
calling super, and wondered why I hadn't thought of that myself. How on 
earth did I fail to realise that a kwarg dict was mutable and therefore 
you can remove keyword args, or inject new ones in?

Given the plethora of articles that take a dim, if not outright negative, 
view of super, it is good to see one that takes a positive view. Thanks 
Raymond!



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


Re: Python's super() considered super!

2011-05-27 Thread Duncan Booth
Steven D'Aprano  wrote:

> I was thrilled to learn a new trick, popping keyword arguments before 
> calling super, and wondered why I hadn't thought of that myself. How on 
> earth did I fail to realise that a kwarg dict was mutable and therefore 
> you can remove keyword args, or inject new ones in?
> 
Probably because most of the time it is better to avoid mutating kwargs. 
Instead of popping an argument you simply declare it as a named argument in 
the method signature. Instead of injecting new ones you can pass them as 
named arguments.


def foo(x=None, **kwargs):
bar(y=2, **kwargs)


def bar(**kwargs):
print(kwargs)

>>> foo(x=1, z=3)
{'y': 2, 'z': 3}
>>> foo(x=1, y=2, z=3)
Traceback (most recent call last):
  File "", line 1, in 
foo(x=1, y=2, z=3)
  File "", line 2, in foo
bar(y=2, **kwargs)
TypeError: bar() got multiple values for keyword argument 'y'

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bug in str.startswith() and str.endswith()

2011-05-27 Thread Mel
Terry Reedy wrote:

> To me, that says pretty clearly that start and end have to be
> 'positions', ie, ints or other index types. So I would say that the
> error message is a bug. I see so reason why one would want to use None
> rather that 0 for start or None rather than nothing for end.

If you're trying to wrap a call to startswith in a function that "looks 
like" startswith, there's no easy way to pass in the information that your 
caller wants the default parameters.  The case I ran into was

def wrapped_range (start, stop=None, span=None):
do_some_things()
result = range (start, stop, span)  # range doesn't(/didn't) accept this
return result
   

Tne answer in that case was to take *args as the parameter to wrapped_range 
and count arguments to distinguish between the different calls to range. 

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


Re: The worth of comments

2011-05-27 Thread D'Arcy J.M. Cain
On Fri, 27 May 2011 00:02:23 -0700
Tim Roberts  wrote:
> Ruby has a lot of followers, and I am trying to get excited about it, but
> it has succumbed to the same special-characters-as-syntax disease that
> killed Perl.  Much Ruby code is just unreadable.

What?  The recent Perl flame war wasn't enough entertainment for
you?  ;-)

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The worth of comments

2011-05-27 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> (Did I *really* write that code? It has my name on it.)

Most version control systems have an annotate command which lets you see 
who wrote a given line of code.  Some of them are even honest enough to 
call the command "blame" instead of "annotate" :-)

And, yes, it's always a rude shock when I stare at some hunk of code, 
mutter, "who wrote this crap!?" and fire up annotate/blame only to 
discover my name on it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-27 Thread Roy Smith
In article <948l8nf33...@mid.individual.net>,
 Gregory Ewing  wrote:

> John Bokma wrote:
> 
> > A Perl programmer will call this line noise:
> > 
> > double_word_re = re.compile(r"\b(?P\w+)\s+(?P=word)(?!\w)",
> > re.IGNORECASE)

One of the truly awesome things about the Python re library is that it 
lets you write complex regexes like this:

pattern = r"""\b # beginning of line
  (?P\w+)  # a word
  \s+# some whitespace
  (?P=word)(?!\w)# the same word again
   """
double_word_re = re.compile(pattern,  re.I | re.X)

Sometimes regex really is the best tool.  It's often the most compact, 
or fastest, or clearest way to express something complicated.  
Fortunately, re.X mode gives you a way to write truly monster regexes 
and still having them not be total line noise.

It's a shame that the Python community has evolved to be so anti-regex 
that most people never consider using them.  While Perl's attitude to 
regex may be "when the only tool you have is a hammer, everything looks 
like a nail", Python's seems to be, "I've got a great collection of all 
kinds of neat tools, so I'm going to pretend the hammer that's in there 
doesn't exist because I once smashed my thumb with it and it hurt a lot".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bug in str.startswith() and str.endswith()

2011-05-27 Thread Roy Smith
In article ,
 Stefan Behnel  wrote:

> Roy Smith, 27.05.2011 03:13:
> >   Ethan Furman wrote:
> >
> >> -->  'this is a test'.startswith('this')
> >> True
> >> -->  'this is a test'.startswith('this', None, None)
> >> Traceback (most recent call last):
> >> File "", line 1, in
> >> TypeError: slice indices must be integers or None or have an __index__
> >> method
> > [...]
> >> Any reason this is not a bug?
> >
> > +1 for it being a bug.
> 
> Meaning that the right thing to do at this point is to file a bug report.

And now we just need to figure out if it's a bug in the code or the 
documentation :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The worth of comments

2011-05-27 Thread Grant Edwards
On 2011-05-27, Ben Finney  wrote:
> Richard Parker  writes:
>
>> On May 26, 2011, at 4:28 AM, python-list-requ...@python.org wrote:
>>
>> > My experience is that comments in Python are of relatively low
>> > usefulness. (For avoidance of doubt: not *zero* usefulness, merely
>> > low.)

I've seen plenty of comments who's usefulness was not zero.  It was
less than zero.

>> > I can name variables, functions and classes with sensible,
>> > self- documenting names.
>
> I am largely in agreement with this position (including the ???not *zero*
> usefulness??? caveat).
>
>> I'm less inclined to use comments on each line, or selected lines, but
>> rather use block comments instead. They require more thought and time
>> to write; however, the intended functionality of the code that follows
>> can be described in full.
>
> This I disagree with. If a section of code is interesting enough to
> deserve an explanation, then it is better to capture it in a
> helpfully-named function with its doc string having the explanation.

I consider docstrings to be the same as comments, so there's not
really much disagreement.

-- 
Grant Edwards   grant.b.edwardsYow! Am I in Milwaukee?
  at   
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread sturlamolden
On 26 Mai, 18:31, Raymond Hettinger  wrote:
> I just posted a tutorial and how-to guide for making effective use of
> super().
>
> One of the reviewers, David Beazley, said, "Wow,  that's really
> great!    I see this becoming the definitive post on the subject"
>
> The direct link is:
>
>  http://rhettinger.wordpress.com/2011/05/26/super-considered-super/

I really don't like the Python 2 syntax of super, as it violates
the DRY principle: Why do I need to write super(type(self),self)
when super() will do? Assuming that 'self' will always be named
'self' in my code, I tend to patch __builtins__.super like this:

import sys
def super():
self = sys._getframe().f_back.f_locals['self']
return __builtins__.super(type(self),self)

This way the nice Python 3.x syntax can be used in Python 2.x.


Sturla






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


Re: English Idiom in Unix: Directory Recursively

2011-05-27 Thread harrismh777

Steven D'Aprano wrote:

You really do
need to know whether the car you drive uses leaded or unleaded.


   Actually, you need to know whether your car can burn 85 gas (at 
about 60 cents /gallon cheaper... and, whether 85 gas will have enough 
energy to move the car without using 35% more fuel... making it about 
$1.00 /gallon more expensive  ehem.




:-}






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


Re: Python's super() considered super!

2011-05-27 Thread Mel
sturlamolden wrote:

> I really don't like the Python 2 syntax of super, as it violates
> the DRY principle: Why do I need to write super(type(self),self)
> when super() will do? Assuming that 'self' will always be named
> 'self' in my code, I tend to patch __builtins__.super like this:
> 
> import sys
> def super():
> self = sys._getframe().f_back.f_locals['self']
> return __builtins__.super(type(self),self)
> 
> This way the nice Python 3.x syntax can be used in Python 2.x.

Python causes trouble by letting the users get at the internals, but things 
like this make it worthwhile.

Mel.

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


Re: Abandoning Python

2011-05-27 Thread harrismh777

Paul Rubin wrote:

Haskell probably has the most vibrant development community at
the moment but its learning curve is quite steep, and it has
various shortcomings some of which are being worked on but others
of which may be insurmountable.



Yes.   You might want to lurk on:

http://lambda-the-ultimate.org/



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


Re: Beginner needs advice

2011-05-27 Thread harrismh777

Colin J. Williams wrote:

It would be safer to stick with Python 2.7 initially and then consider
the transition to 3.2 later.


I must disagree with Colin's statement. If you are a complete beginner 
with Python... then there is going to a learning curve for you... and 
that curve should be 3.2---  period.


It is true that some modules are not ready for 3.x, and it is also true 
that many installed systems (probably most) do not have 3.x installed.


But that is not the point. The point is that 3.x is completely 
incompatible with 2.x (some call it a dialect, but that is a lie). 
Python3 is the future of the language, and if you're new to Python, then 
learn 3.x, move forward and don't look back... seriously.



kind regards,
m harris



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


Re: Python's super() considered super!

2011-05-27 Thread Steven D'Aprano
On Fri, 27 May 2011 10:33:20 -0400, Mel wrote:

> sturlamolden wrote:
> 
>> I really don't like the Python 2 syntax of super, as it violates the
>> DRY principle: Why do I need to write super(type(self),self) when
>> super() will do? Assuming that 'self' will always be named 'self' in my
>> code, I tend to patch __builtins__.super like this:
>> 
>> import sys
>> def super():
>> self = sys._getframe().f_back.f_locals['self'] 
>> return __builtins__.super(type(self),self)
>> 
>> This way the nice Python 3.x syntax can be used in Python 2.x.
> 
> Python causes trouble by letting the users get at the internals, but
> things like this make it worthwhile.

Only if by "worthwhile" you mean "buggy as hell".


>>> import sys
>>>
>>> def super():
... self = sys._getframe().f_back.f_locals['self']
... return __builtins__.super(type(self),self)
...
>>> class A(object):
... def __init__(self):
... super().__init__()
...
>>> class B(A):
... def __init__(self):
... super().__init__()
...
>>> a = A()
>>> b = B()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in __init__
  [...]
  File "", line 3, in __init__
RuntimeError: maximum recursion depth exceeded


Do not use super(type(self), self), because it does not do what you think 
it does:

b = B() calls B.__init__(self)
... which calls super(type(self), self) = super(B, self)
... which calls A.__init__(self)
... which calls super(type(self), self) = super(B, self) *not* A
... which loops forever

type(self) does not return B inside B methods and A inside A methods, it 
returns the class of the instance.


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


Re: Python's super() considered super!

2011-05-27 Thread Michele Simionato
The fact that even experienced programmers fail to see that
super(type(self),self) in Python 2 is NOT equivalent to super()
in Python 3 is telling something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Duncan Booth
sturlamolden  wrote:

> On 26 Mai, 18:31, Raymond Hettinger  wrote:
>> I just posted a tutorial and how-to guide for making effective use of
>> super().
>>
>> One of the reviewers, David Beazley, said, "Wow,  that's really
>> great!    I see this becoming the definitive post on the subject"
>>
>> The direct link is:
>>
>>  http://rhettinger.wordpress.com/2011/05/26/super-considered-super/
> 
> I really don't like the Python 2 syntax of super, as it violates
> the DRY principle: Why do I need to write super(type(self),self)
> when super() will do? Assuming that 'self' will always be named
> 'self' in my code, I tend to patch __builtins__.super like this:
> 
> import sys
> def super():
> self = sys._getframe().f_back.f_locals['self']
> return __builtins__.super(type(self),self)
> 
> This way the nice Python 3.x syntax can be used in Python 2.x.
> 
> 
Oh dear, you haven't thought this one through.

After your code above, try this:

>>> class A(object):
def foo(self):
print "A.foo"


>>> class B(A):
def foo(self):
print "B.foo"
super().foo()

>>> B().foo()
B.foo
A.foo

So far so good.
Now try this:

>>> class C(B): pass

>>> C().foo()
... infinite recursion follows ...

Oops. There's a reason why Python 2 requires you to be explicit about 
the class; you simply cannot work it out automatically at run time. 
Python 3 fixes this by working it out at compile time, but for Python 2 
there is no way around it.


-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread harrismh777

Steven D'Aprano wrote:

Python causes trouble by letting the users get at the internals, but
>  things like this make it worthwhile.



Only if by "worthwhile" you mean "buggy as hell".


I *don't* believe this... the king of metaphors and bogus analogies 
has come up with 'buggy as hell' !!?


   No no, you might have buggy as grubs-under-a-damp-log, or buggy as 
'moths-around-an-incandecent-lamp'  ,  or  you could have 'hot-as-hell,' 
but  'buggy-as-hell' just doesn't say what needs say'in...



... I'm just saying




:)



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


Re: Python's super() considered super!

2011-05-27 Thread sturlamolden
On 27 Mai, 16:27, sturlamolden  wrote:

> Assuming that 'self' will always be named
> 'self' in my code, I tend to patch __builtins__.super like this:
>
> import sys
> def super():
>     self = sys._getframe().f_back.f_locals['self']
>     return __builtins__.super(type(self),self)


A monkey-patch to __builtins__.super would probably also work.

Assuming the first argument to the callee is 'self' or 'cls':

import sys
_super = __builtins__.super
def monkeypatch(*args, **kwargs):
if (args == ()) and (kwargs=={}):
try:
obj = sys._getframe().f_back.f_locals['self']
except KeyError:
obj = sys._getframe().f_back.f_locals['cls']
return _super(type(obj),obj)
else:
return _super(*args, **kwargs)

class patcher(object):
   def __init__(self):
  __builtins__.super = monkeypatch
   def __del__(self):
  __builtins__.super = _super

_patch = patcher()



Sturla

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


Re: Python's super() considered super!

2011-05-27 Thread sturlamolden
On 27 Mai, 17:05, Duncan Booth  wrote:

> >>> class C(B): pass
> >>> C().foo()
>
> ... infinite recursion follows ...

That's true :(

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


Re: Python's super() considered super!

2011-05-27 Thread sturlamolden
On 27 Mai, 17:05, Duncan Booth  wrote:

> Oops. There's a reason why Python 2 requires you to be explicit about
> the class; you simply cannot work it out automatically at run time.
> Python 3 fixes this by working it out at compile time, but for Python 2
> there is no way around it.

Then it should be a keyword, not a function.

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


Re: Beginner needs advice

2011-05-27 Thread Steven D'Aprano
On Fri, 27 May 2011 09:40:53 -0500, harrismh777 wrote:

> 3.x is completely incompatible with 2.x (some call it a dialect, 
> but that is a lie).

"Completely incompatible"? A "lie"?


import math
import random
my_list = [3, 5, 7, 9]
n = random.choice(my_list)
if n%3:
func = math.sin
else:
func = math.cos

y = func(math.pi/n)*10
L = ['spam']*(int(y))
for item in L:
print(item)


is valid syntax in every version of Python from 1.5 to 3.2, and it does 
the same thing in all of them. Would you care to revise your claims?



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


Re: The worth of comments

2011-05-27 Thread Miki Tebeka
https://docs.google.com/present/view?id=ah82mvnssv5d_162dbgx78gw ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by list-appending behavior

2011-05-27 Thread MRAB

On 27/05/2011 07:34, Tim Roberts wrote:

MRAB  wrote:


I'd just like to point out that it's a convention, not a rigid rule.


Reminds me of the catch-phrase from the first Pirates of the Caribbean
movie: "It's more of a guideline than a rule."


Much like the Zen of Python.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Steven D'Aprano
On Fri, 27 May 2011 08:31:40 -0700, sturlamolden wrote:

> On 27 Mai, 17:05, Duncan Booth  wrote:
> 
>> Oops. There's a reason why Python 2 requires you to be explicit about
>> the class; you simply cannot work it out automatically at run time.
>> Python 3 fixes this by working it out at compile time, but for Python 2
>> there is no way around it.
> 
> Then it should be a keyword, not a function.

Why? The fault is not that super is a function, or that you monkey-
patched it, or that you used a private function to do that monkey-
patching. The fault was that you made a common, but silly, mistake when 
reasoning about type(self) inside a class. 

I made the same mistake: assume that type(self) will always be the same 
class as that the method is defined in. But of course it won't be. With 
the luxury of hindsight, it is a silly mistake to make, but I promise you 
that you're not the first, and won't be the last, to make it.



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


Re: [Python-ideas] Adding 'bytes' as alias for 'latin_1' codec.

2011-05-27 Thread MRAB

On 27/05/2011 10:27, Nick Coghlan wrote:

On Fri, May 27, 2011 at 6:46 PM, Stephen J. Turnbull  wrote:

  >  What method is invoked to convert the numbers to text? What encoding
  >  is used to convert those numbers to text? How does this operation
  >  avoid also converting the *bytes* object to text and then reencoding
  >  it?

OTOH, Nick, aren't you making this harder than it needs to be?  After
all,


To me, the defining feature of str.format() over str.__mod__() is the
ability for types to provide their own __format__ methods, rather than
being limited to a predefined set of types known to the interpreter.
If bytes were to reuse the same name, then I'd want to see similar
flexibility.

Now, a *different* bytes method (bytes.interpolate, perhaps?), limited
to specific types may make sense, but such an alternative *shouldn't*
be conflated with the text formatting API.

However, proponents of such an addition need to clearly articulate
their use cases and proposed solution in a PEP to make it clear that
they aren't merely trying to perpetuate the bytes/text confusion that
plagues 2.x 8-bit strings.

We can almost certainly do better when it comes to constructing byte
sequences from component parts, but simply saying "oh, just add a
format() method to bytes objects" doesn't cut it, since the associated
magic methods for str.format are all string based, and bytes
interpolation also needs to address encoding issues for anything that
isn't already a byte sequence.


I would've thought that a "format" (or equivalent) method for bytes
would work like struct.pack, so b"{0}".format(23) wouldn't return
b'23', but you could have:

>>> b'{0:b}'.format(23)
b'\x17'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 92, Issue 232

2011-05-27 Thread Richard Parker
 Sometimes
>> I'll drop in suggestions to future maintainers like, "consider
>> refactoring with with perform_frobnitz_action()"
> 
> Usually, I address future-me with comments like that (on the
> assumption that there's nobody in the world sadistic enough to want to
> maintain my code). But I never name future-me, the comments will be
> addressed to "the subsequent maintainer" or somesuch. I do assume,
> though, that future-me has forgotten everything about the code, and
> since past-me left some comments that current-me has read, I think the
> assumption is fairly accurate. (Did I *really* write that code? It has
> my name on it.)
> 
> Chris Angelico
> 

Rather than sadistic, one would likely be masochistic to undertake the 
maintenance of  my code :-) I have had many moments where I have later asked 
the question "Did I write this code?."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why did Quora choose Python for its development?

2011-05-27 Thread Ethan Furman

Thorsten Kampe wrote:

* Steven D'Aprano (27 May 2011 03:07:30 GMT)
Okay, I've stayed silent while people criticize me long enough. What 
exactly did I say that was impolite? 


Nothing.


John threw down a distinct challenge:

if Python is really so much better than Python [sic] 
readability wise, why do I have such a hard time dropping

Perl and moving on?
[...]
If I got it wrong about John, oh well, I said it was a guess, and
trying to get inside someone else's head is always a chancy business.


Why were you trying to speculate in response to such a - sorry - dumb[1] 
question?


He asked the question not once, but multiple times (IIRC at least three, 
possible more) -- after a while it stops being rhetorical.


I would say also, if you don't want an answer, don't ask the question.

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


Re: bug in str.startswith() and str.endswith()

2011-05-27 Thread Ethan Furman

Ethan Furman wrote:

Any reason this is not a bug?


Looks like someone else beat me to filing:

http://bugs.python.org/issue11828

Looks like they fixed it as well.

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


Re: The worth of comments

2011-05-27 Thread Irmen de Jong

On 27-05-11 15:54, Grant Edwards wrote:

On 2011-05-27, Ben Finney  wrote:

Richard Parker  writes:


On May 26, 2011, at 4:28 AM, python-list-requ...@python.org wrote:


My experience is that comments in Python are of relatively low
usefulness. (For avoidance of doubt: not *zero* usefulness, merely
low.)


I've seen plenty of comments who's usefulness was not zero.  It was
less than zero.


Someone once taught me, "There is one thing worse than having no 
comments in the source code:  having incorrect (or 'lying') comments in 
the code."


Grant, I guess you hint at such comments?

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


Re: Python's super() considered super!

2011-05-27 Thread Ethan Furman

Duncan Booth wrote:

Steven D'Aprano  wrote:

I was thrilled to learn a new trick, popping keyword arguments before 
calling super, and wondered why I hadn't thought of that myself. How on 
earth did I fail to realise that a kwarg dict was mutable and therefore 
you can remove keyword args, or inject new ones in?


Probably because most of the time it is better to avoid mutating kwargs. 
Instead of popping an argument you simply declare it as a named argument in 
the method signature. Instead of injecting new ones you can pass them as 
named arguments.



def foo(x=None, **kwargs):
bar(y=2, **kwargs)


def bar(**kwargs):
print(kwargs)


foo(x=1, z=3)

{'y': 2, 'z': 3}

foo(x=1, y=2, z=3)

Traceback (most recent call last):
  File "", line 1, in 
foo(x=1, y=2, z=3)
  File "", line 2, in foo
bar(y=2, **kwargs)
TypeError: bar() got multiple values for keyword argument 'y'


And the above error is exactly why you don't want to use named arguments 
in MI -- because you don't know in what order the methods will be 
called, you cannot know which named arguments to supply to the method 
that super() will call next.


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


Re: The worth of comments

2011-05-27 Thread Grant Edwards
On 2011-05-27, Miki Tebeka  wrote:

> https://docs.google.com/present/view?id=ah82mvnssv5d_162dbgx78gw ;)

I just realized that Usenet is sort of like radio.  

After hearing/reading somebody for years, I don't seem to have a
detailed image of them in my head, but when I finally do see a picture
of them, my initial reaction is almost always "no, that's not at all
what I thought he/she looked like".   Odd.

-- 
Grant Edwards   grant.b.edwardsYow! I demand IMPUNITY!
  at   
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The worth of comments

2011-05-27 Thread Grant Edwards
On 2011-05-27, Irmen de Jong  wrote:
> On 27-05-11 15:54, Grant Edwards wrote:
>> On 2011-05-27, Ben Finney  wrote:
>>> Richard Parker  writes:
>>>
 On May 26, 2011, at 4:28 AM, python-list-requ...@python.org wrote:

> My experience is that comments in Python are of relatively low
> usefulness. (For avoidance of doubt: not *zero* usefulness, merely
> low.)
>>
>> I've seen plenty of comments who's usefulness was not zero.  It was
>> less than zero.
>
> Someone once taught me, "There is one thing worse than having no 
> comments in the source code: having incorrect (or 'lying') comments
> in the code."
>
> Grant, I guess you hint at such comments?

Yes.  :)

When trying to find a bug in code written by sombody else, I often
first go through and delete all of the comments so as not to be
mislead.

The comments reflect what the author _thought_ the code did
_at_some_point_in_the_past_.  What matters is what the code actually
does at the present.

-- 
Grant Edwards   grant.b.edwardsYow! ... If I had heart
  at   failure right now,
  gmail.comI couldn't be a more
   fortunate man!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Eric Snow
On Fri, May 27, 2011 at 4:37 AM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Fri, 27 May 2011 18:49:52 +1000, Ben Finney wrote:
>
> > Raymond Hettinger  writes:
> >
> >> Hope you enjoyed the post.
> >
> > I certainly did.
> >
> > But I'm not better enlightened on why ‘super’ is a good thing.
>
> Perhaps Raymond assumed that by now everybody knows that multiple
> inheritance in Python that doesn't use super is buggy. super() was
> introduced in version 2.2 in order to overcome bugs in MI, making it
> about 8 years old now.
>
> (Technically, it's only MI with diamond-shaped inheritance, but that
> applies to *all* new-style classes. If you're writing multiple
> inheritance in Python 3 without using super, your code is a land-mine
> waiting to go off. If you're writing single inheritance, it's *still* a
> land-mine, just waiting for some poor caller to use it in a MI context.)
>
> But I do agree with you in that I expected to see at least some
> discussion of why super should be actively preferred over calling the
> parent class directly.
>
>
Seems like he does just that for most of the first section.


>
>
> The
> > exquisite care that you describe programmers needing to maintain is IMO
> > just as much a deterrent as the super-is-harmful essay.
>
> I don't see that Raymond describes anything needing "exquisite care".
> It's more common sense really: ensure that your method signature and that
> of your parents' match, plus good work-arounds for when they don't.
> Anyone using inheritance is almost certainly 98% of the way there, unless
> they're writing classes like this and wondering why they don't work :)
>
> class MyBrokenList(list):
>def __len__(self):
>n = list.__len__(self, extra=42)
>return n + 1
>def __getitem__(self, i):
>return list.__getitem__(self) + 1
>def last_item(self):
>return list.last_item(self) + 1
>
>
> I was thrilled to learn a new trick, popping keyword arguments before
> calling super, and wondered why I hadn't thought of that myself. How on
> earth did I fail to realise that a kwarg dict was mutable and therefore
> you can remove keyword args, or inject new ones in?
>
> Given the plethora of articles that take a dim, if not outright negative,
> view of super, it is good to see one that takes a positive view. Thanks
> Raymond!
>
>
+1

-eric


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


RE: Puzzled by list-appending behavior

2011-05-27 Thread Prasad, Ramit
>I have to say, I do like Python's lack of keywords for these things

I thought True/False were among the list of keywords in Python 3.x ? Or are 
those the only keywords?


Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423
This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The worth of comments

2011-05-27 Thread Ethan Furman

Miki Tebeka wrote:

https://docs.google.com/present/view?id=ah82mvnssv5d_162dbgx78gw ;)


+1

That was hilarious.

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


RE: Python's super() considered super!

2011-05-27 Thread Prasad, Ramit
>>We also, though, need *real* URLs. Blind URLs through obfuscation
>>services have their uses, but surely not in a forum like this. The real
>>URL is http://news.ycombinator.com/item?id=2588262>.

I remember reading a news article where a man was arrested (or was it fired) 
for pornography because he clicked a link. I would *REALLY* prefer not to be 
4chan-ed into jail (or fired) because I could not safely tell what a shortened 
URL really pointed to. Besides, shortened URLs do not live as long and are more 
likely to fail when people search the archives.

Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The worth of comments

2011-05-27 Thread Patty


- Original Message - 
From: "Ethan Furman" 

To: 
Sent: Friday, May 27, 2011 11:14 AM
Subject: Re: The worth of comments



Miki Tebeka wrote:

https://docs.google.com/present/view?id=ah82mvnssv5d_162dbgx78gw ;)


+1

That was hilarious.

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




I know - since I am not working right now, it totally made me wonder why I 
put comments in
Python code at all -- or even have anything to do with code -- and plans 
being made to spend

the rest of the day laying around in the hammock :)

Patty 


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


RE: The worth of comments

2011-05-27 Thread Prasad, Ramit
>(Did I *really* write that code? It has my name on it.)

Damn those ninja programmers who stole your name and coded something!


Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Ian Kelly
On Thu, May 26, 2011 at 10:31 AM, Raymond Hettinger  wrote:
> I just posted a tutorial and how-to guide for making effective use of
> super().

I posted this already on the HackerNews thread but it seems to have
largely gone unnoticed, so I'm reposting it here.

It seems to me that the example of combining built-in dictionary
classes is naively optimistic. For starters, OrderedDict, as it
happens, does not use super! It calls the dict super-class methods
directly. Since dict luckily happens to be the next class in the MRO,
this doesn't really matter for the purpose of this example, but I can
envision a scenario where some plucky programmer inherits from both
OrderedCounter and some other dict subclass, and the result doesn't
work because OrderedDict does the wrong thing.

And OrderedDict isn't the only one. Maybe for some reason I would like
to have an OrderedCounter where all the counts default to 42. So I do
this:

  class DefaultOrderedCounter(defaultdict, OrderedCounter):
  pass
  doc = DefaultOrderedCounter(lambda: 42)
  doc.update('abracadabra')

Which results in:

  Traceback (most recent call last):
File "", line 1, in 
File "c:\python32\lib\collections.py", line 507, in update
  _count_elements(self, iterable)
File "c:\python32\lib\collections.py", line 63, in __setitem__
  self.__map[key] = link = Link()
  AttributeError: 'DefaultOrderedCounter' object has no attribute
'_OrderedDict__map'

Whoops! Apparently defaultdict doesn't use super either. Of course a
better way to do this would be to subclass OrderedCounter and just
override the __missing__ method by hand, but that's not the point.

The article goes into "How to Incorporate a Non-cooperative Class",
which basically says "wrap it up in a proxy class". But that's not
really going to work here, since the result would be two separate
dicts, with the defaultdictwrapper methods operating on one dict, and
the other methods operating on the other.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Chris Angelico
On Sat, May 28, 2011 at 4:10 AM, Prasad, Ramit
 wrote:
>>>We also, though, need *real* URLs. Blind URLs through obfuscation
>>>services have their uses, but surely not in a forum like this. The real
>>>URL is http://news.ycombinator.com/item?id=2588262>.
>
> I remember reading a news article where a man was arrested (or was it fired) 
> for pornography because he clicked a link. I would *REALLY* prefer not to be 
> 4chan-ed into jail (or fired) because I could not safely tell what a 
> shortened URL really pointed to. Besides, shortened URLs do not live as long 
> and are more likely to fail when people search the archives.

I've seen FAR more dead links than dead URL shortening services. It's
a lot more likely that the destination will go down than that the
tinyurl service will lose its data.

If you're worried about where you're going, grab a URL renderer;
TinyURL.com has "preview mode" which you can set with a cookie, and
for others, all you need is something which takes a URL off the
clipboard, requests it, gets the Location: header, and puts that on
the clipboard for you. I coded such a facility into my MUD client
(RosMud), because shortened URLs are important when lines are limited
to 80 characters (less some overhead); it'd be quite easy to build a
little Python-GTK or Python-TK app that gives you a nice window and
makes it easy.

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


[ANN] Python 2.5.6 released

2011-05-27 Thread Martin v. Löwis
On behalf of the Python development team and the Python community, I'm
happy to announce the release of Python 2.5.6. There were no changes
since the release candidate.

This is a source-only release that only includes security fixes. The
last full bug-fix release of Python 2.5 was Python 2.5.4. Users are
encouraged to upgrade to the latest release of Python 2.7 (which is
2.7.1 at this point). This release is most likely the final release of
Python 2.5; under the current release policy, no security issues in
Python 2.5 will be fixed after October, 2011.

This releases fixes issues with the urllib, urllib2, SimpleHTTPServer,
and audiop modules. See the release notes at the website (also
available as Misc/NEWS in the source distribution) for details of bugs
fixed.

For more information on Python 2.5.6, including download links for
various platforms, release notes, and known issues, please see:

http://www.python.org/2.5.6

Highlights of the previous major Python releases are available from
the Python 2.5 page, at

http://www.python.org/2.5/highlights.html

Enjoy this release,
Martin

Martin v. Loewis
mar...@v.loewis.de
Python Release Manager
(on behalf of the entire python-dev team)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Puzzled by list-appending behavior

2011-05-27 Thread Ethan Furman

Prasad, Ramit wrote:

I have to say, I do like Python's lack of keywords for these things


I thought True/False were among the list of keywords in Python 3.x ? Or are 
those the only keywords?


http://docs.python.org/py3k/reference/lexical_analysis.html#keywords

False  class  finallyis return
None   continue   forlambda try
True   deffrom   nonlocal   while
anddelglobal notwith
as elif   if or yield
assert else   import pass
break  except in raise

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


Re: Python's super() considered super!

2011-05-27 Thread Chris Angelico
On Sat, May 28, 2011 at 4:31 AM, Ian Kelly  wrote:
> It seems to me that the example of combining built-in dictionary
> classes is naively optimistic.

So... Can anyone offer a non-trivial example of multiple inheritance
that *doesn't* have pitfalls? From what I've seen, MI always seems to
require cooperation from the authors of all involved classes. It may
be a useful tool when you control everything, but whenever you use
someone else's code, there seems to be this massive barrier of risk
(if that makes sense). For the DefaultOrderedCounter, I would be
strongly inclined to inherit singly, and then manually implement the
other half (whichever half is easier); in this case that happens to be
trivial (override __missing__), but even were it not, it would be a
means of being certain that things won't break.

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


Re: Python 3.2 bug? Reading the last line of a file

2011-05-27 Thread tkp...@hotmail.com
This is exactly what I want to do - I can then pick up various
elements of the list and turn them into floats, ints, etc. I have not
ever used decode, and will look it up in the docs to better understand
it. I can't thank everyone enough for the generous serving of help and
guidance - I certainly would not have discovered all this on my own.

Sincerely


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


Re: Why did Quora choose Python for its development?

2011-05-27 Thread Karim

On 05/27/2011 03:47 PM, Roy Smith wrote:

In article<948l8nf33...@mid.individual.net>,
  Gregory Ewing  wrote:


John Bokma wrote:


A Perl programmer will call this line noise:

double_word_re = re.compile(r"\b(?P\w+)\s+(?P=word)(?!\w)",
 re.IGNORECASE)

One of the truly awesome things about the Python re library is that it
lets you write complex regexes like this:

pattern = r"""\b # beginning of line
   (?P\w+)  # a word
   \s+# some whitespace
   (?P=word)(?!\w)# the same word again
"""
double_word_re = re.compile(pattern,  re.I | re.X)

Sometimes regex really is the best tool.  It's often the most compact,
or fastest, or clearest way to express something complicated.
Fortunately, re.X mode gives you a way to write truly monster regexes
and still having them not be total line noise.

It's a shame that the Python community has evolved to be so anti-regex
that most people never consider using them.  While Perl's attitude to
regex may be "when the only tool you have is a hammer, everything looks
like a nail", Python's seems to be, "I've got a great collection of all
kinds of neat tools, so I'm going to pretend the hammer that's in there
doesn't exist because I once smashed my thumb with it and it hurt a lot".


HAHAHAHAHAHA Very funny!

This thread is awsome.

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


sys.tracebacklimit not working in Python 3.2?

2011-05-27 Thread Thorsten Kampe
Hi,

> type test.py
import sys

sys.tracebacklimit = 0
import doesnotexist

> python test.py
ImportError: No module named doesnotexist

> python3 test.py
Traceback (most recent call last):
  File "test.py", line 4, in 
import doesnotexist
ImportError: No module named doesnotexist

The 3.2 documentation says "When set to 0 or less, all traceback 
information is suppressed and only the exception type and value are 
printed". Bug?

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


Re: Beginner needs advice

2011-05-27 Thread harrismh777

Steven D'Aprano wrote:

Would you care to revise your claims?


No.


You have erected a straw-man... once again.


Most 2.x code *will not* run correctly in 3.x/  Most of the best 
improvements and enhancements of 3.x will not back-port to below 2.7, 
and almost none of them will back-port before 2.6 (class decorations, 
for instance).


Some interfaces have changed! cmp keyword, but lets not bring that up 
again


Many syntaxes have changed or have disappeared...

... and some commands (like reload for instance) either don't exist in 
3.x, or have been hidden, replaced, or changed...



All of these things are for the better, I must add.  But, the point is 
that 3.x is completely incompatible with 2.x in real ways.  Arguing that 
this is *not true* because you are able to create a code block that just 
happens 'to work' in all versions (and that hasn't been verified yet) 
does not in *any* way 'prove' that 3.x is a compatible dialect---  far 
from it... its a straw-man argument.



kind regards,

m harris


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


Re: Python's super() considered super!

2011-05-27 Thread John Nagle

On 5/27/2011 11:46 AM, Chris Angelico wrote:

On Sat, May 28, 2011 at 4:31 AM, Ian Kelly  wrote:

It seems to me that the example of combining built-in dictionary
classes is naively optimistic.


So... Can anyone offer a non-trivial example of multiple inheritance
that *doesn't* have pitfalls?   From what I've seen, MI always seems > to require cooperation from 

the authors of all involved classes.

Good point.

Multiple inheritance is messy enough when the structure is just
a tree.  When the structure is allowed to be a directed acyclic
graph, the whole thing just gets too complicated.

It doesn't even necessarily do what you want.  If, say, you
have two classes that need dictionaries, and were implemented
by inheriting from "dict", a class that imports both has one
"dict", not two - something that was not anticipated in the
design of the original classes.  That ought to be an error,
not a single "dict" shared by two unconnected classes.

What causes this kind of mess is a determination not to
report anything as an error if it can be given some kind of
meaningful semantics, even if the semantics have marginal
value.  That's the kind of thinking which leads to

[1,2] * 2

returning

[1,2,1,2]



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


Re: Beginner needs advice

2011-05-27 Thread Ethan Furman

Lew Schwartz wrote:
So, if I read between the lines correctly, you recommend Python 3? Does 
the windows version install with a development environment?


Dabo, last I checked, uses wxPython, which uses wxWidgets (sp?), which 
is not yet ported to Python 3.  So if you got that route you'll need to 
stay with 2.7.


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


changing current dir and executing a shell script

2011-05-27 Thread suresh
Hi,
I want to execute the following command line stuff from inside python. 
$cd directory
$./executable

I tried the following but I get errors
import subprocess
subprocess.check_call('cd dir_name;./executable')

Due to filename path issues, I cannot try this version.
subprocess.check_call('./dir_name/executable')

Any suggestions?
thanks
suresh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread Stefan Behnel

Steven D'Aprano, 27.05.2011 18:06:

On Fri, 27 May 2011 08:31:40 -0700, sturlamolden wrote:


On 27 Mai, 17:05, Duncan Booth  wrote:


Oops. There's a reason why Python 2 requires you to be explicit about
the class; you simply cannot work it out automatically at run time.
Python 3 fixes this by working it out at compile time, but for Python 2
there is no way around it.


Then it should be a keyword, not a function.


Why?


I think Sturla is referring to the "compile time" bit. CPython cannot know 
that the builtin super() will be called at runtime, even if it sees a 
"super()" function call.


CPython doesn't evaluate the super call at compile time, it only keeps a 
reference to the surrounding class in the code object of the method. So 
super() without arguments basically inherits the class argument from the 
context the method was found in at compile time. This has two quirks:


1) Copying a method from one class to another keeps the original context. 
So the class argument to super() is basically fixed at compile time, 
regardless of the class the method will be executed on at runtime.


2) The class is only kept as a reference when CPython sees a function call 
that looks like "super" at compile time, which isn't much more than a 
heuristic.


The PEP doesn't mention the first issue, but it is actually explicit about 
the second issue:


http://www.python.org/dev/peps/pep-3135/

"""
While super is not a reserved word, the parser recognizes the use of super 
in a method definition and only passes in the __class__ cell when this is 
found. Thus, calling a global alias of super without arguments will not 
necessarily work.

"""

And the prove:

  >>> _super = super
  >>> class T(object):
  ...   def test(self): print('TEST')
 ...
  >>> class B(T):
  ...   def meth(self): _super().test()
  ...
  >>> B().meth()
  Traceback (most recent call last):
  SystemError: super(): __class__ cell not found

I assume this is done in order to reduce the chance of accidentally keeping 
a class object alive for eternity, only because a method was originally 
defined therein that inherits the class reference in its code object. So 
it's a tradeoff between memory overhead and usability issues.


While I think that the tradeoff is generally ok, I agree with Sturla that a 
keyword would have been the correct solution, whereas this is a clear 
"works only in the common cases" approach.


Stefan

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


Re: Python's super() considered super!

2011-05-27 Thread Ethan Furman
I suspect the larger issue is that Multiple Inheritance is complex, but 
folks don't appreciate that.  Ask anyone about meta-classes and their 
eyes bug-out, but MI?  Simple!  NOT.


On the other hand, perhaps the docs should declare that the built-in 
objects are not designed for MI, so that that, at least, would be one 
less bug waiting to happen.


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


Re: changing current dir and executing a shell script

2011-05-27 Thread Dan Stromberg
Each command will be run in a distinct subprocess.  A CWD is typically local
to a given subprocess.  So after the first command/subprocess exits, your
cd's change is no longer there.

Try doing it in one command, with the two original commands separated by a
semicolon.

On Fri, May 27, 2011 at 2:25 PM, suresh  wrote:

> Hi,
> I want to execute the following command line stuff from inside python.
> $cd directory
> $./executable
>
> I tried the following but I get errors
> import subprocess
> subprocess.check_call('cd dir_name;./executable')
>
> Due to filename path issues, I cannot try this version.
> subprocess.check_call('./dir_name/executable')
>
> Any suggestions?
> thanks
> suresh
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing current dir and executing a shell script

2011-05-27 Thread Albert Hopkins
On Fri, 2011-05-27 at 14:25 -0700, suresh wrote:
> Hi,
> I want to execute the following command line stuff from inside python. 
> $cd directory
> $./executable
> 
> I tried the following but I get errors
> import subprocess
> subprocess.check_call('cd dir_name;./executable')
> 
> Due to filename path issues, I cannot try this version.
> subprocess.check_call('./dir_name/executable')
> 

You don't want to do this because "cd" is a built-in shell command, and
subprocess does not execute within a shell (by default).

The proper way to do this is to use the "cwd" keyword argument to
subprocess calls, i.e.:

>>> subprocess.check_call(('/path/to/exec',), cwd="/path/to/dir")

-a


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


Re: changing current dir and executing a shell script

2011-05-27 Thread Thorsten Kampe
* suresh (Fri, 27 May 2011 14:25:52 -0700 (PDT))
> I want to execute the following command line stuff from inside python. 
> $cd directory
> $./executable
> 
> I tried the following but I get errors
> import subprocess
> subprocess.check_call('cd dir_name;./executable')
> 
> Due to filename path issues, I cannot try this version.
> subprocess.check_call('./dir_name/executable')

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


Re: Beginner needs advice

2011-05-27 Thread Chris Angelico
On Sat, May 28, 2011 at 6:40 AM, harrismh777  wrote:
> Most 2.x code *will not* run correctly in 3.x/  Most of the best
> improvements and enhancements of 3.x will not back-port to below 2.7, and
> almost none of them will back-port before 2.6 (class decorations, for
> instance).

What's with the "below 2.7"? If you're comparing 3.x and 2.x, wouldn't
it be most plausible to compare 3.2 and 2.7?

And, the biggest reason for 2.x code not running on 3.x is probably
the print function. (Guess made without any data beyond my own
personal corpus of Python 2 code.) That's something that can be
corrected by, oh, I dunno, the 2to3 translator maybe? And the
__future__ import makes 2.6+ work the same way as 3.x.

> All of these things are for the better, I must add.  But, the point is that
> 3.x is completely incompatible with 2.x in real ways.  Arguing that this is
> *not true* because you are able to create a code block that just happens 'to
> work' in all versions (and that hasn't been verified yet) does not in *any*
> way 'prove' that 3.x is a compatible dialect---  far from it... its a
> straw-man argument.

You're correct that one code block does not prove the point. But your
argument is just as flimsy. To say that "most" 2.x code is
incompatible with 3.x is to deny the 2to3 utility, and you're ignoring
the people who deliberately write code that can cross-execute on
either version - which is really not that difficult, if you take some
care and use __future__ directives.

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


Re: Python's super() considered super!

2011-05-27 Thread Ryan Kelly
On Fri, 2011-05-27 at 15:05 +, Duncan Booth wrote:
> sturlamolden  wrote:
> > I really don't like the Python 2 syntax of super, as it violates
> > the DRY principle: Why do I need to write super(type(self),self)
> > when super() will do? Assuming that 'self' will always be named
> > 'self' in my code, I tend to patch __builtins__.super like this:
> > 
> > import sys
> > def super():
> > self = sys._getframe().f_back.f_locals['self']
> > return __builtins__.super(type(self),self)
> > 
> > This way the nice Python 3.x syntax can be used in Python 2.x.
> > 
> > 
> Oh dear, you haven't thought this one through.
>
> ...snip...
>
> >>> C().foo()
> ... infinite recursion follows ...
> 
> Oops. There's a reason why Python 2 requires you to be explicit about 
> the class; you simply cannot work it out automatically at run time. 
> Python 3 fixes this by working it out at compile time, but for Python 2 
> there is no way around it.

Oh?  There's not much that can't be done at runtime if you're willing to
work hard enough.  Let me propose the following awful awful hack:


  import sys

  _builtin_super = __builtins__.super

  _sentinel = object()

  def _auto_super(typ=_sentinel,type_or_obj=_sentinel):
  """Automagically call correct super() at runtime"""
  #  Infer the correct call if used without arguments.
  if typ is _sentinel:
  # We'll need to do some frame hacking.
  f = sys._getframe(1)
  # Get the first positional argument of the function.
  type_or_obj = f.f_locals[f.f_code.co_varnames[0]]
  # Get the MRO for investigation
  try:
  mro = type_or_obj.__mro__
  except AttributeError:
  try:
  mro = type_or_obj.__class__.__mro__
  except AttributeError:
  raise RuntimeError("super() used with old-style class")
  #  Now, find the class owning the currently-executing method.
  for typ in mro:
  for meth in typ.__dict__.itervalues():
  if not isinstance(meth,type(_auto_super)):
  continue
  if meth.func_code is f.f_code:
  # Aha!  Found you.
  break
  else:
  continue
  break
  else:
  raise RuntimeError("super() called outside a method")
  #  Now just dispatch to builtin super.
  if type_or_obj is not _sentinel:
  return _builtin_super(typ,type_or_obj)
  return _builtin_super(typ)


Now, try is with the following:

class Base(object):
def hello(self,msg):
print "hello", msg

class Sub1(Base):
def hello(self,msg):
print "gunna say it"
super().hello(msg)

class Sub2(Base):
def hello(self,msg):
print "yes I am"
super().hello(msg)

class Diamond(Sub1,Sub2):
def hello(self,msg):
print "here we go..."
super().hello(msg)

d = Diamond()
d.hello("autosuper!")


And you get the expected output:

here we go...
gunna say it
yes I am
hello autosuper!


There may well be some cases where this breaks down, but it seems to do
the right thing in simple cases.


Not that I'm recommending anyone use this, of course...




   Ryan


-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
r...@rfk.id.au|  http://www.rfk.id.au/ramblings/gpg/ for details



signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's super() considered super!

2011-05-27 Thread sturlamolden
On 27 Mai, 23:49, Stefan Behnel  wrote:

> I think Sturla is referring to the "compile time" bit. CPython cannot know
> that the builtin super() will be called at runtime, even if it sees a
> "super()" function call.

Yes. And opposite: CPython cannot know that builtin super() is not
called,
even if it does not see the name 'super'. I can easily make foo()
alias super().

In both cases, the cure is a keyword -- or make sure that __class__
is always defined.

If super is to be I keyword, we could argue that self and cls should
be
keywords as well, and methods should always be bound. That speaks in
favour
of a super() function. But then it should always be evaluated at run-
time,
without any magic from the parser.

Magic functions belong in Perl, not Python.

Sturla



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


Re: Python's super() considered super!

2011-05-27 Thread sturlamolden
On 27 Mai, 18:06, Steven D'Aprano  wrote:

> Why? The fault is not that super is a function, or that you monkey-
> patched it, or that you used a private function to do that monkey-
> patching. The fault was that you made a common, but silly, mistake when
> reasoning about type(self) inside a class.

That was indeed a silly mistake, but not what I am talking about.
See Stefan's reponse.


Sturla


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


Re: Beginner needs advice

2011-05-27 Thread harrismh777

Chris Angelico wrote:

To say that "most" 2.x code is
incompatible with 3.x is to deny the 2to3 utility,


   Oh, yes absolutely. Please don't misunderstand... anyone... I'm not 
saying that code cannot be migrated... migration can usually occur 
between incompatible releases and and between languages!... all I'm 
saying is that 3.x is not compatible with 2.x code (completely not 
compatible), and if you're a noob there is no reason to learn 2.x/ 
Learn 3.x and pickup whatever needs to be gained from 2.x if it comes 
up... we're talking about learning python as a newbie--- go with 3.x and 
never look back... seriously...




and you're ignoring
the people who deliberately write code that can cross-execute on
either version - which is really not that difficult,



That's what I do... but I'm not a newbie. I have existing code that 
needs to be migrated, and I have an interest in creating research apps 
that will run on existing 2.x systems but will be ready and waiting for 
the time when the system moves to 3.x.  I need to know both 2.6 and 3.2 
very well. And I'll be honest about this, it is very frustrating. There 
are literally hundreds of changes and variations (its all in the 
details).  Many Pythonists are not honest about this... because they 
don't want to scare folks away from 3.x, and I don't really blame them. 
But the true picture is that 3.x is (way better) and completely 
incompatible with 2.x.   Lying about this isn't helpful to anyone coming 
on board with Python. Just tell them the truth...



kind regards,

m harris

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


Re: Beginner needs advice

2011-05-27 Thread Ethan Furman

harrismh777 wrote:

Chris Angelico wrote:

To say that "most" 2.x code is
incompatible with 3.x is to deny the 2to3 utility,


all I'm 
saying is that 3.x is not compatible with 2.x code (completely not 
compatible)



and you're ignoring
the people who deliberately write code that can cross-execute on
either version - which is really not that difficult,


That's what I do... 

>
Lying about this isn't helpful to anyone coming 
on board with Python. Just tell them the truth...


Um -- how can you have on the one hand "completely not compatible" and 
on the other "code that can cross-execute on either version"?


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


Re: Beginner needs advice

2011-05-27 Thread Dan Stromberg
On Fri, May 27, 2011 at 7:40 AM, harrismh777 wrote:

> Colin J. Williams wrote:
>
>> It would be safer to stick with Python 2.7 initially and then consider
>> the transition to 3.2 later.
>>
>
> I must disagree with Colin's statement. If you are a complete beginner with
> Python... then there is going to a learning curve for you... and that curve
> should be 3.2---  period.
>

I almost agree with this, but not quite: A newbie should start with 3.2, but
regrettably fall back to 2.7 -=IF=- there's a necessary dependency that
hasn't been updated for whatever project(s) they're working on.

>
> The point is that 3.x is completely incompatible with 2.x (some call it a
> dialect, but that is a lie). Python3 is the future of the language, and if
> you're new to Python, then learn 3.x, move forward and don't look back...
> seriously.
>

3.x and 2.x are not that extremely incompatible.  You usually can't just
take 2.x code and run it, unmodified, on 3.x.  However, there is a common
subset that is pretty viable.  EG:
http://stromberg.dnsalias.org/~dstromberg/backshift/

Backshift is a relatively substantial piece of code (4400 lines and
counting), but it runs fine on CPython 2.x, CPython 3.x, PyPy and Jython
(Jython just slightly post-2.5.2 - they aren't planning to cut a new release
that's compatible, but it's in their SCM), without any help from 2to3 or
3to2.  It was written from the start with the intent of being very portable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing current dir and executing a shell script

2011-05-27 Thread suresh
On Friday, May 27, 2011 3:19:22 PM UTC-7, Albert Hopkins wrote:
> On Fri, 2011-05-27 at 14:25 -0700, suresh wrote:
> > Hi,
> > I want to execute the following command line stuff from inside python. 
> > $cd directory
> > $./executable
> > 
> > I tried the following but I get errors
> > import subprocess
> > subprocess.check_call('cd dir_name;./executable')
> > 
> > Due to filename path issues, I cannot try this version.
> > subprocess.check_call('./dir_name/executable')
> > 
> 
> You don't want to do this because "cd" is a built-in shell command, and
> subprocess does not execute within a shell (by default).
> 
> The proper way to do this is to use the "cwd" keyword argument to
> subprocess calls, i.e.:
> 
> >>> subprocess.check_call(('/path/to/exec',), cwd="/path/to/dir")
> 
> -a

It works. thank you very much. I have been struggling with this for a very 
long time. 
suresh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GIL in alternative implementations

2011-05-27 Thread Daniel Kluev
> So I'd like to know: how do these other implementations handle concurrency
> matters for their primitive types, and prevent them from getting corrupted
> in multithreaded programs (if they do) ? I'm not only thinking about python
> types, but also primitive containers and types used in .Net and Java VMs,
> which aren't atomic elements either at an assembly-level point of view.

Well, they definitely have some shortcomings:

test.py:

from threading import Thread
class X(object):
pass
obj = X()
obj.x = 0

def f(*args):
   for i in range(1):
   obj.x += 1

threads = []
for i in range(100):
t = Thread(target=f)
threads.append(t)
t.start()

for t in threads:
while t.isAlive():
t.join(1)

print(obj.x)

> python test.py
100
> pypy test.py
100
> jython-2.5 test.py
19217
> ipy test.py
59040

Not that this thing is reasonable to do in real code, but cpython and
other implementations with GIL at least give you some safety margin.

-- 
With best regards,
Daniel Kluev
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bdist_wininst: install_script not run on uninstall

2011-05-27 Thread Mark Hammond

On 26/05/2011 6:00 PM, Wilbert Berendsen wrote:

Op donderdag 26 mei 2011 schreef Mark:


Wilbert wrote:


can anybody find out why the install script is not run?


Works for me in the pywin32 install script - maybe you should make the
smallest possible example that doesn't work and post the entire thing here?


Sorry, I was wrong.  It apparently does *not* work for me either :( 
This is a bug in distutils/bdist_wininst - I just created 
http://bugs.python.org/issue12200 with the details and your samples, and 
sadly I can't think of a work around you can use until this is fixed 
(which I might get to soon, but not this weekend...)


Cheers,

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


Re: Beginner needs advice

2011-05-27 Thread Thomas Rachel

Am 27.05.2011 17:52 schrieb Steven D'Aprano:

On Fri, 27 May 2011 09:40:53 -0500, harrismh777 wrote:


3.x is completely incompatible with 2.x (some call it a dialect,
but that is a lie).


"Completely incompatible"? A "lie"?


Hard word, but it is true. Many things can and will fall on your feet 
when moving.


There are very many subtle differences.



import math
import random
my_list = [3, 5, 7, 9]
n = random.choice(my_list)
if n%3:
 func = math.sin
else:
 func = math.cos

y = func(math.pi/n)*10
L = ['spam']*(int(y))
for item in L:
 print(item)


is valid syntax in every version of Python from 1.5 to 3.2, and it does
the same thing in all of them.


C and C++ guys complain if these languages are intermixed. Even there it 
is possible to write a program which is valid in both of them. 
Nevertheless, they are two different languages.


So are Py2 and Py3, IMHO.


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


Re: Python's super() considered super!

2011-05-27 Thread Thomas Rachel

Am 28.05.2011 01:57 schrieb sturlamolden:


Yes. And opposite: CPython cannot know that builtin super() is not
called,
even if it does not see the name 'super'. I can easily make foo()
alias super().


Another alternative would have been to make use of __xxx magic.

If every class had an "automatically available" attribute, e. g. 
___classname which thus could be accessed via __classname 
from inside, keeping the 2.x syntax would have been the best, using 
super(__classname, self).




In both cases, the cure is a keyword -- or make sure that __class__
is always defined.

If super is to be I keyword, we could argue that self and cls should
be keywords as well, and methods should always be bound. That speaks in
favour of a super() function. But then it should always be evaluated at run-
time, without any magic from the parser.

Magic functions belong in Perl, not Python.


ACK.


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


Re: Why did Quora choose Python for its development?

2011-05-27 Thread Carl Banks
On Friday, May 27, 2011 6:47:21 AM UTC-7, Roy Smith wrote:
> In article <948l8n...@mid.individual.net>,
>  Gregory Ewing  wrote:
> 
> > John Bokma wrote:
> > 
> > > A Perl programmer will call this line noise:
> > > 
> > > double_word_re = re.compile(r"\b(?P\w+)\s+(?P=word)(?!\w)",
> > > re.IGNORECASE)
> 
> One of the truly awesome things about the Python re library is that it 
> lets you write complex regexes like this:
> 
> pattern = r"""\b # beginning of line
>   (?P\w+)  # a word
>   \s+# some whitespace
>   (?P=word)(?!\w)# the same word again
>"""
> double_word_re = re.compile(pattern,  re.I | re.X)

Perl has the X flag as well, in fact I'm pretty sure Perl originated it.  Just 
saying.


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


Re: Beginner needs advice

2011-05-27 Thread Steven D'Aprano
On Fri, 27 May 2011 20:02:39 -0500, harrismh777 wrote:

> But the true picture is that 3.x is (way better) and completely
> incompatible with 2.x.   Lying about this isn't helpful to anyone coming
> on board with Python. Just tell them the truth...

Take your own advice and stop accusing others of lying when it is you 
spreading falsehoods about Python 3.

It is simply NOT TRUE that Python 3 is "completely incompatible" with 
Python 2. You keep making this accusation, but even the most cursory look 
at Python syntax, keywords, built-in objects, execution model, and 
standard library show that most things keep the same interface, and most 
of the remainder change in backward compatible ways.

There are some backwards incompatibilities, but nearly all of them can be 
resolved by an automated fixer, no human intelligence required.

Far from being "completely incompatible", the truth is that Python 2.7 
and 3.2 are more like 99% compatible. This is why there are 168 
identical .py files in the Python 2.7 and 3.2a standard libraries.

[steve@sylar ~]$ diff -rqbs --exclude="*.py[co]" /usr/local/lib/
python2.7/ /usr/local/lib/python3.2/ | grep identical | grep \\.py | wc -l
168


Calling Python 2 and Python 3 "different languages", as you have done, is 
simply wrong. Lisp and Python are different languages; Ruby and Python 
are different languages. Forth and Python are different languages. Python 
2 and 3 are not. They are the same language that share nearly everything 
in common but have a few significant differences.

Calling them "completely incompatible" is completely inaccurate.



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


Re: English Idiom in Unix: Directory Recursively

2011-05-27 Thread David Schwartz
On May 20, 12:00 am, Jonathan de Boyne Pollard  wrote:

> Indeed. And the algorithms that are employed to perform the operations
> so described are recursive.

Actually, they almost never are. Iterative algorithms are almost
always used to avoid a stack explosion. However, the terminology is
still correct. When you are asked if the operation should be performed
recursively, it is asking whether you want the same effect you would
get if a recursive algorithm was used.

Essentially, there is an implied 'as if' rule. The user doesn't care
how the program accomplishes the task, the user just needs to specify
what task the program should accomplish. This is common throughout the
discipline of programming. (Most standards have an explicit 'as if'
rule that says that when the standard specifies X, they don't
literally mean that X must happen. They mean the behavior must be
indistinguishable from X happening.)

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


Re: Beginner needs advice

2011-05-27 Thread Steven D'Aprano
On Fri, 27 May 2011 15:40:53 -0500, harrismh777 wrote:

> Steven D'Aprano wrote:
>> Would you care to revise your claims?
> 
> No.
> 
> 
> You have erected a straw-man... once again.

You keep using that term, but it is clear to me that you don't have the 
foggiest idea of what the straw-man fallacy is.

A straw man is not when somebody points out holes in your argument, or 
unwanted implications that you didn't realise were there. It is when 
somebody makes claims on your behalf that you did not make to discredit 
you, not because you don't understand the implications of your own 
argument.

You stated that Python 2 and Python 3 are COMPLETELY INCOMPATIBLE -- your 
words, not mine. You have repeated that claim, in this very post, and 
others, despite having been shown that they are not completely 
incompatible at all, that it is possible to write both forward and 
backward compatible code that works in every version of Python from 1.5 
through 3.2 inclusive.

Yes, it is true that you can also write code that works in 2.5 but not 
3.2, but so what? You can also write code that works in 2.5 but not 2.6:

raise "some error"  # works in 2.5 and older

Or 2.4 and 2.5:

True = 23  # works in 2.4 and older

or 2.3 and 2.4:

None = 42  # works in 2.3 and older


Do you think that Python 2.3, 2.4, 2.5 and 2.6 are four completely 
different languages, and if not, why not?

Python 3 is not the first backwards incompatible version of Python.


[...]
> All of these things are for the better, I must add.  But, the point is
> that 3.x is completely incompatible with 2.x in real ways.

And you've done it again, despite the fact that you can write compatible 
code that works in all versions of Python from 1.5 to 3.2, and easily 
write non-trivial code that works in 2.7 and 3.2. For larger projects, 
it's probably better to keep a separate 2.x and 3.x fork, but that's for 
convenience, nothing more: numpy, for example, supports 2 and 3 out of a 
single code base.

http://www.mail-archive.com/numpy-discussion%40scipy.org/msg26524.html


Perhaps you don't understand what "completely" means and are confusing it 
with "slightly".



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


Re: Beginner needs advice

2011-05-27 Thread Thorsten Kampe
* Thomas Rachel (Sat, 28 May 2011 07:06:53 +0200)
> Am 27.05.2011 17:52 schrieb Steven D'Aprano:
> > On Fri, 27 May 2011 09:40:53 -0500, harrismh777 wrote:
> >> 3.x is completely incompatible with 2.x (some call it a dialect,
> >> but that is a lie).
> >
> > "Completely incompatible"? A "lie"?
> 
> Hard word, but it is true. Many things can and will fall on your feet
> when moving.

I think we should stop talking about (in)compatability because everyone 
seems to associate something different with that term (incompatible = 
"no Python2 to code will run with Python3", "not all Python2 code will 
run with Python3").

The question is: if you want (or have) to run your code under Python3, 
how likely is that it will run unmodified? My experience is: unless the 
code is especially written with Python3 compatability or just a short 
snippet, it's actually quite unlikely that it will run.

I modified three programs/modules (none of them written with Python3 in 
mind - I was thinking that Python 3000 would come out some day after 
Perl 6, PHP 6 and GNU Hurd; how could I know that the Python developers 
actually mean business?)

One is a tool box kind of module. I had to insert lots of "list()" and 
add a complete function that would deal with the different behaviour of 
"sort". Probably easy to find the problems if you have extensive unit 
tests but without it was a tedious nightmare.

The second a kind of script template. gettext.install has no "unicode = 
True". Easy fix but I wondered why Python 3 does not ignore the keyword 
simply.

The third, a more real world complete application using PyQt. Took me 
about a day to fix. The problem was not just with the code but also with 
the tools (pyuic4, pyrcc4). Without the PyQt mailing list this wouldn't 
have been possible. Still: a complete workday (or even more) for 150 
lines of code.


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


Re: Beginner needs advice

2011-05-27 Thread Chris Angelico
On Sat, May 28, 2011 at 4:38 PM, Thorsten Kampe
 wrote:
> The question is: if you want (or have) to run your code under Python3,
> how likely is that it will run unmodified? My experience is: unless the
> code is especially written with Python3 compatability or just a short
> snippet, it's actually quite unlikely that it will run.
>

But what about the 2to3 tool? If you use that, then how much more is
there to deal with?

I installed Python 3 and found that a little bandwidth monitor stopped
working. After running it through 2to3, there were only a couple of
things needing fixing, including the HTTPS library (it didn't like my
Unicode strings, I had to go b" " for them), but the bulk of it was
fine.

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


Re: Beginner needs advice

2011-05-27 Thread Thorsten Kampe
* Thorsten Kampe (Sat, 28 May 2011 08:38:54 +0200)
> My experience is: unless the code is especially written with Python3
> compatability [...]

Oops, I meant "unless the code is specifically written with Python3 
compatability in mind [...]"

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