Re: if the else short form

2010-10-01 Thread Arnaud Delobelle
Paul Rubin  writes:

> Steven D'Aprano  writes:
>> Incorrect. bools *are* ints in Python, beyond any doubt.
>
> Python 2.6.2 (r262:71600, Jun  4 2010, 18:28:58) 
> >>> type(3)==type(True)
> False

Of course, but it's the wrong thing to ask if you want know if bools are
ints.  To find out via their types, you should ask:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
>>> issubclass(type(True), type(3))
True

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


Re: Crummy BS Script

2010-10-01 Thread Steven D'Aprano
On Fri, 01 Oct 2010 21:05:09 -0700, flebber wrote:

> On Oct 2, 9:27 am, MRAB  wrote:
>> On 01/10/2010 23:29, Burton Samograd wrote:>
>> flebber  writes:
>>
>> >> But where is this saving the imported file and under what name?
>>
>> > Looks like samples.csv:
>>
>> >> f = open('samples.csv', 'w')
>>
>> It'll be in the current working directory, which is given by:
>>
>>      os.getcwd()
> 
> So how do I call the output to direct it to file? I can't see which part
> to get.


I don't understand your question. What do you mean "call the output" -- 
you normally don't call the output, you call a function or program to get 
output. The output is already directed to a file, as you were shown -- it 
is written to the file samples.csv in the current directory.

Perhaps if you explain your question more carefully, we might be able to 
help a little more.




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


Re: if the else short form

2010-10-01 Thread Steven D'Aprano
On Fri, 01 Oct 2010 22:19:14 -0700, Paul Rubin wrote:

> Steven D'Aprano  writes:
>> Incorrect. bools *are* ints in Python, beyond any doubt.
> 
> Python 2.6.2 (r262:71600, Jun  4 2010, 18:28:58)
> >>> type(3)==type(True)
> False

So? Instances of a subclasses are still instances of the superclass.

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Steven D'Aprano
On Fri, 01 Oct 2010 11:56:24 +0200, Pascal J. Bourguignon wrote:

> Actually, it's hard to find a language that has no compiler generating
> faster code than C...

Perl. Python. Ruby. Applescript. Hypertalk. Tcl. RPL. Frink. Inform 7. 
ActionScript. Dylan. Emerald. And hundreds more serious languages, to say 
nothing of dozens of esoteric languages like Chef, Oook, Whitespace, 
Shakespeare, and Intercal.

It's actually hard to think of languages with implementations that 
*consistently* beat or match the gcc C compiler: C++ and Forth come to 
mind immediately. Lua and Javascript sometimes manages to beat C. Scala, 
Java, Pascal, Fortran, Ada often come close, where "close" means within a 
factor of 5 times slower.

See http://shootout.alioth.debian.org/ for more benchmarks.

Of course, all benchmarks are flawed, if not broken. The very concept of 
"which language is faster" is nonsense. High-level languages aren't 
executed directly, and if they were, the parse/interpret/execute cycle is 
*so slow* that they would all lose (Think of the speed of scripting 
languages like bash.) That's why virtually all languages are compiled, to 
byte-code that is executed in a virtual machine, or machine code that is 
executed directly in a real machine. So the real questions are:

* which virtual machines are faster when performing a certain task?
* which compilers generate the best (virtual or real) machine code for a 
given task?

and most interestingly:

* given the competing demands of ease of development and maintenance, 
versus the demands of speed of execution, versus correctness of code, 
which language is best for my specific needs?

Which is why we're not all writing in COBOL.


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


Re: Problem saving uploaded files in Python3

2010-10-01 Thread Chris Rebert
On Fri, Oct 1, 2010 at 11:13 PM,   wrote:
> Hello, i control the problem of the data what is uploaded by the POST
> method, in the web if the file is a text theres no problem
> but the trouble comes when it's an enconded file as a Picture or other what
> the when the system insert the data into the file
> well it doesn 't encoded in the write way i will put all the code, from the
> area whats take the environ['wsgi.input'] to the area
> thats save the file:
>
> tmpData = str(rawData)[1:].strip("' '")#Here the data from the
> environ['wsgi.input'], first i convert the byte into a string delete the
> first field that represent the b and after i strip the single quotes
> dat = tmpData.split('\\r')#Then i split all the data in the '\\r'
> s = open('/home/hidura/test.png', 'w')#I open the test.png file.

> Where is the mistake?

If you're on Windows, you'll need to open the file in binary mode:
s = open('/home/hidura/test.png', 'wb')

If you're not on Windows, then something else is the problem.

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


Problem saving uploaded files in Python3

2010-10-01 Thread hidura
Hello, i control the problem of the data what is uploaded by the POST  
method, in the web if the file is a text theres no problem
but the trouble comes when it's an enconded file as a Picture or other what  
the when the system insert the data into the file
well it doesn 't encoded in the write way i will put all the code, from the  
area whats take the environ['wsgi.input'] to the area

thats save the file:

tmpData = str(rawData)[1:].strip("' '")#Here the data from the  
environ['wsgi.input'], first i convert the byte into a string delete the  
first field that represent the b and after i strip the single quotes

dat = tmpData.split('\\r')#Then i split all the data in the '\\r'
s = open('/home/hidura/test.png', 'w')#I open the test.png file.
for cont in range(5,150):#Now beging in the 5th position to the 150th  
position

s.write(dat[cont])#Insert the piece of the data in the file.
s.close()#Then closed.

Where is the mistake?

Thankyou in advance.

--
Diego Hidalgo D.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-01 Thread Paul Rubin
Steven D'Aprano  writes:
> Incorrect. bools *are* ints in Python, beyond any doubt.

Python 2.6.2 (r262:71600, Jun  4 2010, 18:28:58) 
>>> type(3)==type(True)
False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sequence multiplied by -1

2010-10-01 Thread Steven D'Aprano
On Fri, 01 Oct 2010 14:56:52 +0200, Antoon Pardon wrote:

> Think about the following possibility.
> 
> Someone provides you with a library of functions that act on sequences.
> They rely on the fact that '+' concatenates.
> 
> Someone else provides you with a library of functions that act on
> numbers. They rely on the fact that '+' provides addition.
> 
> Now however you write your sequence like numbers or number like
> sequences one of those libraries will be useless for it.

And? So what? Sequences aren't numbers. Numbers aren't sequences. You 
can't expect every library to correctly work with every data type 
regardless of the polymorphism of operators.

If you have no idea what x is, you can't possibly expect to know what 
function(x) does, *for any function*. 

(Actually, there may be one or two exceptions, like id(x). But fewer than 
you think -- even str(x) is not guaranteed to work for arbitrary types.)

If you don't know whether x is a number or a sequence, you can't know 
what x.sort() will do, or math.sqrt(x), or x+x. Why single out x+x as 
more disturbing than the other examples?


>> -- which would it do with only one
>> symbol?
> 
> But why limit ourselves to one symbol for different kind of operations,
> to begin with?

Because the more symbols you have, the higher the learning curve to 
become proficient in the language, and the more like line-noise the code 
becomes. If you want APL or Perl, you know where to find them -- they're 
perfectly reasonable languages, but they have made design choices that 
are not Python's design choices.

We use operators, because for certain common operations it is more 
convenient and natural to use infix notation than function notation. And 
polymorphism is useful, because it reduces the size of namespaces and 
therefore the burden on the programmer. Putting these two factors 
together, instead of:

concat_lists
concat_tuples
concat_strings
concat_bytes
add_floats
add_ints
add_rationals
add_decimals

plus mixed-operand versions of at least some of them, we have a single 
symbol, +, for all of these. Arguing about whether it should be a single 
operator + or two operators + & is a comparatively trivial matter. I 
believe that the similarity between concatenation and addition is close 
enough that it is appropriate to use one symbol for both, and likewise 
between repetition and multiplication. I'm glad that Guido apparently 
agrees with me.



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


Re: if the else short form

2010-10-01 Thread Steven D'Aprano
On Fri, 01 Oct 2010 11:23:25 -0700, John Nagle wrote:

>> Why so ? The doc clearly states that booleans are integers with True ==
>> 1 and False == 0, so there's nothing implicit here.
> 
>  Python "bool" values are NOT integers.  They can be coerced to
> integers for historical reasons.  

Incorrect. bools *are* ints in Python, beyond any doubt.

>>> isinstance(True, int)
True

True and False are instances of int. That's all you need to know.


> But "str(True)" is "True".

I assume that you're not comparing the literal strings "str(True)" and 
"True" (which would make your claim incorrect). Nevertheless, leaving out 
the quotes is also incorrect:

>>> str(True) is True
False

The only way to get your claim to work is to mix'n'match quotation marks, 
leaving one pair in and dropping the other:

>>> str(True) is "True"
True

But so what? What do you think that proves? All it shows is an 
implementation detail to do with caching of certain small strings:

>>> str(5) is "5"
True



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


Re: sequence multiplied by -1

2010-10-01 Thread Steven D'Aprano
On Fri, 01 Oct 2010 10:24:11 -0700, Carl Banks wrote:

> On Sep 26, 8:20 am, Grant Edwards  wrote:
[..]
>> So now I suppose "+" for string concatenation is a bad thing.
> 
> Yes.  It's not the end of the world, but a separate concatenation
> operator would have been better.  Then there's no temptation to special
> case a failure of sum(list_of_strings), because it's not a sum any more.

I'll give you the case of sum, and I'll admit that I've often thought 
that concatenation should be written & rather than +, but I wonder how 
much difference it would really make?

If we wrote s & t for concatenation instead of s + t, would people now be 
bitching that it uses the same operator as bitwise-and?

If so, then we haven't gained anything, and the only thing that would 
satisfy such people would be for every function name and operator to be 
unique -- something which is impossible in practice, even if it were 
desirable.

And if not, then ask yourself, why is it acceptable for bitwise-and and 
concatenation to share the same operator, but not for addition and 
concatenation? Is it just because addition is more common than bitwise-
and?

> As for repeat, I can't personally think of a time I ever repeated
> anything but a single item, and that only rarely.  It's not useful
> enough to deserve its own syntax, and the language wouldn't have
> suffered one bit if it had been a method of sequences.

I disagree. I think that the ability to write:

line = "-"*50

pays for everything. But I accept that this is a matter of opinion, and 
others may disagree. When you create your own language, feel free to do 
something different :)



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


Re: Crummy BS Script

2010-10-01 Thread flebber
On Oct 2, 9:27 am, MRAB  wrote:
> On 01/10/2010 23:29, Burton Samograd wrote:> flebber  
> writes:
>
> >> But where is this saving the imported file and under what name?
>
> > Looks like samples.csv:
>
> >> f = open('samples.csv', 'w')
>
> It'll be in the current working directory, which is given by:
>
>      os.getcwd()

So how do I call the output to direct it to file? I can't see which
part to get.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Paul Rubin
Raffael Cavallaro 
writes:
>> prints appears to be the 2000th Fibonacci number rather than the 1000th.
> I think you're mistaken. fib(0) = 0, fib(1) = 1, fib(2) = 1, fib(3) =
> 2 ... fib(11)= 89 ...

Whoops, you're right, I messed up my program while refactoring it.   Sorry.

> you like we can do it iteratively instead, which, as in haskel, takes
> no perceptible time:

I couldn't tell whether the earlier version with the expt 5 was a
direct solution of the recurrence, or what.

>  2. the result of fib(1000) is going to overflow c integer types

Yes, it's a real shame that most cpu's these days don't have a hardware
trap for int overflow.  That would allow much safer programming for the
large amount of code where the programmer expects to never overflow
but can be caught by surprise.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Raffael Cavallaro

On 2010-10-01 22:44:11 -0400, Paul Rubin said:


I have no idea what that fancy algorithm is doing, but the number it
prints appears to be the 2000th Fibonacci number rather than the 1000th.


