please, help with python 3.1

2010-08-02 Thread Alan
Hello List,

Please, can someone at least try this code below in python 3 and report me
back whether it works or not? Because for me this code works in python 2.6
but not with python 3.1. Thanks!


from __future__ import print_function
import os, subprocess, signal

def signal_handler( signum, frame ):

print( "PID: %s" % pid )
print( "Timed out! Process %s killed, max exec time (%ss) exceeded" %
(pid, timeTol ) )
os.kill( int( pid ), 15 )
raise Exception( "Taking too long to finish... aborting!" )

if __name__ == '__main__':

timeTol = 5

cmd = 'find /'

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(timeTol)

p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout
= subprocess.PIPE)
pid = p.pid

out = str( p.communicate()[0].decode() )
print(out)


Alan

-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple (I hope!) problem

2010-08-02 Thread Steven D'Aprano
On Mon, 02 Aug 2010 17:19:46 -0700, samwyse wrote:

> Fortunately, I don't need the functionality of the object, I just want
> something that won't generate an error when I use it.  So, what is the
> quickest way to to create such an object (replacing the 'pass' in my
> first snippet).  My solution is this:
> 
> class C:
> def filter(self, *args, **kwds):
> pass
> register = C()
> 
> but it seems like I should be able to do something "better", as measured
> by lines of code, faking more than just a 'filter' method, or both.  Any
> ideas?  Thanks!


You want a variation on the Null Object design pattern.

class NullWithMethods(object):
def __getattr__(self, name):
return self
def __call__(self, *args, **kwargs):
pass


And in action:

>>> c = NullWithMethods()
>>> c.spam("hello", "world")
>>> c.something_completely_unlikely.spam.ham("hello", "world", foo=42)



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


Re: Trying to set a cookie within a python script

2010-08-02 Thread Νίκος
>On 2 Αύγ, 23:57, Thomas Jollans  wrote:

> So: tripple-check that
>
>  * your file is 
>  * Python knows that
>  * the web browser knows that

Thank you! i used print ''' Content-Type: text/html; charset=UTF-8 /
n''' and it worked.
I'am still pretty confused about the encodings.

Please tell me the difference between 3 things.

a) Asking Notepad++(my editor) to save all my python scripts as UTF-8
without BOM.
b) Using this line '# -*- coding: utf-8 -*-' Isn't this line supposed
to tell browser that the contents of this python script as in UTF-8
and to handle it as such?
c) print ''' Content-Type: text/html; charset=UTF-8 /n'''

Please explain to me as simple as you can because from the time with
php and perl encodings not only gave me a hard time but also caused my
program to produce internal server errors so i need to understand the
differences.

=
Also in the other problem with the cookie iam trying to set:
=
if os.environ.get('HTTP_COOKIE') and cookie.has_key('visitor') ==
'nikos':#if visitor cookie exist
print "Next time i will count you"
cookie['visitor'] = ( 'nikos', time() - 1 ) #this cookie 
will expire
now
else:
print "I wont be counting you any more"
cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 )  #this 
cookie
will expire in an year
=

Why always the code block pertainign to 'else' get exectuted ane never
the code of 'if'
The idea is who ever runs 'koukos.py' to set/unset himself out of the
counter count so i need i way to set/unset the browser cookie!

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


Re: sending a file chunk by chunk instead as a whole to a web server

2010-08-02 Thread Ryan Kelly
On Tue, 2010-08-03 at 10:45 +0530, Kushal Kumaran wrote:
> On Mon, Aug 2, 2010 at 12:22 PM, Sanjeeb  wrote:
> > Hi,
> > I have a web client which send a file to a server as multipart form
> > data, the sending of data is from
> > http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/.
> >
> > I dont want to open the whole file to memory(at cliend end) and then
> > send, i just want to send part by part, say chunk of 1024 bytes to the
> > server and then assemble at the server end.
> >
> > Could some one suggest what would be the best way to do this?
> >
> 
> There's no reason why sending the whole file implies reading the whole
> file into memory at one time.  You can just read your desired chunk
> size and send it, then read the next chunk, and so on.  You might have
> to first find the total size to calculate what to set Content-Length
> to.

More concretely, you would restructure the encode_multipart_formdata()
function as a generator, yielding chunks of data to send one at a time.
Something like this:

def post_multipart(host,selector,fields,files):
...snip...
h.endheaders()
for chunk in encode_multipart_formdata_chunks(fields,files):
h.send(chunk)
errcode, errmsg, headers = h.getreply()
return h.file.read()


def encode_multipart_formdata(fields,files):
BOUNDARY = '--ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
for (key, value) in fields:
yield '--' + BOUNDARY
yield 'Content-Disposition: form-data; name="%s"' % key
yield ''
yield value
for (key, filename, value) in files:
yield '--' + BOUNDARY
yield 'Content-Disposition: form-data; name="%s"; filename="%s"' % 
(key, filename)
...etc...
...etc...

There are many improvements to make, but this should get you started.
For example, you'll need to calculate the total content-length rather
than just calling len(body) to obtain it.  That's left as an exercise to
the reader.


Ryan


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



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


Re: let optionparse.Optionparser ignore unknown command line switches.

2010-08-02 Thread Michele Simionato
On Aug 1, 1:08 pm, News123  wrote:
> I wondered, whether there's a simple/standard way to let
> the Optionparser just ignore unknown command line switches.
>
> thanks in advance for any ideas

I will plug in my own work on plac: http://pypi.python.org/pypi/plac
Your problem would be solved as follows:

import plac

@plac.annotations(test=('a flag', 'flag', 't'))
def main(test, *ignore):
print test, ignore

if __name__ == '__main__':
plac.call(main, ["-t","--ignoreme_and_dont_fail"])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sending a file chunk by chunk instead as a whole to a web server

2010-08-02 Thread Kushal Kumaran
On Mon, Aug 2, 2010 at 12:22 PM, Sanjeeb  wrote:
> Hi,
> I have a web client which send a file to a server as multipart form
> data, the sending of data is from
> http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/.
>
> I dont want to open the whole file to memory(at cliend end) and then
> send, i just want to send part by part, say chunk of 1024 bytes to the
> server and then assemble at the server end.
>
> Could some one suggest what would be the best way to do this?
>

There's no reason why sending the whole file implies reading the whole
file into memory at one time.  You can just read your desired chunk
size and send it, then read the next chunk, and so on.  You might have
to first find the total size to calculate what to set Content-Length
to.

ISTR questions of this nature have been asked in the past on this list.

-- 
regards,
kushal
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sending a file chunk by chunk instead as a whole to a web server

2010-08-02 Thread Sanjeeb
On Aug 2, 11:52 am, Sanjeeb  wrote:
> Hi,
> I have a web client which send a file to a server as multipart form
> data, the sending of data is 
> fromhttp://code.activestate.com/recipes/146306-http-client-to-post-using-
>
> I dont want to open the whole file to memory(at cliend end) and then
> send, i just want to send part by part, say chunk of 1024 bytes to the
> server and then assemble at the server end.
>
> Could some one suggest what would be the best way to do this?
>
> Regards
> -Sanjeeb

Hey any taker for this question???
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to run Python 2.7 on Windows 7 and any suggestions onbooks/websites for "dummies guide to python" type learning

2010-08-02 Thread Mark Tolonen


"ben owen"  wrote in message 
news:snt124-w51cdf963a687dd653cc804cc...@phx.gbl...


Hi everyone, I'm new to this and was needing help with trying to learn/work 
with Python 2.7 on my computer. I'm running Windows 7 and trying to learn 
python programming from an older book from 1999 by Mark Lutz and David 
Ascher my boss gave me, and for some reason none of my script/modules for 
the exercises are working on my comp. Mostly they give either a syntax error 
on the python command line or something about the file/module not being 
found on the windows command line. Also, does anyone where i can find/get 
something similar to the book for my own?


Ben



Post actual code and actual results including error messages (cut-n-paste) 
and you'll get better answers.


Google is your friend for finding books and tutorials.

-Mark


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


Re: Why is python not written in C++ ?

2010-08-02 Thread Aahz
In article <2b473423-0a22-4f4d-943f-31ea2d602...@z10g2000yqb.googlegroups.com>,
sturlamolden   wrote:
>
>And since this is comp.lang.python, I'll add in that this sometimes
>applies to Python as well. Python, like C++, can have the call stack
>rewinded by an exception. If we call some raw OS resource allocation,
>e.g. malloc or fopen using ctypes, we have to place a deallocation in
>__del__ (and make sure the object is newer put in a reference cycle).
>The safer option, however, is to use a C extension object, which is
>guaranteed to have the destructor called (that is, __dealloc__ when
>using Cython or Pyrex).

Actually, with Python 2.6 or later, the Pythonic solution is to use
``with``.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Normal is what cuts off your sixth finger and your tail..."  --Siobhan
-- 
http://mail.python.org/mailman/listinfo/python-list


Seeking help with urllib2 response reading

2010-08-02 Thread Hiral Shah
Hi All,

I am facing problem reading response from urllib2 request. i.e. with read()
method.

I am trying to access XMLAPI using python. I am getting weird behavior from
server, when reading response.Code for calling XMLAPI is as follows:

  headers = {'Content-type': 'application/x-www-form-urlencoded'}
  request = urllib2.Request(siteXMLAPIURL,xmlStr,headers)
  response = urllib2.urlopen(request)
  print response.read()

In above code:
xmlStr: is String containing XML request
siteXMLAPIURL: URL of the site to send request. It is in form "
https://xxx.xxx.com/XXXService/XXXService

Problem Description:

I am calling URL for creating product by passing methodname(CreateProduct),
productId, productCreateDate, productCreateTime etc in XML form.  Call to
XMLAPI always succeed and product is created on site. But when I call
.read() method to print response, then "productCreateTimes" gets changed on
server !!

For example,
Case 1: Not using .read() method. (i.e. commenting print line in above code)
Calling API by passing productCreateTime = 08/02/10 08:00:00,and then
product is being created with time 08/02/10 08:00:00. i.e. everything is
fine here

Now,
Case 2: Using read() method (i.e. having print line is code)
Calling API by passing productCreateTime = 08/02/10 08:00:00 and then
product is being created with time 08/02/10 09:00:00. Here, server is adding
one more hour to productCrateTime. Which is really strange for me!!

FYI: If I access same API with java, everything is fine all time.

I am unable to understand why read() method is changing server behavior!!
Can anyone please guide me in same?

Thank you so much for your time. Waiting for your reply.

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Aahz
In article ,
Roy Smith   wrote:
>In article , a...@pythoncraft.com (Aahz) 
>wrote:
>>
>> http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html
>
>The same story has been floating around for eons, just with the names 
>changed.  I saw one where Wirth was ostensibly making fun of the people 
>who didn't understand that Pascal was all just a joke.
>
>I'm sure if you go back far enough, you can find a McCarthy / Lisp 
>version.  It probably goes something like, "So, anyway, we tried to 
>figure out what was the most absurd way to abuse punctuation we could 
>imagine.  Somebody suggested that every program would have to end with 
>37 close parentheses.  When we finally stopped laughing, we started 
>sketching out a grammar on the chalkboard that would let us do that".

http://www.netfunny.com/rhf/jokes/90q2/lispcode.html
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

