Re: Pythonic way of saying 'at least one of a, b, or c is in some_list'

2010-10-29 Thread [email protected]
On Oct 28, 11:56 am, Arnaud Delobelle  wrote:
> "[email protected]"  writes:
> > It's clear but tedious to write:
>
> > if 'monday" in days_off or "tuesday" in days_off:
> >     doSomething
>
> > I currently am tending to write:
>
> > if any([d for d in ['monday', 'tuesday'] if d in days_off]):
> >     doSomething
>
> > Is there a better pythonic idiom for this situation?
>
> The latter can be written more concisely:
>
>     if any(d in days_off for d in ['monday', 'tuesday']):
>         # do something
>

For the list comprehension approach, I like this much better. In the
situation I am thinking of, it very naturally reads as 'if any of my
days off is monday or tuesday', rather than the logically equivalent,
but somewhat convoluted 'if any of monday or tuesday is one of my days
off'.

I should note that efficiency is not an issue to me here; this is for
when you have, say, a list user_options of at most around 15 options
or so, and you want to perform some action if one or more of a, b, or
c is an option listed in user_options. Big O notation isn't so
relevant as readability and 'naturalness'.

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


Re: Pythonic way of saying 'at least one of a, b, or c is in some_list'

2010-10-29 Thread Carl Banks
On Oct 28, 10:50 pm, Paul Rubin  wrote:
> John Nagle  writes:
> >    d1 = set('monday','tuesday')
> >    days_off = set('saturday','sunday')
> >    if not d1.isdisjoint(days_off) :...
> >    This is cheaper than intersection, since it doesn't have to
> > allocate and construct a set. It just tests whether any element in the
> > smaller of the two sets is in the larger one.
>
> I wonder what the complexity is, since the simplest implementation using
> the dict-like features of sets is quadratic.

I don't how isdisjoint is implemented, nor exactly what you mean by
dict-like features, but this implementation is linear on length of
smaller_set in the typical case:

def disjoint(smaller_set,larger_set):
for item in smaller_set:
if item in larger_set:
return False
return True


(Unless you meant worst case, which I don't consider important for
dictionary lookups.)


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


Re: Pythonic way of saying 'at least one of a, b, or c is in some_list'

2010-10-29 Thread HEK
On Oct 28, 6:16 pm, "[email protected]"
 wrote:
> It's clear but tedious to write:
>
> if 'monday" in days_off or "tuesday" in days_off:
>     doSomething
>
> I currently am tending to write:
>
> if any([d for d in ['monday', 'tuesday'] if d in days_off]):
>     doSomething
>
> Is there a better pythonic idiom for this situation?
>
> Cheers - Chas

The most pythonic way is the following:

class anyof(set):
def __contains__(self,item):
if isinstance(item,anyof):
for it in item:
if self.__contains__(it):
return True
else:
return False
return super(anyof,self).__contains__(item)

daysoff=anyof(['Saterday','Sunday'])
assert anyof(['monday','tuesday']) in daysoff

best regards
Hassan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embarrassing class question

2010-10-29 Thread Gregory Ewing

Brendan wrote:

I use
Python sporadically, and frequently use the dir command to learn or
remind myself of class methods.


You can clean up dir() by defining __all__ as a list of
names that you want to officially export. Other names will
still be there, but they won't show up in the dir() listing.

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


Re: functions, list, default parameters

2010-10-29 Thread Gregory Ewing

John Nagle wrote:

On 10/21/2010 2:51 PM, Chris Rebert wrote:



This is a common newbie stumbling-block: Don't use lists (or anything
mutable) as default argument values



That really should be an error.


No, it shouldn't. The criterion isn't whether the object is
mutable, but whether you actually mutate it. If you treat it
as read-only, there's no problem.

Since not all Python data types have immutable variants,
sometimes it's necessary to do this.

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


Re: embarrassing class question

2010-10-29 Thread Paul Rudin
Gregory Ewing  writes:

> Brendan wrote:
>> I use
>> Python sporadically, and frequently use the dir command to learn or
>> remind myself of class methods.
>
> You can clean up dir() by defining __all__ as a list of
> names that you want to officially export. Other names will
> still be there, but they won't show up in the dir() listing.

I'm not sure that's necessarily a good idea... when you're trying to figure
out why something behaves in a certain way you want to check for the
presence of methods with special names.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way of saying 'at least one of a, b, or c is in some_list'

2010-10-29 Thread Xavier Ho
Not sure why you use the for-else syntax without a break or continue. And
I'm also not sure on the readability.

-Xav on his Froyo
On 29/10/2010 6:21 PM, "HEK"  wrote:
> On Oct 28, 6:16 pm, "[email protected]"
>  wrote:
>> It's clear but tedious to write:
>>
>> if 'monday" in days_off or "tuesday" in days_off:
>> doSomething
>>
>> I currently am tending to write:
>>
>> if any([d for d in ['monday', 'tuesday'] if d in days_off]):
>> doSomething
>>
>> Is there a better pythonic idiom for this situation?
>>
>> Cheers - Chas
>
> The most pythonic way is the following:
>
> class anyof(set):
> def __contains__(self,item):
> if isinstance(item,anyof):
> for it in item:
> if self.__contains__(it):
> return True
> else:
> return False
> return super(anyof,self).__contains__(item)
>
> daysoff=anyof(['Saterday','Sunday'])
> assert anyof(['monday','tuesday']) in daysoff
>
> best regards
> Hassan
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unix-head needs to Windows-ize his Python script (II)

2010-10-29 Thread Gregory Ewing

Lawrence D'Oliveiro wrote:

You mean “GUI console”. So non-GUI apps get a GUI element whether they want 
it or not, while GUI ones don’t. That’s completely backwards.


The "G" in GUI stands for "Graphical". I wouldn't call a window that
displays nothing but text "graphical".

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


Re: functions, list, default parameters

2010-10-29 Thread Steven D'Aprano
On Fri, 29 Oct 2010 21:24:23 +1300, Gregory Ewing wrote:

> John Nagle wrote:
>> On 10/21/2010 2:51 PM, Chris Rebert wrote:
> 
>>> This is a common newbie stumbling-block: Don't use lists (or anything
>>> mutable) as default argument values
> 
>> That really should be an error.
> 
> No, it shouldn't. The criterion isn't whether the object is mutable, but
> whether you actually mutate it. If you treat it as read-only, there's no
> problem.

And how does Python know whether some arbitrary default object is mutable 
or not?

> Since not all Python data types have immutable variants, sometimes it's
> necessary to do this.


And sometimes you want the behaviour as it is.


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


Re: Unix-head needs to Windows-ize his Python script (II)

2010-10-29 Thread Gregory Ewing

gb345 wrote:


I see how clicking directly on these files would obviate the need
to specify the path of the interpreter, but it's still not clear
to me how the interpreter would know where to look for the myscript.py
module that both the GUI scripts require.


If it's in the same directory as the GUI script, or in some
known location relative to it, you should be able to locate
it based on the fact that sys.path[0] starts off containing
the pathname of the directory containing the running script.

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


Re: Python changes

2010-10-29 Thread Steven D'Aprano
On Thu, 28 Oct 2010 14:14:43 -0400, Craig McRoberts wrote:

> First off, greetings from a newbie!
> 
> Here's the deal. I gained a passable knowledge of Python nearly ten
> years ago. Then I decided a career in the computer sciences wasn't for
> me, and I let it go. Now I find myself back in the development arena,
> and I'd like to pick up Python again. How much has it changed in my ten
> years' absence? I've already resigned myself to starting over from the
> beginning, but are my books from that time period even worth using now?

The one sentence summary: if you're on a tight budget, and want to re-
learn Python on the cheap, you can reuse your old books, plus free 
resources on the web, but if you're in a hurry it will be easier to buy 
some new books.

Longer version:

Ten years ago would have been around version 1.5 or 2.0, give or take. As 
a language, Python has been very conservative. The basic syntax of Python 
1.5 still works. If you stick to Python 2.6 or 2.7, there have been 
virtually no backwards incompatible changes since version 1.5. The only 
exceptions I can think of:

* some libraries have been dropped;
* a change in the way hex() and oct() of negative numbers is displayed;
* nested functions behave differently;
* the occasional new keyword has been added (e.g. yield).

Other than that, you can take virtually any example from Python 1.5 and 
run it in Python 2.7 and it should still work. It might not be the best 
way to solve the problem, but it should do it.

Most of the changes from 1.5 to 2.7 have involved *adding* features, 
rather than taking them away. To learn the new features, read the Fine 
Manual, especially the What's New that comes out with every new version, 
or go out and buy a book covering the latest version.

If you advance to Python 3.1, you can add to the list of backward 
incompatibilities:

* minor differences in the way classes work;
* print is now a function, not a statement;
* strings are now Unicode, rather than bytes;
* various functions and methods which used to return lists now return 
iterators;

plus others I've forgotten. That makes a jump from 1.5 to 3.1 rather more 
problematic, but it can still be done -- the basic language is still 
almost identical, the syntax hasn't changed much, but there's a whole lot 
of new functionality that will make your life easier.



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


Re: "Strong typing vs. strong testing" [OT]

2010-10-29 Thread Gregory Ewing

Mark Wooding wrote:


Would the world be a better place if we had a name for 2 pi rather than
pi itself?


I don't think so. The women working in the factory in India
that makes most of the worlds 2s would be out of a job.

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


Re: Python changes

2010-10-29 Thread Steven D'Aprano
On Thu, 28 Oct 2010 20:16:45 +0100, Teenan wrote:

> On Thu, 2010-10-28 at 15:03 -0400, Craig McRoberts wrote:
>> Thanks for the prompt replies. Sounds like it's time to hit a
>> bookstore.
>> 
>> Craig McRoberts
> 
> You could do a lot worse than getting 'Dive into Python' (There's even a
> nice new version just for python 3.0)

Not everyone is enamored of "Dive into Python". (Personally, I don't have 
an option on it.)

http://oppugn.us/posts/1272050135.html

