Re: sum() requires number, not simply __add__

2012-02-24 Thread Peter Otten
Buck Golemon wrote:

> I feel like the design of sum() is inconsistent with other language
> features of python. Often python doesn't require a specific type, only
> that the type implement certain methods.
> 
> Given a class that implements __add__ why should sum() not be able to
> operate on that class?
> 
> We can fix this in a backward-compatible way, I believe.
> 
> Demonstration:
> I'd expect these two error messages to be identical, but they are
> not.
> 
>  >>> class C(object): pass
>  >>> c = C()
>  >>> sum((c,c))
> TypeError: unsupported operand type(s) for +: 'int' and 'C'
> >>> c + c
> TypeError: unsupported operand type(s) for +: 'C' and 'C'

You could explicitly provide a null object:

>>> class Null(object):
... def __add__(self, other):
... return other
...
>>> null = Null()
>>> class A(object):
... def __init__(self, v):
... self.v = v
... def __add__(self, other):
... return A("%s+%s" % (self, other))
... def __str__(self):
... return self.v
... def __repr__(self):
... return "A(%r)" % self. v
...
>>> sum(map(A, "abc"))
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'int' and 'A'
>>> sum(map(A, "abc"), null)
A('a+b+c')


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


Re: Please verify!!

2012-02-24 Thread Ben Finney
Andrew Berg  writes:

> On 2/23/2012 4:43 PM, Dave Angel wrote:
> > First thing I'd do is to disable tab logic in the editor.  When you 
> > press the tab key, there's no excuse for an editor to actually put a tab 
> > in the file.  It should adjust the column by adding the appropriate 
> > number of spaces.
> Unless, of course, you know, you actually /want/ to use tabs (the
> horror!). The decision whether to use tabs or spaces shouldn't be made
> for the novice programmer.

Those two positions yo describe are in conflict.

Are you referring to novice programmers – who, by any reasonable
definition of “novice”, don't have an opinion on the tabs-versus-spaces
indentation debate?

Or are you talking about people who are experienced enough to have an
opinion and expect their editor to allow them the choice?

> I recommend using UTF-8 always unless there's some reason not to.

Likewise, I recommend using spaces for indentation always, unless
there's some reason not to.

The reason is the same: spaces for indentation and UTF-8 for encoding
will both allow them the best chance of ignoring the issue as
irrelevant, by enabling the smoothest collaboration with the vast
majority of other programmers who have to work with them.

And in both those issues, I think it's ludicrous to expect the novice
programmer to care enough about the matter to have an opinion and select
a configuration option. The editor authors should choose the best option
for them as a default, and let most users sail on, happily ignorant of
the flame wars they have avoided.