(You knew I was going to post that, right?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread rantingrick
On Aug 2, 7:53 pm, samwyse  wrote:

> It's the same results; however many people don't like these results
> because they feel that whitespace occupies a privileged role.  People
> generally agree that a string of consecutive commas means missing
> values, but a string of consecutive spaces just means someone held the
> space-bar down too long.  To accommodate this viewpoint, the string
> split is special-cased to behave differently when None is passed as a
> separator.  First, it splits on any number of whitespace characters,
> like this:

Well we could have created another method like "splitstrip()". However
then folks would complain that they must remember two methods that are
almost identical. Uggh, you just can't win. There is always the
naysayers no matter what you do!

PS: Great post by the way. Highly informative for the pynoobs.

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


Re: simple integer subclass

2010-08-02 Thread rantingrick
On Aug 2, 6:52 pm, Andreas Pfrengle  wrote:
> I'm trying to define a subclass of int called int1. An int1-object
> shall behave exactly like an int-object, with the only difference that
> the displayed value shall be value + 1 (it will be used to display
> array indices starting at 1 instead of 0)

Is zero based indexing that bad for you? I also think this is a very
bad idea unless you can offer a sensible use case -- for which i
cannot imagine.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling a class method from a menu in a different class

2010-08-02 Thread rantingrick

Chris,

It looks as if you are calling a class object and not an instance
object. However i cannot be for sure because you are using improper
Python style. All classes should be capwords. But here again you have
used camelcase for the class identifiers "radarWidgets" and
"mainDisplay", which is bad bad bad!!

You been asking multiple questions about this code for the last couple
of days (and thats fine). However, maybe you would do everyone a favor
by posting the entire code so we can offer suggestions. Just seeing
seeing a snipit here and a snipit there is not helping because we
don't know where else you may be screwing up that we cannot see.

It seems you're committing many faux pas with not only your coding
style but also your coding practices. I've seen overuse of globals and
bad styles and on and on. So post the entire code so myself and others
can go through this mess and get it sorted out. If you keep on with
your bad habits you're never going to become proficient with Python.

I am sorry if this post seems condescending because that is not the
case.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default behavior

2010-08-02 Thread John Posner

On 7/31/2010 1:31 PM, John Posner wrote:


Caveat -- there's another description of defaultdict here:

http://docs.python.org/library/collections.html#collections.defaultdict

... and it's bogus. This other description claims that __missing__ is a
method of defaultdict, not of dict.


Following is a possible replacement for the bogus description. Comments 
welcome. I intend to submit a Python doc bug, and I'd like to have a 
clean alternative to propose.


--

class collections.defaultdict([default_factory[, ...]])

defaultdict is a dict subclass that can guarantee success on key 
lookups: if a key does not currently exist in a defaultdict object, a 
"default value factory" is called to provide a value for that key.  The 
"default value factory" is a callable object (typically, a function) 
that takes no arguments. You specify this callable as the first argument 
to defaultdict(). Additional defaultdict() arguments are the same as for 
dict().


The "default value factory" callable is stored as an attribute, 
default_factory, of the newly created defaultdict object. If you call 
defaultdict() with no arguments, or with None as the first argument, the 
default_factory attribute is set to None. You can reassign the 
default_factory attribute of an existing defaultdict object to another 
callable, or to None.


When a lookup of a non-existent key is performed in a defaultdict 
object, its default_factory attribute is evaluated, and the resulting 
object is called:


* If the call produces a value, that value is returned as the result of 
the lookup. In addition, the key-value pair is inserted into the 
defaultdict.


* If the call raises an exception, it is propagated unchanged.

* If the default_factory attribute evaluates to None, a KeyError 
exception is raised, with the non-existent key as its argument. (The 
defaultdict behaves exactly like a standard dict in this case.)


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


Re: Why is python not written in C++ ?

2010-08-02 Thread Roy Smith
In article 
<7d95c0d3-718d-4958-9364-263c833f1...@i24g2000yqa.googlegroups.com>,
 sturlamolden  wrote:

> On 3 Aug, 02:47, Roy Smith  wrote:
> 
> > This one I don't understand.  Yes, I get RAII, but surely there are
> > valid reasons to allocate memory outside of constructors.  Containers
> > which resize themselves (such as std::vector) are one obvious example.
> 
> That is because an exception might skip an arbitrarily placed delete[]
> or std::fclose when it rewinds the stack...

Well, OK, but there's still nothing wrong with allocating memory outside 
of constructors, as long as you make sure the destructor cleans it up.  
Or you have made some other arrangements to make sure it's cleaned up 
(try/catch, auto_pointer, etc).
-- 
http://mail.python.org/mailman/listinfo/python-list


paypal wholesale gucci shoes (paypal payment)

2010-08-02 Thread world-trade
paypal wholesale d&g shoes (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale gucci shoes (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale lv shoes (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale NBA shoes (paypal payment)
( http://www.24hours-buy.com/  )
paypal wholesale nike (paypal payment)
( http://www.24hours-buy.com/  )
paypal wholesale adidas shoes (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale chanel shoes (paypal payment)
( http://www.24hours-buy.com/  )
paypal wholesale bape hoody (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale antick jeans (paypal payment)
( http://www.24hours-buy.com/  )
paypal wholesale diesel jeans (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale artful dudger (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale bag(lv gucci coach chanel d&g dior ed  fendi )
(paypal payment)(http://www.24hours-buy.com/ )
paypal wholesale clothing (paypal payment)
( http://www.24hours-buy.com/  )
paypal wholesale lrg,jeans,hoody, (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale evisu jeans,hoody,shirt (paypal payment)
( http://www.24hours-buy.com/ )

paypal wholesale Prada (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale Puma (paypal payment)( http://www.24hours-buy.com/ )
paypal wholesale Sand (paypal payment)( http://www.24hours-buy.com/ )
paypal wholesale Shox (paypal payment)( http://www.24hours-buy.com/ )
paypal wholesale soccer (paypal payment)
( http://www.24hours-buy.com/  )
paypal wholesale LV (paypal payment)( http://www.24hours-buy.com/ )
paypal wholesale Versace (paypal payment)
( http://www.24hours-buy.com/  )
paypal wholesale Women (paypal payment)
( http://www.24hours-buy.com/ )
paypal wholesale Y-3 (paypal payment)( http://www.24hours-buy.com/  )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Normalizing A Vector

2010-08-02 Thread sturlamolden
On 30 Jul, 13:46, Lawrence D'Oliveiro  wrote:

> Say a vector V is a tuple of 3 numbers, not all zero. You want to normalize
> it (scale all components by the same factor) so its magnitude is 1.
>
> The usual way is something like this:
>
>     L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2])
>     V = (V[0] / L, V[1] / L, V[2] / L)
>
> What I don’t like is having that intermediate variable L leftover after the
> computation.

L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2])
V = (V[0] / L, V[1] / L, V[2] / L)
del L

But this is the kind of programming tasks where NumPy is nice:

V[:] = V / np.sqrt((V**2).sum())


Sturla


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


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 3 Aug, 04:03, sturlamolden  wrote:

> struct File {
>     std::FILE *fid;
>     File(const char *name) {
>         // acquire resource in constructor
>         fid = std::fopen(name);
>         if (!fid) throw some_exception;
>     }
>     ~File() {
>         // free resource in destructor
>         if(fid) std::flose(fid);
>     }
>
> };

And since this is comp.lang.python, I'll add in that this sometimes
applies to Python as well. Python, like C++, can have the call stack
rewinded by an exception. If we call some raw OS resource allocation,
e.g. malloc or fopen using ctypes, we have to place a deallocation in
__del__ (and make sure the object is newer put in a reference cycle).
The safer option, however, is to use a C extension object, which is
guaranteed to have the destructor called (that is, __dealloc__ when
using Cython or Pyrex).

If we place raw resource allocation arbitrarily in Python code, it is
just as bad as in C++. But in Python, programmers avoid this trap by
mostly never allocating raw OS resources from within Python code. E.g.
Python's file object is programmed to close itself on garbage
collection, unlike a pointer retured from fopen using ctypes.

Sturla





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


Re: constructing and using large lexicon in a program

2010-08-02 Thread Dan Stromberg
On Mon, Aug 2, 2010 at 10:46 AM, Majdi Sawalha wrote:

> Dear List members,
>
> I am developing a morphological analyzer that depends on a large lexicon. i
> construct a Lexicon class that reades a text file and construct a dictionary
> of the lexicon entries.
> the other class will use the lexicon class to chech if the word is found in
> the lexicon. the problem that this takes long time as each time an object of
> that class created, then it needs to call the lexicon many times. then when
> the lexicon is called it re-construct the lexicon again. is there any way to
> construct the lexicon one time during the execution of the program? and then
> the other modules will search the already constructed lexicon.
>
> best regards
> Majdi
>
>
> Faculty of Engineering
> School of Computing
> University of Leeds
> Leeds, LS2 9JT
> UK
> http://www.comp.leeds.ac.uk/sawalha
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
You want an object with a global lifetime.  I often wish Python had a nice
equivalent to static variables in C.

Sometimes people suggest doing this with a function or method argument that
takes a default value that looks like it would be different each time the
function is called, but in reality, it's evaluated once when the
function/method is created.

EG:

$ cat t
#!/usr/local/cpython-2.7/bin/python

import time

def fn(x = time.time()):
print x

for i in xrange(5):
fn()
time.sleep(1)

benchbox-dstromberg:~/src/global-lifetime i486-pc-linux-gnu 13955 - above
cmd done 2010 Mon Aug 02 07:16 PM

$ ./t
1280801789.33
1280801789.33
1280801789.33
1280801789.33
1280801789.33
benchbox-dstromberg:~/src/global-lifetime i486-pc-linux-gnu 13955 - above
cmd done 2010 Mon Aug 02 07:16 PM

IOW, it's printing the same time each iteration, despite having a 10
millisecond precision and a 1 second sleep between each call.


BTW, for storing a truly large lexicon, you might be better off with a trie
than a dictionary (AKA hash table), though I'm sure some lexicons aren't
huge enough to require it.  One simple way of doing a trie would be to mkdir
an empty directory, and then for each ith subdirectory depth beneath that,
have it correspond to the ith character of your word in your lexicon.
 That's probably not a terribly efficient trie, but I think it may get the
point across - you're not storing common prefixes over and over.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 3 Aug, 02:47, Roy Smith  wrote:

> This one I don't understand.  Yes, I get RAII, but surely there are
> valid reasons to allocate memory outside of constructors.  Containers
> which resize themselves (such as std::vector) are one obvious example.

That is because an exception might skip an arbitrarily placed delete[]
or std::fclose when it rewinds the stack, so to avoid resource leaks
they must be places inside a destructor of an object on the stack
(which will be called).

This is unsafe, anyone who writes this in C++ should be flogged:

void foobar()
{
   std::FILE *fid = fopen("whatever");
   // some code here
   std::fclose(fid);
}


This idiom is safer :

struct File {
std::FILE *fid;
File(const char *name) {
// acquire resource in constructor
fid = std::fopen(name);
if (!fid) throw some_exception;
}
~File() {
// free resource in destructor
if(fid) std::flose(fid);
}
};

void foobar()
{
File file("whatever");
// some code here
}

It is for the very same reason we should use std::vector instead of
new[] for arrays. It is why new and delete should only be used inside
constructors/destructors. It also why C++ has references in addition
to pointers.

Which means this is bad in C++, as new and delete is arbitrarily
placed:

void foobar()
{
File *myfile = new File("whatever);
// some code here
delete myfile;
}

An object should go on the stack, because if an exception is thrown,
we need the destructor call. Which is why this (as shown above) is
ok:

void foobar()
{
File file("whatever");
// some code here
}

This is the kind of gotchas that allows C++ to shoot your leg off.

In comparison C is much more forgiving, because there is no exceptions
(unless you use setjmp/longjmp). This is ok in C, but not in C++:

void foobar()
{
   FILE *fid = fopen("whatever");
   // some code here
   fclose(fid);
}

For the same reason we can place malloc and free wherever we like in C
code. But in C++ we must restrict std::malloc and std::free (as well
as new and delete) to constructor and destructor pairs.

This kind of design is mandatory to make safe C++ programs. But it is
not enforced by the compiler. And since the majority of C++
programmers don't obey by these rules, Java and C# tends to produce
far less runtime errors and memory/resource leaks. And C++ textbooks
tends to avoid teaching these important details. I'm inclined to
believe it is because the authors don't understand it themselves.

Objects on the stack are also required for operator overloading in C+
+. A common novice mistake is this:

  std::vector *myvec = new std::vector(10);
  myvec[5] = 10.0; // why does the compiler complain?

And then the novice will spend hours contemplating why the stupid
compiler claims the type of myvec[5] is std::vector. There was
recently a post to the Cython mailing list claiming there is a bug in
Cython's auto-generated C++ because of this. But this is how it should
be:

  std::vector myvec(10);
  myvec[5] = 10.0; // ok

And now we see why C++ has references, as that is how we can
efficiently reference and object on the stack without getting the
operator overloading problem above.

C++ is good, but most programmers are better off with C. It has fewer
gotchas. And if we need OOP, we have Python...

Sturla














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


Re: Normalizing A Vector

2010-08-02 Thread Lawrence D'Oliveiro
In message <6dw5o.72330$ds3.63...@hurricane>, Bartc wrote:

> There's a cost involved in using those fancy constructions.

Sure. But at the point that starts to matter, you have to ask yourself why 
you’re not rewriting the CPU-intensive part in C.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Elementtree and XMLSchem instance type

2010-08-02 Thread Lawrence D'Oliveiro
In message
<6627204c-d0b1-456d-94bd-76d946ad2...@g6g2000pro.googlegroups.com>, Carl 
Banks wrote:

> On Aug 1, 5:43 pm, Lawrence D'Oliveiro 
> wrote:
>
>> In message
>> <96e47fd8-c939-48a2-9a2b-92afa720c...@k1g2000prl.googlegroups.com>, Carl
>> Banks wrote:
>>
>>> My general feeling is that ElementTree is a lot handier for reading
>>> and writing your own XML formats, than for handling XML files produced
>>> by other tools.
>>
>> Why is that? I’ve successfully used it to parse SVG files produced by
>> Inkscape .
> 
> I said it was not handy, not that is was not useful.

If you want to split hairs, I didn’t say it was “useful”, and I certainly 
found it very “handy” for that purpose.

> And you don't *have* to try to start an argument over every tiny thing
> you disagree with.

What else is USENET for? :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple integer subclass

2010-08-02 Thread Carl Banks
On Aug 2, 4:52 pm, Andreas Pfrengle  wrote:
> I'm trying to define a subclass of int called int1. An int1-object
> shall behave exactly like an int-object, with the only difference that
> the displayed value shall be value + 1 (it will be used to display
> array indices starting at 1 instead of 0). Right now I have:
>
> class int1(int):
>     def __str__(self):
>         return int.__str__(self + 1)
>
> However, if I calculate with int1 and int- (or other number) objects,
> the result is always coerced to an int (or other number object), e.g:
> a = int1(5)
> b = 5
> print a      # "6"
> print a+b  #"10"
>
> How can I tell int1 to be the "default integer object"? Do I need to
> overload *every* mathematical operation method of int, or is there an
> easier way?

(Preface: I normally don't offer recommendations without answering the
question as asked, but once in a while it has to be done.)

I **highly** recommend against this approach.

You are creating an object that differs from a built-in, int, in a
highly misleading way that only makes sense in a very limited context,
and this object's modified behavior gives no clue that it's been
modified in such as way.  (That is, it's not possible to tell if the
object's not a regular int just by looking at __str__()'s return
value.)  To make matters worse, you want to program this object to
coerce other integers, so there's a risk of these objects escaping
from the context where they make sense.

This is just a bad idea.  The type is not the place to implement
behavior that makes sense only in a limited context.  Instead, do
something like this:

print "Item %d is %s." % (i+1, s[i])


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


Re: Why is python not written in C++ ?

2010-08-02 Thread Roy Smith
In article , a...@pythoncraft.com (Aahz) 
wrote:

> http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html

The same story has been floating around for eons, just with the names 
changed.  I saw one where Wirth was ostensibly making fun of the people 
who didn't understand that Pascal was all just a joke.

I'm sure if you go back far enough, you can find a McCarthy / Lisp 
version.  It probably goes something like, "So, anyway, we tried to 
figure out what was the most absurd way to abuse punctuation we could 
imagine.  Somebody suggested that every program would have to end with 
37 close parentheses.  When we finally stopped laughing, we started 
sketching out a grammar on the chalkboard that would let us do that".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread samwyse
On Aug 2, 12:34 pm, John Nagle  wrote:
> The regular expression "split" behaves slightly differently than string
> split:

I'm going to argue that it's the string split that's behaving oddly.
To see why, let's first look at some simple CSV values:
cat,dog
,missing,,values,

How many fields are on each line and what are they?  Here's what
re.split(',') says:

>>> re.split(',', 'cat,dog')
['cat', 'dog']
>>> re.split(',', ',missing,,values,')
['', 'missing', '', 'values', '']

Note that the presence of missing values is clearly flagged via the
presence of empty strings in the results.  Now let's look at string
split:

>>> 'cat,dog'.split(',')
['cat', 'dog']
>>> ',missing,,values,'.split(',')
['', 'missing', '', 'values', '']

It's the same results.  Let's try it again, but replacing the commas
with spaces.

>>> re.split(' ', 'cat dog')
['cat', 'dog']
>>> re.split(' ', ' missing  values ')
['', 'missing', '', 'values', '']
>>> 'cat dog'.split(' ')
['cat', 'dog']
>>> ' missing  values '.split(' ')
['', 'missing', '', 'values', '']

It's the same results; however many people don't like these results
because they feel that whitespace occupies a privileged role.  People
generally agree that a string of consecutive commas means missing
values, but a string of consecutive spaces just means someone held the
space-bar down too long.  To accommodate this viewpoint, the string
split is special-cased to behave differently when None is passed as a
separator.  First, it splits on any number of whitespace characters,
like this:

>>> re.split('\s+', ' missing  values ')
['', 'missing', 'values', '']
>>> re.split('\s+', 'cat dog')
['cat', 'dog']

But it also eliminates any empty strings from the head and tail of the
list, because that's what people generally expect when splitting on
whitespace:

>>> 'cat dog'.split(None)
['cat', 'dog']
>>> ' missing  values '.split(None)
['missing', 'values']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Roy Smith
In article 
<0ed1fb16-87cb-4fb9-85b2-08d876445...@q22g2000yqm.googlegroups.com>,
 sturlamolden  wrote:

> The typical examples revealing incompetence are use of
> new[] instead of std::vector

To be fair, there were usable C++ compilers before there were usable STL 
implementations.  Thus, it should not be surprising to find older C++ 
code bases eschewing the use of STL.  That's not to say that this trend 
should be propagated in current educational material.

> and dynamic resourse allocation outside contructors.

This one I don't understand.  Yes, I get RAII, but surely there are 
valid reasons to allocate memory outside of constructors.  Containers 
which resize themselves (such as std::vector) are one obvious example.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Paul Rubin
sturlamolden  writes:
> It is annyingly verbose, reminds me of Pascal (I hate the looks of
> it), and is rumoured to produce slow bloatware. 

The earliest Ada compilers were terrible, but they are about like C
compilers now, so the output code is ok (see Alioth shootout for
example).  I agree about the verbosity but I don't think that's too big
a problem in the sorts of systems that need to be written in such
languages.

> And don't forget Ariane 5 ;)

I have looked into that a few times and I do wonder whether the language
or release process could have been of any help.  One possibility is
using something like SPARK to ensure the absence of overflow exceptions.
Another is automatic test generation something like

  http://www.stanford.edu/~engler/klee-osdi-2008.pdf 

but that approach was probably unknown at the time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple integer subclass

2010-08-02 Thread samwyse
On Aug 2, 6:52 pm, Andreas Pfrengle  wrote:
> I'm trying to define a subclass of int called int1. An int1-object
> shall behave exactly like an int-object, with the only difference that
> the displayed value shall be value + 1 (it will be used to display
> array indices starting at 1 instead of 0). Right now I have:
>
> class int1(int):
>     def __str__(self):
>         return int.__str__(self + 1)
>
> However, if I calculate with int1 and int- (or other number) objects,
> the result is always coerced to an int (or other number object), e.g:
> a = int1(5)
> b = 5
> print a      # "6"
> print a+b  #"10"
>
> How can I tell int1 to be the "default integer object"? Do I need to
> overload *every* mathematical operation method of int, or is there an
> easier way?

I had a similar problem a few years ago, and couldn't find a solution
then.  The thread from back then may shed some light on your problem.
http://groups.google.com/group/comp.lang.python/browse_thread/thread/10cfe2affc265ac/2ad03b121c1c6489
-- 
http://mail.python.org/mailman/listinfo/python-list


simple (I hope!) problem

2010-08-02 Thread samwyse
I'm writing for the Google app engine and have stubbed my toe yet
again on a simple obstacle.  Non-trivial app engines programs require
the import of several modules that aren't normally in my PYTHONPATH.
I'd like to be able to test my code outside of the app engine
framework.  I've tried several solutions in the past that worked but
weren't particularly elegant or portable.  Now I've had a new idea.
Here's my latest attempt:

import os, re
if __name__ == '__main__':
pass
else
from google.appengine.ext import webapp
register = webapp.template.create_template_register()

This works great, except my code makes use of the resister object in
several places, like this:

register.filter(emptylines)

Fortunately, I don't need the functionality of the object, I just want
something that won't generate an error when I use it.  So, what is the
quickest way to to create such an object (replacing the 'pass' in my
first snippet).  My solution is this:

class C:
def filter(self, *args, **kwds):
pass
register = C()

but it seems like I should be able to do something "better", as
measured by lines of code, faking more than just a 'filter' method, or
both.  Any ideas?  Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Peter
On Aug 3, 8:27 am, Paul Rubin  wrote:
...
>
> Certain folks in the functional-programming community consider OO to be
> a 1980's or 1990's approach that didn't work out, and that what it was
> really trying to supply was polymorphism.  C++ programs these days
> apparently tend to use template-based generics rather than objects and
> inheritance for that purpose.  
>
> I've never programmed in Ada but I'm intrigued by these articles:
>
>  http://adahome.com/Ammo/cpp2ada.html
>  http://www.adaic.org/whyada/ada-vs-c/cada_art.html
>
> I have the impression that Ada has an undeservedly bad rap because of
> its early implementations and its origins in military bureaucracy.  I'd
> certainly consider it as an alternative to C or C++ if I had to write a
> big program in a traditional procedural language.

I used to work for defence contractors - Ada (IMO :-)) is the very
best OO language for real-time and embedded systems. It scales
fantastically well to large, multi-platform jobs as well. If I had my
way we would use it where I work now (biomedical field) but that isn't
an option - too many folk are brought up on a steady diet of C/C++ and
therefore don't know any better, plus there is a dearth of Ada
compilers for the CPU's that we use here (all embedded work). I have
used fortran, C, C++, some Java, Ada (and Python :-)), if I had my
choice for the type of programming I do here at work, it would
definitely go to Ada by a country mile.

Having said that though, I won't replace Python with it on my desktop
for the type of stuff I do around the fringes of my job (test scripts
etc) and my personal programming :-)

But for anyone who wants to expand their horizons, learning Ada would
be an excellent choice (although like any learning activity, unless
you have a concrete goal in mind you will probably just waste your
time :-)). It is not an easy language to just pick up and run with
because the strong type-checking FORCES you to think about and design
your program very carefully from the very beginning - something that
many programmers find an abhorrence for :-) But I always used to tell
people - by the time I got a program to compile then I figured 99% of
the bugs were already discovered! Try that with C/C++ or almost any
other language you care to name :-)

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


calling a class method from a menu in a different class

2010-08-02 Thread Chris Hare

What I am trying to do is call a class function from a menu, for example

displaySubMenu.add_radiobutton(label="Medium", 
variable=radarPanelSize, command=radarWidgets.refresh) 

class radarWidgets:
def __init__(self,root):
self.window = root
def refresh(self):
global radar
global refreshTimer
self.refreshTimer.cancel()
logging.debug("handlesRadarRefreshByTimer()")
#
# destroy the existing frame the radar is in
#
self.w.destroy()
self.lblLastUpdate.destroy()
self.btnRefresh.destroy()
#
# rebuild the radarWidgets
#
self.createImage()
self.refreshTimer = threading.Timer( 900, self.refresh)
self.refreshTimer.start()

This doesn't work because the instance of radarWidgets was defined in a 
different class ..

class mainDisplay:
def __init__(self,root):
self.window = root
def show(self): 
#
# Configure the base frame
# 
base=Frame(self.window,bg=backColor,width=1200, height=800)
base.grid()
frameRadar = Frame(base, bd=0, bg=backColor)
frameRadar.grid(row=2,column=1,sticky=N+E+S+W)
#
radar = radarWidgets(frameRadar)
radar.show()

so the actual instance is called "radar".  If I put the instance name in the 
menu item, I get an error that "radar" is unknown.  If I use 
RadarWidgets.refresh ins the command for the menu, I get the error:

TypeError: unbound method refresh() must be called with radarWidgets instance 
as first argument (got nothing instead)

Any ideas?

Thanks!



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


Re: Why is python not written in C++ ?

2010-08-02 Thread Carey Tilden
On Mon, Aug 2, 2010 at 3:18 PM, sturlamolden  wrote:
>
> Perl is written in C++. That is not enough to make me want to use
> it ;)

I realize this was meant to be funny, but it's not true, and detracts
from the point you were trying to make.  Maybe skip the pointless jabs
at Perl and stick to things you know more about.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Christian Heimes
Am 03.08.2010 01:03, schrieb Aahz:
> http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html

I don't understand why the URL contains the word "joke". Every word is
true. Hell yeah! :)

Christian

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


simple integer subclass

2010-08-02 Thread Andreas Pfrengle
I'm trying to define a subclass of int called int1. An int1-object
shall behave exactly like an int-object, with the only difference that
the displayed value shall be value + 1 (it will be used to display
array indices starting at 1 instead of 0). Right now I have:

class int1(int):
def __str__(self):
return int.__str__(self + 1)

However, if I calculate with int1 and int- (or other number) objects,
the result is always coerced to an int (or other number object), e.g:
a = int1(5)
b = 5
print a  # "6"
print a+b  #"10"

How can I tell int1 to be the "default integer object"? Do I need to
overload *every* mathematical operation method of int, or is there an
easier way?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 3 Aug, 01:37, Mark Lawrence  wrote:

> A bug is a bug is a bug?

According to Grace Hopper, a bug might be a moth, in which case the
best debugger is a pair of forceps.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread MRAB

Mark Lawrence wrote:

On 02/08/2010 19:14, Benjamin Kaplan wrote:

On Mon, Aug 2, 2010 at 9:51 AM, David Robinow  wrote:


On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan
  wrote:

...
So these are the packages needed just to run Python in Ubuntu. It 
doesn't

include the packages required for the kernel, the desktop environment,

the

window manager, the terminal, and whatever else you want running. In my
fairly clean Ubuntu VM (I use it almost exclusively for testing), I 
have

close to 1500 packages installed.

  As an admittedly stupid comparison, I have 1579 DLLs in my
\windows\system32 directory.
Some number of these have been upgraded by Windows Update. This is XP
Service Pack 3.
I'm not sure if this means that Windows is better because it has more
packages or that it is worse because it's got too many. :)
  --



A package is usually more than one file.
http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist 





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





This is all very well, but what is the unladen airspeed velocity of a 
swallow in flight?  Answers on a postcard please, given that I expect 
both direction and speed!



African or European? :-)
--
http://mail.python.org/mailman/listinfo/python-list


Package management (was: Why is there no platform independent way of clearing a terminal?)

2010-08-02 Thread Ben Finney
Mark Lawrence  writes:

> How does any user or an admin cope with 500 packages?

Operating systems with good package management come with tools that help
the administrator do this job easily.

Also, operating systems with good package management encourage the
small-pieces-loosely-joined philosophy to apply to packages also: the
packages tend to be smaller and more focussed, and fit together in more
well-defined ways, than those on other OSen.

This isn't automatic, but the support of a good package management
system allows a robust policy to be implemented by the vendor for good
quality packages in the OS.

So “installing 500 packages” is not an unusual nor onerous thing to do
on such an OS. The job of making them all work well together is
delegated upstream, to one's distribution vendor. But the fact that
they're small pieces, loosely joined, means that if any one of them is
causing a problem, it's far more likely that a motivated administrator
can do something about it locally, rather than being at the mercy of the
vendor.

> Can Python help here, assume an eight hour working day?

Sadly, Python's package management is rather lacking by these standards.
The Distutils legacy assumption of “package recipient, system
administrator, and end user are all the same person”, among other design
decisions, makes it unusually difficult to have the necessary separation
of concerns between OS packaging, system administration, and end user.

There have been great strides in recent years to improve the Distutils
shortcomings (see the Distutils forum archives for the details), but the
changes are in part backward-incompatible, and it will be some time
before Python is on a par with, e.g., Perl in this area.

> So every working day you have 57.6 seconds to use each package.

Your mistaken assumption is that one would use these packages separate
from each other. That's like assuming that the limit of usefulness of
modules in a Python program is how much one can use each of them
separate from all the others.

In both cases, they're not used separately most of the time; they're
used in conjunction, and their distinction is more to enable the people
responsible for maintaining them to do so as distinct pieces when it
makes sense to do so, and as larger aggregate collections when that
makes sense.

OS packages are not only applications. They are any discrete, coherent
“piece” of an operating system; applications usually encompass one or
several packages, and most packages are not applications.

-- 
 \   “We must respect the other fellow's religion, but only in the |
  `\   sense and to the extent that we respect his theory that his |
_o__) wife is beautiful and his children smart.” —Henry L. Mencken |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Mark Lawrence

On 03/08/2010 00:14, Martin Gregorie wrote:

On Mon, 02 Aug 2010 15:54:52 -0700, sturlamolden wrote:


On 3 Aug, 00:27, Paul Rubin  wrote:


Certain folks in the functional-programming community consider OO to be
a 1980's or 1990's approach that didn't work out, and that what it was
really trying to supply was polymorphism.  C++ programs these days
apparently tend to use template-based generics rather than objects and
inheritance for that purpose.


It avoids virtual function calls at the expense of unreable code and
errors that are nearly impossible to trace. It seems many thinks this is
a good idea because Microsoft did this with ATL and WTL. There are also
those who thinks template metaprogramming is a good idea. But who uses a
C++ compiler to dumb to unroll a for loop? In my experience, trying to
outsmart a modern compiler is almost always a bad idea.


I have the impression that Ada has an undeservedly bad rap because of
its early implementations and its origins in military bureaucracy.


It is annyingly verbose, reminds me of Pascal (I hate the looks of it),
and is rumoured to produce slow bloatware.



And don't forget Ariane 5 ;)


This had nothing to do with Ada per se and everything to do with
shortcuts:

- re-use of an Ariane 4 component without changing its parameters
   to match the Ariane 5 flight profile
- not removing Ariane 4-only code intended to handle launch holds
   and not used at all in Ariane 5
- a programming fault that allowed an exception code to be sent
   to another component as if it was valid data.

Inadequate testing allowed all these to be flown without finding the
errors.

Bottom line: All this would still have happened regardless of the
programming language used. However, don't just listen to me: read the
final report on Ariane 501 here:

http://www.di.unito.it/~damiani/ariane5rep.html



A bug is a bug is a bug?

Except in my code.  Never written a bug in my life.  Cross my heart and 
hope to die.  Of course I'm lying. :)


Kindest regards.

Mark Lawrence.

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Mark Lawrence

On 03/08/2010 00:03, Aahz wrote:

In article,
Peter  wrote:

On Aug 3, 7:42=A0am, Mark Lawrence  wrote:

On 02/08/2010 00:08, candide wrote:

I can't understand why any serious programmer mentions C++. As soon as I
read it, I have to rush either to the kitchen to find a bowl to throw up
in, or head for the toilet so I can talk to the great white telephone.


With you there Mark - IMO C++ is an abortion that should never have
seen the light of day. The idea of experimenting with creating an OO
language by extending C wasn't such a bad idea for a "play thing" (by
Stroustrop) but the fact that it somehow escaped from the Lab and
people picked it up and ran with it on a commercial basis is just
plain wrong!


http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html


Haven't been able to read this properly as the stomach has been shaking 
too much to control the mouse and/or arrow keys/page up/down etc.  Hum, 
marks out of 10, 1.649072354865927**trillions.  For the cryptographers, 
is this a decent random number?


Kindest regards.

Mark Lawrence

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


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 3 Aug, 01:14, Martin Gregorie 
wrote:

> Bottom line: All this would still have happened regardless of the
> programming language used.

I am quite sure C and Fortran makes it unlikely for an unhandled
exception to trigger the autodestruct sequence. But it's nice to know
when flying that modern avionics is programmed in a language where
this is possible.

;)

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Martin Gregorie
On Mon, 02 Aug 2010 15:54:52 -0700, sturlamolden wrote:

> On 3 Aug, 00:27, Paul Rubin  wrote:
> 
>> Certain folks in the functional-programming community consider OO to be
>> a 1980's or 1990's approach that didn't work out, and that what it was
>> really trying to supply was polymorphism.  C++ programs these days
>> apparently tend to use template-based generics rather than objects and
>> inheritance for that purpose.
> 
> It avoids virtual function calls at the expense of unreable code and
> errors that are nearly impossible to trace. It seems many thinks this is
> a good idea because Microsoft did this with ATL and WTL. There are also
> those who thinks template metaprogramming is a good idea. But who uses a
> C++ compiler to dumb to unroll a for loop? In my experience, trying to
> outsmart a modern compiler is almost always a bad idea.
> 
>> I have the impression that Ada has an undeservedly bad rap because of
>> its early implementations and its origins in military bureaucracy.
> 
> It is annyingly verbose, reminds me of Pascal (I hate the looks of it),
> and is rumoured to produce slow bloatware. 

> And don't forget Ariane 5 ;)
> 
This had nothing to do with Ada per se and everything to do with 
shortcuts:

- re-use of an Ariane 4 component without changing its parameters
  to match the Ariane 5 flight profile
- not removing Ariane 4-only code intended to handle launch holds
  and not used at all in Ariane 5
- a programming fault that allowed an exception code to be sent
  to another component as if it was valid data.

Inadequate testing allowed all these to be flown without finding the 
errors.

Bottom line: All this would still have happened regardless of the 
programming language used. However, don't just listen to me: read the 
final report on Ariane 501 here: 

http://www.di.unito.it/~damiani/ariane5rep.html


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Aahz
In article ,
Peter   wrote:
>On Aug 3, 7:42=A0am, Mark Lawrence  wrote:
>> On 02/08/2010 00:08, candide wrote:
>>
>> I can't understand why any serious programmer mentions C++. As soon as I
>> read it, I have to rush either to the kitchen to find a bowl to throw up
>> in, or head for the toilet so I can talk to the great white telephone.
>
>With you there Mark - IMO C++ is an abortion that should never have
>seen the light of day. The idea of experimenting with creating an OO
>language by extending C wasn't such a bad idea for a "play thing" (by
>Stroustrop) but the fact that it somehow escaped from the Lab and
>people picked it up and ran with it on a commercial basis is just
>plain wrong!

http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Normal is what cuts off your sixth finger and your tail..."  --Siobhan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 3 Aug, 00:27, Paul Rubin  wrote:

> Certain folks in the functional-programming community consider OO to be
> a 1980's or 1990's approach that didn't work out, and that what it was
> really trying to supply was polymorphism.  C++ programs these days
> apparently tend to use template-based generics rather than objects and
> inheritance for that purpose.  

It avoids virtual function calls at the expense of unreable code and
errors that are nearly impossible to trace. It seems many thinks this
is a good idea because Microsoft did this with ATL and WTL. There are
also those who thinks template metaprogramming is a good idea. But who
uses a C++ compiler to dumb to unroll a for loop? In my experience,
trying to outsmart a modern compiler is almost always a bad idea.

> I have the impression that Ada has an undeservedly bad rap because of
> its early implementations and its origins in military bureaucracy.  

It is annyingly verbose, reminds me of Pascal (I hate the looks of
it), and is rumoured to produce slow bloatware. And don't forget
Ariane 5 ;)


> I'd
> certainly consider it as an alternative to C or C++ if I had to write a
> big program in a traditional procedural language.

I still prefer Fortran 95 :-)







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


Re: Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning

2010-08-02 Thread James Mills
On Tue, Aug 3, 2010 at 8:07 AM, ben owen  wrote:
> Hi everyone, I'm new to this and was needing help with trying to learn/work
> with Python 2.7 on my computer. I'm running Windows 7 and trying to learn
> python programming from an older book from 1999 by Mark Lutz and David
> Ascher my boss gave me, and for some reason none of my script/modules for
> the exercises are working on my comp. Mostly they give either a syntax error
> on the python command line or something about the file/module not being
> found on the windows command line. Also, does anyone where i can find/get
> something similar to the book for my own?

Start with the mighty fine Python tutorial on the
Python Documentation website (1)

cheers
James

1. http://docs.python.org/

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 2 Aug, 05:04, Tomasz Rola  wrote:

> And one should not forget about performance. C++ was for a long time
> behind C, and even now some parts (like iostreams) should be avoided in
> fast code.

For fast I/O one must use platform specific APIs, such as Windows' i/o
completion ports and memory mapping.

iostreams in C++ and stdio in C are ok for less demanding tasks.


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


Re: Why is python not written in C++ ?

2010-08-02 Thread Paul Rubin
Michael Torrie  writes:
> Sometimes, C++ is just the right tool for the job, despite all its
> warts  C++'s object semantics (guaranteed destruction, scoping,
> etc) can sometimes work very well when you need the speed of a
> compiled language, but don't want to be quite as low-level as C.
> 
> In this case, C++ is certainly not a better tool for the job than C.

The stuff C++ adds to C is a mix of good and bad, and it's reasonably
possible to use just the good stuff and ignore the bad.  At that point
you've got a pure improvement over C, although a lot of C's shortcomings
can't be papered over and still remain.

Certain folks in the functional-programming community consider OO to be
a 1980's or 1990's approach that didn't work out, and that what it was
really trying to supply was polymorphism.  C++ programs these days
apparently tend to use template-based generics rather than objects and
inheritance for that purpose.  

I've never programmed in Ada but I'm intrigued by these articles:

  http://adahome.com/Ammo/cpp2ada.html 
  http://www.adaic.org/whyada/ada-vs-c/cada_art.html

I have the impression that Ada has an undeservedly bad rap because of
its early implementations and its origins in military bureaucracy.  I'd
certainly consider it as an alternative to C or C++ if I had to write a
big program in a traditional procedural language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread sturlamolden
On 2 Aug, 01:08, candide  wrote:

> Has it ever been planned to rewrite in C++ the historical implementation
> (of course in an object oriented design) ?

OO programming is possible in C.  Just take a look at GNOME and GTK.

Perl is written in C++. That is not enough to make me want to use
it ;)

To be honest, C++ can be a great tool. But very few know how to use it
correctly. C++ textbooks are also written by people who don't
understand the language, and teach bad habits. The typical examples
revealing incompetence are use of new[] instead of std::vector, and
dynamic resourse allocation outside contructors.

C++ compilers used to be bloatware generators; C++ compilers of 2010
are not comparable to those of 1990. C++ is also a PITA for
portability. It is not sufficient for Python to only build with
Microsoft Visual Studio.








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


Trying to run Python 2.7 on Windows 7 and any suggestions on books/websites for "dummies guide to python" type learning

2010-08-02 Thread ben owen

Hi everyone, I'm new to this and was needing help with trying to learn/work 
with Python 2.7 on my computer. I'm running Windows 7 and trying to learn 
python programming from an older book from 1999 by Mark Lutz and David Ascher 
my boss gave me, and for some reason none of my script/modules for the 
exercises are working on my comp. Mostly they give either a syntax error on the 
python command line or something about the file/module not being found on the 
windows command line. Also, does anyone where i can find/get something similar 
to the book for my own?

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


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread Thomas Jollans
On 08/02/2010 11:22 PM, John Nagle wrote:
>> [ s in rexp.split(long_s) if s ]
> 
>Of course I can discard the blank strings afterward, but
> is there some way to do it in the "split" operation?  If
> not, then the default case for "split()" is too non-standard.
> 
>(Also, "if s" won't work;   if s != ''   might)

Of course it will work. Empty sequences are considered false in Python.

Python 3.1.2 (release31-maint, Jul  8 2010, 09:18:08)
[GCC 4.4.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> sprexp = re.compile(r'\s+')
>>> [s for s in sprexp.split('   spaces   every where !  ') if s]
['spaces', 'every', 'where', '!']
>>> list(filter(bool, sprexp.split('   more  spaces \r\n\t\t  ')))
['more', 'spaces']
>>>

(of course, the list comprehension I posted earlier was missing a couple
of words, which was very careless of me)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Michael Torrie
On 08/02/2010 03:42 PM, Mark Lawrence wrote:
> I can't understand why any serious programmer mentions C++. As soon as I 
> read it, I have to rush either to the kitchen to find a bowl to throw up 
> in, or head for the toilet so I can talk to the great white telephone.

Sometimes, C++ is just the right tool for the job, despite all its
warts.  For example, programming GTK apps with GTKmm in C++ is way more
pleasant than using C (but nowhere as pleasant as Python).  C++'s object
semantics (guaranteed destruction, scoping, etc) can sometimes work very
well when you need the speed of a compiled language, but don't want to
be quite as low-level as C.

In this case, C++ is certainly not a better tool for the job than C.
But plenty of serious programmers know how to leverage C++ and do so
quite successfully.  Just because C++ makes you ill in no way proves
that C++ is unfit for certain purposes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Peter
On Aug 3, 7:42 am, Mark Lawrence  wrote:
> On 02/08/2010 00:08, candide wrote:

>
> I can't understand why any serious programmer mentions C++. As soon as I
> read it, I have to rush either to the kitchen to find a bowl to throw up
> in, or head for the toilet so I can talk to the great white telephone.
>
> Kindest regards.
>
> Mark Lawrence.

With you there Mark - IMO C++ is an abortion that should never have
seen the light of day. The idea of experimenting with creating an OO
language by extending C wasn't such a bad idea for a "play thing" (by
Stroustrop) but the fact that it somehow escaped from the Lab and
people picked it up and ran with it on a commercial basis is just
plain wrong!

Personally I liken it to one of those genetically engineered diseases
they play around with in biological warfare labs - and unfortunately
this one escaped! It has probably set the computing industry back
untold years in terms of advancement...

Unfortunately I am forced to use it in my day to day life, but at the
end of every day I go home and use a purgative to get it out of my
system. But there are many deluded youngsters out there who just don't
seem to know any better, but then the signs of the breakdown of
society surround us on a daily basis and I guess C++ is just another
signpost on the way...

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


Re: how best to clear objects from a frame

2010-08-02 Thread Mark Lawrence

On 02/08/2010 04:13, rantingrick wrote:

On Aug 1, 7:12 pm, Chris Hare  wrote:

Here is the situation:

I have a window with a bunch of widgets in it.  I want to clear the objects in 
a given frame and recreate them to update them.


You need to check out the "w.update" and "w.update_idletasks" methods
available on all Tkinter widgets. Just FYI: to remove a widget from
view without destroying it use "w.pack_forget" or "w.grid_forget".
However if you are simply trying to refresh a widget use one of the
update methods.


I don't understand the technical content of this thread, but I'm very 
pleased to see rantingrick being positive, well done!!! :) I know that 
we've crossed swords in the past but believe that bygones should be 
bygones.  Can we call it quits and help to take Python forward?


Kindest regards.

Mark Lawrence.

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


Re: Why is python not written in C++ ?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 00:08, candide wrote:

Python is an object oriented langage (OOL). The Python main
implementation is written in pure and "old" C90. Is it for historical
reasons?

C is not an OOL and C++ strongly is. I wonder if it wouldn't be more
suitable to implement an OOL with another one.

Has it ever been planned to rewrite in C++ the historical implementation
(of course in an object oriented design) ?


I can't understand why any serious programmer mentions C++. As soon as I 
read it, I have to rush either to the kitchen to find a bowl to throw up 
in, or head for the toilet so I can talk to the great white telephone.


Kindest regards.

Mark Lawrence.

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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 19:14, Benjamin Kaplan wrote:

On Mon, Aug 2, 2010 at 9:51 AM, David Robinow  wrote:


On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan
  wrote:

...
So these are the packages needed just to run Python in Ubuntu. It doesn't
include the packages required for the kernel, the desktop environment,

the

window manager, the terminal, and whatever else you want running. In my
fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
close to 1500 packages installed.

  As an admittedly stupid comparison, I have 1579 DLLs in my
\windows\system32 directory.
Some number of these have been upgraded by Windows Update. This is XP
Service Pack 3.
I'm not sure if this means that Windows is better because it has more
packages or that it is worse because it's got too many. :)
  --



A package is usually more than one file.
http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist



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





This is all very well, but what is the unladen airspeed velocity of a 
swallow in flight?  Answers on a postcard please, given that I expect 
both direction and speed!


Kindest regards.

Mark Lawrence.

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


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread Benjamin Kaplan
On Mon, Aug 2, 2010 at 2:22 PM, John Nagle  wrote:

> On 8/2/2010 12:52 PM, Thomas Jollans wrote:
>
>> On 08/02/2010 09:41 PM, John Nagle wrote:
>>
>>> On 8/2/2010 11:02 AM, MRAB wrote:
>>>
 John Nagle wrote:

> The regular expression "split" behaves slightly differently than
> string split:
>
 occurrences of pattern", which is not too helpful.
>>>

> It's the plain str.split() which is unusual in that:

 1. it splits on sequences of whitespace instead of one per occurrence;

>>>
>>>That can be emulated with the obvious regular expression:
>>>
>>> re.compile(r'\W+')
>>>
>>> 2. it discards leading and trailing sequences of whitespace.

>>>
>>>But that can't, or at least I can't figure out how to do it.
>>>
>>
>> [ s in rexp.split(long_s) if s ]
>>
>
>   Of course I can discard the blank strings afterward, but
> is there some way to do it in the "split" operation?  If
> not, then the default case for "split()" is too non-standard.
>
>   (Also, "if s" won't work;   if s != ''   might)
>
>John Nagle
> --
>


What makes it non-standard? The fact that it's not a 1-line
regex? The default case for str.split is designed to handle the most common
case: you want to break a string into words, where a word is defined as a
sequence of non-whitespace characters.


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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 17:53, donn wrote:

On 02/08/2010 17:35, Mark Lawrence wrote:

aka the colon. :)

Ha. This is a case of the colon being the appendix!

\d

 Is there a better newsgroup in the world than c.l.py? No!

Kindest regards.

Mark Lawrence.

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


checking that process binds a port, fuser functionality

2010-08-02 Thread Zdenek Maxa
Hello,

I need to start a process (using subprocess.Popen()) and wait until the
new process either fails or successfully binds a specified port. The
fuser command seems to be indented exactly for this purpose. Could
anyone please provided a hint to a handy Python library to do this or
would the advice be to parse fuser command output?

This needs to happen on Linux and Python 2.4.

Thanks a lot in advance.

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


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread John Nagle

On 8/2/2010 12:52 PM, Thomas Jollans wrote:

On 08/02/2010 09:41 PM, John Nagle wrote:

On 8/2/2010 11:02 AM, MRAB wrote:

John Nagle wrote:

The regular expression "split" behaves slightly differently than
string split:

occurrences of pattern", which is not too helpful.



It's the plain str.split() which is unusual in that:

1. it splits on sequences of whitespace instead of one per occurrence;


That can be emulated with the obvious regular expression:

 re.compile(r'\W+')


2. it discards leading and trailing sequences of whitespace.


But that can't, or at least I can't figure out how to do it.


[ s in rexp.split(long_s) if s ]


   Of course I can discard the blank strings afterward, but
is there some way to do it in the "split" operation?  If
not, then the default case for "split()" is too non-standard.

   (Also, "if s" won't work;   if s != ''   might)

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


Re: let optionparse.Optionparser ignore unknown command line switches.

2010-08-02 Thread News123
On 08/01/2010 07:53 PM, Jon Clements wrote:
> On 1 Aug, 16:43, News123  wrote:
>> On 08/01/2010 05:34 PM, Steven W. Orr wrote:
>>
>>
>>
>>> On 08/01/10 07:27, quoth News123:
 On 08/01/2010 01:08 PM, News123 wrote:
> I wondered, whether there's a simple/standard way to let
> the Optionparser just ignore unknown command line switches.
>>
 In order to  illustrate, what I try to achieve:
>>
 import optparse
 parser = optparse.OptionParser()
 parser.add_option("-t","--test",dest="test",action="store_true")
 argv=["tst.py","-t","--ignoreme_and_dont_fail"]
 try:
 (options,args)=parser.parse_args(argv)
 except:
 # due to --ignoreme_and_dont_fail
 # I will end up here and neither options nor
 # args will be populated
 print "parser error:"
 # However I would love to be able to see here
 # that options.test is true despite the
 # error, that occurred afterwards
 print "T",options.test
>>
>> in my case one imported module should parse some of the options (but
>> only the one it understands) already during import.
>> the main program will have to parse the same options again.
> 
> Take it up a level.
> 
> Dedicate a module (called app_configuration) or something to do the
> option parsing -- everything the application can support is listed
> there... It's a bad idea to ignore invalid options...
Well the main application would abort the program. I'ts jsut one module
which would like to pre-fetch some options.
> 
> When that's imported it runs the parsing for sys.argv whatever... and
> you guarantee a variable called app_settings (or whatever) is present
> in that module.
> 
> Any module that needs the settings, just imports app_configuration and
> tries to take what it understands...
> 
> Would that work for you?
> 

It's not really what I'm looking for, though it might be what I'll end
up doing.

currently I have several apps all importing one module, but all parsing
different options.

There's one common option and I'd like to have one module behaving
differently depending on this option.

My idea was to just change this one module and leave everything else
unmodified.

Another not so nice solution, which could be a very quick and dirty hack
(to be removed lateron) would be to just add to this one module


if "--myoption" in sys.argv:
dosomething

but I'd have prefered a real Optionparser (ignoring unknown options)
I could even make sure, that the unknown options follow the common options.







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


Re: Trying to set a cookie within a python script

2010-08-02 Thread Thomas Jollans
On 08/02/2010 10:13 PM, Νίκος wrote:
> Hello, any ideas?!

That's no way to treat a friendly volunteer mailing list like this one!


On 08/02/2010 02:32 PM, Νίκος wrote:
> As for the encoding Notepad++, which is what i use for an editor say
> its UTF-8 without BOM.
> 
> Isn't this what i'm supposed to use?
> 
> My Python scripts only containes english and greek letters, so i
> though usign UTF-8 is the way to go. No?! Please if you explain to me
> in greater detail!

As I said, you have to tell the browser what you're up to.

Also, I just checked the link (shame on me), and you're not using UTF-8
at all. You're using some weird Windows-xyz or ISO-8859-xyz Greek
codepage from the previous millennium. (which obviously my browser
didn't know, it thought you were using ISO-8859-1, because that's what
my browser does, which you weren't)


So: tripple-check that

 * your file is 
 * Python knows that
 * the web browser knows that
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to set a cookie within a python script

2010-08-02 Thread Thomas Jollans
On 08/02/2010 04:20 AM, Νίκος wrote:
> Also my greek print appear in funny encoding although i do use # -*-
> coding: utf-8 -*-

That's because you never told the web browser which encoding you're using.

Content-Type: text/html; charset=UTF-8
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces, scoping and variables

2010-08-02 Thread rantingrick
On Aug 2, 3:12 pm, Chris Hare  wrote:
> Thanks to everyone for answering my question.  I think its clear now.  I'll 
> just go the "stuff 'em in a module and import that" route.

Chris, first of all i want you to know that this message is not meant
to offend but it may offend you -- hopefully your a rational person
and can deal with criticism.

This code is horrible. What are you trying to do exactly? Is this
purely academic or are you actually using this code for a real
purpose? The "Net" class looks like a dialog. Are you wishing to
create a dialog? If so, then you would be better off subclassing
tkSimpleDialog.Dialog instead of rolling your own. Please explain what
you are trying to do from a users perspective so we can properly guide
you.

Also you should use 4 space indention and never use tabs. This is the
accepted way. Although Python does allow freedom i would suggest that
coding in a uniformly accepted manner is more productive for the
entire community. Google "Python Style Guide" for more info.

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


Re: how best to clear objects from a frame

2010-08-02 Thread Chris Hare

On Aug 1, 2010, at 10:13 PM, rantingrick wrote:

> On Aug 1, 7:12 pm, Chris Hare  wrote:
>> Here is the situation:
>> 
>> I have a window with a bunch of widgets in it.  I want to clear the objects 
>> in a given frame and recreate them to update them.  
> 
> You need to check out the "w.update" and "w.update_idletasks" methods
> available on all Tkinter widgets. Just FYI: to remove a widget from
> view without destroying it use "w.pack_forget" or "w.grid_forget".
> However if you are simply trying to refresh a widget use one of the
> update methods.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I will have a look at those.  Consider a frame with a label and a button.  How 
do I address the label to change it from another function in the class?  

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


Re: Trying to set a cookie within a python script

2010-08-02 Thread Νίκος
Hello, any ideas?!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces, scoping and variables

2010-08-02 Thread Chris Hare
Thanks to everyone for answering my question.  I think its clear now.  I'll 
just go the "stuff 'em in a module and import that" route.

Chris

On Aug 2, 2010, at 3:03 PM, MRAB wrote:

> Chris Hare wrote:
>> I am having a problem getting around this variable namespace thing.
>> Consider these code bits
>> File a.py
>> from Tkinter import *
>> import a1
>> def doAgain():
>>  x = a1.Net()
>>  x.show("Again!")
>> root = Tk()
>> root.title("test")
>> f = Frame(root,bg="Yellow")
>> l = Button(root,text="window 1",command=doAgain)
>> f.grid()
>> l.grid()
>> a = 5
>> x = a1.Net()
>> x.show("window 2")
>> if __name__ == "__main__":
>>  root.mainloop()
>> File a1.py
>> from Tkinter import *
>> class Net:
>>  def __init__(self):
>>  self.window = Toplevel()
>>  def show(self,t):   
>>  self.l = Label(self.window,text=t)
>>  self.l.grid()
>>button = Button(self.window, text="Again")
>>  button.bind("", self.Again)
>>button2 = Button(self.window, text="Dismiss")
>>  button2.bind("", self.hide)
>>  button.grid()
>>  button2.grid()
>>  def Again(self,event):
>>  x = Net()
>>  x.show(a)
>>  def hide(self,event):
>>  self.window.destroy()
>> When I run a.py, it imports a1.py and click on the Again button, I get the 
>> error
>> Exception in Tkinter callback
>> Traceback (most recent call last):
>>  File 
>> "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
>>  line 1410, in __call__
>>return self.func(*args)
>>  File "/Volumes/Development/py/a1.py", line 17, in Again
>>x.show(a)
>> NameError: global name 'a' is not defined
>> I believe this is the expected behavior.  so my question is this -- how do I 
>> tell the code in a1.py about the variable a, which exists in a.py?  Do I 
>> have to pass it as part of the function call, or what?  using
>> global a
>> in a1.py doesn't change anything.
>> since I am using SQLite for the disk database, I was thinking I could keep 
>> all the "global" variables in an in memory database and just access them 
>> when I need to, but other ideas are welcome.
> Why in a database? If you need the modules to share it then you could
> put it in a shared module and refer to it there:
> 
> File a.py
> -
> import my_globals
> ...
> my_globals.a = 5
> 
> 
> File a1.py
> --
> import my_globals
> ...
>   x.show(my_globals.a)
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: namespaces, scoping and variables

2010-08-02 Thread Ethan Furman

Chris Hare wrote:

I am having a problem getting around this variable namespace thing.

Consider these code bits

File a.py
from Tkinter import *
import a1

def doAgain():
x = a1.Net()
x.show("Again!")

root = Tk()
root.title("test")
f = Frame(root,bg="Yellow")
l = Button(root,text="window 1",command=doAgain)
f.grid()
l.grid()
a = 5
x = a1.Net()
x.show("window 2")
if __name__ == "__main__":
root.mainloop()

File a1.py
from Tkinter import *

class Net:
def __init__(self):
self.window = Toplevel()
def show(self,t):   
self.l = Label(self.window,text=t)
self.l.grid()
button = Button(self.window, text="Again")
button.bind("", self.Again)
button2 = Button(self.window, text="Dismiss")
button2.bind("", self.hide)
button.grid()
button2.grid()
def Again(self,event):
x = Net()
x.show(a)
def hide(self,event):
self.window.destroy()


When I run a.py, it imports a1.py and click on the Again button, I get the error

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1410, in __call__
return self.func(*args)
  File "/Volumes/Development/py/a1.py", line 17, in Again
x.show(a)
NameError: global name 'a' is not defined

I believe this is the expected behavior.  so my question is this -- how do I 
tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
to pass it as part of the function call, or what?  using

global a

in a1.py doesn't change anything.


The global keyword does not make a variable global.  It tells the 
interpreter that the variable in question can be find in the module 
scope, not the function/method scope.  In other words, the variable is 
global to the module, but not to the whole program.


What you'll need to do is pass a into Net when you instanciate it, like 
so (untested):


  def doAgain():
  x = a1.Net(a)
  x.show("Again!")

and in Net:

class Net:
def __init__(self, some_number):
self.some_number = some_number
self.window = Toplevel()
.
.
.
def Again(self,event):
x = Net(self.some_number)
x.show()

Keep in mind, though, that if you change a in a.py after you've 
instanciated Net, your Net instance will not see the change.  For the 
change to show up, a would need to be mutable, and you would have to 
mutate it.  The other option is to change the Net instance's some_number 
directly (i.e. x.some_number = 9).


Hope this helps.

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


Re: namespaces, scoping and variables

2010-08-02 Thread MRAB

Chris Hare wrote:

I am having a problem getting around this variable namespace thing.

Consider these code bits

File a.py
from Tkinter import *
import a1

def doAgain():
x = a1.Net()
x.show("Again!")

root = Tk()
root.title("test")
f = Frame(root,bg="Yellow")
l = Button(root,text="window 1",command=doAgain)
f.grid()
l.grid()
a = 5
x = a1.Net()
x.show("window 2")
if __name__ == "__main__":
root.mainloop()

File a1.py
from Tkinter import *

class Net:
def __init__(self):
self.window = Toplevel()
def show(self,t):   
self.l = Label(self.window,text=t)
self.l.grid()
button = Button(self.window, text="Again")
button.bind("", self.Again)
button2 = Button(self.window, text="Dismiss")
button2.bind("", self.hide)
button.grid()
button2.grid()
def Again(self,event):
x = Net()
x.show(a)
def hide(self,event):
self.window.destroy()


When I run a.py, it imports a1.py and click on the Again button, I get the error

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1410, in __call__
return self.func(*args)
  File "/Volumes/Development/py/a1.py", line 17, in Again
x.show(a)
NameError: global name 'a' is not defined

I believe this is the expected behavior.  so my question is this -- how do I 
tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
to pass it as part of the function call, or what?  using

global a

in a1.py doesn't change anything.

since I am using SQLite for the disk database, I was thinking I could keep all the 
"global" variables in an in memory database and just access them when I need 
to, but other ideas are welcome.


Why in a database? If you need the modules to share it then you could
put it in a shared module and refer to it there:

File a.py
-
import my_globals
...
my_globals.a = 5


File a1.py
--
import my_globals
...
x.show(my_globals.a)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Mithrandir
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 08/01/2010 07:34 PM, Albert Hopkins wrote:
> On Mon, 2010-08-02 at 01:08 +0200, candide wrote:
>> Python is an object oriented langage (OOL). The Python main 
>> implementation is written in pure and "old" C90. Is it for historical 
>> reasons?
>>
>> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more 
>> suitable to implement an OOL with another one.
>>
>> Has it ever been planned to rewrite in C++ the historical implementation 
>> (of course in an object oriented design) ?
> 
> Disclaimer: I am neither a C nor C++ programmer.  In fact I can barely
> even program in Python ;-)
> 
> I would propose that in fact most programming languages are implemented
> in C.  Sun's (Oracle's) Java compiler and runtime are written in ANSI C.
> The core of the Gnu Compiler Collection (which includes C++ and
> Objective-C compilers) is written in C.  The official Ruby is
> implemented in C. The Squeak Smalltalk implementation uses C instead of
> C++.  I can't even think of a programming language that is implemented
> in C++ (maybe C++ is).
> 
> C seems to be a good, portable language for writing interpreters and
> compilers.
> 
> But I wonder if someone has/has tried to write a programming language in
> C++ and what were their experiences.
> 

(Sorry if this is a double post, but apparently my last one didn't go
through.)

I know that LOLCode has a .NET implementation (1), although it's "very
much alpha."  And someone was apparently working on a C++ only
implementation of LOLCode (2), although that was 3 years ago.

LOLCode itself is very much alpha anyway and development seems to be
very slow (or dead.)

Python has a way of extending it's modules with C or C++ (3).

1: http://lolcode.com/implementations/lolcode.net
2: http://forum.lolcode.com/viewtopic.php?id=14
3: http://docs.python.org/release/2.5.2/ext/intro.html

- -- 
People should read more.
https://secure.wikimedia.org/wikipedia/en/wiki/User:MithrandirAgain
"All that is gold does not glitter,
not all those who wander are lost;
the old that is strong does not wither,
deep roots are not reached by the frost.
- From the ashes a fire shall be woken,
a light from the shadows shall spring;
renewed shall be blade that was broken,
the crownless again shall be king."
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.10 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJMVyNqAAoJEKo37V1xH7gTeOUH/2/KYc4busZbATSB09ZUgW+v
BmydxDTZaPQd0B56JWSeUiz0/kZrufdDrVc3XUTNNF2oa8ExW51IgsaZOxn2UJGv
ydplycT1axs5hrzDG72v2Oo7/poPDxSsvpF58dBsb0XSI25I+orHKrTQpwvKz9cf
x6nzahUoygTbaVqZUyxCW2Tc7Rv4T2gpskssD8sIYqaRNofNnPbf3h3NA+q4LMkR
+F2UF3r1RE1jwJhs6RNAvUJBdLrHkA3isRsjQE38l6AioLdeTs2yrRtc+6xUkAig
RxR11qLZl5OOer/Jrmg1My0+ZTYGnIcAfChxPh1YnHuYbp+H7doqLjlKIkoXZms=
=F9Ou
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespaces, scoping and variables

2010-08-02 Thread Dave Angel

Chris Hare wrote:

I am having a problem getting around this variable namespace thing.

Consider these code bits

File a.py
from Tkinter import *
import a1

def doAgain():
x =1.Net()
x.show("Again!")

root =k()
root.title("test")
f =rame(root,bg="Yellow")
l =utton(root,text="window 1",command=doAgain)
f.grid()
l.grid()
a =
x =1.Net()
x.show("window 2")
if __name__ ="__main__":
root.mainloop()

File a1.py
from Tkinter import *

class Net:
def __init__(self):
self.window =oplevel()
def show(self,t):   
self.l =abel(self.window,text=t)
self.l.grid()
button =utton(self.window, text="Again")
button.bind("", self.Again)
button2 =utton(self.window, text="Dismiss")
button2.bind("", self.hide)
button.grid()
button2.grid()
def Again(self,event):
x =et()
x.show(a)
def hide(self,event):
self.window.destroy()


When I run a.py, it imports a1.py and click on the Again button, I get the error

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1410, in __call__
return self.func(*args)
  File "/Volumes/Development/py/a1.py", line 17, in Again
x.show(a)
NameError: global name 'a' is not defined

I believe this is the expected behavior.  so my question is this -- how do I 
tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
to pass it as part of the function call, or what?  using

global a

in a1.py doesn't change anything.

since I am using SQLite for the disk database, I was thinking I could keep all the 
"global" variables in an in memory database and just access them when I need 
to, but other ideas are welcome.

Thanks,
Chris


  
First rule is never have circular referencing between modules.  In other 
words, since a.py imports a1.py, a.py can refer to things in a1.py, but 
never the other way around.  Any time you need to look backwards, find 
another means.


One approach is to create another module c.py as a container to hold 
those things that both a and a1 need.  That way they both import c, and 
there's no problem.


Another approach is to pass the global from a.py into a1.py, and use it 
that way.


And since you only have these two modules, you could just define it in 
a1.py, and reference it from a.py as

  a1.a

I would point out that using the same name for a module and a global 
variable is bad practice.  it certainly makes it hard to describe in 
this case.


HTH,
DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread Thomas Jollans
On 08/02/2010 09:41 PM, John Nagle wrote:
> On 8/2/2010 11:02 AM, MRAB wrote:
>> John Nagle wrote:
>>> The regular expression "split" behaves slightly differently than
>>> string split:
> occurrences of pattern", which is not too helpful.
>>>
>> It's the plain str.split() which is unusual in that:
>>
>> 1. it splits on sequences of whitespace instead of one per occurrence;
> 
>That can be emulated with the obvious regular expression:
> 
> re.compile(r'\W+')
> 
>> 2. it discards leading and trailing sequences of whitespace.
> 
>But that can't, or at least I can't figure out how to do it.

[ s in rexp.split(long_s) if s ]

> 
>> It just happens that the unusual one is the most commonly used one, if
>> you see what I mean! :-)
> 
>The no-argument form of "split" shouldn't be that much of a special
> case.
> 
> John Nagle
> 

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


Re: namespaces, scoping and variables

2010-08-02 Thread Thomas Jollans
On 08/02/2010 09:33 PM, Chris Hare wrote:
> I am having a problem getting around this variable namespace thing.
> 
> Consider these code bits
> 
> File a.py
> from Tkinter import *
> import a1
> 
> def doAgain():
>   x = a1.Net()
>   x.show("Again!")
> 
> root = Tk()
> root.title("test")
> f = Frame(root,bg="Yellow")
> l = Button(root,text="window 1",command=doAgain)
> f.grid()
> l.grid()
> a = 5
> x = a1.Net()
> x.show("window 2")
> if __name__ == "__main__":
>   root.mainloop()
> 
> File a1.py
> from Tkinter import *
> 
> class Net:
>   def __init__(self):
>   self.window = Toplevel()
>   def show(self,t):   
>   self.l = Label(self.window,text=t)
>   self.l.grid()
> button = Button(self.window, text="Again")
>   button.bind("", self.Again)
> button2 = Button(self.window, text="Dismiss")
>   button2.bind("", self.hide)
>   button.grid()
>   button2.grid()
>   def Again(self,event):
>   x = Net()
>   x.show(a)
>   def hide(self,event):
>   self.window.destroy()
> 
> 
> When I run a.py, it imports a1.py and click on the Again button, I get the 
> error
> 
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File 
> "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
>  line 1410, in __call__
> return self.func(*args)
>   File "/Volumes/Development/py/a1.py", line 17, in Again
> x.show(a)
> NameError: global name 'a' is not defined
> 
> I believe this is the expected behavior.  so my question is this -- how do I 
> tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
> to pass it as part of the function call, or what?  using
> 
> global a
> 
> in a1.py doesn't change anything.
> 
> since I am using SQLite for the disk database, I was thinking I could keep 
> all the "global" variables in an in memory database and just access them when 
> I need to, but other ideas are welcome.

"global" in Python isn't the same as "global" in C, or in PHP.

"Global" is, in essence, a shorter way of saying "within the scope of
this module" -- which keeps the "global" nice and clean.

You should probably just pass in the object you call "a" when creating
the object that uses it, or when calling the function/method when
calling it. If you don't want to do that, you can simply import the
module where your global data is stored -- beware of "from XYZ import
...", though - that copies the variables, and won't do you much good here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread John Nagle

On 8/2/2010 11:02 AM, MRAB wrote:

John Nagle wrote:

The regular expression "split" behaves slightly differently than
string split:

occurrences of pattern", which is not too helpful.



It's the plain str.split() which is unusual in that:

1. it splits on sequences of whitespace instead of one per occurrence;


   That can be emulated with the obvious regular expression:

re.compile(r'\W+')


2. it discards leading and trailing sequences of whitespace.


   But that can't, or at least I can't figure out how to do it.


It just happens that the unusual one is the most commonly used one, if
you see what I mean! :-)


   The no-argument form of "split" shouldn't be that much of a special
case.

John Nagle

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


namespaces, scoping and variables

2010-08-02 Thread Chris Hare
I am having a problem getting around this variable namespace thing.

Consider these code bits

File a.py
from Tkinter import *
import a1

def doAgain():
x = a1.Net()
x.show("Again!")

root = Tk()
root.title("test")
f = Frame(root,bg="Yellow")
l = Button(root,text="window 1",command=doAgain)
f.grid()
l.grid()
a = 5
x = a1.Net()
x.show("window 2")
if __name__ == "__main__":
root.mainloop()

File a1.py
from Tkinter import *

class Net:
def __init__(self):
self.window = Toplevel()
def show(self,t):   
self.l = Label(self.window,text=t)
self.l.grid()
button = Button(self.window, text="Again")
button.bind("", self.Again)
button2 = Button(self.window, text="Dismiss")
button2.bind("", self.hide)
button.grid()
button2.grid()
def Again(self,event):
x = Net()
x.show(a)
def hide(self,event):
self.window.destroy()


When I run a.py, it imports a1.py and click on the Again button, I get the error

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1410, in __call__
return self.func(*args)
  File "/Volumes/Development/py/a1.py", line 17, in Again
x.show(a)
NameError: global name 'a' is not defined

I believe this is the expected behavior.  so my question is this -- how do I 
tell the code in a1.py about the variable a, which exists in a.py?  Do I have 
to pass it as part of the function call, or what?  using

global a

in a1.py doesn't change anything.

since I am using SQLite for the disk database, I was thinking I could keep all 
the "global" variables in an in memory database and just access them when I 
need to, but other ideas are welcome.

Thanks,
Chris

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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Benjamin Kaplan
On Mon, Aug 2, 2010 at 9:51 AM, David Robinow  wrote:

> On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan
>  wrote:
> >...
> > So these are the packages needed just to run Python in Ubuntu. It doesn't
> > include the packages required for the kernel, the desktop environment,
> the
> > window manager, the terminal, and whatever else you want running. In my
> > fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
> > close to 1500 packages installed.
>  As an admittedly stupid comparison, I have 1579 DLLs in my
> \windows\system32 directory.
> Some number of these have been upgraded by Windows Update. This is XP
> Service Pack 3.
> I'm not sure if this means that Windows is better because it has more
> packages or that it is worse because it's got too many. :)
>  --
>

A package is usually more than one file.
http://packages.ubuntu.com/lucid/amd64/linux-image-2.6.32-21-generic/filelist


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


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread Peter Otten
John Nagle wrote:

> The regular string split operation doesn't yield empty strings:
> 
> >>> "   HELLO   THERE ".split()
> ['HELLO', 'THERE']

Note that invocation without separator argument (or None as the separator) 
is special in that respect:

>>> " hello there ".split(" ")
['', 'hello', 'there', '']

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


Re: Behavior of re.split on empty strings is unexpected

2010-08-02 Thread MRAB

John Nagle wrote:
The regular expression "split" behaves slightly differently than string 
split:


 >>> import re
 >>> kresplit = re.compile(r'[^\w\&]+',re.UNICODE)   


 >>> kresplit2.split("   HELLOTHERE   ")
['', 'HELLO', 'THERE', '']

 >>> kresplit2.split("VERISIGN INC.")
['VERISIGN', 'INC', '']

I'd thought that "split" would never produce an empty string, but
it will.

The regular string split operation doesn't yield empty strings:

 >>> "   HELLO   THERE ".split()
['HELLO', 'THERE']


Yes it does.

>>> "   HELLOTHERE   ".split(" ")
['', '', '', 'HELLO', '', '', '', 'THERE', '', '', '']


If I try to get the functionality of string split with re:

 >>> s2 = "   HELLO   THERE  "
 >>> kresplit4 = re.compile(r'\W+', re.UNICODE)
 >>> kresplit4.split(s2)
['', 'HELLO', 'THERE', '']

I still get empty strings.

The documentation just describes re.split as "Split string by the 
occurrences of pattern", which is not too helpful.



It's the plain str.split() which is unusual in that:

1. it splits on sequences of whitespace instead of one per occurrence;

2. it discards leading and trailing sequences of whitespace.

Compare:

>>> "  A  B  ".split(" ")
['', '', 'A', '', 'B', '', '']

with:

>>> "  A  B  ".split()
['A', 'B']

It just happens that the unusual one is the most commonly used one, if
you see what I mean! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: constructing and using large lexicon in a program

2010-08-02 Thread Michael Torrie
On 08/02/2010 11:46 AM, Majdi Sawalha wrote:
> I am developing a morphological analyzer that depends on a large lexicon. i 
> construct a Lexicon class that reades a text file and construct a dictionary 
> of 
> the lexicon entries. 
> the other class will use the lexicon class to chech if the word is found in 
> the 
> lexicon. the problem that this takes long time as each time an object of that 
> class created, then it needs to call the lexicon many times. then when the 
> lexicon is called it re-construct the lexicon again. is there any way to 
> construct the lexicon one time during the execution of the program? and then 
> the 
> other modules will search the already constructed lexicon.

Can you not create a module that, upon import, initializes this lexicon
as a module attribute?  Modules are by definition singleton objects,
which is the pattern that you probably need.  Any other module could
import this module and get the already-created lexicon object.
-- 
http://mail.python.org/mailman/listinfo/python-list


constructing and using large lexicon in a program

2010-08-02 Thread Majdi Sawalha
Dear List members,

I am developing a morphological analyzer that depends on a large lexicon. i 
construct a Lexicon class that reades a text file and construct a dictionary of 
the lexicon entries. 
the other class will use the lexicon class to chech if the word is found in the 
lexicon. the problem that this takes long time as each time an object of that 
class created, then it needs to call the lexicon many times. then when the 
lexicon is called it re-construct the lexicon again. is there any way to 
construct the lexicon one time during the execution of the program? and then 
the 
other modules will search the already constructed lexicon.

best regards
Majdi
 
Faculty of Engineering
School of Computing
University of Leeds
Leeds, LS2 9JT
UK
http://www.comp.leeds.ac.uk/sawalha 


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


Behavior of re.split on empty strings is unexpected

2010-08-02 Thread John Nagle
The regular expression "split" behaves slightly differently than string 
split:


>>> import re
>>> kresplit = re.compile(r'[^\w\&]+',re.UNICODE)  

>>> kresplit2.split("   HELLOTHERE   ")
['', 'HELLO', 'THERE', '']

>>> kresplit2.split("VERISIGN INC.")
['VERISIGN', 'INC', '']

I'd thought that "split" would never produce an empty string, but
it will.

The regular string split operation doesn't yield empty strings:

>>> "   HELLO   THERE ".split()
['HELLO', 'THERE']

If I try to get the functionality of string split with re:

>>> s2 = "   HELLO   THERE  "
>>> kresplit4 = re.compile(r'\W+', re.UNICODE)
>>> kresplit4.split(s2)
['', 'HELLO', 'THERE', '']

I still get empty strings.

The documentation just describes re.split as "Split string by the 
occurrences of pattern", which is not too helpful.


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


Re: Merging two dictionaries

2010-08-02 Thread Paul Rubin
Douglas Garstang  writes:
> where line 42 is 'assert type(default(k))==dict', and the inputs are:

Woops, cut and paste error.  default(k) should say default[k].  Or you
could remove the assertion altogether.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accumulate function in python

2010-08-02 Thread Aahz
In article <7xpqyjgvjm@ruckus.brouhaha.com>,
Paul Rubin   wrote:
>
>I think Peter Otten's solution involving a generator is the one most in
>the current Python spirit.  It's cleaner (for my tastes) than the ones
>that use things like list.append.

Agreed
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"Normal is what cuts off your sixth finger and your tail..."  --Siobhan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run subprocesses in parallel

2010-08-02 Thread Nobody
On Mon, 02 Aug 2010 14:21:38 +0200, Christian Heimes wrote:

> You might want to drop shell=True and use
> a list as arguments instead.

The two issues (whether "shell" is True/False and whether the command is
a list or string) are orthogonal.

You should always use a list for the command, unless you are given a
string (e.g. by the user) which must be executed verbatim.

> The shell=True argument is frowned upon and
> should only be used if your really, really need a shell.

It's the use of a string (rather than a list) for the command which is
particularly frowned upon, as this tends to be error prone if any of the
arguments contain characters which are significant to the shell (most
commonly spaces, although other characters are also problematic).

On Unix, using a list for the command effectively necessitates that
shell=False (if you use a list with shell=True, the first element in the
list is executed as the command, with any remaining elements used to
initialise $1, $2, etc).

On Windows, the list is converted to a string in the same way regardless
of whether shell is True or False. The shell parameter determines whether
the string is passed directly to CreateProcess or whether it has
"%COMSPEC% /c " prepended to it. If shell is False, the first element in
the list (the program) must refer to a binary executable and include the
.exe (etc) extension. If shell is True, the program can be a batch file,
Python script, etc, and will be executed according to its extension.

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


Re: Merging two dictionaries

2010-08-02 Thread Douglas Garstang
On Mon, Aug 2, 2010 at 1:09 AM, Peter Otten <__pete...@web.de> wrote:
> Douglas Garstang wrote:
>
>> I have the two dictionaries below. How can I merge them, such that:
>>
>> 1. The cluster dictionary contains the additional elements from the
>> default dictionary.
>> 2. Nothing is removed from the cluster dictionary.
>
> def inplace_merge(default, cluster):
>    assert isinstance(default, dict)
>    assert isinstance(cluster, dict)
>
>    d = set(default)
>    c = set(cluster)
>    default_only = d - c
>    both = d & c
>    for key in both:
>        dv = default[key]
>        cv = cluster[key]
>        if isinstance(cv, dict):
>            inplace_merge(dv, cv)
>    cluster.update((dk, default[dk]) for dk in default_only)
>
> should work once you've fixed your example dicts.
>
> Peter
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Wooo! I think that did it!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread donn

On 02/08/2010 17:35, Mark Lawrence wrote:

aka the colon. :)

Ha. This is a case of the colon being the appendix!

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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread David Robinow
On Mon, Aug 2, 2010 at 11:41 AM, Benjamin Kaplan
 wrote:
>...
> So these are the packages needed just to run Python in Ubuntu. It doesn't
> include the packages required for the kernel, the desktop environment, the
> window manager, the terminal, and whatever else you want running. In my
> fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
> close to 1500 packages installed.
 As an admittedly stupid comparison, I have 1579 DLLs in my
\windows\system32 directory.
Some number of these have been upgraded by Windows Update. This is XP
Service Pack 3.
I'm not sure if this means that Windows is better because it has more
packages or that it is worse because it's got too many. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Merging two dictionaries

2010-08-02 Thread Peter Otten
Douglas Garstang wrote:

> On Mon, Aug 2, 2010 at 12:47 AM, Paul Rubin  
wrote:

>> If yes, then the following works for me:
>>
>>def merge(cluster, default):
>># destructively merge default into cluster
>>for k,v in cluster.iteritems():
>>if k in default and type(v)==dict:
>>assert type(default(k))==dict
>>merge(v,default[k])
>>for k,v in default.iteritems():
>>if k not in cluster:
>>cluster[k] = v
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> 
> Hmmm, using that gives me:
> 
> Traceback (most recent call last):
>   File "./test4.py", line 48, in ?
> merge(cluster, default)
>   File "./test4.py", line 42, in merge
> assert type(default(k))==dict
> TypeError: 'dict' object is not callable
> 
> where line 42 is 'assert type(default(k))==dict', and the inputs are:

Not making an attempt to understand the code that you are about to use?

default(k) 

should be

default[k]

Peter

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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Ethan Furman

Steven D'Aprano wrote:

On Sat, 31 Jul 2010 13:29:25 +, Brian Victor wrote:


Steven D'Aprano wrote:

On Sat, 31 Jul 2010 14:25:39 +1200, Gregory Ewing wrote:


Steven D'Aprano wrote:


  A
 / \
C   B
 \ /
  D
 / \
E   F

Yes, a super call might jog left from C to B, but only when being
called from one of the lower classes D-F. That's still an upwards
call relative to the originator, not sidewards.

But it's not an upward call relative to the class mentioned in the
super() call, which is why I say it's misleading.

Which class would that be?

I think I'm going to need an example that demonstrates what you mean,
because I can't make heads or tails of it. Are you suggesting that a
call to super(C, self).method() from within C might call
B.method(self)?

Yes, it would.

[snip example]

Right, now I see what you mean. I don't have a problem with that 
behaviour, it is the correct behaviour, and you are making the call from 
D in the first place, so it *must* call B at some point.


If you initiate the call from C instead:

[snip]

I think the point is that when D initiates the  super() chain, and C 
calls super, B will then get its turn -- which has to seem arbitrary 
from C's point of view.


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


Re: Merging two dictionaries

2010-08-02 Thread Douglas Garstang
On Mon, Aug 2, 2010 at 12:47 AM, Paul Rubin  wrote:
> Douglas Garstang  writes:
>> default = {...
>>                 'data_sources': { ...
>> cluster = {...
>>                 'data_source': { ...
>
> Did you want both of those to say the same thing instead of one
> of them being 'data_source' and the other 'data_sources' ?
>
> If yes, then the following works for me:
>
>    def merge(cluster, default):
>        # destructively merge default into cluster
>        for k,v in cluster.iteritems():
>            if k in default and type(v)==dict:
>                assert type(default(k))==dict
>                merge(v,default[k])
>        for k,v in default.iteritems():
>            if k not in cluster:
>                cluster[k] = v
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Hmmm, using that gives me:

Traceback (most recent call last):
  File "./test4.py", line 48, in ?
merge(cluster, default)
  File "./test4.py", line 42, in merge
assert type(default(k))==dict
TypeError: 'dict' object is not callable

where line 42 is 'assert type(default(k))==dict', and the inputs are:

default = {
'cluster': {
'platform': {
'elements': {
'data_sources': {
'elements': {
'db_min_pool_size': 10
},
},
},
},
}
}

cluster = {
'cluster': {
'name': 'Customer 1',
'description': 'Customer Production',
'environment': 'production',
'platform': {
'elements': {
'data_source': {
'elements': {
'username': 'username',
'password': 'password'
},
},
},
},
}
}

and it's called with:

merge(cluster, default)

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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 16:41, Benjamin Kaplan wrote:

On Mon, Aug 2, 2010 at 8:21 AM, Mark Lawrencewrote:


On 01/08/2010 12:10, Lawrence D'Oliveiro wrote:


In message, Mark
Lawrence wrote:

  On 01/08/2010 08:18, Lawrence D'Oliveiro wrote:


  In message, Mark

Lawrence wrote:

  On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:


  In message, Mark

Lawrence wrote:

  Personally I find double clicking on an msi file rather easier.




Easier than apt-get dist-upgrade?



I'm sorry but I only do English, could you please translate. :)



I run Debian Unstable, which has new goodies coming out on a weekly
basis. The last time I checked for updates, there were over 500 packages
I had installed for which updates were available. It only took a command
like the above to upgrade them all.

How many .msi files would you have to click on to achieve the Windows
equivalent?



... I simply couldn't cope with over 500 installed packages.



Precisely my point. Go back to playing with your .msi toys.

Oh, and.



Repeating what was obviously deliberately snipped.

"No idea, but your mental capacity is clearly infinitely higher than mine,
as I simply couldn't cope with over 500 installed packages.  What do they
all do, make your lunch and fetch the beer from the fridge amongst other
things?"

How does any user or an admin cope with 500 packages?  Can Python help
here, assume an eight hour working day?

c:\Python31\Lib>python
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

8*60*60/500

57.6

So every working day you have 57.6 seconds to use each package. Strangely I
don't think anyone will get too much done.  Am I in cloud cuckoo land or are
you?



You seem to be mistaken as to what a "package" is.

Python :
* python
* python-minimal
* python2.6
* libbz2
* libc6
* libdb4.8
* libncursesw5
* libreadline6
* mime-support
* python2.6-minimal
* libssl0.9.8
* zlib1g
* debconf
* perl-base
* dpkg
* coreutils
* lzma
* libacl1
* libattr1
* libselinux1
* libgcc1
* libstdc++6
* gcc-4.4-base
* libncurses5
* readline-common

So these are the packages needed just to run Python in Ubuntu. It doesn't
include the packages required for the kernel, the desktop environment, the
window manager, the terminal, and whatever else you want running. In my
fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
close to 1500 packages installed.


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





I'll stick with my msi files and/or windows update then, unless I have 
the luck to get back to VMS.  As I said earlier it strikes me that this 
*nix stuff is simply archaic.


Kindest regards.

Mark Lawrence.


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


Re: Why is python not written in C++ ?

2010-08-02 Thread Thomas Jollans
On 08/02/2010 04:42 PM, Grant Edwards wrote:
> On 2010-08-02, Christian Heimes  wrote:
> 
>> In your opinion what would Python gain from a C++ implementation?
> 
> Greater buzzword-compliance -- an important characteristic highly
> prized by Human-Resources poeple and mid-level managers here in the
> US.
> 
> ;)
> 

C++Python would never beat IronPython on that front
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread David Cournapeau
On Mon, Aug 2, 2010 at 10:20 AM, Christian Heimes  wrote:

>
> In your opinion what would Python gain from a C++ implementation?

The elusive advantages of "OO" in C++ are relatively minor compared to
RIIA which would make reference counting much easier to deal with. But
even that is not a strong enough argument for C++. The little C++ we
have in scipy had causes a lot of headache - C++ portability is still
an issue once you are outside the 4-5 main OS/Compilers combinations,

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


THANKS GOD! I GOT $2000 FROM PAYPAL....

2010-08-02 Thread paypal cash
THANKS GOD!  I GOT $2000 FROM PAYPAL  At  http://ukcollegegirls.co.cc

I have hidden the PayPal Form link in an image.
in that website On Top Side Above search box ,
click on image and enter your  PayPal  id And Your name.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Benjamin Kaplan
On Mon, Aug 2, 2010 at 8:21 AM, Mark Lawrence wrote:

> On 01/08/2010 12:10, Lawrence D'Oliveiro wrote:
>
>> In message, Mark
>> Lawrence wrote:
>>
>>  On 01/08/2010 08:18, Lawrence D'Oliveiro wrote:
>>>
>>>  In message, Mark
 Lawrence wrote:

  On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:
>
>  In message, Mark
>> Lawrence wrote:
>>
>>  Personally I find double clicking on an msi file rather easier.
>>>
>>
>> Easier than apt-get dist-upgrade?
>>
>
> I'm sorry but I only do English, could you please translate. :)
>

 I run Debian Unstable, which has new goodies coming out on a weekly
 basis. The last time I checked for updates, there were over 500 packages
 I had installed for which updates were available. It only took a command
 like the above to upgrade them all.

 How many .msi files would you have to click on to achieve the Windows
 equivalent?

>>>
>>> ... I simply couldn't cope with over 500 installed packages.
>>>
>>
>> Precisely my point. Go back to playing with your .msi toys.
>>
>> Oh, and.
>>
>
> Repeating what was obviously deliberately snipped.
>
> "No idea, but your mental capacity is clearly infinitely higher than mine,
> as I simply couldn't cope with over 500 installed packages.  What do they
> all do, make your lunch and fetch the beer from the fridge amongst other
> things?"
>
> How does any user or an admin cope with 500 packages?  Can Python help
> here, assume an eight hour working day?
>
> c:\Python31\Lib>python
> Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> 8*60*60/500
> 57.6
>
> So every working day you have 57.6 seconds to use each package. Strangely I
> don't think anyone will get too much done.  Am I in cloud cuckoo land or are
> you?
>
>
You seem to be mistaken as to what a "package" is.

Python :
* python
* python-minimal
* python2.6
* libbz2
* libc6
* libdb4.8
* libncursesw5
* libreadline6
* mime-support
* python2.6-minimal
* libssl0.9.8
* zlib1g
* debconf
* perl-base
* dpkg
* coreutils
* lzma
* libacl1
* libattr1
* libselinux1
* libgcc1
* libstdc++6
* gcc-4.4-base
* libncurses5
* readline-common

So these are the packages needed just to run Python in Ubuntu. It doesn't
include the packages required for the kernel, the desktop environment, the
window manager, the terminal, and whatever else you want running. In my
fairly clean Ubuntu VM (I use it almost exclusively for testing), I have
close to 1500 packages installed.






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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 07:15, Michele Simionato wrote:

On Jul 31, 5:08 am, Steven D'Aprano  wrote:

I have read Michelle Simionato's articles on super in Python.


One "l" please! I am a man! ;-)


Please prove it, get your bits out!!! :)


 M. Simionato



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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-02 Thread Mark Lawrence

On 02/08/2010 10:23, Jean-Michel Pichavant wrote:

Paul Rubin wrote:

Michele Simionato  writes:

I am actually more radical than that. From
http://www.artima.com/weblogs/viewpost.jsp?thread=237121:
In this series I have argued that super is tricky; I think nobody can...


When I look at that URL, I see a Java stack dump:

java.lang.RuntimeException:
com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid
at
com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112)

...

Seems appropriate.

remove the ending double dot.

JM


aka the colon. :)

Cheers.

Mark  Lawrence

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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-02 Thread Mark Lawrence

On 01/08/2010 12:10, Lawrence D'Oliveiro wrote:

In message, Mark
Lawrence wrote:


On 01/08/2010 08:18, Lawrence D'Oliveiro wrote:


In message, Mark
Lawrence wrote:


On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:


In message, Mark
Lawrence wrote:


Personally I find double clicking on an msi file rather easier.


Easier than apt-get dist-upgrade?


I'm sorry but I only do English, could you please translate. :)


I run Debian Unstable, which has new goodies coming out on a weekly
basis. The last time I checked for updates, there were over 500 packages
I had installed for which updates were available. It only took a command
like the above to upgrade them all.

How many .msi files would you have to click on to achieve the Windows
equivalent?


... I simply couldn't cope with over 500 installed packages.


Precisely my point. Go back to playing with your .msi toys.

Oh, and.


Repeating what was obviously deliberately snipped.

"No idea, but your mental capacity is clearly infinitely higher than 
mine, as I simply couldn't cope with over 500 installed packages.  What 
do they all do, make your lunch and fetch the beer from the fridge 
amongst other things?"


How does any user or an admin cope with 500 packages?  Can Python help 
here, assume an eight hour working day?


c:\Python31\Lib>python
Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> 8*60*60/500
57.6

So every working day you have 57.6 seconds to use each package. 
Strangely I don't think anyone will get too much done.  Am I in cloud 
cuckoo land or are you?


As it happens, I'm also not a windows fan, did most of my work on VMS. 
Which to repeat myself stands for Very Much Safer.  Thinking of which 
did *nix ever get around to providing proper clustering, or does VMS 
still rule?


Mark Lawrence.

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


AMY JACKSON HOT PICTURES including upcoming movies, biography,

2010-08-02 Thread amyjack1
AMY JACKSON HOT PICTURES including upcoming movies, biography,

http://amyjacksons.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-02 Thread Grant Edwards
On 2010-08-02, Christian Heimes  wrote:

> In your opinion what would Python gain from a C++ implementation?

Greater buzzword-compliance -- an important characteristic highly
prized by Human-Resources poeple and mid-level managers here in the
US.

;)

-- 
Grant

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


Re: Mechanize - save to XML or CSV

2010-08-02 Thread Simon Brunning
On 2 August 2010 14:13, flebber  wrote:
> HI guys and gals this is probably a simple question but I can't find
> the answer directly in the docs for python mechanize.
>
> http://pypi.python.org/pypi/mechanize/
>
> Is it possible to retrieve and save a web page data as xml or a csv
> file?

Sure, but mechanize only does the first half of the job. You retrieve
the data using mechanize, then use another module for the save-as bit.
ElementTree for XML and csv for, um, for csv are both in the standard
library.

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


  1   2   >