I can, however, recommend "Learning Python" by Mark Lutz, although in 
fairness the version I read was way back in the Dark Ages of Python 1.5.


> hmmm bookstore.. those are the things they had before Amazon right? ;)

Yeah, back when it was possible to buy things without leaving digital 
traces that will be around forever.


-- 
Steven

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


Re: Exception Handling in Python 3

2010-10-29 Thread Gregory Ewing

Steve Holden wrote:


Yeah, that's a given. Ruby would probably let you do that, but Python
insists that you don't dick around with the built-in types. And roghtly
so, IMHO.


Some restrictions on this are necessary -- it obviously
wouldn't be safe to allow replacing the class of an
object with one having an incompatible C layout, and
most built-in types have their own unique layout.

I think it's easier in Ruby, because all objects in
Ruby look pretty much the same at the C level. Not
sure of the details, though.

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


Re: How on Factorial

2010-10-29 Thread Steven D'Aprano
On Thu, 28 Oct 2010 10:13:15 -0400, Dave Angel wrote:

> Inverting the bits of a floating point number wouldn't make much sense,
> so fortunately it gives an error.

>>> from struct import pack, unpack
>>>
>>> def float_as_int(x):
... bits = pack("d", x)
... return unpack("q", bits)[0]
...
>>> def int_as_float(i):
... bits = pack("q", i)
... return unpack("d", bits)[0]
...
>>>
>>> float_as_int(1.123)
4607736361554183979
>>> int_as_float(~4607736361554183979)
-3.7536
>>>
>>> int_as_float( ~float_as_int(0.0) )
nan



Makes perfect sense to me :)



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


Re: Exception Handling in Python 3

2010-10-29 Thread Gregory Ewing

Chris Rebert wrote:

Your Traceback is merely being made slightly longer/more
complicated than you'd prefer; however, conversely, what if a bug was
to be introduced into your exception handler? Then you'd likely very
much appreciate the "superfluous" Traceback info.


I think what's disturbing about this is that the two halves of
the extended traceback are printed in the wrong order. We're
all used to looking down the bottom of the traceback to see
where the error originated, but with the new format, that point
is buried somewhere in the middle.

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


Re: Pythonic way of saying 'at least one of a, b, or c is in some_list'

2010-10-29 Thread Steven D'Aprano
On Thu, 28 Oct 2010 09:16:42 -0700, [email protected] wrote:

> It's clear but tedious to write:
> 
> if 'monday" in days_off or "tuesday" in days_off:
> doSomething
> 
> I currently am tending to write:
> 
> if any([d for d in ['monday', 'tuesday'] if d in days_off]):
> doSomething


Use a simple generator expression and any.

if any(day in days_off for day in ['monday', 'tuesday']):
doSomething

You (partially) defeat the short-circuiting behaviour of any() by using a 
list comprehension.

If you have a lot of items to test against, make days_off a set instead 
of a list, which makes each `in` test O(1) instead of O(N). For small N, 
the overhead of creating the set is probably going to be bigger than the 
saving, so stick to a list.

Other than that, doing set operations is overkill -- it obfuscates the 
intention of the code for very little gain, and possibly negative gain. 
And as for the suggestion that you create a helper class to do the work, 
that's surely the recommended way to do it in Java rather than Python.


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


Re: Pythonic way of saying 'at least one of a, b, or c is in some_list'

2010-10-29 Thread Adam Przybyla
[email protected]  wrote:
> It's clear but tedious to write:
> 
> if 'monday" in days_off or "tuesday" in days_off:
>doSomething
> 
> I currently am tending to write:
> 
> if any([d for d in ['monday', 'tuesday'] if d in days_off]):
>doSomething
> 
> Is there a better pythonic idiom for this situation?
... hmmm, try this:
if set(['monday', 'tuesday'])&set(days_off):
dosomething
Regards
Adam Przybyla
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyGUI 2.3

2010-10-29 Thread Gregory Ewing

Daniel Fetchinson wrote:


The problem is that some part of the application gets installed to

/home/fetchinson/.local/lib/python2.6/site-packages/GUI

and some other parts get installed to

/home/fetchinson/.local/lib/python/site-packages/GUI


Which parts get installed in which places, exactly?

I'm puzzled, because I can't see anything in the setup.py
that could result in things getting split up like this.
I'm wondering whether there is some breakage in distutils.

--
Greg

This email may be confidential and subject to legal privilege, it may
not reflect the views of the University of Canterbury, and it is not
guaranteed to be virus free. If you are not an intended recipient,
please notify the sender immediately and erase all copies of the message
and any attachments.

Please refer to http://www.canterbury.ac.nz/emaildisclaimer for more
information.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyGUI 2.3

2010-10-29 Thread Gregory Ewing

Daniel Fetchinson wrote:


Any reason your project is not easy_installable?


Mainly because I'm not a setuptools user and haven't been
motivated to learn how to do this so far.

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


Re: Exception Handling in Python 3

2010-10-29 Thread Chris Rebert
On Fri, Oct 29, 2010 at 2:30 AM, Gregory Ewing
 wrote:
> Chris Rebert wrote:
>>
>> Your Traceback is merely being made slightly longer/more
>> complicated than you'd prefer; however, conversely, what if a bug was
>> to be introduced into your exception handler? Then you'd likely very
>> much appreciate the "superfluous" Traceback info.
>
> I think what's disturbing about this is that the two halves of
> the extended traceback are printed in the wrong order. We're
> all used to looking down the bottom of the traceback to see
> where the error originated, but with the new format, that point
> is buried somewhere in the middle.

True, but swapping the order would only worsen Steve's problem. Most
of his users presumably won't care about the underlying KeyError and
would rather be presented with the AttributeError as the proximate
"origin", despite that being technically inaccurate in the way you
suggest. Six of one, half dozen of the other though.

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


Suppressing __context__

2010-10-29 Thread Antoine Pitrou
On Sun, 24 Oct 2010 10:48:23 +0200
"Martin v. Loewis"  wrote:
> 
> You may now wonder whether it is possible to set __context__ to None
> somehow. See PEP 3134:
> 
> Open Issue: Suppressing Context
> 
> As written, this PEP makes it impossible to suppress '__context__',
> since setting exc.__context__ to None in an 'except' or 'finally'
> clause will only result in it being set again when exc is raised.

It is not easily discoverable, but it is possible to suppress
__context__ by using a bare re-raise afterwards:

>>> try:
...   try: 1/0
...   except ZeroDivisionError: raise KeyError
... except BaseException as e:
...   e.__context__ = None
...   raise
... 
Traceback (most recent call last):
  File "", line 3, in 
KeyError


Regards

Antoine.


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


Re: Suppressing __context__

2010-10-29 Thread Chris Rebert
On Fri, Oct 29, 2010 at 4:02 AM, Antoine Pitrou  wrote:
> On Sun, 24 Oct 2010 10:48:23 +0200
> "Martin v. Loewis"  wrote:
>>
>> You may now wonder whether it is possible to set __context__ to None
>> somehow. See PEP 3134:
>>
>> Open Issue: Suppressing Context
>>
>>     As written, this PEP makes it impossible to suppress '__context__',
>>     since setting exc.__context__ to None in an 'except' or 'finally'
>>     clause will only result in it being set again when exc is raised.
>
> It is not easily discoverable, but it is possible to suppress
> __context__ by using a bare re-raise afterwards:
>
 try:
> ...   try: 1/0
> ...   except ZeroDivisionError: raise KeyError
> ... except BaseException as e:
> ...   e.__context__ = None
> ...   raise
> ...
> Traceback (most recent call last):
>  File "", line 3, in 
> KeyError

So, how/why does that work?

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


DateTime object

2010-10-29 Thread jf

Hi,

I've a bug in my code and I'm trying de reproduce it.

To trace the bug I print arguments, and it produces this:
{'date': }

My question is: what is: ?

I use mx.DateTime put if I print it I get:


So what kind of object  is ?

Thanks.

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


Re: DateTime object

2010-10-29 Thread Luca Bel
Take a look here:

http://pypi.python.org/pypi/DateTime/