I think you're mistaken. fib(0) = 0, fib(1) = 1, fib(2) = 1, fib(3) = 2 
... fib(11)= 89 ...
fib(1000) = 
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875


If 

you like we can do it iteratively instead, which, as in haskel, takes 
no perceptible time:


CL-USER 133 > (defun fib (x)
   (if (< x 1) 0
 (loop
  repeat x
  for previous = 0 then result
  and result = 1 then (+ result previous)
  finally (return result
FIB

CL-USER 134 > (compile 'fib)
FIB
NIL
NIL

CL-USER 135 > (time (fib 1000))
Timing the evaluation of (FIB 1000)

User time=0.000
System time  =0.000
Elapsed time =0.000
Allocation   = 60088 bytes
0 Page faults
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875

The 


relevant points are:

1. common lisp implementations produce fast code
2. the result of fib(1000) is going to overflow c integer types

warmest regards,

Ralph



--
Raffael Cavallaro

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


Regular Expression Skipping Match

2010-10-01 Thread AON LAZIO
Hi python pals,
   I need this help, say I have
   h = "Hello \n World"
   How would I create a regular expression that match only "Hello World"?
(ignore \n in the middle)
   Thanks in advance

-- 
Aonlazio
'Peace is always the way.' NW
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
"BartC"  writes:

> "Pascal J. Bourguignon"  wrote in message
> news:877hi1iq2o@kuiper.lan.informatimago.com...
>> "BartC"  writes:
>
>>> (defun fib (n)
>>>   (if (< n 2)
>>>   n
>>>   (+ n (fib (- n 1)) (fib (- n 2)) )
>>> ))
>>>
>>> But it gave the wrong results and it took ages to figure out why. Even
>
>>> I thought you were saying that Lisp (and dynamic typing in general)
>>> was better for pointing out errors? The above error in C would have
>>> been picked up more easily I think (due to less parentheses clutter,
>>> and more obvious separators between terms).
>>
>> There are more parentheses in C (you must take into account {} and []
>> too, and <> in C++), and the additionnal separators in C are clutter.
>
> I mentioned 'C' because it's one of the cross-posted languages; I normally
> use my own language. Nevertheless, both of these (as well as Python and
> probably many others) require no more than 4 parentheses in the line in
> question; the Lisp line above uses 12
So what?

> (including the 2 I moved to the next
> line for clarity).

Actually for clarity, properly formated lisp code would be like:

(defun fib (n)
  (if (< n 2)
  n
  (+ n
 (fib (- n 1))
 (fib (- n 2)


> And needing an extra "+" when you want to add 3 things instead of 2, sort of
> makes it obvious that you do have 3 things instead of 2... In fact the error
> would never have got so far. Sometimes redundancy in syntax is useful.

On the other hand, baroque syntaxes requires more wetware cycles so
you're left with less to think about important matters, such as knowing
what fib is...


-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Paul Rubin
Raffael Cavallaro  writes:
> CL-USER 119 > (defun fib (n)
>(/ (loop for k from 1 to n by 2
> sum (/ (* (expt 5 (/ (1- k) 2)) (fact n))
>(fact k) (fact (- n k
>   (expt 2 (1- n
> CL-USER 122 > (time (fib 1000))
> Timing the evaluation of (FIB 1000)
> 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875

I have no idea what that fancy algorithm is doing, but the number it
prints appears to be the 2000th Fibonacci number rather than the 1000th.
And it took 0.76 seconds even compiled.  This Haskell code took no
perceptible time even in the ghci interpreter:

main = print (fib 0 1 !! 2000)
  where
fib a b = a:(a+b):fib b (a+b)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Raffael Cavallaro

On 2010-10-01 16:47:02 -0400, BartC said:

I had a quick look at Lisp to see if your claims had any basis. I tried 
this program:


(defun fib (n)
   (if (< n 2)
   n
   (+ n (fib (- n 1)) (fib (- n 2)) )
))

But it gave the wrong results and it took ages to figure out why. Even 
after downloading a working version for comparison, it's was difficult 
to spot the extraneous 'n' (I think I was concentrating on getting the 
round brackets all in the right places).


I saw it immediately, but I'm familiar with lisp and you are not - 
those two parentheses (what you call "round brackets") on a line by 
themselves are a dead giveaway.




I thought you were saying that Lisp (and dynamic typing in general) was 
better for pointing out errors? The above error in C would have been 
picked up more easily I think (due to less parentheses clutter, and 
more obvious separators between terms).


As for speed, executing fib(38) took about 60 seconds on my machine 
(gnu clisp with no switches set). (Compared with 3.5 seconds, for my 
own interpreted, dynamic language, and 0.6 seconds for C.)


Compiled lisp is fast, but you need to actually compile it:

CL-USER 96 > (defun fib (n)
(declare (optimize speed (debug 0)))
(if (< n 2)
  n
  (+ (fib (- n 1)) (fib (- n 2)
FIB

CL-USER 97 > (compile 'fib)
FIB
NIL
NIL

CL-USER 98 > (time (fib 38))
Timing the evaluation of (FIB 38)

User time=0.888
System time  =0.002
Elapsed time =0.877
Allocation   = 142568 bytes
0 Page faults
39088169

which is in the same range as your .6 seconds for your equivalent c program.

What happens when you want fib(1000) or fib(100)? Then the naive 
recursive version isn't very useful (it's just too slow), and the 
result is going to overflow c integer types.


in lisp:

CL-USER 118 > (defun fact (n) (if (zerop n) 1 (* n (fact (1- n)
FACT

CL-USER 119 > (defun fib (n)
   (/ (loop for k from 1 to n by 2
sum (/ (* (expt 5 (/ (1- k) 2)) (fact n))
   (fact k) (fact (- n k
  (expt 2 (1- n
FIB

CL-USER 120 > (compile 'fact)
FACT
NIL
NIL

CL-USER 121 > (compile 'fib)
FIB
NIL
NIL

CL-USER 122 > (time (fib 1000))
Timing the evaluation of (FIB 1000)

User time=0.760
System time  =0.007
Elapsed time =0.748
Allocation   = 474522008 bytes
147 Page faults
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875

warmest 


regards,

Ralph

--
Raffael Cavallaro

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread BartC

"Pascal J. Bourguignon"  wrote in message
news:877hi1iq2o@kuiper.lan.informatimago.com...

"BartC"  writes:



(defun fib (n)
  (if (< n 2)
  n
  (+ n (fib (- n 1)) (fib (- n 2)) )
))

But it gave the wrong results and it took ages to figure out why. Even



I thought you were saying that Lisp (and dynamic typing in general)
was better for pointing out errors? The above error in C would have
been picked up more easily I think (due to less parentheses clutter,
and more obvious separators between terms).


There are more parentheses in C (you must take into account {} and []
too, and <> in C++), and the additionnal separators in C are clutter.


I mentioned 'C' because it's one of the cross-posted languages; I normally
use my own language. Nevertheless, both of these (as well as Python and
probably many others) require no more than 4 parentheses in the line in
question; the Lisp line above uses 12 (including the 2 I moved to the next
line for clarity).

And needing an extra "+" when you want to add 3 things instead of 2, sort of
makes it obvious that you do have 3 things instead of 2... In fact the error
would never have got so far. Sometimes redundancy in syntax is useful.


As for speed, executing fib(38) took about 60 seconds on my machine
(gnu clisp with no switches set).


Yes, you choosed the ONLY CL implementation having an interpreter by
default, and which when compiling, compiles to a virtual machine.  This
happens also to be my favorite CL implementation, which tells you how
much I care about those silly time benchmarks.


Well, 60 seconds is pretty slow even for an interpreter; even plain CPython
took only 30 seconds.


If you want to try a CL implementation generating faster code, try SBCL.


OK.


--
Bartc 


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


Re: Crummy BS Script

2010-10-01 Thread MRAB

On 01/10/2010 23:29, Burton Samograd wrote:

flebber  writes:


But where is this saving the imported file and under what name?


Looks like samples.csv:


f = open('samples.csv', 'w')



It'll be in the current working directory, which is given by:

os.getcwd()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Crummy BS Script

2010-10-01 Thread Burton Samograd
flebber  writes:

> But where is this saving the imported file and under what name?

Looks like samples.csv:

> f = open('samples.csv', 'w')

--
Burton Samograd

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


Crummy BS Script

2010-10-01 Thread flebber
I have a simple question regarding the Beuatiful soup crummy script.
The last line is f.write('%s, %s, %s, %s, %s \n' % (i, t[0], t[1],
t[2], t[3])), But where is this saving the imported file and under
what name?

#!/usr/bin/env python
# ogm-sampples.py
# Author: Matt Mayes
# March 11, 2008
"""
-- This requires the Beautiful Soup mod: 
http://www.crummy.com/software/BeautifulSoup/
--
Steps:
1. Identify all 's that are preceded with '' (which denotes a header here)
2. Pull that font text, and store as dictionary key
3. Extract all links and link text from the list, generate a link
title and type (pdf/html/404) store as tuples in
appropriate dict key (note that some list items contain more than 1
link, this handles it) If it's a 404, it will
not be added to the list.
4. Identify if it's linking to an HTML page or PDF
5. If it's a local pdf referenced by a root value ("/file.pdf"), it
strips the slash. Modify to suit your needs.
6. Generate a CSV file of results
"""

import urllib2, re
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen("http://www.givegoodweb.com/examples/ogm-
samples.html")
soup = BeautifulSoup(page)
fontStart = re.compile(r'?')
fontEnd = re.compile(r'')
titleSearch = re.compile(r'title=')
getTitle = re.compile(r'(.*)',re.DOTALL|re.MULTILINE)
emailSearch = re.compile(r'mailto')

def removeNL(x):
"""cleans a string of new lines and spaces"""
s = x.split('\n')
s = [x.strip() for x in s]
x = " ".join(s)
return x.lstrip()

ul_tags = {}

for ul in soup.html.body.findAll('ul'):
links = []
x = ul.findPrevious('font', color="#3C378C").renderContents()
if '\n' in x:
x = removeNL(x)
for li in ul.findAll('li'):
line = []
for a in li.findAll('a'):
c = removeNL(str(a.contents[0]))
c = fontStart.sub('', c)
c = fontEnd.sub('', c)
href = str(a.get('href'))
if href[-3:].lower() == 'pdf':
type = 'pdf'
title = "PDF sample"
elif emailSearch.search(href):
title = 'email'
else:
type = 'html'
try:
f = urllib2.urlopen(href)
# reading in 2000 characters should to 
it
t = getTitle.search(f.read(2000))
if t :
title = t.group(1)
title = removeNL(title)
else : title = "open link"
except urllib2.HTTPError, e:
title = 404
f.close()
if title != 404:
line.append((c, href.lstrip('/'), type, title))
links.append(line)
ul_tags[x] = links

page.close()

f = open('samples.csv', 'w')

for i in ul_tags.iterkeys():
for x in ul_tags[i]:
for t in x:
f.write('%s, %s, %s, %s, %s \n' % (i, t[0], t[1], t[2], 
t[3]))

f.close()

I got it from http://pastie.textmate.org/164503
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
"BartC"  writes:

> "Pascal J. Bourguignon"  wrote in message
> news:87sk0qkzhz@kuiper.lan.informatimago.com...
>
>> Nothing extraordinary here.  Common Lisp is more efficient than C.
>> http://www.lrde.epita.fr/~didier/research/verna.06.ecoop.pdf
>> http://portal.acm.org/citation.cfm?id=1144168
>>
>> Actually, it's hard to find a language that has no compiler generating
>> faster code than C...
>
> I had a quick look at Lisp to see if your claims had any basis. I
> tried this program:
>
> (defun fib (n)
>   (if (< n 2)
>   n
>   (+ n (fib (- n 1)) (fib (- n 2)) )
> ))
>
> But it gave the wrong results and it took ages to figure out why. Even
> after downloading a working version for comparison, it's was difficult
> to spot the extraneous 'n' (I think I was concentrating on getting the
> round brackets all in the right places).
>
> I thought you were saying that Lisp (and dynamic typing in general)
> was better for pointing out errors? The above error in C would have
> been picked up more easily I think (due to less parentheses clutter,
> and more obvious separators between terms).

There are more parentheses in C (you must take into account {} and []
too, and <> in C++), and the additionnal separators in C are clutter.


> As for speed, executing fib(38) took about 60 seconds on my machine
> (gnu clisp with no switches set). 

Yes, you choosed the ONLY CL implementation having an interpreter by
default, and which when compiling, compiles to a virtual machine.  This
happens also to be my favorite CL implementation, which tells you how
much I care about those silly time benchmarks.

If you want to try a CL implementation generating faster code, try SBCL.


> (Compared with 3.5 seconds, for my
> own interpreted, dynamic language, and 0.6 seconds for C.)

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: difference between %s and %d

2010-10-01 Thread Arnaud Delobelle
Ethan Furman  writes:

> If I'm printing the number 735, or any other positive or negative
> integer, is there any difference between %7s and %7d?
>
> ~Ethan~

To link with another thread:

>>> "%s" % True
'True'
>>> "%d" % True
'1'

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread BartC
"Pascal J. Bourguignon"  wrote in message 
news:87sk0qkzhz@kuiper.lan.informatimago.com...



Nothing extraordinary here.  Common Lisp is more efficient than C.
http://www.lrde.epita.fr/~didier/research/verna.06.ecoop.pdf
http://portal.acm.org/citation.cfm?id=1144168

Actually, it's hard to find a language that has no compiler generating
faster code than C...


I had a quick look at Lisp to see if your claims had any basis. I tried this 
program:


(defun fib (n)
  (if (< n 2)
  n
  (+ n (fib (- n 1)) (fib (- n 2)) )
))

But it gave the wrong results and it took ages to figure out why. Even after 
downloading a working version for comparison, it's was difficult to spot the 
extraneous 'n' (I think I was concentrating on getting the round brackets 
all in the right places).


I thought you were saying that Lisp (and dynamic typing in general) was 
better for pointing out errors? The above error in C would have been picked 
up more easily I think (due to less parentheses clutter, and more obvious 
separators between terms).


As for speed, executing fib(38) took about 60 seconds on my machine (gnu 
clisp with no switches set). (Compared with 3.5 seconds, for my own 
interpreted, dynamic language, and 0.6 seconds for C.)


--
bartc 


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


ElementTree handling nested tag

2010-10-01 Thread tekion
All,
I have the following xml tag:


  httpRequest
  HTTP://cmd.wma.ibm.com:80/
  GET
  200
   


I am interested in:
   httpRequest
  HTTP://cmd.wma.ibm.com:80/
  GET
  200
as well as the upper layer tag. How do I get at the nest tag listed
above?  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: difference between %s and %d

2010-10-01 Thread Ethan Furman

Ethan Furman wrote:
If I'm printing the number 735, or any other positive or negative 
integer, is there any difference between %7s and %7d?


Grant Edwards wrote:
> Let's ask Python:
>
>   --> [n for n in range(-,,123) if ("%7d" % n)
>   != ("%7s" % n)]
>   []
>
>   --> [n for n in range(-9,9) if ("%7d" % n) != ("%7s" % n)]
>   []
>
> Apparently not.

MRAB wrote:
> "%s" uses str(). In Python 2.7:
>
>  --> class MyInt(int):
> ... def __init__(self, value):
> ... int.__init__(self, value)
> ... def __str__(self):
> ... return "MyInt(%d)" % self
> ...
>  --> MyInt(735)
> 735
>  --> "%7d" % MyInt(735)
> '735'
>  --> "%7s" % MyInt(735)
> 'MyInt(735)'


Thanks!  Both enlightening answers.

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


Re: difference between %s and %d

2010-10-01 Thread MRAB

On 01/10/2010 20:15, Ethan Furman wrote:

If I'm printing the number 735, or any other positive or negative
integer, is there any difference between %7s and %7d?


"%s" uses str(). In Python 2.7:

>>> class MyInt(int):
... def __init__(self, value):
... int.__init__(self, value)
... def __str__(self):
... return "MyInt(%d)" % self
...
>>> MyInt(735)
735
>>> "%7d" % MyInt(735)
'735'
>>> "%7s" % MyInt(735)
'MyInt(735)'
--
http://mail.python.org/mailman/listinfo/python-list



Re: difference between %s and %d

2010-10-01 Thread Grant Edwards
On 2010-10-01, Ethan Furman  wrote:

> If I'm printing the number 735, or any other positive or negative
> integer, is there any difference between %7s and %7d?

Let's ask Python:

  >>> [n for n in range(-,,123) if ("%7d" % n) != ("%7s" % n)]
  []

  >>> [n for n in range(-9,9) if ("%7d" % n) != ("%7s" % n)]
  []
  
Apparently not.

-- 
Grant Edwards   grant.b.edwardsYow! What I want to find
  at   out is -- do parrots know
  gmail.commuch about Astro-Turf?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __file__ is sometimes absolute, sometimes relative

2010-10-01 Thread Antoine Pitrou
On Fri, 1 Oct 2010 21:00:02 +0200
Sébastien Barthélemy  wrote:
> Hi,
> 
> Arnaud, Christian, thank you for your help.
> 
> I'll use abspath, it's shorter.
> 
> Any idea why it's sometimes absolute, sometimes not?

AFAICT, that's because sys.path contains some absolute paths and some
relative ones.

Regards

Antoine.


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


difference between %s and %d

2010-10-01 Thread Ethan Furman
If I'm printing the number 735, or any other positive or negative 
integer, is there any difference between %7s and %7d?


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


Re: if the else short form

2010-10-01 Thread Ethan Furman

John Nagle wrote:

On 10/1/2010 12:42 AM, bruno.desthuilli...@gmail.com wrote:

On 30 sep, 19:22, Andreas Waldenburger
wrote:

>>>

But it does violate the "explicit is better than implicit" tenet, don't
you think?


Why so ? The doc clearly states that booleans are integers with True
== 1 and False == 0, so there's nothing implicit here.


Python "bool" values are NOT integers.  They can be coerced to
integers for historical reasons.  But "str(True)" is "True".


Okay, so they are *subtypes* of integers, to be precise... but what, 
exactly, does the string representation of an object have to do with its 
type?


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


IMAP support

2010-10-01 Thread pakalk
Hello,

Can anyone help me find GOOD IMAP library for python? Imaplib is..
ekhm... nevermind... Is there any good library?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Keith Thompson
p...@informatimago.com (Pascal J. Bourguignon) writes:
> Seebs  writes:
>> On 2010-10-01, Pascal J. Bourguignon  wrote:
>>> Seebs  writes:
 On 2010-10-01, Pascal J. Bourguignon  wrote:
> compiler passes wrong type  wrong resultfails at run-time
> (the programmer (with exception
> spends hoursexplaining this is
> finding the the wrong type)
> problem)
>>>
 I have no clue what exact scenario you're talking about here.  I've never
 seen a bug that could plausibly be described as "compiler passes wrong
 type" which wasn't picked up quickly by running with more warnings enabled.
>>
>>> This is the scenario discussed in this thread, a long is passed to
>>> maximum without a compiler warning.
>>
>> The compiler didn't pass the wrong type, the user did.
>
> And the compiler passed it on without saying anything.

Because the user didn't use the option (-Wconversion) that would have
caused the compiler to warn about it.

[...]

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __file__ is sometimes absolute, sometimes relative

2010-10-01 Thread Sébastien Barthélemy
Hi,

Arnaud, Christian, thank you for your help.

I'll use abspath, it's shorter.

Any idea why it's sometimes absolute, sometimes not?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Keith Thompson
RG  writes:
> In article ,
>  Seebs  wrote:
>
>> On 2010-09-30, RG  wrote:
>> > That gives (what I would consider to be) false positives, e.g.:
>> 
>> > [...@mighty:~]$ cat foo.c
>> 
>> > void foo(long x) {}
>> 
>> > int main() { foo(1); }
>> > [...@mighty:~]$ gcc -Wconversion foo.c
>> > foo.c: In function ???main???:
>> > foo.c:4: warning: passing argument 1 of ???foo??? with different width due 
>> > to prototype
>> 
>> But it's *not* a false positive.  The compiler is not claiming that the
>> conversion couldn't be done -- it's just telling you that there is a
>> change of type going on.
>
> Again, you can't have it both ways.  Either a warning is a "compiler 
> error" according to the claim at issue (see below) or it is not.  If it 
> is, then this is a false positive.  If it is not, then my previous 
> example refutes the claim.
[...]

In this case, the conversion (from int to long) cannot fail (barring
undefined behavior elsewhere in the program), because long is
guaranteed to be able to hold any value within the range of int.

It would be reasonable, at least as an option, to warn only about
conversions that can fail, or only about conversions that can lose
information, perhaps distinguishing between implicit conversions
and explicit conversions (casts).

Even the warning about foo(1) is not entirely unreasonable; some
programmers might prefer to write foo(1L) rather than foo(1),
to make it clear that the argument being passed is of type long
rather than int.

I don't know whether gcc provides this level of control over which
conversions it warns about, but again, that's a gcc issue, not a
C issue.

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Keith Thompson
TheFlyingDutchman  writes:
> On Sep 30, 10:37 pm, RG  wrote:
>> In article <87tyl63cag@mail.geddis.org>,
>>  Don Geddis  wrote:
>> > Keith Thompson  wrote on Thu, 30 Sep 2010:
>> > > RG  writes:
>> > >> You're missing a lot of context.  I'm not trying to criticize C, just to
>> > >> refute a false claim that was made about it.
>> > > Can you cite the article that made this false claim, and exactly what
>> > > the false claim was?
>>
>> >http://groups.google.com/group/comp.lang.lisp/msg/431925448da59481
>>
>> >         Message-ID:
>> >         <0497e39d-6bd1-429d-a86f-f4c89babe...@u31g2000pru.googlegroups.com>
>> >         From: TheFlyingDutchman 
>> >         Newsgroups: comp.lang.lisp
>>
>> >         [...]
>> >         in C I can have a function maximum(int a, int b) that will always
>> >         work. Never blow up, and never give an invalid answer. If someone
>> >         tries to call it incorrectly it is a compile error.
>> >         [...]

That was slightly overstated.  In fact, you can have such a
function that will always work when called correctly, *unless*
something else has caused the program's behavior to be undefined,
in which case all bets are off.

[...]

> Thanks from me as well, Don. I was worried that people would start to
> believe that the original statement was what you said it was:
>
> "I'm not even saying it's a flaw in the language.  All I'm saying is
> that
> the original claim -- that any error in a C program will be caught by
> the compiler -- is false, and more specifically, that it can be
> demonstrated to be false without appeal to unknown run-time input."

Yes, that would have been an absurd claim if anyone had actually
made it.

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Keith Thompson
Seebs  writes:
> On 2010-10-01, TheFlyingDutchman  wrote:
>>> > ? ? ? ? in C I can have a function maximum(int a, int b) that will always
>>> > ? ? ? ? work. Never blow up, and never give an invalid answer. If someone
>>> > ? ? ? ? tries to call it incorrectly it is a compile error.
>
>>> I would agree that the third sentence is arguably wrong, simply
>>> because there's no such thing (outside #error) of a mandate to stop
>>> compiling. ?However, my understanding was that the dispute was over
>>> the second sentence, and that's certainly correct.
>
>> Why do you consider the term "compile error" a "mandate to stop
>> compiling"?
>
> Because that's what people normally mean -- compilation failed.

At least for C, I'd say it refers to a syntax error or constraint
violation, i.e., something that requires a diagnostic.

[...]

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread RG
In article ,
 Seebs  wrote:

> On 2010-10-01, RG  wrote:
> > Again, you can't have it both ways.  Either a warning is a "compiler 
> > error" according to the claim at issue (see below) or it is not.  If it 
> > is, then this is a false positive.
> 
> No, it isn't.  It's a correctly identified type mismatch.
> 
> You keep moving the goal posts from the actual standard of a false positive
> (the compiler warns that something is of the wrong type when it's not of
> the wrong type) to a made-up standard (the compiler warns that something is
> of the wrong type when it is indeed of the wrong type, but could be safely
> converted to the right type).
> 
> It doesn't matter whether, in a given case, you *could* safely perform
> the conversion.  If you don't perform the conversion, and the compiler points
> this out, that's not a false positive.
> 
> >> Those goal posts are sorta red shifted at this point.
> 
> > At this point I would like to quote a wise man who once said:
> 
> >> May I suggest that, if you don't want to use words and terminology
> >> precisely, perhaps computer programming is not for you?
> 
> > Red shifted?
> 
> Moving away fast enough that their color has visibly changed.
> 
> > The truth of this claim hinges on the definitions of "work", "never blow 
> > up", "invalid", "call incorrectly" and "compile error."  Define these 
> > however you like, the result will be that the claim is either false or 
> > vacuous.
> 
> Not really.  If you use the most obvious and natural meanings *for a
> statically typed language*, it is obvious that it is true.
> 
> And indeed, significantly so.  In the real world, programs written in
> scripting languages with runtime typing are fairly likely to throw occasional
> exceptions because something is of the wrong type.  In a statically typed
> language, the of-the-wrong-type is something which can, by definition, be
> caught at compile time.
> 
> The fundamental thing you seem to be getting stuck on is that you're assuming
> that if a conversion could be made, that it should be and it should be
> automatic and silent.  That, however, is at odds with discussion of a
> statically typed language.  There's a reason we have the option of converting
> things from one type to another.

No, this is not what I'm getting stuck on.  I understand the technical 
theory behind statically typed languages.  What I'm getting "stuck" on 
is this:

> In a statically typed language, the of-the-wrong-type is something which
> can, by definition, be caught at compile time.

Any time something is true "by definition" that is an indication that 
it's not a particularly useful fact.  The whole concept of "type" is a 
red herring.  It's like this: there are some properties of programs that 
can be determined statically, and others that can't.  Some of the 
properties that can't be determined statically matter in practice.  But 
all of the properties that can be determined statically can also be 
determined dynamically.  The *only* advantage that static analysis has 
is that *sometimes* it can determine *some* properties of a program 
faster or with less effort than a dynamic approach would.

What I take issue with is the implication made by advocates of static 
analysis that static analysis is somehow *inherently* superior to 
dynamic analysis, that static analysis can provide some sort of 
"guarantee" of reliability that actually has some sort of practical 
meaning in the real world.  It doesn't.  The net effect of static 
analysis in the real world is to make programmers complacent about 
properties of programs that can only be determined at run time, to make 
them think that compiling without errors means something, and that if a 
program compiles without errors then there is no need for run-time 
checking of any sort.  *You* may not believe these things, but the vast 
majority of programmers who use statically typed languages do believe 
these things, even if only tacitly.  The result is a world where 
software by and large is a horrific mess of stack overflows, null 
pointer exceptions, core dumps, and security holes.

I'm not saying that static analysis is not useful.  It is.  What I'm 
saying is that static analysis is nowhere near as useful as its 
advocates like to imply that it is.  And it's better to forego static 
analysis and *know* that you're flying without a net at run-time than to 
use it and think that you're safe when you're really not.

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Ian Collins

On 10/ 2/10 05:18 AM, Pascal J. Bourguignon wrote:

Seebs  writes:


On 2010-10-01, Pascal J. Bourguignon  wrote:

 static  dynamic

compiler detects wrong type fail at compile fails at run-time
 (with exception
 explaining this is
 the wrong type)


Unless, of course, the "wrong type" happens to be compatible enough to
pass.  In which case, it's unclear whether it is the "wrong type" or not.


compiler passes wrong type  wrong resultfails at run-time
 (the programmer (with exception
 spends hoursexplaining this is
 finding the the wrong type)
 problem)


I have no clue what exact scenario you're talking about here.  I've never
seen a bug that could plausibly be described as "compiler passes wrong
type" which wasn't picked up quickly by running with more warnings enabled.


This is the scenario discussed in this thread, a long is passed to
maximum without a compiler warning.


Which will cause the test for the bit of code doing the call to fail. 
So it fails at run-time with a failed test, just as it would in a 
dynamic language.


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


Re: if the else short form

2010-10-01 Thread John Nagle

On 10/1/2010 12:42 AM, bruno.desthuilli...@gmail.com wrote:

On 30 sep, 19:22, Andreas Waldenburger
wrote:

On Thu, 30 Sep 2010 03:42:29 -0700 (PDT)

"bruno.desthuilli...@gmail.com"  wrote:

On 29 sep, 19:20, Seebs  wrote:

On 2010-09-29, Tracubik  wrote:

button = gtk.Button(("False,", "True,")[fill==True])



Oh, what a nasty idiom.



Well, it's not very different from dict-based dispatch , which is the
core of OO polymorphic dispatch in quite a few dynamic OOPLs.



Anyway, it's a common Python idiom and one that's not specially hard
to grasp so I don't see any legibility problem here.


But it does violate the "explicit is better than implicit" tenet, don't
you think?


Why so ? The doc clearly states that booleans are integers with True
== 1 and False == 0, so there's nothing implicit here.


Python "bool" values are NOT integers.  They can be coerced to
integers for historical reasons.  But "str(True)" is "True".

The above could be better written as

button = gtk.Button(str(fill))

John Nagle

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
Seebs  writes:

> On 2010-10-01, Pascal J. Bourguignon  wrote:
>> Seebs  writes:
>>> On 2010-10-01, Pascal J. Bourguignon  wrote:
 compiler passes wrong type  wrong resultfails at run-time
 (the programmer (with exception
 spends hoursexplaining this is
 finding the the wrong type)
 problem)
>>
>>> I have no clue what exact scenario you're talking about here.  I've never
>>> seen a bug that could plausibly be described as "compiler passes wrong
>>> type" which wasn't picked up quickly by running with more warnings enabled.
>
>> This is the scenario discussed in this thread, a long is passed to
>> maximum without a compiler warning.
>
> The compiler didn't pass the wrong type, the user did.

And the compiler passed it on without saying anything.

>>> And on the other end of things, it is not always obvious or straightforward
>>> to figure out *why* the dynamic language has ended up with something of the
>>> wrong type, or what's wrong with that type.
>
>> It is on the contrary rather obvious or easily discoverable, looking at
>> the backtrace, and inspecting the data structures referenced from it.
>
> This is a fascinating assertion, but it is slightly marred by not actually
> being generally true.  It's often the case that it's pretty obvious, but
> sometimes it's not so obvious -- it can take quite a bit of doing to figure
> out how or where some hunk of a data structure got set up wrong.  It's very
> easy to find the call where a nil was passed to something expecting some kind
> of integer; it's sometimes not so easy to find the completely unrelated hunk
> of code which modified the data structure half an hour earlier.

When debugging C program, you are perfectly right.  
But I don't observe the same when debugging lisp programs. 


-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sequence multiplied by -1

2010-10-01 Thread Carl Banks
On Sep 26, 8:20 am, Grant Edwards  wrote:
> On 2010-09-26, Paul Rubin  wrote:
>
> > Steven D'Aprano  writes:
> >> There's nothing obscure or unintuitive about "spam"*3 = "spamspamspam",
> > Why would it not be ["spam","spam","spam"] or even "ssspppaaammm"?
>
> Because
>
> 3 * "spam" == "spam" + "spam" + "spam"
>
> Just like
>
> 3 * 6 = 6 + 6 + 6
>
> So now I suppose "+" for string concatenation is a bad thing.

Yes.  It's not the end of the world, but a separate concatenation
operator would have been better.  Then there's no temptation to
special case a failure of sum(list_of_strings), because it's not a sum
any more.

As for repeat, I can't personally think of a time I ever repeated
anything but a single item, and that only rarely.  It's not useful
enough to deserve its own syntax, and the language wouldn't have
suffered one bit if it had been a method of sequences.


Carl Banks


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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Terry Reedy

On 10/1/2010 2:28 AM, TheFlyingDutchman wrote:



 in C I can have a function maximum(int a, int b) that will always
 work. Never blow up, and never give an invalid answer. If someone
 tries to call it incorrectly it is a compile error.


I would agree that the third sentence is arguably wrong, simply
because there's no such thing (outside #error) of a mandate to stop
compiling.  However, my understanding was that the dispute was over
the second sentence, and that's certainly correct.


Why do you consider the term "compile error" a "mandate to stop
compiling"? What do you say to refer to the situation when you have a
statement in your program that the compiler finds is an error? And is
it really material whether the compiler flagged an error and stopped,
or flagged an error and looked for additional errors???


For the purpose of the argument, I do not think it matters whether the 
compiler looks for additional errors before it stops compiling. More to 
to point is whether or not it eventually produces an object file that 
can be linked into an executable file. 'Compile error' (as opposed to 
'compile warning') should mean that it does not.


--
Terry Jan Reedy

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Seebs
On 2010-10-01, Pascal J. Bourguignon  wrote:
> Seebs  writes:
>> On 2010-10-01, Pascal J. Bourguignon  wrote:
>>> compiler passes wrong type  wrong resultfails at run-time
>>> (the programmer (with exception
>>> spends hoursexplaining this is
>>> finding the the wrong type)
>>> problem)
>
>> I have no clue what exact scenario you're talking about here.  I've never
>> seen a bug that could plausibly be described as "compiler passes wrong
>> type" which wasn't picked up quickly by running with more warnings enabled.

> This is the scenario discussed in this thread, a long is passed to
> maximum without a compiler warning.

The compiler didn't pass the wrong type, the user did.

>> And on the other end of things, it is not always obvious or straightforward
>> to figure out *why* the dynamic language has ended up with something of the
>> wrong type, or what's wrong with that type.

> It is on the contrary rather obvious or easily discoverable, looking at
> the backtrace, and inspecting the data structures referenced from it.

This is a fascinating assertion, but it is slightly marred by not actually
being generally true.  It's often the case that it's pretty obvious, but
sometimes it's not so obvious -- it can take quite a bit of doing to figure
out how or where some hunk of a data structure got set up wrong.  It's very
easy to find the call where a nil was passed to something expecting some kind
of integer; it's sometimes not so easy to find the completely unrelated hunk
of code which modified the data structure half an hour earlier.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sequence multiplied by -1

2010-10-01 Thread Emile van Sebille

On 10/1/2010 9:44 AM Emile van Sebille said...

On 10/1/2010 5:56 AM Antoon Pardon said...


Someone provides you with a library of functions that act on sequences.
They rely on the fact that '+' concatenates.

Someone else provides you with a library of functions that act on
numbers. They rely on the fact that '+' provides addition.



But you can do that now -- you just can't have a class that provides
_both_ behaviors.


Well, you can, but that's why you don't...


>>> class Guess:
...   def __init__(self,val):
... self.val = val
...   def __add__(self,other):
... try:
...   other / 1
...   return self.val + other
... except:
...   return "%s%s" % (self.val,other)
...
>>> c = Guess(7)
>>> c+4
11
>>> c+"4"
'74'

Emile





 >>> class Addem:
... def __init__(self,val):
... self.val = val
... def __add__(self,other):
... return self.val + other
...
 >>> class Concatem:
... def __init__(self,val):
... self.val = val
... def __add__(self,other):
... return "%s%s" % (self.val,other)
...
 >>>
 >>> a = Addem(7)
 >>> a+4
11
 >>>
 >>> b = Concatem(7)
 >>> b+4
'74'


Emile




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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread John Nagle

On 10/1/2010 7:17 AM, Rui Maciel wrote:

Pascal J. Bourguignon wrote:


Nothing extraordinary here.  Common Lisp is more efficient than C.
http://www.lrde.epita.fr/~didier/research/verna.06.ecoop.pdf
http://portal.acm.org/citation.cfm?id=1144168


I don't know if you are intentionally trying to be deceitful or if you honestly 
didn't spent much
time thinking about this issue.  To be brief I will only point out the 
following topics:


a) no language is inherently more or less efficient than any other language.  
The efficiency
aspect is only related to how those languages are implemented (i.e., the 
investments made in
optimizing the compilers/interpreters)
b) Just because someone invested enough effort to optimize a specific 
implementation of language X
to run, under a specific scenario, a benchmark faster than some other 
implementation of language Y
it doesn't mean that language X's implementation outperforms or even matches 
every implementation
of language Y under every conceivable scenario.


If the implementation has an omniscient compiler, yes.  If not,
some languages have serious speed penalties.

Python has some inherent performance problems stemming from
its "gratuitous hidden dynamism".  That is, there are
bits of dynamism which are very unlikely, but not visible at
compile time, and thus very difficult to optimize out.
For example, it's possible to add an attribute to an object
from outside the object's class.  It's thus very difficult to
detect at compile time which classes could use static "slots",
and which could not.  Python allows replacing a function at
run time, even while another thread is executing in it.
(Even PHP disallows that.)  This breaks a wide range of
optimizations.  And then, of course, there's the "global
interpreter lock" problem.

Dynamism is not the problem.  It's hidden dynamism, which
forces compiling for the worst case all the time, that's
the problem.

Most of these problems come from CPython,
which is a naive interpreter.  The feature set of Python
is well matched to a naive interpreter.

The organizational situation is a lot like the one with
Pascal and Wirth. There'a a very straightforward way to write
a recursive-descent Pascal compiler that compiles to a stack
notation.  Wirth wrote one of those, and insisted that the
language should be very close to what a compiler of that form
can do.  This eventually killed Pascal.

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


Re: sequence multiplied by -1

2010-10-01 Thread Emile van Sebille

On 10/1/2010 5:56 AM Antoon Pardon said...


Someone provides you with a library of functions that act on sequences.
They rely on the fact that '+' concatenates.

Someone else provides you with a library of functions that act on
numbers. They rely on the fact that '+' provides addition.



But you can do that now -- you just can't have a class that provides 
_both_ behaviors.


>>> class Addem:
...   def __init__(self,val):
... self.val = val
...   def __add__(self,other):
... return self.val + other
...
>>> class Concatem:
...   def __init__(self,val):
... self.val = val
...   def __add__(self,other):
... return "%s%s" % (self.val,other)
...
>>>
>>> a = Addem(7)
>>> a+4
11
>>>
>>> b = Concatem(7)
>>> b+4
'74'


Emile

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


Re: __file__ is sometimes absolute, sometimes relative

2010-10-01 Thread Arnaud Delobelle
Sébastien Barthélemy  writes:

> Hello,

Hi!

> I use a data file that lies on disk in the same directory that the
> module which makes use of it.
>
> The data file is checked in the repository and gets installed by
> the distutils ``package_data`` directive, so it is in place both
> during development and after and install.
>
> In my program, I need to find the absolute path to this data file.
>
> I could think of 3 ways to do this:
> 1. using the __path__ property in the module
> 2. using __file__ property in the module
> 3. using __file__ and os.getcwd() in the module

I have used the following, but I don't know either if it is a good way:

os.path.dirname(os.path.realpath(__file__))

-- 
Arnaud

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


Re: discussion

2010-10-01 Thread Brian Curtin
On Thu, Sep 30, 2010 at 21:12, Geo_subodh  wrote:

> please send me the simple python code that uses input number greater
> than3 digits(>3 digits) and  checks whether the number is palindrome
> or not.


$ cat homework.py
raise NotImplementedError
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
Seebs  writes:

> On 2010-10-01, Pascal J. Bourguignon  wrote:
>> static  dynamic
>>
>> compiler detects wrong type fail at compile fails at run-time
>> (with exception
>> explaining this is
>> the wrong type)
>
> Unless, of course, the "wrong type" happens to be compatible enough to
> pass.  In which case, it's unclear whether it is the "wrong type" or not.
>
>> compiler passes wrong type  wrong resultfails at run-time
>> (the programmer (with exception
>> spends hoursexplaining this is
>> finding the the wrong type)
>> problem)
>
> I have no clue what exact scenario you're talking about here.  I've never
> seen a bug that could plausibly be described as "compiler passes wrong
> type" which wasn't picked up quickly by running with more warnings enabled.

This is the scenario discussed in this thread, a long is passed to
maximum without a compiler warning.


> And on the other end of things, it is not always obvious or straightforward
> to figure out *why* the dynamic language has ended up with something of the
> wrong type, or what's wrong with that type.

It is on the contrary rather obvious or easily discoverable, looking at
the backtrace, and inspecting the data structures referenced from it.


-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
"BartC"  writes:

> "Pascal J. Bourguignon"  wrote in message
> news:87zkuyjawh@kuiper.lan.informatimago.com...
>> "BartC"  writes:
>>
>>> "Pascal J. Bourguignon"  wrote in message
>
 When Intel will realize that 99% of its users are running VM
>>>
>>> Which one?
>>
>> Any implementation of a controlled environment is a virtual machine.
>> Sometimes it is explicitely defined, such as in clisp, parot or jvm, but
>> more often it is implicit, such as in sbcl, or worse, developed in an
>> ad-hoc way in applications (eg. written in C++).
>
> But if you had to implement a VM directly in hardware, which one (of
> the several varieties) would you choose?
>
> And having chosen one, how would that impact the performance of a
> language with an incompatible VM?

Indeed.  C running on LispMachine, wasn't so fast.  All this bit
twiddling and pointer computing...  But if that could be construed as a
reason why to use dynamic languages (they run faster!) than C, it'd be
all for the best!


Otherwise we need to further go down the road of VM (cf. the hardware
virtualization stream), down to the microcode.  Again, it's because of
the cheapness of microprocessors founders that we forgot for a long time
the notion of microcode, which was found more often on big irons.
Nowadays the biggest microprocessors are back on the track of microcode;
this should be open, and virtual machines should be more routinely
implemented in microcode.


> Perhaps processors executing native code as it is now, aren't such a
> bad idea.

Perhaps if they had a more controlled execution model it would be a
better idea.  Remember that processors are like they are because C (and
unix) is like it is!


-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread rustom
On Oct 1, 7:17 pm, Rui Maciel  wrote:

> a) no language is inherently more or less efficient than any other language.  
> The efficiency
> aspect is only related to how those languages are implemented (i.e., the 
> investments made in
> optimizing the compilers/interpreters)

I used to believe the same. But if you see Richard Bird's paper:

More haste less speed 
http://www.comlab.ox.ac.uk/people/richard.bird/online/BirdJonesDeMoor1997More.pdf

maybe you would rethink this position?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Seebs
On 2010-10-01, Steven D'Aprano  wrote:
> Now can we (by which I mean *you*) stop cross-posting C talk to multiple 
> newsgroups that don't have anything to do with C?

Fair enough.  The original thread does seem to have been crossposted in
an innovative way.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python becoming orphaned over ssh

2010-10-01 Thread Jean-Paul Calderone
On Oct 1, 10:35 am, Antoine Pitrou  wrote:
> On Thu, 30 Sep 2010 07:01:09 -0700 (PDT)
>
> Jean-Paul Calderone  wrote:
>
> > But signal dispositions are inherited by child processes.  So you run
> > ping from your short Python program, and it inherits SIGPIPE being
> > ignored.  And it's written in C, not Python, so when it writes to the
> > pipe, there's no exception.  So ping never gets any indication that it
> > should exit.
>
> But doesn't write() fail with EPIPE in that situation?
> That would mean `ping` ignores any error return from write().
>

Quite so.  A quick look at ping.c from iputils confirms this - there
are many write() and fprintf() calls with no error handling.

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Seebs
On 2010-10-01, RG  wrote:
> Again, you can't have it both ways.  Either a warning is a "compiler 
> error" according to the claim at issue (see below) or it is not.  If it 
> is, then this is a false positive.

No, it isn't.  It's a correctly identified type mismatch.

You keep moving the goal posts from the actual standard of a false positive
(the compiler warns that something is of the wrong type when it's not of
the wrong type) to a made-up standard (the compiler warns that something is
of the wrong type when it is indeed of the wrong type, but could be safely
converted to the right type).

It doesn't matter whether, in a given case, you *could* safely perform
the conversion.  If you don't perform the conversion, and the compiler points
this out, that's not a false positive.

>> Those goal posts are sorta red shifted at this point.

> At this point I would like to quote a wise man who once said:

>> May I suggest that, if you don't want to use words and terminology
>> precisely, perhaps computer programming is not for you?

> Red shifted?

Moving away fast enough that their color has visibly changed.

> The truth of this claim hinges on the definitions of "work", "never blow 
> up", "invalid", "call incorrectly" and "compile error."  Define these 
> however you like, the result will be that the claim is either false or 
> vacuous.

Not really.  If you use the most obvious and natural meanings *for a
statically typed language*, it is obvious that it is true.

And indeed, significantly so.  In the real world, programs written in
scripting languages with runtime typing are fairly likely to throw occasional
exceptions because something is of the wrong type.  In a statically typed
language, the of-the-wrong-type is something which can, by definition, be
caught at compile time.

The fundamental thing you seem to be getting stuck on is that you're assuming
that if a conversion could be made, that it should be and it should be
automatic and silent.  That, however, is at odds with discussion of a
statically typed language.  There's a reason we have the option of converting
things from one type to another.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Seebs
On 2010-10-01, Pascal J. Bourguignon  wrote:
> static  dynamic
>
> compiler detects wrong type fail at compile fails at run-time
> (with exception
> explaining this is
> the wrong type)

Unless, of course, the "wrong type" happens to be compatible enough to
pass.  In which case, it's unclear whether it is the "wrong type" or not.

> compiler passes wrong type  wrong resultfails at run-time
> (the programmer (with exception
> spends hoursexplaining this is
> finding the the wrong type)
> problem)

I have no clue what exact scenario you're talking about here.  I've never
seen a bug that could plausibly be described as "compiler passes wrong
type" which wasn't picked up quickly by running with more warnings enabled.

And on the other end of things, it is not always obvious or straightforward
to figure out *why* the dynamic language has ended up with something of the
wrong type, or what's wrong with that type.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Seebs
On 2010-10-01, Pascal J. Bourguignon  wrote:
> Seebs  writes:
>> The obvious simple maximum() in C will not raise an exception nor return
>> something which isn't an int in any program which is not on its face
>> invalid in the call.  This is by definite contrast with several of the
>> interpreted languages, 

> This has nothing to do with the fact that these languages have
> implementations using the interpreter pattern instead of a compiler.

True, but it's a good enough statistical correlation to serve in many
cases.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Seebs
On 2010-10-01, TheFlyingDutchman  wrote:
>> > ? ? ? ? in C I can have a function maximum(int a, int b) that will always
>> > ? ? ? ? work. Never blow up, and never give an invalid answer. If someone
>> > ? ? ? ? tries to call it incorrectly it is a compile error.

>> I would agree that the third sentence is arguably wrong, simply
>> because there's no such thing (outside #error) of a mandate to stop
>> compiling. ?However, my understanding was that the dispute was over
>> the second sentence, and that's certainly correct.

> Why do you consider the term "compile error" a "mandate to stop
> compiling"?

Because that's what people normally mean -- compilation failed.

> What do you say to refer to the situation when you have a
> statement in your program that the compiler finds is an error? And is
> it really material whether the compiler flagged an error and stopped,
> or flagged an error and looked for additional errors???

It might be, because someone might argue that if the compiler will generate
code for a bad construct, it hasn't really produced a "compiler error", just
a warning.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespace hacking question

2010-10-01 Thread bruno.desthuilli...@gmail.com
On 1 oct, 14:12, Fuzzyman  wrote:
> On Sep 30, 6:07 pm, kj  wrote:
>
>
>
> > This is a recurrent situation: I want to initialize a whole bunch
> > of local variables in a uniform way, but after initialization, I
> > need to do different things with the various variables.
>
> > What I end up doing is using a dict:
>
> > d = dict()
> > for v in ('spam', 'ham', 'eggs'):
> >     d[v] = init(v)
>
> > foo(d['spam'])
> > bar(d['ham'])
> > baz(d['eggs'])
>
> > This is fine, but I'd like to get rid of the tedium of typing all
> > those extra d['...']s.
>
> > I.e., what I would *like* to do is something closer to this:
>
> > d = locals()
> > for v in ('spam', 'ham', 'eggs'):
> >     d[v] = init(v)
>
> > foo(spam)
> > bar(ham)
> > baz(eggs)
>
> > ...but this results in errors like "NameError: global name 'spam' is
> > not defined".
>
> > But the problem is deeper than the fact that the error above would
> > suggest, because even this fails:
>
> > spam = ham = eggs = None
> > d = locals()
> > for v in ('spam', 'ham', 'eggs'):
> >     d[v] = init(v)
>
> > foo(spam) # calls foo(None)
> > bar(ham)  # calls bar(None)
> > baz(eggs) # calls baz(None)
>
> > In other words, setting the value of locals()['x'] does not set
> > the value of the local variable x.
>
> > I also tried a hack using eval:
>
> > for v in ('spam', 'ham', 'eggs'):
> >     eval "%s = init('%s')" % (v, v)
>
> > but the "=" sign in the eval string resulted in a "SyntaxError:
> > invalid syntax".
>
> > Is there any way to use a loop to set a whole bunch of local
> > variables (and later refer to these variables by their individual
> > names)?
>
> One way:
>
> import sys
> module = sys.modules[__name__]
>
> for entry in ('spam', 'eggs', 'ham'):
>     setattr(module, entry, 'some value')
>

Only works on globals - which you can already set using globals()
IIRC.

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


Re: Determine sockets in use by python

2010-10-01 Thread Antoine Pitrou
On Thu, 30 Sep 2010 12:32:45 -0700
Jim Mellander  wrote:
> Thanks, I realized that even if I found out relevant info on the
> socket, I would probably need to use ctypes to  provide a low level
> interface to select, as the socket wouldn't be a python socket object,
> unless there is some way to promote a c socket to a python socket
> object.
> 
> Appreciate the info, folks.

You can also try to monkeypatch the socket module (before importing the
3rd-party library) and replace the socket.socket() constructor with a
custom one which tracks all created sockets in a structure of your
choice.

Not very pretty of course.


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


Re: Python becoming orphaned over ssh

2010-10-01 Thread Antoine Pitrou
On Thu, 30 Sep 2010 07:01:09 -0700 (PDT)
Jean-Paul Calderone  wrote:
> 
> But signal dispositions are inherited by child processes.  So you run
> ping from your short Python program, and it inherits SIGPIPE being
> ignored.  And it's written in C, not Python, so when it writes to the
> pipe, there's no exception.  So ping never gets any indication that it
> should exit.

But doesn't write() fail with EPIPE in that situation?
That would mean `ping` ignores any error return from write().

Regards

Antoine.


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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Rui Maciel
Pascal J. Bourguignon wrote:

> Nothing extraordinary here.  Common Lisp is more efficient than C.
> http://www.lrde.epita.fr/~didier/research/verna.06.ecoop.pdf
> http://portal.acm.org/citation.cfm?id=1144168

I don't know if you are intentionally trying to be deceitful or if you honestly 
didn't spent much 
time thinking about this issue.  To be brief I will only point out the 
following topics:


a) no language is inherently more or less efficient than any other language.  
The efficiency 
aspect is only related to how those languages are implemented (i.e., the 
investments made in 
optimizing the compilers/interpreters)
b) Just because someone invested enough effort to optimize a specific 
implementation of language X 
to run, under a specific scenario, a benchmark faster than some other 
implementation of language Y 
it doesn't mean that language X's implementation outperforms or even matches 
every implementation 
of language Y under every conceivable scenario.


Regarding the links that you've provided, again I don't know if you intended to 
be dishonest or if 
you simply didn't read them.  The first link, entitled "Beating C in Scientific 
Computing 
Applications On the Behavior and Performance of LISP, Part 1", basically 
compares a highly 
optimized implementation of lisp (quite literally the "current state of the art 
in COMMON -LISP 
compiler technology") with a standard, run of the mill C implementation by 
performing a very 
specific benchmark.  If that wasn't enough, the C implementation they adopted 
to represent C was 
none other than GCC 4.0.3.  As we all know, the 4.0 branch of GCC was still 
experimental an ran 
notoriously worse than the 3.4 branch[1].

But even though you've ignored this, the article's authors haven't.  They've 
stated the following 
on their article:


We must admit however that this point of view is not totally unjustified. Recent 
studies (Neuss, 
2003; Quam, 2005) on various numerical computation algorithms find that LISP 
code compiled with C 
MU - CL can run at 60% of the speed of equivalent C code.


So, where exactly do you base your claims?


 
> Actually, it's hard to find a language that has no compiler generating
> faster code than C...

Once again, I don't know if you are intentionally trying to be deceitful.  If 
an undergraduate 
student happens to write a C compiler for a compiler class which employs no 
optimization 
whatsoevere then that will not mean that every single C compiler is incapable 
of generating 
efficient code. 


Rui Maciel


[1] http://coyotegulch.com/reviews/gcc4/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread BartC


"Pascal J. Bourguignon"  wrote in message 
news:87zkuyjawh@kuiper.lan.informatimago.com...

"BartC"  writes:


"Pascal J. Bourguignon"  wrote in message



When Intel will realize that 99% of its users are running VM


Which one?


Any implementation of a controlled environment is a virtual machine.
Sometimes it is explicitely defined, such as in clisp, parot or jvm, but
more often it is implicit, such as in sbcl, or worse, developed in an
ad-hoc way in applications (eg. written in C++).


But if you had to implement a VM directly in hardware, which one (of the 
several varieties) would you choose?


And having chosen one, how would that impact the performance of a language 
with an incompatible VM?


Perhaps processors executing native code as it is now, aren't such a bad 
idea.


--
Bartc 


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


Re: discussion

2010-10-01 Thread BartC
"Geo_subodh"  wrote in message 
news:31a08825-bb72-4e9f-8710-a39fe2bc9...@u31g2000pru.googlegroups.com...

please send me the simple python code that uses input number greater
than3 digits(>3 digits) and  checks whether the number is palindrome
or not.


The following works without using strings (although leading zeros are 
ignored, so that 01210 returns False):


def fpalindrome(n):
   if n<0: return False
   if n<10: return True

   digits=1
   a=n
   while a>=10:
   digits=digits+1
   a=a//10

   lastdigit=n%10
   firstdigit=n//(10**(digits-1))

   if firstdigit!=lastdigit: return False
   if digits==2: return True

   middledigits=n//10-firstdigit*(10**(digits-2))

   return fpalindrome(middledigits)

print fpalindrome(12345678987654321)

--
Bartc 


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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Rui Maciel
George Neuner wrote:

> That's true.  But it is a situation where the conversion to SI units
> loses precision and therefore probably shouldn't be done.



> I don't care to check it ... the fact that the SI unit involves 12
> decimal places whereas the imperial unit involves 3 tells me the
> conversion probably shouldn't be done in a program that wants
> accuracy.


Your comment is absurd for multiple reasons.   As we are focusing on the 
computational aspect of 
this issue then I will only say this:  If we are dealing with a computer 
representation of numbers 
then, as long as the numeric data type provides enough precision, it is 
perfectly irrelevant if a 
decimal representation of a certain number involves 12 or 3 decimal places.  
The only precision 
issues which affect a calculation is the ones arising from a) the ability to 
exactly represent a 
certain number in a specific representation and b) the precision errors 
produced by arithmetic 
operations.


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


Fwd: Python becoming orphaned over ssh

2010-10-01 Thread David
(Sending again to the list, I mailed Jean-Paul off-list by mistake, sorry).

On Thu, Sep 30, 2010 at 4:01 PM, Jean-Paul Calderone
 wrote:
> You can fix this by resetting the signal disposition of SIGPIPE for
> the ping process:
>
>    #!/usr/bin/python
>    import signal
>
>    def reset():
>        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
>
>    from subprocess import check_call
>    check_call(['ping', 'www.google.com'], preexec_fn=reset)
>
> Very likely the subprocess module should be resetting the disposition
> of signals that Python itself has fiddled with (and resetting any
> other unusual state that the child is going to inherit, but nothing
> else comes immediately to mind).
> --

Thanks, that works for me. Also  thanks to Gregory (Python developer)
for fixing it so quickly (don't want to litter the bug tracker with
thanks).

Small annoyance: Though it's fixed with ping, wget still has the
problem. However, I compared the two script versions again (test.sh,
and test.py) for wget, and actually bash has the same problem as
python, so I assume it's a wget bug this time (I'll go report the bug
to them next). Is it that unusual to run scripts over non-interactive
SSH, and then interrupt with Ctrl+C? :-). So I guess for now I need to
keep my previous workaround for now, rather than switching to the
preexec_fn syntax.

Also, I don't 100% follow that explanation about the pipes. I read a
bit more over here:

http://en.wikipedia.org/wiki/SIGPIPE

And it seems like SIGPIPE would apply in a case like this:

ping www.google.com | test.py

But I'm not calling ping like that. I guess it applies to regular
stream, non-piping operations, too? ie, something like this is
happening

[ping output] passes through==> [test.py] ==> passes through [ssh] ==>
passes through => [more ssh, bash, etc, up to my terminal]

And when ssh disappears, then Linux automatically sends ping SIGPIPE,
because it's output can no longer be "passed through" to anywhere.

Pretty interesting, but I'm a noob with this stuff. If I want to learn
more, would this WP article (and linked pages) be a good place to
learn more?

http://en.wikipedia.org/wiki/Signal_%28computing%29

Thanks,

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
"BartC"  writes:

> "Pascal J. Bourguignon"  wrote in message
> news:87sk0qkzhz@kuiper.lan.informatimago.com...
>> rustom  writes:
>
>>> Much more mainstream, C# is almost as 'managed' as dynamic languages
>>> and has efficiency comparable to C.
>>
>> Nothing extraordinary here.  Common Lisp is more efficient than C.
>> http://www.lrde.epita.fr/~didier/research/verna.06.ecoop.pdf
>> http://portal.acm.org/citation.cfm?id=1144168
>
> It seems that to make Lisp fast, you have to introduce static
> typing. Which is not much different to writing in C, other than the
> syntax.
>
>> Actually, it's hard to find a language that has no compiler generating
>> faster code than C...
>
> But those implementers have to try very hard to beat C. Meanwhile C
> can be plenty fast without doing anything special.
>
>> When Intel will realize that 99% of its users are running VM
>
> Which one?

Any implementation of a controlled environment is a virtual machine.
Sometimes it is explicitely defined, such as in clisp, parot or jvm, but
more often it is implicit, such as in sbcl, or worse, developed in an
ad-hoc way in applications (eg. written in C++).


-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Rui Maciel
namekuseijin wrote:

>> in C I can have a function maximum(int a, int b) that will always
>> work. Never blow up, and never give an invalid answer. If someone
>> tries to call it incorrectly it is a compile error.
>> In a dynamic typed language maximum(a, b) can be called with incorrect
>> datatypes. Even if I make it so it can handle many types as you did
>> above, it could still be inadvertantly called with a file handle for a
>> parameter or some other type not provided for. So does Eckel and
>> others, when they are writing their dynamically typed code advocate
>> just letting the function blow up or give a bogus answer, or do they
>> check for valid types passed? If they are checking for valid types it
>> would seem that any benefits gained by not specifying type are lost by
>> checking for type. And if they don't check for type it would seem that
>> their code's error handling is poor.
> 
> that is a lie.
> 
> Compilation only makes sure that values provided at compilation-time
> are of the right datatype.
> 
> What happens though is that in the real world, pretty much all
> computation depends on user provided values at runtime.  See where are
> we heading?

You are confusing two completely different and independent concepts, which is a 
language's typing 
sytem and input validation.  TheFlyingDutchman pointed out the typical problems 
associated with 
weakly typed languages while you tried to contradict him by complaining about 
input sanity issues.  
The thing is, input sanity issues are perfectly independent of a language's 
typing system.  
Therefore, arguing about the need to perform sanity checks on programs written 
on language X or Y 
does nothing to tackle the issues related to passing a variable/object of the 
"wrong" type as a 
parameter to some function.


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


Re: sequence multiplied by -1

2010-10-01 Thread Antoon Pardon
On Thu, Sep 30, 2010 at 07:02:40AM -0700, Emile van Sebille wrote:
> On 9/30/2010 5:10 AM Antoon Pardon said...
> >On Sun, Sep 26, 2010 at 03:20:18PM +, Grant Edwards wrote:
> >>On 2010-09-26, Paul Rubin  wrote:
> >>>Steven D'Aprano  writes:
> There's nothing obscure or unintuitive about "spam"*3 = "spamspamspam",
> >>
> >>>Why would it not be ["spam","spam","spam"] or even "ssspppaaammm"?
> >>
> >>Because
> >>
> >>3 * "spam" == "spam" + "spam" + "spam"
> >>
> >>Just like
> >>
> >>3 * 6 = 6 + 6 + 6
> >>
> >>So now I suppose "+" for string concatenation is a bad thing.
> >
> >Well I find it an unfortunate choice. The problem is, that it is not that
> >unusual to want some class to have the possibility of both addition and
> >concatenation. But since we only one symbol for both operations, you will
> >have to loose some consistency over this.
> >
> 
> Which is actually a good thing for a class that wants to have both
> concatenation and addition

Why? What is good about losing consistency? It is in this case necessary
but that doesn't make it good.

Think about the following possibility.

Someone provides you with a library of functions that act on sequences.
They rely on the fact that '+' concatenates.

Someone else provides you with a library of functions that act on
numbers. They rely on the fact that '+' provides addition.

Now however you write your sequence like numbers or number like sequences
one of those libraries will be useless for it.

> -- which would it do with only one
> symbol?

But why limit ourselves to one symbol for different kind of operations,
to begin with?

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread BartC
"Pascal J. Bourguignon"  wrote in message 
news:87sk0qkzhz@kuiper.lan.informatimago.com...

rustom  writes:



Much more mainstream, C# is almost as 'managed' as dynamic languages
and has efficiency comparable to C.


Nothing extraordinary here.  Common Lisp is more efficient than C.
http://www.lrde.epita.fr/~didier/research/verna.06.ecoop.pdf
http://portal.acm.org/citation.cfm?id=1144168


It seems that to make Lisp fast, you have to introduce static typing. Which 
is not much different to writing in C, other than the syntax.



Actually, it's hard to find a language that has no compiler generating
faster code than C...


But those implementers have to try very hard to beat C. Meanwhile C can be 
plenty fast without doing anything special.



When Intel will realize that 99% of its users are running VM


Which one?

--
Bartc 


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


Re: namespace hacking question

2010-10-01 Thread Fuzzyman
On Sep 30, 6:07 pm, kj  wrote:
> This is a recurrent situation: I want to initialize a whole bunch
> of local variables in a uniform way, but after initialization, I
> need to do different things with the various variables.
>
> What I end up doing is using a dict:
>
> d = dict()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)
>
> foo(d['spam'])
> bar(d['ham'])
> baz(d['eggs'])
>
> This is fine, but I'd like to get rid of the tedium of typing all
> those extra d['...']s.
>
> I.e., what I would *like* to do is something closer to this:
>
> d = locals()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)
>
> foo(spam)
> bar(ham)
> baz(eggs)
>
> ...but this results in errors like "NameError: global name 'spam' is
> not defined".
>
> But the problem is deeper than the fact that the error above would
> suggest, because even this fails:
>
> spam = ham = eggs = None
> d = locals()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)
>
> foo(spam) # calls foo(None)
> bar(ham)  # calls bar(None)
> baz(eggs) # calls baz(None)
>
> In other words, setting the value of locals()['x'] does not set
> the value of the local variable x.
>
> I also tried a hack using eval:
>
> for v in ('spam', 'ham', 'eggs'):
>     eval "%s = init('%s')" % (v, v)
>
> but the "=" sign in the eval string resulted in a "SyntaxError:
> invalid syntax".
>
> Is there any way to use a loop to set a whole bunch of local
> variables (and later refer to these variables by their individual
> names)?
>

One way:

import sys
module = sys.modules[__name__]

for entry in ('spam', 'eggs', 'ham'):
setattr(module, entry, 'some value')


Michael Foord
--
http://www.voidspace.org.uk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __file__ is sometimes absolute, sometimes relative

2010-10-01 Thread Christian Heimes
Am 01.10.2010 13:00, schrieb Sébastien Barthélemy:
> Hello,
> 
> I use a data file that lies on disk in the same directory that the
> module which makes use of it.
> 
> The data file is checked in the repository and gets installed by
> the distutils ``package_data`` directive, so it is in place both
> during development and after and install.
> 
> In my program, I need to find the absolute path to this data file.
> 
> I could think of 3 ways to do this:
> 1. using the __path__ property in the module
> 2. using __file__ property in the module
> 3. using __file__ and os.getcwd() in the module

Use the abspath function of the os.path module:

HERE = os.path.dirname(os.path.abspath(__file__))

Christian

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


__file__ is sometimes absolute, sometimes relative

2010-10-01 Thread Sébastien Barthélemy
Hello,

I use a data file that lies on disk in the same directory that the
module which makes use of it.

The data file is checked in the repository and gets installed by
the distutils ``package_data`` directive, so it is in place both
during development and after and install.

In my program, I need to find the absolute path to this data file.

I could think of 3 ways to do this:
1. using the __path__ property in the module
2. using __file__ property in the module
3. using __file__ and os.getcwd() in the module

The first option does not work, because __path__ is initialised after the
module is loaded (apparently).

Solution 2  works, but behaves differently when ran from python or
from a doctest file. The path in __file__ is absolute if the program
is ran directly by ``python``, and relative if it is ran by
``python -m doctest``.

Solution 3 works. However if there is a better way to do this, please let me
know.

I could not find anything documenting what the proper value for __file__
should be. Maybe my problem with solution 2 is a bug in doctest or runpy?

I put up a simple example exhibiting the problem.

Here are the results on my mac (using python from macport)
I get the same results using python 2.6, 2.7 and 3.1

$ python2.6 test.py
/Users/seb/Devel/arboris-python/src/pyfile
/Users/seb/Devel/arboris-python/src/pyfile/mod.pyc
/Users/seb/Devel/arboris-python/src/pyfile
/Users/seb/Devel/arboris-python/src/pyfile

$ python2.6 -m doctest test.txt
**
File "test.txt", line 5, in test.txt
Failed example:
print mod.__file__
Expected:
/Users/seb/Devel/arboris-python/src/pyfile/mod.pyc
Got:
mod.pyc
**
File "test.txt", line 7, in test.txt
Failed example:
print(mod.whereami)
Expected:
/Users/seb/Devel/arboris-python/src/pyfile
Got:

**
File "test.txt", line 9, in test.txt
Failed example:
print(mod.whereami2)
Expected:
/Users/seb/Devel/arboris-python/src/pyfile
Got:
/Users/seb/Devel/arboris-python/src/pyfile/
**
1 items had failures:
   3 of   6 in test.txt
***Test Failed*** 3 failures.

Cheers
Sebastian
>>> import os
>>> print(os.getcwd())
/Users/seb/Devel/arboris-python/src/pyfile
>>> import mod
>>> print(mod.__file__)
/Users/seb/Devel/arboris-python/src/pyfile/mod.pyc
>>> print(mod.whereami)
/Users/seb/Devel/arboris-python/src/pyfile
>>> print(mod.whereami2)
/Users/seb/Devel/arboris-python/src/pyfile



mod.py
Description: Binary data


test.py
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list


ANNOUNCE - NHI1 / PLMK / libmsgque - Work-Package-II

2010-10-01 Thread Andreas Otto
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Dear User,


ANNOUNCE:Work-Package-II


  libmsgque: Application-Server-Toolkit for
 C, C++, JAVA, C#, TCL, PERL, PYTHON, VB.NET
  PLMK:  Programming-Language-Microkernel
  NHI1:  Non-Human-Intelligence #1


SUMMARY
===

  After six month research workshop with bicycling through the
  'Black Forrest', 'Vosges', 'Switzerland' / 'French' and 'Italy'
  Alps ... I'm back to serve for "Work Package II" of NHI1


Read More At


  http://nhi1.berlios.de/theLink/wp2.htm


mfg

  Andreas Otto (aotto1968)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.15 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJMpb3oAAoJEGTcPijNG3/AzuMH/jU2HKpDL56Imlx25ztWR/Jl
wESKLLj8vBgiFWDUprxpBYF5CHGblXCMfk1CowfnjJ7TiuLKMNhTv/W3V/9gCYbb
C9wNZ6lpl9NYBnfD5QuR6vJsPK9pYY0nhcCh3W1jHOXZ/vlafGhvQETFZp32ukXz
JTWx1LxB4NNxfuXBH5pRnDM9olAVMzndjr/+5QtmM3tQIOKV59wUJWn+1wz+N4Ol
ZwrqYEi355sdFqWdANqlWx5aihInfM25HPZj60lF7lTHWAItJFZDAgjzd55I04wO
S+hvlL18jyTJaJGy/otdYEj3IdVJvc/UzMcOiz9UBSThvhbmTf1OIYr2X9zyGRM=
=gWr2
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C API: Getting PyObject by name

2010-10-01 Thread pbienst
Here is what I tried, but it prints out '-1':

PyObject* obj = PyRun_String("1", Py_single_input,
PyEval_GetGlobals(), PyEval_GetLocals());
long d = PyLong_AsLong(obj);
printf("long:%ld\n", d);
Py_DECREF(obj);

Peter

On Sep 30, 9:24 pm, Thomas Jollans  wrote:
> On Thursday 30 September 2010, it occurred to pbienst to exclaim:
>
> > Hi,
>
> > I'm embedding Python in a C app.
>
> > Say I do the following:
>
> >   PyRun_SimpleString("a = 1")
>
> > Is there then a way to get access to the PyObject corresponding to a,
> > only making use in C of the fact that it's called "a"?
>
> > I've searched through the API docs, but I couldn't really find what I
> > was looking for.
>
> No. Not as such. But you could use PyRun_String, or PyRun_StringFlags. You
> could then access the globals object, but I ask you, why would you want to
> bind the object to a name in the first place? Use the fact that PyRun_String
> returns a reference to the result of an expression!

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


Re: if the else short form

2010-10-01 Thread Antoon Pardon
On Wed, Sep 29, 2010 at 05:58:16AM -0700, bruno.desthuilli...@gmail.com wrote:
> On 29 sep, 13:38, Hrvoje Niksic  wrote:
> > Tracubik  writes:
> >
> > > button = gtk.Button(("False,", "True,")[fill==True])
> 
> (snip)
> 
> > BTW adding "==True" to a boolean value is redundant and can even break
> > for logically true values that don't compare equal to True (such as the
> > number 10 or the string "foo").
> 
> Note that if fill is actually an int outside the (0, 1) domain, it
> will break too. The correct test would be:
> 
>  ("False,", "True,")[bool(fill)])

That is assuming the original coder would want the argument "True,"
in such cases. You don't know that.

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


Re: if the else short form

2010-10-01 Thread Antoon Pardon
On Wed, Sep 29, 2010 at 01:38:48PM +0200, Hrvoje Niksic wrote:
> Tracubik  writes:
> 
> > Hi all,
> > I'm studying PyGTK tutorial and i've found this strange form:
> >
> > button = gtk.Button(("False,", "True,")[fill==True])
> >
> > the label of button is True if fill==True, is False otherwise.
> 
> The tutorial likely predates if/else expression syntax introduced in
> 2.5, which would be spelled as:
> 
> button = gtk.Button("True" if fill else "False")
> 
> BTW adding "==True" to a boolean value is redundant and can even break
> for logically true values that don't compare equal to True (such as the
> number 10 or the string "foo").

But leaving it out can also break things. If for some reason a variable
can have a boolean or a numeric value, that doesn't mean the coder wants
to treat 0 the same as False or any non-zero number the same as True.

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
Seebs  writes:

> On 2010-09-30, Ian Collins  wrote:
>> Which is why agile practices such as TDD have an edge.  If it compiles 
>> *and* passes all its tests, it must be right.
>
> So far as I know, that actually just means that the test suite is
> insufficient.  :)
>
> Based on my experience thus far, anyway, I am pretty sure it's essentially
> not what happens that the tests and code are both correct, and it is usually
> the case either that the tests fail or that there are not enough tests.

It also shows that for languages such as C, you cannot limit the unit tests
to the types declared for the function, but that you should try all the
possible values of the language.

Which basically, is the same as with dynamically typed programming
language, only now, some unit tests will fail early, when trying to
compile them while others will give wrong results later.


static  dynamic

compiler detects wrong type fail at compile fails at run-time
(with exception
explaining this is
the wrong type)

compiler passes wrong type  wrong resultfails at run-time
(the programmer (with exception
spends hoursexplaining this is
finding the the wrong type)
problem)

compiler passes correct typewrong resultwrong result
   (normal bug to be corrected)

compiler passes correct typecorrect result  correct result



-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
rustom  writes:

> Some points that seem to be missed (or Ive missed them?)
>
> 1. A dichotomy is being made between 'static' languages like C and
> 'dynamic' languages like python/lisp. This dichotomy was valid 30
> years ago, not today.  In Haskell for example
>
> - static checking is stronger than in C/C++  -- its very hard if not
> impossible to core dump haskell except through memory exhaustion
>
> - dynamic-ness is almost that of python/lisp -- on can write
> significant haskell programs without type-declaring a single variable/
> function

You're confunding type strongness with the requirement that the
programmer should declare the types, and with the time when the types
are checked.

http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Type_systems

 
type strong   staticexplicitAda
type strong   staticimplicitHaskell
type weak staticexplicitC
type weak staticimplicit  ?
type strong   dynamic   explicit (*)
type strong   dynamic   implicitCommon Lisp
type weak dynamic   explicitObjective-C
type weak dynamic   implicitJavaScript


(*) Usually languages provide explicit typing as an option, but can
deal with implicit typing, when they're dynamic.  


There are also a few languages with no type checking, such as assembler
or Forth.



> Much more mainstream, C# is almost as 'managed' as dynamic languages
> and has efficiency comparable to C.

Nothing extraordinary here.  Common Lisp is more efficient than C.
http://www.lrde.epita.fr/~didier/research/verna.06.ecoop.pdf
http://portal.acm.org/citation.cfm?id=1144168

Actually, it's hard to find a language that has no compiler generating
faster code than C... 


> 2. The dichotomy above misses a more pervasive dichotomy -- hardware
> vs software -- as real today as 30 years ago.
>
> To see this let us lift the discussion from that of *languages* C vs
> Python/Lisp  to philosophies:
> -- C-philosophy: the purpose of type-checking is to maximize (runtime)
> efficiency
> -- Lisp-philosophy: the purpose of type-checking is zero-errors (aka
> seg-faults) via continuous checks at all levels.
>
> If one is honest (and not polemical :-) ) it would admitted that both
> sides are needed in different contexts.
>
> Now Dijkstra pointed (40 years ago) in Discipline of Programming that
> this unfortunate dilemma arises due to lack of hardware support. I am
> unable to reproduce the elegance and succinctness of his language but
> the argument is as follows:
>
> Let us say that for a typical profile of a computer we have for every
> one instruction of the pathological one typified by the maximum
> function, a trillion 'normal' instructions.  This is what he calls a
> very-skew test -- an if-then-else that checks this would go the if-way
> way one trillion times for one else-way.  It is natural for a
> programmer to feel the pinch of these trillion checks and (be inclined
> to) throw them away.
>
> If however the check was put into hardware there would be no such
> dilemma. If every arithmetic operation was always checked for overflow
> *by hardware* even languages committed to efficiency like C could trap
> on errors with no extra cost.
> Likewise Lisp/python-like languages could easily be made more
> efficient.
>
> The diff arises from the fact that software costs per use whereas
> hardware costs per installation -- a transistor, unlike an if, does
> not cost any more if its used once or a trillion times.
>
> In short the problem is not C vs Lisp/Python but architectures like
> Intel wherein:
>
> 1. an overflow bit harmlessly set by a compare operation is
> indistinguishable from one set by a signed arithmetic operation --
> almost certainly a problem
>
> 2. An into instruction (interrupt on overflow) must be inserted into
> the software stream rather than raised as a hardware interrupt.

Hence the use of virtual machine: when your machine doesn't do what you
want, you have to write your own.

When Intel will realize that 99% of its users are running VM, perhaps
they'll start to wonder what they're making wrong...

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
Seebs  writes:

> On 2010-10-01, Don Geddis  wrote:
>> in C I can have a function maximum(int a, int b) that will always
>> work. Never blow up, and never give an invalid answer. If someone
>> tries to call it incorrectly it is a compile error.
>
> I would agree that the third sentence is arguably wrong, simply
> because there's no such thing (outside #error) of a mandate to stop
> compiling.  However, my understanding was that the dispute was over
> the second sentence, and that's certainly correct.
>
> The obvious simple maximum() in C will not raise an exception nor return
> something which isn't an int in any program which is not on its face
> invalid in the call.  This is by definite contrast with several of the
> interpreted languages, 

This has nothing to do with the fact that these languages have
implementations using the interpreter pattern instead of a compiler.

Matter of fact, most Common Lisp implementations just do not have any
interpreter!  (Which doesn't prevent them to have a REPL).


> where a function or subroutine like that cannot
> specify that its argument must be some kind of integer.

This is correct, but this is not a characteristic of dynamic programming
languages.  There are dynamic programming languages where you can
declare the type of the parameters, to allow for static checking.  For
example in Common Lisp (where these declarations are advisory, so the
compiler is free to take them into account or not, depending on what it
can infer from its own side, so any problem here is just a warning: the
program can always handle the problems at run-time).



-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Nick Keighley
On 27 Sep, 18:46, namekuseijin  wrote:



> Fact is:  almost all user data from the external words comes into
> programs as strings.  No typesystem or compiler handles this fact all
> that graceful...

snobol?

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Steven D'Aprano
On Thu, 30 Sep 2010 21:27:03 +, Seebs wrote:

> On 2010-09-30, Ian Collins  wrote:
>> Which is why agile practices such as TDD have an edge.  If it compiles
>> *and* passes all its tests, it must be right.
> 
> So far as I know, that actually just means that the test suite is
> insufficient.

+1 QOTW


Now can we (by which I mean *you*) stop cross-posting C talk to multiple 
newsgroups that don't have anything to do with C?



Thank you.


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


Re: Having problem with subclass

2010-10-01 Thread Steven D'Aprano
On Thu, 30 Sep 2010 18:54:00 -0700, tekion wrote:

> When I move  Bclass to A.py, it works.  Is there some restriction in
> python that sub classing a class has be in the same file as the class
> you're are sub classing? Thanks.

Others have already solved your main problem (you need to refer to 
A.Aclass rather than just Aclass), but I'd like to make another comment.

Unlike Java, Python programmers rarely see the need to have one class per 
file, especially if they are small classes. Generally subclasses will be 
small -- you might only change a handful of methods. I'd even go say as 
to say that the Java (anti-)pattern of placing each and every class into 
its own file is actively frowned upon by Python programmers.

By all means arrange your classes into separate modules if that is the 
most natural way to arrange them, but don't artificially break apart 
related classes into separate modules.



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


Re: discussion

2010-10-01 Thread Steven D'Aprano
On Thu, 30 Sep 2010 19:12:06 -0700, Geo_subodh wrote:

> please send me the simple python code that uses input number greater
> than3 digits(>3 digits) and  checks whether the number is palindrome or
> not.

def is_palindrome_or_not(n):
"""Checks whether the input number n is a palindrome or not."""
if n >= 100:
return n is "palindrome" or n is not "palindrome"
else:
raise ValueError("n must be a positive number with 3+ digits")



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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Pascal J. Bourguignon
Gene  writes:

> The FA or TM dichotomy is more painful to contemplate than you say.
> Making appropriate simplifications for input, any modern computer is a
> FA with 2^(a few trillion) states.  Consequently, the gestalt of
> computer science seems to be to take it on faith that at some very
> large number of states, the FA behavior makes a transition to TM
> behavior for all possible practical purposes (and I mean all).  So
> what is it--really--that's trivial to analyze?  And what is
> impossible?  I'm sorry this is drifting OT and will stop here.


Don't worry, this thread is becoming interesting at least.

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gedit 'External Tools' plugin hashlib weirdness

2010-10-01 Thread Joel Hedlund
I apparently replied to soon.

Removing /usr/lib/python2.4 from PYTHONPATH did not solve the problem.
I think I may have had a launcher-started gedit running somewhere in
the background while testing. Any subsequent terminal-launches would
then just create new windows for the existing (non-bugged) process,
rather than starting a new process and tripping the bug (and by bug I
mean configuration error on my part, most likely).

However, I went further along the sys.path diff and found a path to a
second python2.6 installation. Apparently, this one shipped with a
standalone middleware client for distributed computing, and was
insinuated into my PYTHONPATH via a call to its startup script in
my .bashrc. Removing the call to the startup script solved the problem
again (!)

I still can't explain the traceback though.

But fwiw, this solution made the problem stay solved past a reboot, so
I have high hopes this time.

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


Re: if the else short form

2010-10-01 Thread bruno.desthuilli...@gmail.com
On 30 sep, 19:22, Andreas Waldenburger 
wrote:
> On Thu, 30 Sep 2010 03:42:29 -0700 (PDT)
>
> "bruno.desthuilli...@gmail.com"  wrote:
> > On 29 sep, 19:20, Seebs  wrote:
> > > On 2010-09-29, Tracubik  wrote:
> > > > button = gtk.Button(("False,", "True,")[fill==True])
>
> > > Oh, what a nasty idiom.
>
> > Well, it's not very different from dict-based dispatch , which is the
> > core of OO polymorphic dispatch in quite a few dynamic OOPLs.
>
> > Anyway, it's a common Python idiom and one that's not specially hard
> > to grasp so I don't see any legibility problem here.
>
> But it does violate the "explicit is better than implicit" tenet, don't
> you think?

Why so ? The doc clearly states that booleans are integers with True
== 1 and False == 0, so there's nothing implicit here.

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


Re: "Strong typing vs. strong testing"

2010-10-01 Thread Antony

On 9/30/2010 9:06 AM, Seebs wrote:


At $dayjob, they give us months between feature complete and shipping,

Lucky you
-Antony
--
http://mail.python.org/mailman/listinfo/python-list