-- 
 \   “In the long run nothing can withstand reason and experience, |
  `\and the contradiction which religion offers to both is all too |
_o__)palpable.” —Sigmund Freud |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

2012-02-24 Thread Peter Otten
Ethan Furman wrote:

> Steven D'Aprano wrote:
>> On Thu, 23 Feb 2012 16:30:09 -0800, Alex Willmer wrote:
>> 
>>> This week I was slightly surprised by a behaviour that I've not
>>> considered before. I've long used
>>>
>>> for i, x in enumerate(seq):
>>># do stuff
>>>
>>> as a standard looping-with-index construct. In Python for loops don't
>>> create a scope, so the loop variables are available afterward. I've
>>> sometimes used this to print or return a record count e.g.
>>>
>>> for i, x in enumerate(seq):
>>># do stuff
>>> print 'Processed %i records' % i+1
>>>
>>> However as I found out, if seq is empty then i and x are never created.
>> 
>> This has nothing to do with enumerate. It applies to for loops in
>> general: the loop variable is not initialised if the loop never runs.
>> What value should it take? Zero? Minus one? The empty string? None?
>> Whatever answer Python choose would be almost always wrong, so it refuses
>> to guess.
>> 
>> 
>>> The above code will raise NameError. So if a record count is needed, and
>>> the loop is not guaranteed to execute the following seems more correct:
>>>
>>> i = 0
>>> for x in seq:
>>> # do stuff
>>> i += 1
>>> print 'Processed %i records' % i
>> 
>> What fixes the problem is not avoiding enumerate, or performing the
>> increments in slow Python instead of fast C, but that you initialise the
>> loop variable you care about before the loop in case it doesn't run.
>> 
>> i = 0
>> for i,x in enumerate(seq):
>> # do stuff
>> 
>> is all you need: the addition of one extra line, to initialise the loop
>> variable i (and, if you need it, x) before hand.
> 
> Actually,
> 
> i = -1
> 
> or his reporting will be wrong.

Yes, either

i = -1
for i, x in enumerate(seq):
...
print "%d records" % (i+1)

or

i = 0
for i, x in enumerate(seq, 1):
...
print "%d records" % i

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


subtraction of floating point numbers

2012-02-24 Thread Jaroslav Dobrek
Hello,

when I have Python subtract floating point numbers it yields weird
results. Example:

4822.40 - 4785.52 = 36.87992

Why doesn't Python simply yield the correct result? It doesn't have a
problem with this:

482240 - 478552 = 3688

Can I tell Python in some way to do this differently?

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


Re: subtraction of floating point numbers

2012-02-24 Thread Alain Ketterlin
Jaroslav Dobrek  writes:

> when I have Python subtract floating point numbers it yields weird
> results. Example:
>
> 4822.40 - 4785.52 = 36.87992

We've had this discussion here one or two days ago...

The usual answer is: please read "What Every Computer Scientist Should
Know About Floating Point Arithmetic", at:

http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6768

and check the answers posted these last days. In brief: you're working
with floating point numbers, not reals (i.e., real "reals"). That's
life. Deal with it, or move to specialized packages, like decimal.

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


Re: asynchronous downloading

2012-02-24 Thread Giampaolo Rodolà
Il 24 febbraio 2012 02:10, Plumo  ha scritto:
> that example is excellent - best use of asynchat I have seen so far.
>
> I read through the python-dev archives and found the fundamental problem is 
> no one maintains asnycore / asynchat.

Well, actually I do/did.
Point with asyncore/asynchat is that it's original design is so flawed
and simplicistic it doesn't allow actual customization without
breaking compatibility.
See for example:
http://bugs.python.org/issue6692


--- Giampaolo
http://code.google.com/p/pyftpdlib/
http://code.google.com/p/psutil/
http://code.google.com/p/pysendfile/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please verify!!

2012-02-24 Thread Andrew Berg
On 2/24/2012 2:32 AM, Ben Finney wrote:
> Are you referring to novice programmers – who, by any reasonable
> definition of “novice”, don't have an opinion on the tabs-versus-spaces
> indentation debate?
> 
> Or are you talking about people who are experienced enough to have an
> opinion and expect their editor to allow them the choice?
The former. Opinion doesn't necessarily come with experience - habit
will usually override any minor reason to change. My point is that one
should have an opinion on it, not just be told which is better. I should
clarify that I mean that in a general sense as well, since it may have
come across as a bit of an overreaction.

> The reason is the same: spaces for indentation and UTF-8 for encoding
> will both allow them the best chance of ignoring the issue as
> irrelevant, by enabling the smoothest collaboration with the vast
> majority of other programmers who have to work with them.
If by that, you mean that using spaces is better because it's what the
majority of programmers use, and it makes things much smoother when
working with others, then I agree. When working in a team, it's
definitely not something to argue over.

> And in both those issues, I think it's ludicrous to expect the novice
> programmer to care enough about the matter to have an opinion and select
> a configuration option. The editor authors should choose the best option
> for them as a default, and let most users sail on, happily ignorant of
> the flame wars they have avoided.
A valid point. I think one should have an opinion, but I can see why one
would avoid the issue.

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subtraction of floating point numbers

2012-02-24 Thread Chris Rebert
On Fri, Feb 24, 2012 at 12:41 AM, Jaroslav Dobrek
 wrote:
> Hello,
>
> when I have Python subtract floating point numbers it yields weird
> results. Example:
>
> 4822.40 - 4785.52 = 36.87992
>
> Why doesn't Python simply yield the correct result? It doesn't have a
> problem with this:
>
> 482240 - 478552 = 3688
>
> Can I tell Python in some way to do this differently?

Refer to this thread from 2 days ago:
http://mail.python.org/pipermail/python-list/2012-February/1288344.html

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


Re: storing in list and retrieving.

2012-02-24 Thread Smiley 4321
Thanks. It was very simple with using 'pickle'.

Thanks.
--

On Thu, Feb 23, 2012 at 4:01 PM, Jean-Michel Pichavant <
jeanmic...@sequans.com> wrote:

> Smiley 4321 wrote:
>
>> It requires concepts of 'python persistence' for the code to be designed .
>>
>> Else it simple.
>>
>> Looking for some flow??
>> 
>>
> Hi,
>
> Have a look at 
> http://docs.python.org/**library/pickle.html
>
> Cheers,
>
> JM
>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please verify!!

2012-02-24 Thread Jugurtha Hadjar

On 23/02/2012 23:13, Manish Sharma wrote:

Hi I am new to python language. On my first day, somebody told me that
if any python script file is opened with any editor except python
editor, the file is corrupted. Some spacing or indentation is changed
and script stops working. I was opening the script file in Windows
using Notepad++ but I didn't save anything and closed it. Still it was
suggested to never open the python file in any other editor.

Can anybody please verify this? Can opening a python script in any
editor other than python editor corrupt the script? Did anybody ever
face such type of issue or its just misunderstanding of the concept.

I hope this group is the best place to ask this. Please reply !

:)
Manish


I don't think so, I have used EDIT, Notepad, Notepad++ and they all work 
fine.




PS: What's the "python editor" you were advised to stick with, by the way ?

--
~Jugurtha Hadjar,

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


Re: Please verify!!

2012-02-24 Thread Duncan Booth
Andrew Berg  wrote:

> Yes. However, there are many editors for various platforms that handle
> the different line endings just fine. In fact, Notepad is the only
> editor I can think of off the top of my head that has an issue.

The original question was about Notepad++ which is nothing at all like 
Notepad.

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


Re: Please verify!!

2012-02-24 Thread Andrew Berg
On 2/24/2012 5:21 AM, Duncan Booth wrote:
> The original question was about Notepad++ which is nothing at all like 
> Notepad.
And I did give the OP an answer about Notepad++ specifically in another
message.

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum() requires number, not simply __add__

2012-02-24 Thread Antoon Pardon

On 02/24/2012 12:33 AM, Steven D'Aprano wrote:

If your application stops working after you carelessly mess with
components your application relies on, the right answer is usually:

"Don't do that then."

Python doesn't try to prevent people from shooting themselves in the foot.
   
Yes it does! A simple example is None as a keyword to prevent 
assignments to it.


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


Re: sum() requires number, not simply __add__

2012-02-24 Thread Duncan Booth
Stefan Behnel  wrote:

> I know that you just meant this as an example, but it's worth
> mentioning in this context that it's not exactly efficient to "sum up"
> lists this way because there is a lot of copying involved. Each adding
> of two lists creates a third one and copies all elements into it. So
> it eats a lot of time and space.

If you search back through this group far enough you can find an 
alternative implementation of sum that I suggested which doesn't have the 
same performance problem with lists or strings and also improves the 
accuracy of the result with floats.

In effect what it does is instead of:
  (a + b) + c) + d) + e) + f)
it calculates the sum as:
  ((a + b) + (c + d)) + (e + f)

i.e. in as balanced a manner as it can given that it still has to work from 
left to right.

Of course that could still change the final result for some user defined 
types and never having converted my code to C I have no idea whether or not 
the performance for the intended case would be competitive with the builtin 
sum though I don't see why it wouldn't be.

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


Re: namespace question

2012-02-24 Thread Jean-Michel Pichavant

xixiliguo wrote:

c = [1, 2, 3, 4, 5]
class TEST():
c = [5, 2, 3, 4, 5]
def add( self ):
c[0] = 15

a = TEST()


a.add()

print( c, a.c, TEST.c )

result :
[15, 2, 3, 4, 5] [5, 2, 3, 4, 5] [5, 2, 3, 4, 5]


why a.add() do not update c in Class TEST? but update c in main file
  


Attributes can only accessed by explictly naming the owner, unlike some 
other languages which infer 'this/self'.
When an attribute is not found in the owner, python may look into the 
"outer" namespace. Read the python documentation for an accurate 
description.



Here is an illustration (python 2.5):

c='global'

class TEST():
 c = 'class'
 d = 'classonly'
 def __init__(self):
   self.c='instance'
 def test(self):
   print c
   print TEST.c
   print self.c
   print self.d # this is valid, if d is not found in the instance, 
python will look into the class


t = TEST()

t.test()

global
class
instance
classonly


Note that objects in python are properly named namespaces. locals and 
globals are not, so be careful while naming those (in few words: don't 
use globals)


c = 'global'

def foo():
 c = 'local'
 print c # same name for 2 different objects

def bar():
 print c
 global c # the global statement is quite strange, it applies to the 
whole block, even previous statements, ppl usually put it at the 
begining of the block though


foo()
bar()

'local'
'global'

Cheers,

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


Re: Please verify!!

2012-02-24 Thread Steven D'Aprano
On Fri, 24 Feb 2012 03:18:18 -0600, Andrew Berg wrote:

> On 2/24/2012 2:32 AM, Ben Finney wrote:
>> Are you referring to novice programmers – who, by any reasonable
>> definition of “novice”, don't have an opinion on the tabs-versus-spaces
>> indentation debate?
>> 
>> Or are you talking about people who are experienced enough to have an
>> opinion and expect their editor to allow them the choice?
>
> The former. Opinion doesn't necessarily come with experience - habit
> will usually override any minor reason to change. My point is that one
> should have an opinion on it, not just be told which is better. I should
> clarify that I mean that in a general sense as well, since it may have
> come across as a bit of an overreaction.

"My opinion is that we shouldn't use either tabs or spaces, but capital 
Zs instead, 'cos I like Zs and we don't use enough of them!"

Opinions need to be informed to be better than useless. By definition 
newbies don't have the experience to have informed opinions. You are 
encouraging people who lack the experience to make an informed decision 
to take sides in the "tabs vs spaces" question on the basis of... what? 
Gut feeling? Astrology? Feng shui? Whether they find it easy to say the 
word "space" or have a lisp and prefer "tab" instead?

There are many times that we can't afford to sit on the fence. Lacking 
experience to decide between spaces and tabs, we can't just say "I won't 
use either", or "I'll use both" (unless you do so in separate files). So 
how can we make a decision?

The usual way is to listen to others, who do have the experience to make 
a decision (even if only imperfectly). But you've just told us off for 
passing on our experience/opinions to newbies, so in effect you're saying 
that people shouldn't learn from the experiences of others.

That, I think, is a terrible philosophy. Life is too short to gain an 
opinion for ourselves about everything, and too difficult to sit on the 
fence.

The right way is to encourage newbies to listen to the arguments put 
forth, and *then* make up their own mind, or in the absence of easily 
understood arguments (let's face it, many technical decisions only make 
sense after years of study, experience or careful reasoning) on the basis 
of any consensus amongst experts. Often there may be no absolutely right 
or wrong answers.

Personally, I prefer tabs for theoretical reasons and spaces for 
practical ones. I think that the world would be better off if we all 
standardised on tabs instead of spaces, but since that's not going to 
happen, I can interoperate better with the mass of broken tools out 
there, and with other people, by using spaces.

I wonder whether Windows users tend to be more sympathetic to tabs than 
Unix/Linux users, and if so, I wonder what if anything that means.


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


Does turtledemo in Python 3.2 actually work?

2012-02-24 Thread Steven D'Aprano
Python 3.2 includes turtledemo, a demonstration program for the turtle 
module.

When I run it, I can load the turtle scripts, and the GUI application 
says "Press the start button", but there is no start button.

Can anyone else confirm this as a bug?

http://docs.python.org/py3k/library/turtle.html#demo-scripts



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


Re: A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

2012-02-24 Thread Rick Johnson
On Feb 23, 6:30 pm, Alex Willmer  wrote:
> [...]
> as a standard looping-with-index construct. In Python for loops don't
> create a scope, so the loop variables are available afterward. I've
> sometimes used this to print or return a record count e.g.
>
> for i, x in enumerate(seq):
>    # do stuff
> print 'Processed %i records' % i+1

You could employ the "else clause" of "for loops" to your advantage;
(psst: which coincidentally are working pro-bono in this down
economy!)

>>> for x in []:
... print x
... else:
... print 'Empty Iterable'
Empty Iterable

>>> for i,o in enumerate([]):
... print i, o
... else:
... print 'Empty Iterable'
Empty Iterable

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


Re: Does turtledemo in Python 3.2 actually work?

2012-02-24 Thread Arnaud Delobelle
On 24 February 2012 12:25, Steven D'Aprano
 wrote:
> Python 3.2 includes turtledemo, a demonstration program for the turtle
> module.
>
> When I run it, I can load the turtle scripts, and the GUI application
> says "Press the start button", but there is no start button.
>
> Can anyone else confirm this as a bug?
>
> http://docs.python.org/py3k/library/turtle.html#demo-scripts

Just tested with Python 3.2.1 on Mac OS X 10.6.8 and all seems fine.
Perhaps if you say which platform it's failing on, others will be able
to reproduce the failure on the same platform?

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


Re: A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

2012-02-24 Thread Peter Otten
Rick Johnson wrote:

> On Feb 23, 6:30 pm, Alex Willmer  wrote:
>> [...]
>> as a standard looping-with-index construct. In Python for loops don't
>> create a scope, so the loop variables are available afterward. I've
>> sometimes used this to print or return a record count e.g.
>>
>> for i, x in enumerate(seq):
>> # do stuff
>> print 'Processed %i records' % i+1
> 
> You could employ the "else clause" of "for loops" to your advantage;

 for x in []:
> ... print x
> ... else:
> ... print 'Empty Iterable'
> Empty Iterable
> 
 for i,o in enumerate([]):
> ... print i, o
> ... else:
> ... print 'Empty Iterable'
> Empty Iterable

No:


>>> for i in []:
... pass
... else:
... print "else"
...
else
>>> for i in [42]:
... pass
... else:
... print "else"
...
else
>>> for i in [42]:
... break
... else:
... print "else"
...
>>>

The code in the else suite executes only when the for loop is left via 
break. A non-empty iterable is required but not sufficient.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

2012-02-24 Thread Peter Otten
Peter Otten wrote:

> The code in the else suite executes only when the for loop is left via
> break. 

Oops, the following statement is nonsense:

> A non-empty iterable is required but not sufficient.

Let me try again:

A non-empty iterable is required but not sufficient to *skip* the else-suite 
of a for loop.

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


Re: Just curious: why is /usr/bin/python not a symlink?

2012-02-24 Thread Roy Smith
In article ,
 Thomas Rachel 
  
 wrote:

> Not only that, [hard and symbolic links] have slightly different 
> semantics.

This is true, but only for very large values of "slightly".

Symlinks, for example, can cross file system boundaries (including NFS 
mount points).  Symlinks can refer to locations that don't exist!  For 
example:

~$ ln -s foobar foo
~$ ls -l foo
lrwxr-xr-x  1 roy  staff  6 Feb 24 08:15 foo -> foobar
~$ cat foo
cat: foo: No such file or directory

Symlinks can be chained (i.e. a symlink points to someplace which in 
turn is another symlink).  They're really very different beasts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please verify!!

2012-02-24 Thread Andrew Berg
On 2/24/2012 6:20 AM, Steven D'Aprano wrote:
> Opinions need to be informed to be better than useless. By definition 
> newbies don't have the experience to have informed opinions.
I thought I had implied that I meant informed opinions, but apparently not.

> There are many times that we can't afford to sit on the fence. Lacking 
> experience to decide between spaces and tabs, we can't just say "I won't 
> use either", or "I'll use both" (unless you do so in separate files). So 
> how can we make a decision?
> 
> The usual way is to listen to others, who do have the experience to make 
> a decision (even if only imperfectly). But you've just told us off for 
> passing on our experience/opinions to newbies, so in effect you're saying 
> that people shouldn't learn from the experiences of others.
I don't mean that no one should ever give an opinion. Saying you prefer
spaces because you've had to deal with broken editors that don't handle
tabs well is quite different from saying an editor is wrong/broken if it
isn't using space-tabs. Giving an opinion and presenting an argument are
perfectly fine; I don't agree with calling things inherently wrong if
they aren't what you prefer. I had (and have) no problem with Dave
preferring spaces and giving reasons. I have a problem with him implying
that editors should always use space-tabs and never real tabs,
especially in the context of this thread.

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sum() requires number, not simply __add__

2012-02-24 Thread Roy Smith
In article ,
 Antoon Pardon  wrote:

> > Python doesn't try to prevent people from shooting themselves in the foot.
> >
> Yes it does! A simple example is None as a keyword to prevent 
> assignments to it.

Hmmm.  Just playing around with some bizarre things to do with None, and 
discovered this:

>>> import sys as None

doesn't give an error, but also doesn't assign the module to the symbol 
'None'.  Weird.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Mark Lawrence

On 24/02/2012 13:37, Rick Johnson wrote:

I get sick and tired of doing this!!!

if maxlength == UNLIMITED:
 allow_passage()
elif len(string)>  maxlength:
 deny_passage()

What Python needs is some constant that can be compared to ANY numeric
type and that constant will ALWAYS be larger!





Do you want to test for something that is larger than infinity?

--
Cheers.

Mark Lawrence.

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Neil Cerutti
On 2012-02-24, Rick Johnson  wrote:
> I get sick and tired of doing this!!!
>
> if maxlength == UNLIMITED:
> allow_passage()
> elif len(string) > maxlength:
> deny_passage()
>
> What Python needs is some constant that can be compared to ANY
> numeric type and that constant will ALWAYS be larger!

What's the point of that?

The only time I've naively pined for such a thing is when
misapplying C idioms for finding a minimum value.

Python provides an excellent min implementation to use instead.

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Miki Tebeka
float('infinity') should be good enough.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

2012-02-24 Thread Steven D'Aprano
On Fri, 24 Feb 2012 13:44:15 +0100, Peter Otten wrote:

 for i in []:
> ... pass
> ... else:
> ... print "else"
> ...
> else
 for i in [42]:
> ... pass
> ... else:
> ... print "else"
> ...
> else
 for i in [42]:
> ... break
> ... else:
> ... print "else"
> ...


> The code in the else suite executes only when the for loop is left via
> break. A non-empty iterable is required but not sufficient.

You have a typo there. As your examples show, the code in the else suite 
executes only when the for loop is NOT left via break (or return, or an 
exception). The else suite executes regardless of whether the iterable is 
empty or not.


for...else is a very useful construct, but the name is misleading. It 
took me a long time to stop thinking that the else clause executes when 
the for loop was empty.

In Python 4000, I think for loops should be spelled:

for name in iterable:
# for block
then:
# only if not exited with break
else:
# only if iterable is empty

and likewise for while loops.

Unfortunately we can't do the same now, due to the backward-incompatible 
change in behaviour for "else".



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


Re: A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

2012-02-24 Thread Arnaud Delobelle
On 24 February 2012 14:54, Steven D'Aprano
 wrote:

> for...else is a very useful construct, but the name is misleading. It
> took me a long time to stop thinking that the else clause executes when
> the for loop was empty.

This is why I think we should call this construct "for / break / else"
rather than "for / else".

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


Re: A quirk/gotcha of for i, x in enumerate(seq) when seq is empty

2012-02-24 Thread Peter Otten
Steven D'Aprano wrote:

>> The code in the else suite executes only when the for loop is left via
>> break. A non-empty iterable is required but not sufficient.
> 
> You have a typo there. As your examples show, the code in the else suite
> executes only when the for loop is NOT left via break (or return, or an
> exception). The else suite executes regardless of whether the iterable is
> empty or not.

Yup, sorry for the confusion.


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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Rick Johnson
On Feb 24, 8:39 am, Miki Tebeka  wrote:
> float('infinity') should be good enough.

Yes, that is the answer however the implementation is inconsistent.

py> float("inf")
inf
py> float("infinity")
inf
py> int("inf")
Traceback (most recent call last):
  File "", line 1, in 
int("inf")
ValueError: invalid literal for int() with base 10: 'inf'
py> int("infinity")
Traceback (most recent call last):
  File "", line 1, in 
int("infinity")
ValueError: invalid literal for int() with base 10: 'infinity'

The best place for INFINITY is a constant of the math module.

# Hypothetical #
py> from math import INFINITY
py> 1 < INFINITY
True
py> 9 < INFINITY
True
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Mel Wilson
Rick Johnson wrote:

> I get sick and tired of doing this!!!
> 
> if maxlength == UNLIMITED:
> allow_passage()
> elif len(string) > maxlength:
> deny_passage()
> 
> What Python needs is some constant that can be compared to ANY numeric
> type and that constant will ALWAYS be larger!

Easily fixed:



class Greatest (object):
def __cmp__ (self, other):
if isinstance (other, Greatest):
return 0
return 1

def __hash__ (self):
return id (Greatest)

class Least (object):
def __cmp__ (self, other):
if isinstance (other, Least):
return 0
return -1

def __hash__ (self):
return id (Least)



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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Rick Johnson
On Feb 24, 8:25 am, Neil Cerutti  wrote:

> > What Python needs is some constant that can be compared to ANY
> > numeric type and that constant will ALWAYS be larger!
>
> What's the point of that?
>
> The only time I've naively pined for such a thing is when
> misapplying C idioms for finding a minimum value.

The best use case is for default arguments to constructors or func/
meths. If you set the argument to INFINITY instead of -1 (or some
other dumb string value to mean "unlimited") you can omit a useless
conditional block later. Observe:

if maxlength == -1 # unlimited length:
keep_going()
elif len(object) < maxlength:
stop() # because we reached the limit

I see tons and tons of old Python code that uses -1 as an "unlimited"
value, where positive numbers are meant to constrain dome value. I
have always found that to be intuitive; hence my question.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Steven D'Aprano
On Fri, 24 Feb 2012 10:21:45 -0500, Mel Wilson wrote:

> Rick Johnson wrote:
> 
>> I get sick and tired of doing this!!!
>> 
>> if maxlength == UNLIMITED:
>> allow_passage()
>> elif len(string) > maxlength:
>> deny_passage()
>> 
>> What Python needs is some constant that can be compared to ANY numeric
>> type and that constant will ALWAYS be larger!
> 
> Easily fixed:
> 
> 
> 
> class Greatest (object):
> def __cmp__ (self, other):
> if isinstance (other, Greatest):
> return 0
> return 1
> 
> def __hash__ (self):
> return id (Greatest)

__cmp__ no longer exists in Python 3, so this solution could only work in 
Python 2.

Here's a version using rich comparisons:

class Greatest:
__eq__ = __le__ = lambda self, other: isinstance(other, type(self))
__ne__ = __gt__ = lambda self, othr: not isinstance(othr, type(self))
__lt__ = lambda self, other: False
__ge__ = lambda self, other: True
__hash__ = lambda self: 42


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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Rick Johnson
On Feb 24, 9:21 am, Mel Wilson  wrote:

> Easily fixed:
>
> [...snip code...]

Yes i could write my own implementation of INFINITY if i wanted,
although i would have returned True and False as apposed to 1 and 0
AND used the identifiers Infinity and Infinitesimal, but i digress :-
P.

However, INFINITY is something i believe a language should provide;
which python does, albeit inconsistently.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Rick Johnson
On Feb 24, 7:55 am, Mark Lawrence  wrote:
> Do you want to test for something that is larger than infinity?

Not exactly. I want to set a constant that has a value of infinity and
then do comparisons against the constant.

##
# Hypothetical 1 #
##

def confine(string, maxlength=INFINITY):
return string[:maxlength]

py> confine('123')
'123'
py> confine('123', 1)
'1'

##
# Hypothetical 2 #
##

def confine(string, maxlength=INFINITY):
if len(string) < maxlength:
do_something()
else:
twiddle_thumbs()


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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Michael Torrie
On 02/24/2012 08:34 AM, Rick Johnson wrote:
> Yes i could write my own implementation of INFINITY if i wanted,
> although i would have returned True and False as apposed to 1 and 0
> AND used the identifiers Infinity and Infinitesimal, but i digress :-
> P.
> 
> However, INFINITY is something i believe a language should provide;
> which python does, albeit inconsistently.

How do you represent infinity as an binary integer number?  Or are you
suggesting that the integer type (class) be modified to allow an
"infinity" state that really isn't a number at all (could not be stored
as a integer in C)?

Float is a different story because IEEE does define a binary
representation of infinity in the floating-point specification.

I know of no language that has any form of representation of infinity
for integers mainly because there's no way to represent infinity as a
standard twos-compliment binary number.  In a language that deals
directly with types in memory such as C, having an infinity
representation would be possible but would make simple math really hard,
and much slower.

All this reminds me of the original cray supercomputers.  They didn't
use twos compliment for integers so they had two representations of zero
(+0 and -0).  Made programming a bit tricky.  When asked why the cray
didn't just do two's compliment like everyone else, Seymour Cray
responded that when the computer was designed he simply didn't know
about twos compliment.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Mark Lawrence

On 24/02/2012 16:23, Michael Torrie wrote:

On 02/24/2012 08:34 AM, Rick Johnson wrote:

Yes i could write my own implementation of INFINITY if i wanted,
although i would have returned True and False as apposed to 1 and 0
AND used the identifiers Infinity and Infinitesimal, but i digress :-
P.

However, INFINITY is something i believe a language should provide;
which python does, albeit inconsistently.


How do you represent infinity as an binary integer number?  Or are you
suggesting that the integer type (class) be modified to allow an
"infinity" state that really isn't a number at all (could not be stored
as a integer in C)?


The C integer bit doesn't matter since e.g.
>>> 
a=100

>>> a
100L

And no, I'm not going to calculate how much memory I'd need to store a 
string that's this long :)



Float is a different story because IEEE does define a binary
representation of infinity in the floating-point specification.

I know of no language that has any form of representation of infinity
for integers mainly because there's no way to represent infinity as a
standard twos-compliment binary number.  In a language that deals
directly with types in memory such as C, having an infinity
representation would be possible but would make simple math really hard,
and much slower.

All this reminds me of the original cray supercomputers.  They didn't
use twos compliment for integers so they had two representations of zero
(+0 and -0).  Made programming a bit tricky.  When asked why the cray
didn't just do two's compliment like everyone else, Seymour Cray
responded that when the computer was designed he simply didn't know
about twos compliment.


--
Cheers.

Mark Lawrence.

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


Re: multiprocessing, what am I doing wrong?

2012-02-24 Thread Eric Frederich
I can sill get it to freeze and nothing is printed out from the other
except block.
Does it look like I'm doing anything wrong here?

On Thu, Feb 23, 2012 at 3:42 PM, MRAB  wrote:

> On 23/02/2012 17:59, Eric Frederich wrote:
>
>> Below is some pretty simple code and the resulting output.
>> Sometimes the code runs through but sometimes it just freezes for no
>> apparent reason.
>> The output pasted is where it just got frozen on me.
>> It called start() on the 2nd worker but the 2nd worker never seemed to
>> enter the run method.
>>
>>  [snip]
>
> The 2nd worker did enter the run method; there are 2 lines of "2".
>
> Maybe there's an uncaught exception in the run method for some reason.
> Try doing something like this:
>
>
> try:
>args = self.inbox.get_nowait()
> except Queue.Empty:
>break
> except:
>import traceback
>print "*** Exception in worker"
>print >> sys.stderr, traceback.print_exc()
>sys.stderr.flush()
>print "***"
>raise
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just curious: why is /usr/bin/python not a symlink?

2012-02-24 Thread John Roth
On Feb 23, 2:11 pm, Terry Reedy  wrote:
> On 2/23/2012 2:34 PM, HoneyMonster wrote:
>
>
>
>
>
>
>
>
>
> > On Thu, 23 Feb 2012 14:24:23 -0500, Jerry Hill wrote:
>
> >> On Thu, Feb 23, 2012 at 2:11 PM, HoneyMonster
> >>   wrote:
> >>> $ cd /usr/bin $ ls -l python*
> >>> -rwxr-xr-x 2 root root 9496 Oct 27 02:42 python lrwxrwxrwx 1 root root
> >>>     6 Oct 29 19:34 python2 ->  python -rwxr-xr-x 2 root root 9496 Oct 27
> >>> 02:42 python2.7 $ diff -s  python python2.7 Files python and python2.7
> >>> are identical $
>
> >>> I'm just curious: Why two identical files rather than a symlink?
>
> >> It's not two files, it's a hardlink.  You can confirm by running ls -li
> >> python* and comparing the inode numbers.
>
> > You are spot on. Thank you, and sorry for my stupidity.
>
> The question 'why a hardlink rather than symlink' is not stupid. It was
> part of the discussion ofhttp://python.org/dev/peps/pep-0394/
> The answer was 'history' and how things were 20 years ago and either the
> pep or the discussion around it says symlinks are fine now and the
> decision is up to distributors.
>
> --
> Terry Jan Reedy

I believe the changes for PEP 394 are using symlinks. The distro
maintainer can, of course, change that.

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Devin Jeanpierre
On Fri, Feb 24, 2012 at 9:25 AM, Neil Cerutti  wrote:
> The only time I've naively pined for such a thing is when
> misapplying C idioms for finding a minimum value.
>
> Python provides an excellent min implementation to use instead.

min can be a little inconvenient. As soon as anything complicated has
to be done during the min expression, you need to switch to using
something else for sanity's sake. In that vein, I do actually
sometimes use float('inf') (for numbers), or a custom max/min object.



Silly and completely nonserious addendum:

Forgive me, I have spoken in error! min is the one true way, for you
can still do it with a little wrangling, as follows:

@operator.itemgetter(1)
@min
@apply
def closest_object():
for x in xrange(board_width)
for y in xrange(board_height):
try:
entity = board.get_entity(x, y)
except EntityNotFound:
pass
else:
yield distance(player.pos, entity.pos), entity


Please don't kill me.

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


Re: multiprocessing, what am I doing wrong?

2012-02-24 Thread MRAB

On 24/02/2012 17:00, Eric Frederich wrote:

I can sill get it to freeze and nothing is printed out from the other
except block.
Does it look like I'm doing anything wrong here?


[snip]
I don't normally use multiprocessing, so I forgot about a critical
detail. :-(

When the multiprocessing module starts a process, that process
_imports_ the module which contains the function which is to be run, so
what's happening is that when your script is run, it creates and starts
workers, the multiprocessing module makes a new process for each
worker, each of those processes then imports the script, which creates
and starts workers, etc, leading to an ever-increasing number of
processes.

The solution is to ensure that the script/module distinguishes between
being run as the main script and being imported as a module:

#!/usr/bin/env python

import sys
import Queue
import multiprocessing
import time

def FOO(a, b, c):
print 'foo', a, b, c
return (a + b) * c

class MyWorker(multiprocessing.Process):
def __init__(self, inbox, outbox):
super(MyWorker, self).__init__()
self.inbox = inbox
self.outbox = outbox
print >> sys.stderr, '1' * 80; sys.stderr.flush()
def run(self):
print >> sys.stderr, '2' * 80; sys.stderr.flush()
while True:
try:
args = self.inbox.get_nowait()
except Queue.Empty:
break
self.outbox.put(FOO(*args))

if __name__ == '__main__':
# This file is being run as the main script. This part won't be
# run if the file is imported.
todo = multiprocessing.Queue()

for i in xrange(100):
todo.put((i, i+1, i+2))

print >> sys.stderr, 'a' * 80; sys.stderr.flush()
result_queue = multiprocessing.Queue()

print >> sys.stderr, 'b' * 80; sys.stderr.flush()
w1 = MyWorker(todo, result_queue)
print >> sys.stderr, 'c' * 80; sys.stderr.flush()
w2 = MyWorker(todo, result_queue)

print >> sys.stderr, 'd' * 80; sys.stderr.flush()
w1.start()
print >> sys.stderr, 'e' * 80; sys.stderr.flush()
w2.start()
print >> sys.stderr, 'f' * 80; sys.stderr.flush()

for i in xrange(100):
print result_queue.get()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python LOC, .exe size, and refactoring

2012-02-24 Thread CM
On Feb 22, 12:29 am, Steven D'Aprano  wrote:
> On Tue, 21 Feb 2012 19:51:07 -0800, CM wrote:
> > I have an application that I was hoping to reduce a bit the size of its
> > .exe when "packaged" with py2exe.  I'm removing some Python modules such
> > as Tkinter, etc., but now wonder how much I could size I could reduce by
> > refactoring--and therefore shortening--my code.
>
> Well that will depend on how much you refactor it, but frankly, unless
> your code is truly awful, this will be a micro-optimization. py2exe
> bundles a Python runtime environment plus your files into a single exe
> file. Typically the runtime environment will be somewhere around 11MB for
> wxPython GUI apps (or 4MB with compression turned on, which will slow
> your application down).
>
> http://www.py2exe.org/index.cgi/SingleFileExecutable
>
> The runtime environment for Oracle's Java environment starts at 7MB and
> is typically 15MB, plus whatever libraries your own code produces. For
> dot-net applications, the framework can be up to 60MB.
>
> http://weblogs.java.net/blog/stanleyh/archive/2005/05/deployment_unde...
>
> http://www.hanselman.com/blog/SmallestDotNetOnTheSizeOfTheNETFramewor...
>
> While I think 60MB for a basic calculator app is taking the piss, this is
> 2011 not 1987 and we don't have to support floppy disks any more. 11MB
> for a GUI app is nothing to be worried about. That takes, what, 3 minutes
> to download even on a 512 kbps link?
>
> > Is there a rule of thumb that predicts the relationship between the
> > number of lines of Python code and the resultant size of the application
> > (leaving aside the size of imported modules)?
>
> Yes. To a close approximation, for most applications:
>
> size of bundled application = (
>     size of Python runtime environment + size of libraries used
>     )
>
> Your code is most likely insignificant compared to the others.
>
> > Or is there a way to
> > roughly estimate how much would refactoring the code as much as I
> > reasonably can help?  (For example, in some cases there is some cut and
> > paste coding...I know, it's bad).
>
> Look at it this way: take the .pyc file from your code. How big is it?
> Say, it's 200K. That's a BIG file -- the decimal module in the standard
> library is only 152K. Suppose you could cut it in half -- you would save
> 100K. Even if you could somehow cut it down to 1K, you've saved less than
> 200K. Do you care?
>
> Refactoring your code is double-plus good for maintainability. You should
> do it anyway. But don't do it to shrink an 11MB exe down to 10.8MB.
>
> --
> Steven

Thanks.  All helpful advice.  I'm coming in around 14 MB when you
count some libraries, image files, etc., and I think I can live with
that, considering I was able to reduce it from about 20 MB at one
point by some excluding.

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


Re: namespace question

2012-02-24 Thread David
Your code updated to show the difference between a variable, a class
variable, and an instance variable.
c = [1, 2, 3, 4, 5]
class TEST():
c = [5, 2, 3, 4, 5]  ## class variable (TEST.c)
def __init__(self):
self.c = [1, 2, 3, 4, 5] ## instance variable (a.c)

def add(self, c):
self.c[0] = 15   ## instance variable
TEST.c[0] = -1   ## class variable
c[0] = 100   ## variable/list
return c

a = TEST()
c = a.add(c)
print( c, a.c, TEST.c )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Please verify!!

2012-02-24 Thread Chris Angelico
On Fri, Feb 24, 2012 at 11:20 PM, Steven D'Aprano
 wrote:
> Personally, I prefer tabs for theoretical reasons and spaces for
> practical ones. I think that the world would be better off if we all
> standardised on tabs instead of spaces, but since that's not going to
> happen, I can interoperate better with the mass of broken tools out
> there, and with other people, by using spaces.
>

At work, since we have a fairly small core of developers, we
standardized on tabs - mainly because of a couple of devs who
disagreed on how much indentation looked right (I'm of the opinion
that 1 space is insufficient), and having tab characters in the file
allows us to configure our editors differently. I'm definitely in
favour of using tabs where possible, but if you can't close your
environment, spaces are far safer.

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


Parameter guidelines for the Strong AI Singularity

2012-02-24 Thread Mentifex
=== Purpose ===

A parameter in the AI Mind software serves to guide or limit the
operation of a mind-module. If a module is conducting a search of
AI memory, one parameter may govern how much of memory will be
searched, while other parameters may dictate exactly what is to
be looked for. Since it is easier to change a parameter than an
entire mind-module, the use of parameters makes it possible to
have a mind-module serve a general purpose that changes as the
parameters change.

=== Time-parameter ===

The variable "midway" is a parameter for searching the memory space
of the AI Minds. While the AI Minds remain small and experimental,
midway is usually set to zero so that it does not yet play a role.
When the AI is searching backwards in its memory for a concept,
the search starts at the present time and goes backwards to the
midway point. If midway is set at zero, the AI searches the
entire memory. Oftentimes the search stops as soon as one single
result is found, such as an example of how to say the word "NOT".

As the AI Minds grow larger and larger and claim their rightful
habitat on one SuperComputer after another, the midway parameter
will make it possible to limit searches of memory to a reasonable
portion of the entire life-span of the artificial intelligence (AI).
Since a concept may even have a different meaning or interpretation
in the distant past, limiting the search to the most recent portions
of memory helps to maintain a current, present-day frame of mind.
It also helps achieve the goal of maintaining a high speed of
thought,
because the more memory a search must traverse, the slower the
operation
of the software will become, especially if the AI does not yet have
MasPar or massive parallelism in both hardware and software.

The midway parameter does not need to be calculated as exactly
half of the available memory space. The AI mind engineers and the
AI maintenance crews have the option of setting a very low level
for midway at the first installation of a mission-critical AI
for the purpose of exhaustive system-testing, and a more relaxed
value for a fully functional AI contributing usefully to the
collegial operation of the Global AI Overmind. If the AI Minds
could be considered to have an infancy and an adolescence, the
professional mind-tenders might gradually use the midway
setting to knock out the infancy memories and then later even
the tempestuous, tumultuous memories of the AI adolescence -- as in
the science-fiction book, "The Adolescence of P-1".

The parameter "midway" as a limitation on memory-search could even
be subject to dynamic adjustments. If a massive SuperComputer AI
is trying to recall any detail at all about a given topic or name
or idea, and the initial search has no results for a "midway" set
at a half-wit value, there could be a dynamic mechanism to bypass
the "midway" limitation and to search back over all available memory
in a kind of quest for Total Information Awareness (TIA).

=== Speech-parameter ===

The "aud" variable is sent into the SpeechAct module as a parameter
indicating where to start pronouncing a word stored in auditory
memory.
SpeechAct keeps pronouncing the word until the continuation-flag
turns
to zero. If the "aud" parameter starts out in error at zero,
SpeechAct
substitutes a DeFault of one ("1") for "aud" and says the word ERROR
as an indicator to the AI programmer that something is wrong.

=== Language-parameter ===

In a polyglot AI Mind speaking several human languages, there may
need to be a "glot" or "hl" (human language) parameter that allows
the AI to switch out of one human language and into another for
purposes of thinking and communicating. A strong AI like MindForth
may use one massive set of concepts for all languages, but for each
language the vocabulary is different and the syntax is different.
Therefore the ThInk module is not geared to a specific language,
but must call the EnCog module for thinking in English or the
DeCog module for thinking in German (Deutsch).

Even if an AI program awakens to a DeFault setting of one particular
language, there needs to be a mechanism for changing the parameter of
which language to think in. In "Three Days of the Condor", Robert
Redford and Max von Syndow effortlessly switch from English into
French and back again when their secret conversation has a risk of
being overheard by someone walking past them. In the much more
mundane environment of superintelligent AI entities taking over
the world and sharing the planet in joint stewardship with human
beings, each interface between a human being and the AI OverMind
will need a mechanism for setting and resetting the "glot" parameter.
Typically the human input to the AI will set the parameter. Whatever
language the human being uses to address the AI, should govern the
parameter for the AI to think in the chosen language. Of course,
if an AI is working as an interpreter, there may be one language
as input and another language as output.

=== Inpu

Re: Does turtledemo in Python 3.2 actually work?

2012-02-24 Thread Terry Reedy

On 2/24/2012 7:25 AM, Steven D'Aprano wrote:

Python 3.2 includes turtledemo, a demonstration program for the turtle
module.

When I run it, I can load the turtle scripts, and the GUI application
says "Press the start button", but there is no start button.

Can anyone else confirm this as a bug?

http://docs.python.org/py3k/library/turtle.html#demo-scripts


On Win7, all examples run fine except for one traceback with clock.
http://bugs.python.org/issue14117

--
Terry Jan Reedy

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


Re: sum() requires number, not simply __add__

2012-02-24 Thread Terry Reedy

On 2/24/2012 8:23 AM, Roy Smith wrote:

In article,
  Antoon Pardon  wrote:


Python doesn't try to prevent people from shooting themselves in the foot.


Yes it does! A simple example is None as a keyword to prevent
assignments to it.


Hmmm.  Just playing around with some bizarre things to do with None, and
discovered this:


import sys as None


doesn't give an error, but also doesn't assign the module to the symbol
'None'.  Weird.


In 3.2
>>> import sys as None
SyntaxError: invalid syntax

--
Terry Jan Reedy

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


How to handle calling functions from cli

2012-02-24 Thread Rodrick Brown
I have a bunch of sub routines that run independently to perform various system 
checks on my servers. I wanted to get an opinion on the following code I have 
about 25 independent checks and I'm adding the ability to disable certain 
checks that don't apply to certain hosts.


m = { 'a': 'checkDisks()',
  'b': 'checkMemSize()',
  'c': 'checkBondInterfaces()'
}
 
parser = argparse.ArgumentParser(description='Parse command line args.')
parser.add_argument('-x', action="store", dest="d")
r = parser.parse_args(sys.argv[1:])
 
runlist = [ c for c in m.keys() if c not in r.d ]
for runable in runlist:
eval(m[runable])

I'm using temp variable names for now until I find an approach I like.

Is this a good approach ? It doesn't look too pretty and to be honest feels 
awkward? 

Sent from my iPhone
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespace question

2012-02-24 Thread Steven D'Aprano
On Fri, 24 Feb 2012 10:08:43 -0800, David wrote:

> Your code updated to show the difference between a variable, a class
> variable, and an instance variable.

The preferred terms in Python circles are class and instance 
*attributes*, not variables.

An integer variable is a variable holding an integer.

A string variable is a variable holding a string.

A list variable is a variable holding a list.

Therefore a class variable is a variable holding a class, and an instance 
variable is a variable holding an instance.

Yes, in Python, classes and types are first-class objects (pun not 
intended), and it is quite common to store them in variables:

for cls in (int, float, Decimal, Fraction, myint, myfloat):
do_something_with(cls)


Other languages may choose to use illogical terminology if they choose.



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


Re: How to handle calling functions from cli

2012-02-24 Thread Chris Rebert
On Fri, Feb 24, 2012 at 2:16 PM, Rodrick Brown  wrote:
> I have a bunch of sub routines that run independently to perform various 
> system checks on my servers. I wanted to get an opinion on the following code 
> I have about 25 independent checks and I'm adding the ability to disable 
> certain checks that don't apply to certain hosts.
>
>
> m = { 'a': 'checkDisks()',
>          'b': 'checkMemSize()',
>          'c': 'checkBondInterfaces()'
>    }
>
>    parser = argparse.ArgumentParser(description='Parse command line args.')
>    parser.add_argument('-x', action="store", dest="d")
>    r = parser.parse_args(sys.argv[1:])
>
>    runlist = [ c for c in m.keys() if c not in r.d ]
>    for runable in runlist:
>        eval(m[runable])
>
> I'm using temp variable names for now until I find an approach I like.
>
> Is this a good approach ? It doesn't look too pretty and to be honest feels 
> awkward?

You should make use of the fact that functions are first-class objects
in Python:

m = { 'a': checkDisks,
'b': checkMemSize,
'c': checkBondInterfaces }
# …
for runable in runlist:
m[runable]()


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


Re: How to handle calling functions from cli

2012-02-24 Thread Chris Angelico
On Sat, Feb 25, 2012 at 9:16 AM, Rodrick Brown  wrote:
> m = { 'a': 'checkDisks()',
>          'b': 'checkMemSize()',
>          'c': 'checkBondInterfaces()'
>    }
>
>    runlist = [ c for c in m.keys() if c not in r.d ]
>    for runable in runlist:
>        eval(m[runable])

It's a reasonable technique. Does have the downside that your
functions will be called in an unpredictable order, though. If that's
a problem, replace the dictionary with a tuple of tuples (and then
just take off the .items() in the list comp).

I would be inclined to avoid eval, especially if none of your
functions need parameters. Just hold references to the functions
themselves:

checks = {
 'a': checkDisks,
 'b': checkMemSize,
 'c': checkBondInterfaces, # note that this comma is perfectly
legal - all these lines can be structured identically
}

[func[option]() for option,func in checks.items() if option not in r.d]

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Steven D'Aprano
On Fri, 24 Feb 2012 09:23:08 -0700, Michael Torrie wrote:

> All this reminds me of the original cray supercomputers.  They didn't
> use twos compliment for integers so they had two representations of zero
> (+0 and -0).  Made programming a bit tricky.

While there is only one integer zero, I would like to point out that in 
floating point, there are usually two zeroes, -0.0 and +0.0, and that 
this is by design and a feature, not an accident or a bug.

Well-written floating point functions should keep the sign when they 
underflow, e.g.:

py> 1e-200 * 1e-200
0.0
py> 1e-200 * -1e-200
-0.0

and well-written functions should honour those separate zeroes because 
sometimes it makes a difference.



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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Michael Torrie
On 02/24/2012 09:59 AM, Mark Lawrence wrote:
> The C integer bit doesn't matter since e.g.
>  >>> 
> a=100
>  >>> a
> 100L
> 
> And no, I'm not going to calculate how much memory I'd need to store a 
> string that's this long :)

Sure but that doesn't answer the question posed.  How does Rick plan to
represent an infinite integer? Obviously you've shown that with an
infinite amount of memory we could do it quite easily.  But baring that,
how does Rick suggest we should represent an infinite integer?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Chris Angelico
On Sat, Feb 25, 2012 at 10:16 AM, Michael Torrie  wrote:
> Sure but that doesn't answer the question posed.  How does Rick plan to
> represent an infinite integer? Obviously you've shown that with an
> infinite amount of memory we could do it quite easily.  But baring that,
> how does Rick suggest we should represent an infinite integer?

Barring a suggestion from Rick, I think we should define the number 8
to be greater than all other integers. After all, Rick's very much in
favour of evolution, and what would better depict the evolution of
this glorious language than this notation, showing that the infinity
symbol is now walking erect!

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Mark Lawrence

On 24/02/2012 23:16, Michael Torrie wrote:

On 02/24/2012 09:59 AM, Mark Lawrence wrote:

The C integer bit doesn't matter since e.g.
  >>>
a=100
  >>>  a
100L

And no, I'm not going to calculate how much memory I'd need to store a
string that's this long :)


Sure but that doesn't answer the question posed.  How does Rick plan to
represent an infinite integer? Obviously you've shown that with an
infinite amount of memory we could do it quite easily.  But baring that,
how does Rick suggest we should represent an infinite integer?


I understand that a Python integer can run to infinity.  Quite how the 
illustrious rr manages to test for the length of a string that's already 
used all of the memory on his system has baffled me, but I'm sure that 
all the people who frequent this list with their Phds, MScs or whatever 
will soon correct me.


--
Cheers.

Mark Lawrence.

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


Re: namespace question

2012-02-24 Thread Mark Lawrence

On 24/02/2012 22:25, Steven D'Aprano wrote:

On Fri, 24 Feb 2012 10:08:43 -0800, David wrote:


Your code updated to show the difference between a variable, a class
variable, and an instance variable.


The preferred terms in Python circles are class and instance
*attributes*, not variables.

An integer variable is a variable holding an integer.

A string variable is a variable holding a string.

A list variable is a variable holding a list.

Therefore a class variable is a variable holding a class, and an instance
variable is a variable holding an instance.

Yes, in Python, classes and types are first-class objects (pun not
intended), and it is quite common to store them in variables:

for cls in (int, float, Decimal, Fraction, myint, myfloat):
 do_something_with(cls)


Other languages may choose to use illogical terminology if they choose.



Surely you mean names, not variables? :)

--
Cheers.

Mark Lawrence.

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread MRAB

On 24/02/2012 23:16, Michael Torrie wrote:

On 02/24/2012 09:59 AM, Mark Lawrence wrote:

 The C integer bit doesn't matter since e.g.
  >>>
 
a=100
  >>>  a
 
100L

 And no, I'm not going to calculate how much memory I'd need to store a
 string that's this long :)


Sure but that doesn't answer the question posed.  How does Rick plan to
represent an infinite integer? Obviously you've shown that with an
infinite amount of memory we could do it quite easily.  But baring that,
how does Rick suggest we should represent an infinite integer?


We already have arbitrarily long ints, so there could be a special
infinite int singleton (actually, 2 of them, one positive, the other
negative).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please verify!!

2012-02-24 Thread Mark Lawrence

On 24/02/2012 20:41, Chris Angelico wrote:

On Fri, Feb 24, 2012 at 11:20 PM, Steven D'Aprano
  wrote:

Personally, I prefer tabs for theoretical reasons and spaces for
practical ones. I think that the world would be better off if we all
standardised on tabs instead of spaces, but since that's not going to
happen, I can interoperate better with the mass of broken tools out
there, and with other people, by using spaces.



At work, since we have a fairly small core of developers, we
standardized on tabs - mainly because of a couple of devs who
disagreed on how much indentation looked right (I'm of the opinion
that 1 space is insufficient), and having tab characters in the file
allows us to configure our editors differently. I'm definitely in
favour of using tabs where possible, but if you can't close your
environment, spaces are far safer.

ChrisA


Oo, thou sinner, fancy violating PEP 8 and standardising on tabs.

OTOH if that's your standard and you stick to it fine.

What I can't stand is the "I've always done it this way an I ain't movin 
jus cos sum standard says so" attitude.


Yes I have seen this in real life and the person responsible should be 
sacked.


--
Cheers.

Mark Lawrence.

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Fayaz Yusuf Khan
On Saturday 25 Feb 2012 12:37:58 AM MRAB wrote:
> We already have arbitrarily long ints, so there could be a special
> infinite int singleton (actually, 2 of them, one positive, the other
> negative).
Seconded. Although would a wish request to bugs.python.org saying "Allow 
storage of the integer infinity" make any sense to the developers? :P
-- 
Fayaz Yusuf Khan
Cloud developer and architect
Dexetra SS, Bangalore, India
fayaz.yusuf.khan_AT_gmail_DOT_com
fayaz_AT_dexetra_DOT_com
+91-9746-830-823


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


Re: Please verify!!

2012-02-24 Thread Chris Angelico
On Sat, Feb 25, 2012 at 11:49 AM, Mark Lawrence  wrote:
> Oo, thou sinner, fancy violating PEP 8 and standardising on tabs.

PEP 8 applies only to Python code, our standard is across all our
languages :) But yes, I'm a horrible sinner and I like tabs. They
separate the display (do you want tabs to show as four-space indent,
two-centimeter indent, or fifty-pixel indent?) from the structure
(this line is indented two levels). Spaces merge those.

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Ian Kelly
On Fri, Feb 24, 2012 at 10:32 AM, Devin Jeanpierre
 wrote:
> On Fri, Feb 24, 2012 at 9:25 AM, Neil Cerutti  wrote:
>> The only time I've naively pined for such a thing is when
>> misapplying C idioms for finding a minimum value.
>>
>> Python provides an excellent min implementation to use instead.
>
> min can be a little inconvenient. As soon as anything complicated has
> to be done during the min expression, you need to switch to using
> something else for sanity's sake. In that vein, I do actually
> sometimes use float('inf') (for numbers), or a custom max/min object.
>
> 
>
> Silly and completely nonserious addendum:
>
> Forgive me, I have spoken in error! min is the one true way, for you
> can still do it with a little wrangling, as follows:
>
>    @operator.itemgetter(1)
>    @min
>    @apply
>    def closest_object():
>        for x in xrange(board_width)
>            for y in xrange(board_height):
>                try:
>                    entity = board.get_entity(x, y)
>                except EntityNotFound:
>                    pass
>                else:
>                    yield distance(player.pos, entity.pos), entity

Cute, but what's so terrible about:

def all_entities():
for x in xrange(board_width):
for y in xrange(board_height):
try:
yield board.get_entity(x, y)
except EntityNotFound:
pass

closest_object = min(all_entities,
key=lambda e: distance(player.pos, e.pos))

Especially given that all_entities should be reusable in other contexts.

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


Re: namespace question

2012-02-24 Thread Steven D'Aprano
On Sat, 25 Feb 2012 00:39:39 +, Mark Lawrence wrote:

> On 24/02/2012 22:25, Steven D'Aprano wrote:
>> On Fri, 24 Feb 2012 10:08:43 -0800, David wrote:
>>
>>> Your code updated to show the difference between a variable, a class
>>> variable, and an instance variable.
>>
>> The preferred terms in Python circles are class and instance
>> *attributes*, not variables.
>>
>> An integer variable is a variable holding an integer.
>>
>> A string variable is a variable holding a string.
>>
>> A list variable is a variable holding a list.
>>
>> Therefore a class variable is a variable holding a class, and an
>> instance variable is a variable holding an instance.
>>
>> Yes, in Python, classes and types are first-class objects (pun not
>> intended), and it is quite common to store them in variables:
>>
>> for cls in (int, float, Decimal, Fraction, myint, myfloat):
>>  do_something_with(cls)
>>
>>
>> Other languages may choose to use illogical terminology if they choose.
>>
>>
> Surely you mean names, not variables? :)

Well yes, I do, but the idea of classes being first class objects is 
radical enough to some people without also introducing them to the idea 
that there are no variables at all!

I'm very aware that name binding is not quite the same as variables in 
some other languages, but the difference is subtle and doesn't mean that 
the term "variable" is owned by Pascal- or C-like languages. It just 
means that, like most computer science terms, "variable" has subtle 
differences from implementation to implementation.



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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Steven D'Aprano
On Sat, 25 Feb 2012 06:52:09 +0530, Fayaz Yusuf Khan wrote:

> On Saturday 25 Feb 2012 12:37:58 AM MRAB wrote:
>> We already have arbitrarily long ints, so there could be a special
>> infinite int singleton (actually, 2 of them, one positive, the other
>> negative).
> Seconded. Although would a wish request to bugs.python.org saying "Allow
> storage of the integer infinity" make any sense to the developers? :P

If you explained it as a pair of special int values, INF and -INF, rather 
than the storage of an infinite-sized integer, it would make perfect 
sense.

But it would also be rejected, and rightly so, as unnecessary complexity 
for the int type. There are already Decimal and float infinities, just 
use one of them. Or make your own, it's not difficult. Publish it on 
ActiveState, and if people flock to use it, then you will have a good 
argument that this is useful and should be part of the Python built-ins.



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


Re: Please verify!!

2012-02-24 Thread Dave Angel

On 02/24/2012 08:25 PM, Chris Angelico wrote:

On Sat, Feb 25, 2012 at 11:49 AM, Mark Lawrence  wrote:

Oo, thou sinner, fancy violating PEP 8 and standardising on tabs.

PEP 8 applies only to Python code, our standard is across all our
languages :) But yes, I'm a horrible sinner and I like tabs. They
separate the display (do you want tabs to show as four-space indent,
two-centimeter indent, or fifty-pixel indent?) from the structure
(this line is indented two levels). Spaces merge those.

ChrisA


If tabs were ever implemented consistently and reasonably in both an 
editor and a matching language, then I'd consider leaving tabs in the 
file.  But to me, they're just a crude way to compress the file, and the 
space they save is no longer worth the pain they cause  (I came to this 
conclusion 30 years ago, and have re-evaluated it dozens of times as new 
editors and new languages changed the rules.  At that time, I had one of 
my developers write an editor (shipped with our MSDOS system, instead of 
Edlin) that implemented it.)


Some time when i have a lot more time, I'll state one of (many possible) 
the ways that tabs could be made acceptable in a limited environment.  
Almost 40 years ago, I wrote an editor and assembler whose file format 
used a separation character between fields.  I used A0 because our 
screens at the time ignored the high bit, so a file was sort-of readable 
right out of the box.  And the way that the developer jumped between 
fields was the semi-colon key, of course, since that's the position of 
the skip key in the keypunch we were replacing.


However, I don't intend to foist my opinions on others, just to state 
them as opinions.  At the office, we use special comment fields at 
end-of-file to tell Emacs how to deal with a mixture of tabs and 
spaces.  Code written by a dozen people over a dozen years, and nobody 
wanted to enforce a conversion to something common.





--

DaveA

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


SSL on 3.2.2

2012-02-24 Thread Jason Friedman
Hello, attempting to build from source on Ubuntu 11.10.

Before running ./configure I had set this in Modules/Setup.dist:

SSL=/usr/lib/ssl
_ssl _ssl.c \
-DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
-L$(SSL)/lib -lssl -lcrypto

$ ll /usr/lib/ssl
total 4
lrwxrwxrwx 1 root root   14 2012-02-20 17:58 certs -> /etc/ssl/certs
drwxr-xr-x 2 root root 4096 2012-02-20 18:32 misc
lrwxrwxrwx 1 root root   20 2012-02-08 18:04 openssl.cnf -> /etc/ssl/openssl.cnf
lrwxrwxrwx 1 root root   16 2012-02-20 17:58 private -> /etc/ssl/private

$ /opt/python/bin/python3
Python 3.2.2 (default, Feb 24 2012, 20:07:04)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
Traceback (most recent call last):
  File "", line 1, in 
  File "/opt/python/lib/python3.2/ssl.py", line 60, in 
import _ssl # if we can't import it, let the error propagate
ImportError: No module named _ssl
-- 
http://mail.python.org/mailman/listinfo/python-list