I always use this package only with Zope (it's an application server)

If you are simply working in python maybe it's better to use datetime object.

Hi.

On Fri, Oct 29, 2010 at 1:15 PM, jf  wrote:
> Hi,
>
> I've a bug in my code and I'm trying de reproduce it.
>
> To trace the bug I print arguments, and it produces this:
> {'date': }
>
> My question is: what is: ?
>
> I use mx.DateTime put if I print it I get:
> 
>
> So what kind of object  is ?
>
> Thanks.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DateTime object

2010-10-29 Thread Adam Tauno Williams
On Fri, 2010-10-29 at 13:15 +0200, jf wrote: 
> Hi,
> I've a bug in my code and I'm trying de reproduce it.
> To trace the bug I print arguments, and it produces this:
> {'date': }
> My question is: what is: ?
> I use mx.DateTime put if I print it I get:
> 
> So what kind of object  is ?

In this case it is clearly mx.DateTime.DateTime.

__repr__ and __str__ may produce different representations; so it can
just depend on how the 'representation' is being generated.  If you
really want to know the type of an object: use type(x)

from datetime import datetime
x = datetime.now()
type(x)



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


Re: Suppressing __context__

2010-10-29 Thread Antoine Pitrou
On Fri, 29 Oct 2010 04:07:15 -0700
Chris Rebert  wrote:

> On Fri, Oct 29, 2010 at 4:02 AM, Antoine Pitrou  wrote:
> > On Sun, 24 Oct 2010 10:48:23 +0200
> > "Martin v. Loewis"  wrote:
> >>
> >> You may now wonder whether it is possible to set __context__ to None
> >> somehow. See PEP 3134:
> >>
> >> Open Issue: Suppressing Context
> >>
> >>     As written, this PEP makes it impossible to suppress '__context__',
> >>     since setting exc.__context__ to None in an 'except' or 'finally'
> >>     clause will only result in it being set again when exc is raised.
> >
> > It is not easily discoverable, but it is possible to suppress
> > __context__ by using a bare re-raise afterwards:
> >
>  try:
> > ...   try: 1/0
> > ...   except ZeroDivisionError: raise KeyError
> > ... except BaseException as e:
> > ...   e.__context__ = None
> > ...   raise
> > ...
> > Traceback (most recent call last):
> >  File "", line 3, in 
> > KeyError
> 
> So, how/why does that work?

A bare "raise" simply re-raises the currently known exception without
changing anything (neither the traceback nor the context).

This __context__ problem is mostly theoretical, anyway. If you want to
present exceptions to users in a different way, you can write a
catch-all except clause at the root of your program and use the
traceback module to do what you want.

Regards

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


multiprocessing signal defect

2010-10-29 Thread Neal Becker
Seems multiprocessing doesn't behave well with signals:

---
from multiprocessing import Pool
import time

def sleep (dummy):
time.sleep (10)

if __name__ == '__main__':
pool = Pool (processes=2)
result = pool.map (sleep, range (4))

-

start it up
$ python test_multip.py 

--
ps auxf | grep python
nbecker   6605  1.6  0.1 338192  6952 pts/1Sl+  08:03   0:00  |   \_ 
python test_multip.py
nbecker   6606  0.0  0.1 186368  4760 pts/1S+   08:03   0:00  |   
\_ python test_multip.py
nbecker   6607  0.0  0.1 186372  4740 pts/1S+   08:03   0:00  |   
\_ python test_multip.py

kill 6607
 ps auxf | grep python
nbecker   6605  0.5  0.1 338192  6952 pts/1Sl+  08:03   0:00  |   \_ 
python test_multip.py
nbecker   6606  0.0  0.1 186368  4760 pts/1S+   08:03   0:00  |   
\_ python test_multip.py
nbecker   6607  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |   
\_ [python] 

 kill 6606
ps auxf | grep python
nbecker   6605  0.3  0.1 338192  6952 pts/1Sl+  08:03   0:00  |   \_ 
python test_multip.py
nbecker   6606  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |   
\_ [python] 
nbecker   6607  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |   
\_ [python] 

Now we have 2 dead children and the parent is hung forever.

Isn't this a serious defect?

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


Re: multiprocessing signal defect

2010-10-29 Thread Adam Tauno Williams
On Fri, 2010-10-29 at 08:12 -0400, Neal Becker wrote: 
> Seems multiprocessing doesn't behave well with signals:
> -
> from multiprocessing import Pool
> import time
> def sleep (dummy):
> time.sleep (10)
> if __name__ == '__main__':
> pool = Pool (processes=2)
> result = pool.map (sleep, range (4))   
> -
> start it up
> $ python test_multip.py 
> --
> ps auxf | grep python
> nbecker   6605  1.6  0.1 338192  6952 pts/1Sl+  08:03   0:00  |   \_ 
> python test_multip.py
> nbecker   6606  0.0  0.1 186368  4760 pts/1S+   08:03   0:00  |   
> \_ python test_multip.py
> nbecker   6607  0.0  0.1 186372  4740 pts/1S+   08:03   0:00  |   
> \_ python test_multip.py
> kill 6607
>  ps auxf | grep python
> nbecker   6605  0.5  0.1 338192  6952 pts/1Sl+  08:03   0:00  |   \_ 
> python test_multip.py
> nbecker   6606  0.0  0.1 186368  4760 pts/1S+   08:03   0:00  |   
> \_ python test_multip.py
> nbecker   6607  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |   
> \_ [python] 
>  kill 6606
> ps auxf | grep python
> nbecker   6605  0.3  0.1 338192  6952 pts/1Sl+  08:03   0:00  |   \_ 
> python test_multip.py
> nbecker   6606  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |   
> \_ [python] 
> nbecker   6607  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |   
> \_ [python] 
> Now we have 2 dead children and the parent is hung forever.
> Isn't this a serious defect?

No, I think this is just POSIX/UNIX process behavior.  If the parent
never joins on the child the child can never exit [which is what a
Zombie process is].

For example, see the do_verify_workers method in

 

A parent process needs to make some effort to reap its children.



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


Re: multiprocessing signal defect

2010-10-29 Thread Neal Becker
Adam Tauno Williams wrote:

> On Fri, 2010-10-29 at 08:12 -0400, Neal Becker wrote:
>> Seems multiprocessing doesn't behave well with signals:
>> -
>> from multiprocessing import Pool
>> import time
>> def sleep (dummy):
>> time.sleep (10)
>> if __name__ == '__main__':
>> pool = Pool (processes=2)
>> result = pool.map (sleep, range (4))
>> -
>> start it up
>> $ python test_multip.py
>> --
>> ps auxf | grep python
>> nbecker   6605  1.6  0.1 338192  6952 pts/1Sl+  08:03   0:00  |  
>> \_ python test_multip.py
>> nbecker   6606  0.0  0.1 186368  4760 pts/1S+   08:03   0:00  |
>> \_ python test_multip.py
>> nbecker   6607  0.0  0.1 186372  4740 pts/1S+   08:03   0:00  |
>> \_ python test_multip.py
>> kill 6607
>>  ps auxf | grep python
>> nbecker   6605  0.5  0.1 338192  6952 pts/1Sl+  08:03   0:00  |  
>> \_ python test_multip.py
>> nbecker   6606  0.0  0.1 186368  4760 pts/1S+   08:03   0:00  |
>> \_ python test_multip.py
>> nbecker   6607  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |
>> \_ [python] 
>>  kill 6606
>> ps auxf | grep python
>> nbecker   6605  0.3  0.1 338192  6952 pts/1Sl+  08:03   0:00  |  
>> \_ python test_multip.py
>> nbecker   6606  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |
>> \_ [python] 
>> nbecker   6607  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |
>> \_ [python] 
>> Now we have 2 dead children and the parent is hung forever.
>> Isn't this a serious defect?
> 
> No, I think this is just POSIX/UNIX process behavior.  If the parent
> never joins on the child the child can never exit [which is what a
> Zombie process is].
> 
> For example, see the do_verify_workers method in
> 

> 
> A parent process needs to make some effort to reap its children.

Yes, and isn't this a defect in mulitprocessing module that the parent 
process does not reap its children in response to signals like show above?

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


Re: multiprocessing signal defect

2010-10-29 Thread Adam Tauno Williams
On Fri, 2010-10-29 at 08:39 -0400, Neal Becker wrote: 
> Adam Tauno Williams wrote:
> 
> > On Fri, 2010-10-29 at 08:12 -0400, Neal Becker wrote:
> >> Seems multiprocessing doesn't behave well with signals:
> >> -
> >> from multiprocessing import Pool
> >> import time
> >> def sleep (dummy):
> >> time.sleep (10)
> >> if __name__ == '__main__':
> >> pool = Pool (processes=2)
> >> result = pool.map (sleep, range (4))
> >> -
> >> start it up
> >> $ python test_multip.py
> >> --
> >> ps auxf | grep python
> >> nbecker   6605  1.6  0.1 338192  6952 pts/1Sl+  08:03   0:00  |  
> >> \_ python test_multip.py
> >> nbecker   6606  0.0  0.1 186368  4760 pts/1S+   08:03   0:00  |
> >> \_ python test_multip.py
> >> nbecker   6607  0.0  0.1 186372  4740 pts/1S+   08:03   0:00  |
> >> \_ python test_multip.py
> >> kill 6607
> >>  ps auxf | grep python
> >> nbecker   6605  0.5  0.1 338192  6952 pts/1Sl+  08:03   0:00  |  
> >> \_ python test_multip.py
> >> nbecker   6606  0.0  0.1 186368  4760 pts/1S+   08:03   0:00  |
> >> \_ python test_multip.py
> >> nbecker   6607  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |
> >> \_ [python] 
> >>  kill 6606
> >> ps auxf | grep python
> >> nbecker   6605  0.3  0.1 338192  6952 pts/1Sl+  08:03   0:00  |  
> >> \_ python test_multip.py
> >> nbecker   6606  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |
> >> \_ [python] 
> >> nbecker   6607  0.0  0.0  0 0 pts/1Z+   08:03   0:00  |
> >> \_ [python] 
> >> Now we have 2 dead children and the parent is hung forever.
> >> Isn't this a serious defect?
> > No, I think this is just POSIX/UNIX process behavior.  If the parent
> > never joins on the child the child can never exit [which is what a
> > Zombie process is].
> > For example, see the do_verify_workers method in
> 
> > A parent process needs to make some effort to reap its children.
> Yes, and isn't this a defect in mulitprocessing module that the parent 
> process does not reap its children in response to signals like show above?

No, I don't think so.  You're asking the module to over generalize
behavior.  Reaping of the child is important, and that the child needs
to be reaped may matter to the master child (why? did something go
wrong?).  Silently reaping them [which would reduce the size of the
Pool? Or would it dynamically create a new worker?] might have
unintended side effects.  Maybe since Pool specifically generalizes
child management you could make an argument it should reap, but I'm not
sure.  Personally I'd recommend that your worker processes include a
signal handler to do something smart in the case of a "-15" [for which
there isn't really a thread equivalent - can you sent a SystemV style
signal to an individual thread in a process?  I don't think so.]

How would a 'traditional' thread pool behave if a thread abended?  [of
course, that depends on the thread-pool implementation]  The correct
behavior in case of an exception in a thread is a topic of some debate.

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


Re: multiprocessing signal defect

2010-10-29 Thread Antoine Pitrou
On Fri, 29 Oct 2010 10:08:01 -0400
Adam Tauno Williams  wrote:
> 
> No, I don't think so.  You're asking the module to over generalize
> behavior.  Reaping of the child is important, and that the child needs
> to be reaped may matter to the master child (why? did something go
> wrong?).  Silently reaping them [which would reduce the size of the
> Pool? Or would it dynamically create a new worker?] might have
> unintended side effects.  Maybe since Pool specifically generalizes
> child management you could make an argument it should reap, but I'm not
> sure.  Personally I'd recommend that your worker processes include a
> signal handler to do something smart in the case of a "-15" [for which
> there isn't really a thread equivalent - can you sent a SystemV style
> signal to an individual thread in a process?  I don't think so.]
> 
> How would a 'traditional' thread pool behave if a thread abended?  [of
> course, that depends on the thread-pool implementation]

A thread pool would certainly raise an exception in the caller (the
main thread probably) to signal the error.

I tried Neal's program (on 3.2 under Linux) and I don't witness the
same behaviour. The killed process disappears immediately, but the Pool
immediately spawns another process... which means you can't kill the
whole thing using Control-C (it kills one or both of the children but
they immediately get respawned, ad nauseam).

Another issue is that the respawned child doesn't seem to exhaust all
jobs, which means the parent waits indefinitely.

Regards

Antoine.


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


Re: multiprocessing signal defect

2010-10-29 Thread Jean-Paul Calderone
On Oct 29, 10:08 am, Adam Tauno Williams 
wrote:
> signal handler to do something smart in the case of a "-15" [for which
> there isn't really a thread equivalent - can you sent a SystemV style
> signal to an individual thread in a process?  I don't think so.]

Yes.  pthread_kill(P)

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


Re: Suppressing __context__

2010-10-29 Thread Martin v. Loewis
> It is not easily discoverable, but it is possible to suppress
> __context__ by using a bare re-raise afterwards:

I see. I'd wrap this like this:

def raise_no_context(e):
try:
raise e
except:
e.__context__=None
raise

d = {}
try:
val = d['nosuch']
except KeyError:
raise_no_context(AttributeError("No attribute 'nosuch'"))

The downside of this is that the innermost frame will be
raise_no_context, but I suppose that's ok because even the
next-inner frame already reveals implementation details that
developers have learned to ignore.

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


Re: multiprocessing signal defect

2010-10-29 Thread Adam Tauno Williams
On Fri, 2010-10-29 at 07:31 -0700, Jean-Paul Calderone wrote: 
> On Oct 29, 10:08 am, Adam Tauno Williams 
> wrote:
> > signal handler to do something smart in the case of a "-15" [for which
> > there isn't really a thread equivalent - can you sent a SystemV style
> > signal to an individual thread in a process?  I don't think so.]
> Yes.  pthread_kill(P)

Eh, only sort of.


Signal dispositions are process-wide: if a signal handler is installed,
the handler will be invoked in the thread thread, but if the disposition
of the signal is "stop", "continue", or "terminate", this action will
affect the whole process.


Also phthread_kill can only be called for a thread in the same process.
Which is quite different that SystemV signals.

So there can't really be an exact 1:1 match of how thread-signaling vs.
multiprocessing-process-signaling works; which was my point.

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


Re: factorial of negative one (-1)

2010-10-29 Thread Robert Kern

On 10/29/10 12:02 AM, Chris Rebert wrote:

On Thu, Oct 28, 2010 at 9:41 PM, Bj Raz  wrote:

I am working with differential equations of the higher roots of negative
one. (dividing enormous numbers into other enormous numbers to come out with
very reasonable numbers).
I am mixing this in to a script for Maya (the final output is graph-able as
a spiral.)
I have heard that Sage, would be a good program to do this in, but I'd like
to try and get this to work in native python if I can.
The script I am trying to port to Python is; http://pastebin.com/sc1jW1n4.


Unless your code is really long, just include it in the message in the future.
So, for the archive:
indvar = 200;
q = 0;
lnanswer = 0;
for m = 1:150
   lnanswer = (3 * m) * log(indvar) - log(factorial(3 * m))  ;
q(m+1) = q(m)+ ((-1)^m) * exp(lnanswer);
end
lnanswer
q

Also, it helps to point out *what language non-Python code is in*. I'm
guessing MATLAB in this case.

Naive translation attempt (Disclaimer: I don't know much MATLAB):

from math import log, factorial, exp
indvar = 200
q = [0]
lnanswer = 0
for m in range(1, 151):
 lnanswer = (3 * m) * log(indvar) - log(factorial(3 * m))
 q.append(q[-1] + (1 if m % 2 == 0 else -1) * exp(lnanswer))
print(lnanswer)
print(q)


I promised that I would reply when the OP posted here. Except you gave the 
answer that I would have.


To the OP: In your code snippet, q(m+1) and q(m) are not function calls. They 
are array indexing operations (with the special semantics that assigning beyond 
the last element in the array appends a new element to the array). You are not 
setting the result of a function to anything, just building up an array of 
results. You don't need symbolic math libraries like SAGE for this.


--
Robert Kern

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

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


curses and processing terminal escape characters

2010-10-29 Thread mix
Hi,

I'm wondering if there is a way in python to process a string
containing terminal escape characters. Example: Please consider the
following string:

str = ''\x1B[K\x1B[D\x1B[D\x1B[D\x1B[D\x1B[C\x1B[C\x1B[C\x1B[C
\x1b[d\x1b[d\x...@q\x1b[@q\x...@q''

as a result of printing it (print str), the console's output is as
follows:

aaqqqaa

Having such string with the escape codes I would like to call a
function that would process the input and return the "aaqqqaa" string.
Of course I'm aware that any information about colors will be missed.
I'm wondering if the curses module has such functionality.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python changes

2010-10-29 Thread rantingrick
On Oct 28, 2:16 pm, Teenan  wrote:

> hmmm bookstore.. those are the things they had before Amazon right? ;)

hmm Amazon... Is that the place where you buy tutorials when you could
instead get the same info for free with a little Google fu? ;-)

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


Re: Exception Handling in Python 3

2010-10-29 Thread rantingrick
On Oct 24, 7:36 am, Steve Holden  wrote:

> I don't want people to think this is a big deal, however.

Nonsense, this IS a big deal. (and Steve grow a spine already!) I was
not even aware of this issue until you brought it up -- although i
will admit your choice of title is completely misleading!

This new exception handling behavior is completely ridiculous and the
only thing more atrocious than the new exception handling BUG you
uncovered is the "hoop jumping" garbage people have come up with to
make the "new" work as the tried and tested "old".

I am the programmer, and when i say to my interpretor "show this
exception instead of that exception" i expect my interpretor to do
exactly as i say or risk total annihilation!! I don't want my
interpreter "interpreting" my intentions and then doing what it
"thinks" is best for me. I have a wife already, i don't need a virtual
one! We are opening a Pandora's box of mediocrity and confusion when
we start down such a slippery slope as this.

Let me enlighten you fellows... If have i ever learned anything about
programming, i can tell you one rule should always be counted on above
all rules -- that the computer will do exactly what you tell it to do
NOTHING more, and NOTHING less. End of story!


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


str(int_var) formatted

2010-10-29 Thread Tracubik
Hi all,
i've to convert integer x to string, but if x < 10, the string have to be 
'0x' instead of simple 'x'

for example:

x = 9
str(x) --> '09'

x = 32
str(x) --> '32'

x represent hour/minute/second.

I can easily add '0' with a if then block, but is there a built-in way to 
add the '0' automatically?

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


Re: str(int_var) formatted

2010-10-29 Thread Grant Edwards
On 2010-10-29, Tracubik  wrote:
> Hi all,
> i've to convert integer x to string, but if x < 10, the string have to be 
> '0x' instead of simple 'x'
>
> for example:
>
> x = 9
> str(x) --> '09'
>
> x = 32
> str(x) --> '32'
>
> x represent hour/minute/second.
>
> I can easily add '0' with a if then block, but is there a built-in way to 
> add the '0' automatically?

"%02d" % x

-- 
Grant Edwards   grant.b.edwardsYow! INSIDE, I have the
  at   same personality disorder
  gmail.comas LUCY RICARDO!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: str(int_var) formatted

2010-10-29 Thread none

On 29/10/10 16:59, Tracubik wrote:

Hi all,
i've to convert integer x to string, but if x<  10, the string have to be
'0x' instead of simple 'x'

for example:

x = 9
str(x) -->  '09'

x = 32
str(x) -->  '32'

x represent hour/minute/second.

I can easily add '0' with a if then block, but is there a built-in way to
add the '0' automatically?

Thanks
Nico


Python2: "%02d" % x
Python3: format(x,"02d")
--
http://mail.python.org/mailman/listinfo/python-list


RE: str(int_var) formatted

2010-10-29 Thread Andreas Tawn
> Hi all,
> i've to convert integer x to string, but if x < 10, the string have to
> be
> '0x' instead of simple 'x'
> 
> for example:
> 
> x = 9
> str(x) --> '09'
> 
> x = 32
> str(x) --> '32'
> 
> x represent hour/minute/second.
> 
> I can easily add '0' with a if then block, but is there a built-in way
> to
> add the '0' automatically?

>>> x = 9
>>> str(x).zfill(2)
'09'

Cheers,

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


Re: Pythonic way of saying 'at least one of a, b, or c is in some_list'

2010-10-29 Thread [email protected]
On Oct 29, 2:43 am, Steven D'Aprano  wrote:
> On Thu, 28 Oct 2010 09:16:42 -0700, [email protected] wrote:
> > It's clear but tedious to write:
>
> > if 'monday" in days_off or "tuesday" in days_off:
> >     doSomething
>
> > I currently am tending to write:
>
> > if any([d for d in ['monday', 'tuesday'] if d in days_off]):
> >     doSomething
>
> Use a simple generator expression and any.
>
> if any(day in days_off for day in ['monday', 'tuesday']):
>     doSomething
>
> You (partially) defeat the short-circuiting behaviour of any() by using a
> list comprehension.
>

Good point, thanks.

> If you have a lot of items to test against, make days_off a set instead
> of a list, which makes each `in` test O(1) instead of O(N). For small N,
> the overhead of creating the set is probably going to be bigger than the
> saving, so stick to a list.
>
> Other than that, doing set operations is overkill -- it obfuscates the
> intention of the code for very little gain, and possibly negative gain.
> And as for the suggestion that you create a helper class to do the work,
> that's surely the recommended way to do it in Java rather than Python.
>

Agreed. In the situation I am thinking of, N is generally very small,
and readability trumps execution speed.

Cheers - Chas


> --
> Steven

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


Re: DateTime object

2010-10-29 Thread jf

Le 29/10/2010 13:41, Adam Tauno Williams a écrit :

So what kind of object  is ?


In this case it is clearly mx.DateTime.DateTime.

__repr__ and __str__ may produce different representations;


Thanks a lot, in fact it is DateTime from xmlrpclib but your post really 
helped me to find it.

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


Re: Exception Handling in Python 3

2010-10-29 Thread MRAB

On 29/10/2010 11:24, Chris Rebert wrote:

On Fri, Oct 29, 2010 at 2:30 AM, Gregory Ewing
  wrote:

Chris Rebert wrote:


Your Traceback is merely being made slightly longer/more
complicated than you'd prefer; however, conversely, what if a bug was
to be introduced into your exception handler? Then you'd likely very
much appreciate the "superfluous" Traceback info.


I think what's disturbing about this is that the two halves of
the extended traceback are printed in the wrong order. We're
all used to looking down the bottom of the traceback to see
where the error originated, but with the new format, that point
is buried somewhere in the middle.


True, but swapping the order would only worsen Steve's problem. Most
of his users presumably won't care about the underlying KeyError and
would rather be presented with the AttributeError as the proximate
"origin", despite that being technically inaccurate in the way you
suggest. Six of one, half dozen of the other though.


I've just come across the same problem myself.

I wanted to raise an exception that would be more meaningful to the
caller, but the traceback included info on the original exception,
which is an implementation detail.

I understand that it can be useful, but IMHO there should be a simple
way of suppressing it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: str(int_var) formatted

2010-10-29 Thread MRAB

On 29/10/2010 17:18, "none <"@mail.python.org wrote:

On 29/10/10 16:59, Tracubik wrote:

Hi all,
i've to convert integer x to string, but if x< 10, the string have to be
'0x' instead of simple 'x'

for example:

x = 9
str(x) --> '09'

x = 32
str(x) --> '32'

x represent hour/minute/second.

I can easily add '0' with a if then block, but is there a built-in way to
add the '0' automatically?

Thanks
Nico


Python2: "%02d" % x
Python3: format(x,"02d")


Also:

Python 3: "{:02}".format(x)
--
http://mail.python.org/mailman/listinfo/python-list


Re: curses and processing terminal escape characters

2010-10-29 Thread Tim Harig
On 2010-10-29, mix  wrote:
> Hi,
>
> I'm wondering if there is a way in python to process a string
> containing terminal escape characters. Example: Please consider the
> following string:

Python could easily process the escape codes for any given terminal; but,
in general, you would want something that works for more then a single
terminal type.  This means that you need something that can do a reverse
translation of the termcap/terminfo database.

What you might be able to do, is build a dictionary by querying all of the
possible termcap/terminfo functionalities using tgetstr().  Then when you
encounter an escape sequence, you can use the escape sequence from the
dictionary as a template to parse the sequence.

> str = ''\x1B[K\x1B[D\x1B[D\x1B[D\x1B[D\x1B[C\x1B[C\x1B[C\x1B[C
> \x1b[d\x1b[d\x...@q\x1b[@q\x...@q''
>
> as a result of printing it (print str), the console's output is as
> follows:
>
> aaqqqaa

Your example is rather simplified.  Terminal escape coding can get rather
complex.  Paul Williams of vt100.net has some information on writing
terminal emulators at: http://www.vt100.net/emu/

> Having such string with the escape codes I would like to call a
> function that would process the input and return the "aaqqqaa" string.
> Of course I'm aware that any information about colors will be missed.
> I'm wondering if the curses module has such functionality.

Not that I am aware of.

There are a couple of terminal emulation libraries around that you might
want to take a look at.  I don't know of any that currently provide Python
interfaces; but, they shouldn't be too difficult to interface using
something like SWIG.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception Handling in Python 3

2010-10-29 Thread MRAB

On 24/10/2010 13:28, Steve Holden wrote:

On 10/24/2010 4:48 AM, Martin v. Loewis wrote:

Am 24.10.2010 07:01, schrieb Steve Holden:

I was somewhat surprised to discover that Python 3 no longer allows an
exception to be raised in an except clause (or rather that it reports it
as a separate exception that occurred during the handling of the first).


I think you are misinterpreting what you are seeing. The exception being
raised actually *is* an attribute error, and it actually is the
attribute error that gets reported. It's only that reporting an
exception that has a __context__ first reports the context, then reports
the actual exception.


I don't believe I *am* misinterpreting it. The fact of the matter is
that the context is irrelevant to the user, and there should be some way
to suppress it to avoid over-complicating the traceback.

This behavior is quite reasonable during testing, but I would prefer to
exclude an explicit raise directly in the except handler since that is
hardly to be construed as accidental (whereas an exception in a function
called in the handler perhaps *should* be reported).


You may now wonder whether it is possible to set __context__ to None
somehow. See PEP 3134:

Open Issue: Suppressing Context

 As written, this PEP makes it impossible to suppress '__context__',
 since setting exc.__context__ to None in an 'except' or 'finally'
 clause will only result in it being set again when exc is raised.


I have already read that. Peter Otten has separately explained how to
suppress the behavior using sys.excepthook, which appears to be a
halfway satisfactory solution.

Suggestion: an explicit 'raise' in the exception handler excludes the 
context, but if you want to include it then 'raise with'. For example:


# Exclude the context
try:
command_dict[command]()
except KeyError:
raise CommandError("Unknown command")

# Include the context
try:
command_dict[command]()
except KeyError:
raise with CommandError("Unknown command")
--
http://mail.python.org/mailman/listinfo/python-list


Re: Exception Handling in Python 3

2010-10-29 Thread Ethan Furman

MRAB wrote:

On 24/10/2010 13:28, Steve Holden wrote:

On 10/24/2010 4:48 AM, Martin v. Loewis wrote:

Am 24.10.2010 07:01, schrieb Steve Holden:

I was somewhat surprised to discover that Python 3 no longer allows an
exception to be raised in an except clause (or rather that it 
reports it
as a separate exception that occurred during the handling of the 
first).


I think you are misinterpreting what you are seeing. The exception being
raised actually *is* an attribute error, and it actually is the
attribute error that gets reported. It's only that reporting an
exception that has a __context__ first reports the context, then reports
the actual exception.


I don't believe I *am* misinterpreting it. The fact of the matter is
that the context is irrelevant to the user, and there should be some way
to suppress it to avoid over-complicating the traceback.

This behavior is quite reasonable during testing, but I would prefer to
exclude an explicit raise directly in the except handler since that is
hardly to be construed as accidental (whereas an exception in a function
called in the handler perhaps *should* be reported).


You may now wonder whether it is possible to set __context__ to None
somehow. See PEP 3134:

Open Issue: Suppressing Context

 As written, this PEP makes it impossible to suppress '__context__',
 since setting exc.__context__ to None in an 'except' or 'finally'
 clause will only result in it being set again when exc is raised.


I have already read that. Peter Otten has separately explained how to
suppress the behavior using sys.excepthook, which appears to be a
halfway satisfactory solution.

Suggestion: an explicit 'raise' in the exception handler excludes the 
context, but if you want to include it then 'raise with'. For example:


# Exclude the context
try:
command_dict[command]()
except KeyError:
raise CommandError("Unknown command")

# Include the context
try:
command_dict[command]()
except KeyError:
raise with CommandError("Unknown command")


+1

Presumably, this would also keep the context if an actual error occured.

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


Re: curses and processing terminal escape characters

2010-10-29 Thread Dan Stromberg
On Fri, Oct 29, 2010 at 10:35 AM, Tim Harig  wrote:

> On 2010-10-29, mix  wrote:
> > Hi,
> >
> > I'm wondering if there is a way in python to process a string
> > containing terminal escape characters. Example: Please consider the
> > following string:
>
> Python could easily process the escape codes for any given terminal; but,
> in general, you would want something that works for more then a single
> terminal type.  This means that you need something that can do a reverse
> translation of the termcap/terminfo database.
>

Actually, I believe it's become pretty rare for someone to use a terminal or
terminal emulator that doesn't support vt100 escape sequences or a superset
thereof.  My condolences if you try to emulate something that does those
old, nasty Wyse "magic cookies".

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


Re: Exception Handling in Python 3

2010-10-29 Thread Ethan Furman

MRAB wrote:

On 29/10/2010 11:24, Chris Rebert wrote:

On Fri, Oct 29, 2010 at 2:30 AM, Gregory Ewing
  wrote:

Chris Rebert wrote:


Your Traceback is merely being made slightly longer/more
complicated than you'd prefer; however, conversely, what if a bug was
to be introduced into your exception handler? Then you'd likely very
much appreciate the "superfluous" Traceback info.


I think what's disturbing about this is that the two halves of
the extended traceback are printed in the wrong order. We're
all used to looking down the bottom of the traceback to see
where the error originated, but with the new format, that point
is buried somewhere in the middle.


True, but swapping the order would only worsen Steve's problem. Most
of his users presumably won't care about the underlying KeyError and
would rather be presented with the AttributeError as the proximate
"origin", despite that being technically inaccurate in the way you
suggest. Six of one, half dozen of the other though.


I've just come across the same problem myself.

I wanted to raise an exception that would be more meaningful to the
caller, but the traceback included info on the original exception,
which is an implementation detail.

I understand that it can be useful, but IMHO there should be a simple
way of suppressing it.


I agree.  It seems to me that the suppression should happen on the raise 
line, so that we aren't losing the extra information if an actual error 
occurs in the error handler.


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


Re: Calling a method from invoking module

2010-10-29 Thread Dave Angel

On 2:59 PM, Chris Rebert wrote:

On Thu, Oct 28, 2010 at 8:33 PM, Baskaran Sankaran  wrote:

Sorry for the confusion; fooz(), track() and barz() are all members of their
respective classes. I must have missed the self argument while creating the
synthetic example.

Yeah, I realize the mutual import is a bad idea. So, if I merge them into a
single module (but still retaining the two classes) will work right?
Yes, if you define them both in the same module, they can reference each 
other arbitrarily.  But you still have plenty of errors, some of which 
Chris has pointed out.  I can ignore most, but his point about calling a 
function without an instance is important, so I'll comment some more at end.

  I
guess, it will look like this after merging.

Thanks again
-b

* foo_bar.py *

class Foo:
 def fooz(self):
 print "Hello World"
 b =ar()
 c =.barz()
 ...

 def track(self, track_var):
 count +=

That line will raise UnboundLocalError. Where's count initialized?


 return sth2


class Bar:
 def barz(self):
 track_this =..
 if Foo.track(track_this):

You can't call an instance method on a class.


If you really need to call this on the class (because its data spans 
multiple instances, for example), then you should make it a 
classmethod.  Easiest way is as follows:


class Foo:
def fooz(self):
print "Hello World"
b = Bar()
c = b.barz()
...

@classmethod
def track(cls, track_var):
count += 1

Note that the first argument is now the class, so by convention we call 
it cls, rather than self.  And that within a class method, you typically 
reference class attributes.  So you might want to use something like:


class Foo:
count = 0  #I'm a class attribute
def fooz(self):
print "Hello World"
b = Bar()
c = b.barz()
...

@classmethod
def track(cls, track_var):
cls.count += 1



DaveA

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


Re: functions, list, default parameters

2010-10-29 Thread Dan Stromberg
On Thu, Oct 21, 2010 at 7:53 PM, John Nagle  wrote:

> On 10/21/2010 2:51 PM, Chris Rebert wrote:
>
>> On Thu, Oct 21, 2010 at 2:36 PM, Sean Choi  wrote:
>>
>>> I found two similar questions in the mailing list, but I didn't
>>> understand
>>>
>>> the explanations.
>>> I ran this code on Ubuntu 10.04 with Python 2.6.5.
>>> Why do the functions g and  behave differently? If calls (3) and
>>> g(3) both exit their functions in the same state, why do they not enter
>>> in
>>> the same state when I call (4) and g(4)?
>>>
>>> # --
>>> my
>>> code:
>>> def (a, L=[]):
>>>
>>
>> This is a common newbie stumbling-block: Don't use lists (or anything
>> mutable) as default argument values
>>
>
>That really should be an error.


Pylint warns about it.  I think that's enough.

I think it's enough, in part because unfortunately default values have
become overloaded as the way of creating variables with a global lifetime,
and sometimes that's useful to have.  I think it would probably have been
better to make default arguments be evaluated once per function/method
invocation, and add a static modifier to variables, but oh well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fastest way to detect a non-ASCII character in a list of strings.

2010-10-29 Thread Stefan Behnel

Dun Peal, 28.10.2010 09:10:

I find myself surprised at the relatively little use that Cython is seeing.


I don't think it's being used that little. It just doesn't show that 
easily. We get a lot of feedback on the mailing list that suggests that 
it's actually used by all sorts of people in all sorts of places, from tiny 
library wrapper projects to major applications, in-house, server-side and 
OpenSource. I think the reason for that is simple: it works, it solves a 
real-world problem, and it does it well.




You would expect a whole lot of organizations and people to fancy a
language that's about as high-level as Python, yet almost as fast and
down-to-the-metal as C.

Add to that the ability to seamlessly integrate with both your
existing C/++ codebase and your Python codebase, easily mix very high
level abstractions with very low-level machine access... clear winner.


Thanks for the testimony. I hope you don't mind finding it on our project 
main page.


As usual, I think it's not as easy as that. I mean, big companies still use 
Java these days. It's not like you show them a better programming language 
and they'll drop what they hold in their hands and go for it. Cython fits 
well where people use Python anyway, and where C code is something that 
people do not run from screaming. That being said, Cython really plugs a 
huge hole, anywhere between "a friendlier C with a huge standard library" 
and "Python at the speed of C". The image below illustrates it quite well, 
I think (it's from a talk I gave a year ago):


http://behnel.de/cython200910/SimplicityVsSpeed.png



I'd expect Cython to have a far larger userbase, with a long line of
sponsors queuing up to fund further development. Maybe it will get
there some day :-)


:-) I certainly wouldn't object. Funding is something the project can 
seriously benefit from.


Stefan

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


Re: Land Of Lisp is out

2010-10-29 Thread Lawrence D'Oliveiro
In message
, 
[email protected] wrote:

> On 29 Okt., 01:34, Lawrence D'Oliveiro 
> wrote:
>
>> In message
>> ,
>> kodifik wrote:
>>
>>> On Oct 28, 1:55 am, Lawrence D'Oliveiro
>>>  wrote:
>>
 Would it be right to say that the only Lisp still in common use is the
 Elisp built into Emacs?
>>
>> > Surely surpassed by autolisp (a xlisp derivative inside the Autocad
>> > engineering software).
>>
>> How many copies of AutoCAD are there? Given its price, probably something
>> in the five or six figures at most.
> 
> A few million.

Autodesk have probably sold a few million licences, but that would be 
including upgrades.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Land Of Lisp is out

2010-10-29 Thread Alessio Stalla
On 28 Ott, 10:42, [email protected] (Pascal J. Bourguignon)
wrote:
> [email protected] (Stefan Hübner) writes:
> >> Would it be right to say that the only Lisp still in common use is the 
> >> Elisp
> >> built into Emacs?
>
> > Clojure (http://clojure.org) is a Lisp on the JVM. It's gaining more and
> > more traction.
>
> There are actually 2 REAL Lisp on the JVM:
>
> - abclhttp://common-lisp.net/project/armedbear/and
>
> - CLforJavahttp://www.clforjava.org

Well, there are a few Scheme implementations too. Kawa is "famous" for
having been used by Google as the basis for their App Inventor for
Android. And I wouldn't define Clojure a "fake" Lisp. It has some
aspects I don't like, but it is definitely in the Lisp family.
Actually CLforJava as far as I know is missing crucial features (e.g.
CLOS) and in some aspects is more tied to Java than Clojure.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is list comprehension necessary?

2010-10-29 Thread Lawrence D'Oliveiro
In message , Andre 
Alexander Bell wrote:

>>>> i = 5
>>>> l = [i**2 for i in range(3)]
>>>> i
>2

The last line comes out as 5 in Python 3.1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Are Tkinter StringVar (IntVar, etc) thread safe?

2010-10-29 Thread python
Are Tkinter StringVar (IntVar, FloatVar, etc) thread safe, eg.
can a background thread read or write to these objects? Or must I
use a Queue to pass information between my background thread and
my main Tkinter GUI thread and have my main Tkinter thread pop
the Queue and update the application's StringVar's accordingly?

I know my background threads can not read or write a Tkinter
widget directly but I'm unclear on whether StringVar's are
considered widgets or if they are objects far enough removed from
widgets that they are thread safe.

Thank you,
Malcolm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python changes

2010-10-29 Thread Hans-Peter Jansen
On Thursday 28 October 2010, 21:23:03 Craig McRoberts wrote:
> Oh, I like to browse brick-and-mortar enough. But it's been forever
> since I've bought something there.

If you can get your hands on a copy of Mark Summerfield's Programming in 
Python3, check it out. He really raised the accustomed quality levels 
of technical writings for me.

Pete

> On Oct 28, 2010, at 15:16, Teenan  wrote:
> > On Thu, 2010-10-28 at 15:03 -0400, Craig McRoberts wrote:
> >> Thanks for the prompt replies. Sounds like it's time to hit a
> >> bookstore.
> >>
> >> Craig McRoberts
> >
> > You could do a lot worse than getting 'Dive into Python' (There's
> > even a nice new version just for python 3.0)
> >
> > hmmm bookstore.. those are the things they had before Amazon right?
> > ;)


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


Re: is list comprehension necessary?

2010-10-29 Thread Lawrence D'Oliveiro
In message <[email protected]>, John Nagle wrote:

> The weird "functional if" syntax additions were a cave-in to the
> functional crowd, and may have been a mistake.

The only mistake was not putting functional-if into the language in the 
first place, and having to use that strange inside-out syntax to add it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing signal defect

2010-10-29 Thread Antoine Pitrou
On Fri, 29 Oct 2010 08:12:19 -0400
Neal Becker  wrote:
> Seems multiprocessing doesn't behave well with signals:
> [...]

By the way, could you post an issue on the tracker with instructions on
how to reproduce (including OS)?

Thanks

Antoine.


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


Re: Python 2.7 or 3.1

2010-10-29 Thread Lawrence D'Oliveiro
In message , Jorge 
Biquez wrote:

> I was wondering if you can comment more about what alternatives to
> use instead to MySql. My web solutions do not need "all the power" of
> a true database,

Is more than one process likely to access the data at the same time? If so, 
use MySQL.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 or 3.1

2010-10-29 Thread Christian Heimes
Am 29.10.2010 23:16, schrieb Lawrence D'Oliveiro:
> In message , Jorge 
> Biquez wrote:
> 
>> I was wondering if you can comment more about what alternatives to
>> use instead to MySql. My web solutions do not need "all the power" of
>> a true database,
> 
> Is more than one process likely to access the data at the same time? If so, 
> use MySQL.

There are plenty of better open source tools to store data than MySQL.

You need the full power of a RDBMS including referential integrity,
triggers and stored procedures? Use PostgreSQL or Firebird.

You are looking for a simple yet extremely power persistent layer that
supports even transactions, MVCC and networking? Check out ZODB + ZEO.

You have to store and acces a LOT of data? Hadoop may the solution.

Christian

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


Re: Python 2.7 or 3.1

2010-10-29 Thread geremy condra
On Wed, Oct 27, 2010 at 7:18 PM, Braden Faulkner  wrote:
> Would it be safe to say that 2.6 would be even better for beginners than?

Let me just come out with a contrary point of view before you go down
that path. If you're seriously considering using sqlite, then you may
be just as well off using Python3 as 2.7 or 2.6- it's in all of the
above, and Python3 is a big cleanup over previous versions of the
language.

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


Re: Python 2.7 or 3.1

2010-10-29 Thread Jorge Biquez

Hello all

Would you consider a "not so intelligent move" for a newsbie to 
Python to have maybe version 2.7 and 3.x (if that's possible to be 
running together on the same machine) to have them run and be 
learning mainly in 2.7 and see differences in 3.x? In my case I am 
interested mainly in web applications with a database and if possible 
being accesing dbase since a projects still runs a big system under 
dbase format,  or definitely stay with 2.7 for a while until most in 
migrate it t o 3.x?


Thanks in advance
Jorge Biquez

At 05:21 p.m. 29/10/2010, geremy condra wrote:

On Wed, Oct 27, 2010 at 7:18 PM, Braden Faulkner  wrote:
> Would it be safe to say that 2.6 would be even better for beginners than?

Let me just come out with a contrary point of view before you go down
that path. If you're seriously considering using sqlite, then you may
be just as well off using Python3 as 2.7 or 2.6- it's in all of the
above, and Python3 is a big cleanup over previous versions of the
language.

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



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


Re: Exception Handling in Python 3

2010-10-29 Thread Greg Ewing

Chris Rebert wrote:

On Fri, Oct 29, 2010 at 2:30 AM, Gregory Ewing
 wrote:



I think what's disturbing about this is that the two halves of
the extended traceback are printed in the wrong order. We're



True, but swapping the order would only worsen Steve's problem.


Yes, I can see that what Steve's problem requires is a way
of explicitly saying "replace the current exception" without
attaching any context.

However, in the case where the replacement is accidental,
I think it would make more sense to display them in the
opposite order. Both of the exceptions represent bugs in
that situation, so you will want to address them both, and
you might as well get the traceback in a non-confusing order.

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


Re: multiprocessing signal defect

2010-10-29 Thread Neal Becker
Antoine Pitrou wrote:

> On Fri, 29 Oct 2010 08:12:19 -0400
> Neal Becker  wrote:
>> Seems multiprocessing doesn't behave well with signals:
>> [...]
> 
> By the way, could you post an issue on the tracker with instructions on
> how to reproduce (including OS)?
> 
> Thanks
> 
> Antoine.

http://bugs.python.org/issue10239

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


Re: Runtime error

2010-10-29 Thread Peter Pearson
On Thu, 28 Oct 2010 18:26:49 +0200, Sebastian  wrote:
> Hi all,
>
> I am new to python and I don't know how to fix this error. I only try to 
> execute python (or a cgi script) and I get an ouptu like
>
> [...]
> 'import site' failed; traceback:
> Traceback (most recent call last):
> File "/usr/lib/python2.6/site.py", line 513, in 
> main()
> File "/usr/lib/python2.6/site.py", line 496, in main
> known_paths = addsitepackages(known_paths)
> File "/usr/lib/python2.6/site.py", line 288, in addsitepackages
> addsitedir(sitedir, known_paths)
> File "/usr/lib/python2.6/site.py", line 185, in addsitedir
> addpackage(sitedir, name, known_paths)
> File "/usr/lib/python2.6/site.py", line 155, in addpackage
> exec line
> File "", line 1, in 
> File "/usr/lib/python2.6/site.py", line 185, in addsitedir
> addpackage(sitedir, name, known_paths)
> File "/usr/lib/python2.6/site.py", line 155, in addpackage
> exec line
> File "", line 1, in 
> File "/usr/lib/python2.6/site.py", line 185, in addsitedir
> addpackage(sitedir, name, known_paths)
> File "/usr/lib/python2.6/site.py", line 155, in addpackage
> exec line
> [...]
> File "/usr/lib/python2.6/site.py", line 185, in addsitedir
> addpackage(sitedir, name, known_paths)
> File "/usr/lib/python2.6/site.py", line 155, in addpackage
> exec line
> File "", line 1, in 
> File "/usr/lib/python2.6/site.py", line 175, in addsitedir
> sitedir, sitedircase = makepath(sitedir)
> File "/usr/lib/python2.6/site.py", line 76, in makepath
> dir = os.path.abspath(os.path.join(*paths))
> RuntimeError: maximum recursion depth exceeded
>
>
> What is going wrong with my python install? What do I have to change?

While we're waiting for the smart guys to notice your plea,
it will help if you identify your operating system and
show the command that you used to execute Python.  The
parenthetical "or a cgi script" is mysterious to me.

-- 
To email me, substitute nowhere->spamcop, invalid->net.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python 2.7 or 3.1

2010-10-29 Thread Braden Faulkner

I personally would take only one bite at a time. Meaning only do one then do 
the other later. 
But to each it own :)

> Date: Fri, 29 Oct 2010 17:48:11 -0500
> To: [email protected]
> From: [email protected]
> Subject: Re: Python 2.7 or 3.1
> 
> Hello all
> 
> Would you consider a "not so intelligent move" for a newsbie to 
> Python to have maybe version 2.7 and 3.x (if that's possible to be 
> running together on the same machine) to have them run and be 
> learning mainly in 2.7 and see differences in 3.x? In my case I am 
> interested mainly in web applications with a database and if possible 
> being accesing dbase since a projects still runs a big system under 
> dbase format,  or definitely stay with 2.7 for a while until most in 
> migrate it t o 3.x?
> 
> Thanks in advance
> Jorge Biquez
> 
> At 05:21 p.m. 29/10/2010, geremy condra wrote:
> >On Wed, Oct 27, 2010 at 7:18 PM, Braden Faulkner  wrote:
> > > Would it be safe to say that 2.6 would be even better for beginners than?
> >
> >Let me just come out with a contrary point of view before you go down
> >that path. If you're seriously considering using sqlite, then you may
> >be just as well off using Python3 as 2.7 or 2.6- it's in all of the
> >above, and Python3 is a big cleanup over previous versions of the
> >language.
> >
> >Geremy Condra
> >--
> >http://mail.python.org/mailman/listinfo/python-list
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
  -- 
http://mail.python.org/mailman/listinfo/python-list


Re: Runtime error

2010-10-29 Thread John Machin
On Oct 29, 3:26 am, Sebastian  wrote:
> Hi all,
>
> I am new to python and I don't know how to fix this error. I only try to
> execute python (or a cgi script) and I get an ouptu like
>
> [...]
> 'import site' failed; traceback:
> Traceback (most recent call last):
> File "/usr/lib/python2.6/site.py", line 513, in 
> main()
> File "/usr/lib/python2.6/site.py", line 496, in main
> known_paths = addsitepackages(known_paths)
> File "/usr/lib/python2.6/site.py", line 288, in addsitepackages
> addsitedir(sitedir, known_paths)
> File "/usr/lib/python2.6/site.py", line 185, in addsitedir
> addpackage(sitedir, name, known_paths)
> File "/usr/lib/python2.6/site.py", line 155, in addpackage
> exec line
> File "", line 1, in 
> File "/usr/lib/python2.6/site.py", line 185, in addsitedir
> addpackage(sitedir, name, known_paths)
> File "/usr/lib/python2.6/site.py", line 155, in addpackage
> exec line
> File "", line 1, in 
> File "/usr/lib/python2.6/site.py", line 185, in addsitedir
> addpackage(sitedir, name, known_paths)
> File "/usr/lib/python2.6/site.py", line 155, in addpackage
> exec line
> [...]
> File "/usr/lib/python2.6/site.py", line 185, in addsitedir
> addpackage(sitedir, name, known_paths)
> File "/usr/lib/python2.6/site.py", line 155, in addpackage
> exec line
> File "", line 1, in 
> File "/usr/lib/python2.6/site.py", line 175, in addsitedir
> sitedir, sitedircase = makepath(sitedir)
> File "/usr/lib/python2.6/site.py", line 76, in makepath
> dir = os.path.abspath(os.path.join(*paths))
> RuntimeError: maximum recursion depth exceeded
>
> What is going wrong with my python install? What do I have to change?

Reading the code for site.py, it looks like you may have a .pth file
that is self-referential (or a chain or 2 or more .pth files!) that
are sending you around in a loop. If you are having trouble
determining what files are involved, you could put some print
statements in your site.py at about lines 155 and 185 (which appear to
be in the loop, according to the traceback) or step through it with a
debugger.

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


Re: Unix-head needs to Windows-ize his Python script (II)

2010-10-29 Thread Lawrence D'Oliveiro
In message <[email protected]>, Gregory Ewing wrote:

> Lawrence D'Oliveiro wrote:
> 
>> You mean “GUI console”. So non-GUI apps get a GUI element whether they
>> want it or not, while GUI ones don’t. That’s completely backwards.
> 
> The "G" in GUI stands for "Graphical". I wouldn't call a window that
> displays nothing but text "graphical".

And yet it takes a GUI to display it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unix-head needs to Windows-ize his Python script (II)

2010-10-29 Thread Lawrence D'Oliveiro
In message , Dave Angel 
wrote:

> Gee, maybe when "you're trying to track down problems", you might try
> starting the application in a console?

On a rationally-designed OS, I have a choice. I can do that, but that’s not 
really my first resort: the first thing I can do is check in ~/.xsession-
errors to see if there are already some useful messages that might 
illuminate the issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MATLAB:matplotlib::Mathematica::???

2010-10-29 Thread Lawrence D'Oliveiro
In message , kj wrote:

> matplotlib, even in its underlying so-called "OO mode", follows
> MATLAB's graphics model, which, in my very subjective opinion, is
> vastly inferior to Mathematica's.

Speaking as someone who once had to do GUI programming in MATLAB, I think 
it’s really only good for one thing: matrix manipulation. Everything else is 
a tacked-on crock.

> The latter allows for a clean separation between the textual
> specification of a graphic object (which can be very complex), and
> its graphic representation.  Furthermore, it is general enough to
> allow for the composition of graphic objects within other graphic
> objects, to arbitrary depth levels.  This readily allows for the
> representation of complex composite figures ...

I thought every graphics representation worth its salt allowed that. SVG, 
for example. Why not have a look at that? It’s cross-platform, and easy to 
generate and parse using XML libraries.

> More generally, despite its usefulness, I find MATLAB in the end
> to be one big ugly hack, so, as a developer, I would prefer to stay
> clear of anything that is modeled after MATLAB, however loosely.

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


Re: A question I have...

2010-10-29 Thread Lawrence D'Oliveiro
In message , geremy 
condra wrote:

> ... dividing strings by a number doesn't make sense.

The logical meaning would be the opposite of multiplying strings by a 
number:

>>> "abc" * 3
'abcabcabc'
>>> "abcabcabc" // 3
'abc'
>>> "abcabcabc" // "abc"
3
>>> "abcabcabd" // 3
(at this point I would accept a ValueError)


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


Re: Tools for turning Python code into XMI?

2010-10-29 Thread Lawrence D'Oliveiro
In message <[email protected]>, Stefan Schwarzer wrote:

> I'm looking for a tool which can read Python files and write
> a corresponding XMI file for import into UML tools.

UML ... isn’t that something more in vogue among the Java/DotNet corporate-
code-cutter-drone crowd?

Specifically, you’re asking for something that can parse a dynamic language 
and generate a static structural description of that code. I don’t think 
it’s possible, in general.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ftplib - Did the whole file get sent?

2010-10-29 Thread Lawrence D'Oliveiro
In message <[email protected]>, John Nagle wrote:

> Look at sock_close in "socketmodule.c".  Note that it ignores the
> return status on close, always returns None, and never raises an
> exception.  As the Linux manual page for "close" says:
> "Not checking the return value of close() is a common but nevertheless
> serious programming error. It is quite possible that errors on a
> previous write(2) operation are first reported at the final close(). Not
> checking the return value when closing the file may lead to silent loss
> of data."

The close call is the wrong place to report such errors. For output, there 
should be some kind of flush-output call that you can use to get the error. 
Close should just unconditionally tear down the connection, which you can do 
whether the prior transfers were successful or not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Land Of Lisp is out

2010-10-29 Thread namekuseijin
On 29 out, 19:06, Alessio Stalla  wrote:
> On 28 Ott, 10:42, [email protected] (Pascal J. Bourguignon)
> wrote:
>
> > [email protected] (Stefan Hübner) writes:
> > >> Would it be right to say that the only Lisp still in common use is the 
> > >> Elisp
> > >> built into Emacs?
>
> > > Clojure (http://clojure.org) is a Lisp on the JVM. It's gaining more and
> > > more traction.
>
> > There are actually 2 REAL Lisp on the JVM:
>
> > - abclhttp://common-lisp.net/project/armedbear/and
>
> > - CLforJavahttp://www.clforjava.org
>
> Well, there are a few Scheme implementations too. Kawa is "famous" for
> having been used by Google as the basis for their App Inventor for
> Android. And I wouldn't define Clojure a "fake" Lisp. It has some
> aspects I don't like, but it is definitely in the Lisp family.
> Actually CLforJava as far as I know is missing crucial features (e.g.
> CLOS) and in some aspects is more tied to Java than Clojure.

Schemes are also missing CLOS, as is Clojure, and I still see them as
Lisps...

CLforJava is a student project not in the same league as even single-
maintainer projects like bigloo or gambit...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: str(int_var) formatted

2010-10-29 Thread John Yeung
On Oct 29, 11:59 am, Tracubik  wrote:
> i've to convert integer x to string, but if x < 10,
> the string have to be '0x' instead of simple 'x'
>
> for example:
>
> x = 9
> str(x) --> '09'

Everyone else seems to prefer the format-based solutions, which is
fine.  I will give zfill a little exposure, as it seems unloved/
underused:

str(x).zfill(2)

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


Re: downcasting problem

2010-10-29 Thread Lawrence D'Oliveiro
In message , Nikola Skoric wrote:

> I have a file full of lines which I parse into Line objects. I also
> have two subclasses of Line, namely Individual and Family. Constructor
> of both subclasses needs all Line objects in the file to be
> constructed, so I cannot construct subclass objects in the first pass.

Circularity of reference which does not fit into the object-oriented 
insistence on a hierarchy. So the only way around it is to introduce more 
layers of complications which get you further way from solving the original 
problem.

Tell me again, what relevance OO has to the real world?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating PDF file in Python

2010-10-29 Thread Lawrence D'Oliveiro
In message , Ed Keith wrote:

> I need to generate PDF files and I'm exploring what tools to use. I was
> planing on using ReportLab, but recently found some references to pango
> (http://www.pango.org/) and ciaro (http://cairographics.org/) being able
> to generate PDF files. But am having difficulty finding details.

Pango is just a text-layout engine. It doesn’t provide its own rendering
facilities; it relies on graphics APIs like Cairo for that.

For Cairo, just render to a PDF surface
.

> Are there other options I have overlooked?

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


Re: curses and processing terminal escape characters

2010-10-29 Thread Lawrence D'Oliveiro
In message , Tim Harig wrote:

> Python could easily process the escape codes for any given terminal; but,
> in general, you would want something that works for more then a single
> terminal type.

Does anyone still bother with anything other than VT1xx-type terminals?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embarrassing class question

2010-10-29 Thread Lawrence D'Oliveiro
In message <[email protected]>, Peter Pearson wrote:

> Yes, module w imports x, and therefore w.x exists.  Is that bad?

No-one seems to have come out and said this yet (unless it was in one of 
those messages that no longer seem to be accessible on my ISP’s news 
server): Python has no provision for visibility control. That’s it. No 
public/private/protected or anything like that. Everything defined directly 
within a module or class is visible outside it using dir(module_or_class).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: factorial of negative one (-1)

2010-10-29 Thread Bj Raz
Thank you Robert for the clarification.  Since I'm an amateur programmer,
could you please give me a sample of how I would do it.  I'll take some time
to study arrays as well, and how to write them, I know of lists, and tuples,
and dictionaries; from "Dive into Python". but I am very green around the
ears still. :|

On Fri, Oct 29, 2010 at 11:16 AM, Robert Kern  wrote:

> On 10/29/10 12:02 AM, Chris Rebert wrote:
>
>> On Thu, Oct 28, 2010 at 9:41 PM, Bj Raz  wrote:
>>
>>> I am working with differential equations of the higher roots of negative
>>> one. (dividing enormous numbers into other enormous numbers to come out
>>> with
>>> very reasonable numbers).
>>> I am mixing this in to a script for Maya (the final output is graph-able
>>> as
>>> a spiral.)
>>> I have heard that Sage, would be a good program to do this in, but I'd
>>> like
>>> to try and get this to work in native python if I can.
>>> The script I am trying to port to Python is;
>>> http://pastebin.com/sc1jW1n4.
>>>
>>
>> Unless your code is really long, just include it in the message in the
>> future.
>> So, for the archive:
>> indvar = 200;
>> q = 0;
>> lnanswer = 0;
>> for m = 1:150
>>   lnanswer = (3 * m) * log(indvar) - log(factorial(3 * m))  ;
>> q(m+1) = q(m)+ ((-1)^m) * exp(lnanswer);
>> end
>> lnanswer
>> q
>>
>> Also, it helps to point out *what language non-Python code is in*. I'm
>> guessing MATLAB in this case.
>>
>> Naive translation attempt (Disclaimer: I don't know much MATLAB):
>>
>> from math import log, factorial, exp
>> indvar = 200
>> q = [0]
>> lnanswer = 0
>> for m in range(1, 151):
>> lnanswer = (3 * m) * log(indvar) - log(factorial(3 * m))
>> q.append(q[-1] + (1 if m % 2 == 0 else -1) * exp(lnanswer))
>> print(lnanswer)
>> print(q)
>>
>
> I promised that I would reply when the OP posted here. Except you gave the
> answer that I would have.
>
> To the OP: In your code snippet, q(m+1) and q(m) are not function calls.
> They are array indexing operations (with the special semantics that
> assigning beyond the last element in the array appends a new element to the
> array). You are not setting the result of a function to anything, just
> building up an array of results. You don't need symbolic math libraries like
> SAGE for this.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless
> enigma
>  that is made terrible by our own mad attempt to interpret it as though it
> had
>  an underlying truth."
>  -- Umberto Eco
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A question I have...

2010-10-29 Thread Steven D'Aprano
On Sat, 30 Oct 2010 15:05:37 +1300, Lawrence D'Oliveiro wrote:

> In message , geremy
> condra wrote:
> 
>> ... dividing strings by a number doesn't make sense.
> 
> The logical meaning would be the opposite of multiplying strings by a
> number:
>
> >>> "abc" * 3
> 'abcabcabc'
> >>> "abcabcabc" // 3
> 'abc'


That is a hyper-generalisation. Just because * and + are defined for 
strings doesn't mean we have to define other operators as well.

In general, given a string S, there is no substring s such that s*n = S 
and therefore in general S//n will almost always raise an error, for 
nearly all S and nearly all n. Of the infinite number of combinations of 
string S and integer n, only a vanishingly small proportion will define 
S//n. Given how rarely string division would apply, and the lack of any 
real-world use-case, there is no sensible reason to define S//n.

One could define functions that do anything, but very few of them are 
useful. Defining string//int, or string//string, are not some of the 
useful ones. One might as well define math.sqrt("spam\nspam\nspam\spam") 
= "spam" (it's spam in a square, geddit?) and declare that's the 
"logical" meaning. But that would be silly.



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


Re: embarrassing class question

2010-10-29 Thread Gregory Ewing

Paul Rudin wrote:

Gregory Ewing  writes:


You can clean up dir() by defining __all__ as a list of
names that you want to officially export.


I'm not sure that's necessarily a good idea... when you're trying to figure
out why something behaves in a certain way you want to check for the
presence of methods with special names.


If you need to find out what's really there, you can always
look at module.__dict__.keys().

(BTW, there are no function names that have a special meaning
in a module dict -- a module is not like a class.)

--
Greg

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


Re: functions, list, default parameters

2010-10-29 Thread Gregory Ewing

Steven D'Aprano wrote:

And how does Python know whether some arbitrary default object is mutable 
or not?


It doesn't, that's the whole point.

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