[False,True] and [True,True] --> [True, True]?????

2009-04-20 Thread bdb112
Is there any obvious reason why
[False,True] and [True,True]
gives [True, True]

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Non-secure execution environment

2009-04-20 Thread rogeeff
If anyone is interested I end up using rexec kinda class with only
difference that i am using native __builtin__ and resetting __import__
hook to and from local r_import implementation before and after I am
executing code in my environment.

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


Re: Non-secure execution environment

2009-04-20 Thread rogeeff
If anyone is interested I end up using rexec kinda class with only
difference that i am using native __builtin__ and resetting __import__
hook to and from local r_import implementation before and after I am
executing code in my environment.

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


Re: [False,True] and [True,True] --> [True, True]?????

2009-04-20 Thread Andre Engels
On Mon, Apr 20, 2009 at 9:03 AM, bdb112  wrote:
> Is there any obvious reason why
> [False,True] and [True,True]
> gives [True, True]

Well, whether the reason is obvious, I do not know, but the way and
seems to be implemented is:

X and Y =
* X if the boolean value of X is false
* Y if the boolean value of X is true

In this case, bool([False,True]) = true, so the second element is taken.


-- 
André Engels, [email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: and [True,True] --> [True, True]?????

2009-04-20 Thread AggieDan04
On Apr 20, 2:03 am, bdb112  wrote:
> Is there any obvious reason why
> [False,True] and [True,True]
> gives [True, True]
>
> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> (Intel)]

X and Y == (Y if X else X)
X or Y == (X if X else Y)

[False, True] is true, so the and operator returns the second argument.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [False,True] and [True,True] --> [True, True]?????

2009-04-20 Thread Gabriel Genellina
En Mon, 20 Apr 2009 04:03:28 -0300, bdb112   
escribió:



Is there any obvious reason why
[False,True] and [True,True]
gives [True, True]


Yes: short-circuit evaluation.
[False,True] and [True,True] is *not* an element-by-element operation,  
it's a simple expression involving two objects (two lists).
A and B means: check the boolean value of A; if it's false, return A.  
Else, return B.
A non-empty list has a boolean value of true, so the second list is  
returned.


If you want an element-wise operation:
A = [False,True]
B = [True,True]
result = [a and b for a,b in zip(A,B)]
--
Gabriel Genellina

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


Re: The Python standard library and PEP8

2009-04-20 Thread Lawrence D'Oliveiro
In message , Christian 
Heimes wrote:

> Neither Java nor Python are pure object oriented languages.

That's like saying the Soviet Union was never a pure communist country, or 
that the US is not a pure capitalist country. "Pure", it seems, can be 
endlessly redefined to exclude any example you might care to name, that you 
don't happen to like.

In short, it's a meaningless adjective.

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


Re: The Python standard library and PEP8

2009-04-20 Thread Lawrence D'Oliveiro
In message , Aahz wrote:

> What kind of OO language allows you to do this:
> 
> def square(x):
> return x*x
> 
> for i in range(10):
> print square(x)

Take out the "OO" qualifier, and the answer is still "none":

Traceback (most recent call last):
  File "", line 2, in 
NameError: name 'x' is not defined


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


Hello everyone!

2009-04-20 Thread Yilong Deng
I'm a newby here, I love python very much.
Is there any Chinese here?--
http://mail.python.org/mailman/listinfo/python-list


Re: Can some1 review my code?

2009-04-20 Thread David Lees

[email protected] wrote:

When done all this you might feel it is not necessary to review the code
any more, which is then is a good moment to actually request a review :-)




I'll be happy to have a look at it though you might consider posting it
here, more chance of useful feedback ;-)


Great, Thanks a lot I will make sure that I complete what ever you
have listed here and then
request for a review. Well I understand that refusing to post the code
here in the mailing list might
annoy people and posting code here will only help it making it more
robust and clean. I am just being cautious that I don't break any of
the laws at my workplace.


I would second what another poster recommended.  Post snippets.  My 
experience over the last 8 years is that a short post on a single issue 
elicits very helpful responses.  Also these days there many books on 
Python; find one that suits your learning style.



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


PEP 401

2009-04-20 Thread alessiogiovanni . baroni
Are 19 days that I read this PEP; it's all true?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to create an unclosed dialog in wxPython?

2009-04-20 Thread liangguanhui
On 4月18日, 下午9时40分, 书虫  wrote:
> In wxPython, after I create a wx.Frame, I want to create a modeless
> and unclosed dialog. Here is my step:
>
> app = wx.PySimpleApp()
> f = wx.Frame(None, -1, "Test")
> d = wx.Dialog(f, -1, "Test Dialog", style = wx.CAPTION)
> f.Show()
> d.Show()
> app.MainLoop()
>
> As you see, I create a dialog with wx.CAPTION style. And than, there
> is no close button in this dialog. It seems unclosed dialog, but in
> fact, if you enter Alt+F4 in this dialog, it will close. How could I
> do?

Binds the wx.EVT_CLOSE event and ignor it in the handle function.
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Python standard library and PEP8

2009-04-20 Thread Steven D'Aprano
On Mon, 20 Apr 2009 19:18:23 +1200, Lawrence D'Oliveiro wrote:

> In message , Aahz wrote:
> 
>> What kind of OO language allows you to do this:
>> 
>> def square(x):
>> return x*x
>> 
>> for i in range(10):
>> print square(x)
> 
> Take out the "OO" qualifier, and the answer is still "none":
> 
> Traceback (most recent call last):
>   File "", line 2, in 
> NameError: name 'x' is not defined


I can't replicate that error. Did you forget to initialize x before 
running the code snippet?



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


Re: The Python standard library and PEP8

2009-04-20 Thread Terry Reedy

Steven D'Aprano wrote:

On Mon, 20 Apr 2009 19:18:23 +1200, Lawrence D'Oliveiro wrote:


In message , Aahz wrote:


What kind of OO language allows you to do this:

def square(x):
return x*x

for i in range(10):
print square(x)

Take out the "OO" qualifier, and the answer is still "none":

Traceback (most recent call last):
  File "", line 2, in 
NameError: name 'x' is not defined



I can't replicate that error. Did you forget to initialize x before 
running the code snippet?


The code as posted had a typo: 'x' instead of the instended 'i'.

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


Re: QT , Wxwidgets are not just UI framework ?

2009-04-20 Thread Phil Thompson
On Sun, 19 Apr 2009 20:32:23 -0700 (PDT), Old Listener
 wrote:
> On Apr 17, 10:20 am, Phil Thompson 
> wrote:
>> On Fri, 17 Apr 2009 07:04:40 -0700 (PDT), Deep_Feelings
>>
>>
>>
>>  wrote:
>> > On Apr 17, 1:52 pm, "Diez B. Roggisch"  wrote:
>> >> Deep_Feelings wrote:
>> >> > qt include many libraries : network , threading,database ..etc
while
>> >> > Wxwidgets seem similar but with less scope
>>
>> >> > my question is : does these frameworks replace python's (or any
>> >> > other
>> >> > language for that matter) built-in libraries ? or python does not
>> >> > include that sort of libraries ?
>>
>> >> Some it includes, others it doesn't. And they come with different
>> >> features.
>>
>> >> While python comes with a lot of included batteries, for some things
>> >> you
>> >> need a more powerful generator - that's where 3rd-party-libraries
come
>> >> into
>> >> play.
>>
>> >> There are plenty of discussions about which GUI-toolkit is the best -
>> >> google
>> >> this group.
>>
>> >> However, mostly people agree that Qt is the most powerful, but often
>> >> was
>> >> debunked because of it's licensing. This has changed to the much more
>> >> liberal LGPL for Qt4.5.
>>
>> >> Now it might be though that you'd still need to buy a license from
>> >> Phil
>> >> Thompson for his excellent PyQt-wrapping - but I'd personally say
it's
>> >> more
>> >> worth than it actually costs given the power of Qt.
>>
>> >> Diez
>>
>> > thank you
>>
>> > considering that wxwidget is open source and free do you think that QT
>> > lisencing is worth it ?
>>
>> wxWidgets, Qt and PyQt are all open source and free - just not the same
>> open source license.
>>
>> Phil
> 
> Can PyQt be used in the Qt Creator IDE?

I don't know - ask on the PyQt or Creator mailing lists.

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


Re: Equivalent to C bitmasks and enumerations

2009-04-20 Thread Ulrich Eckhardt
Ulrich Eckhardt wrote:
[how to handle bitfields and enumerations in Python]

Thanks to all that answered. The important lessons I learned:
 * You can modify classes, other than in C++ where they are statically
defined. This allows e.g. adding constants.
 * __repr__ should provide output suitable as input to the Python
interpreter if possible.

Very interesting!

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


RE: Keyerror addhandler

2009-04-20 Thread Steven Macintyre
Hi Diez,

I am using 2.4, could that be the cuase of your issue below. 

Ideally, I would like to stay with the 2.4 version and based on two
tutorials, this was what I came up with 

Steven

Steven Macintyre schrieb:
> Hi all,
> 
> I'm wondering if anyone can assist me with this as I am very confused
about
> it now.
> 
> I am getting the following error;
> 
> Traceback (most recent call last):
>   File "/usr/lib/python2.4/logging/config.py", line 191, in fileConfig
> logger.addHandler(handlers[hand])
> KeyError: 'handler_mylogfileHandler'

For me, that fails with

mac-dir:tmp deets$ python2.5 test.py
Traceback (most recent call last):
   File "test.py", line 6, in 
 logging.config.fileConfig("logging.conf")
   File 
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/logging/con
fig.py", 
line 84, in fileConfig
 handlers = _install_handlers(cp, formatters)
   File 
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/logging/con
fig.py", 
line 149, in _install_handlers
 klass = eval(klass, vars(logging))
   File "", line 1, in 
NameError: name 'RotatingFileHandler' is not defined
mac-dir:tmp deets$

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

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


best "void" return of a member function

2009-04-20 Thread Andreas Otto

Hi,

  I'm writing a native language binding for a library.

http://libmsgque.sourceforge.net/

  Every native method called by PYTHON have to return
  a PyObject* even if the function itself does not
  return anything.

  I have 2 possibilities for return a PyObject*


1. the first argument of the method function
-> return self;
2. an entire new empty object
-> return Py_BuildValue("");

  Question: what is the best return statement for a "void" function ?

  P.S:  NULL is not allowed, because NULL is returned in the case
of an "error"


mfg

  Andreas Otto

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


Re: Is there a programming language that is combination ofPythonandBasic?

2009-04-20 Thread Hendrik van Rooyen
"Chris Jones"  wrote:

> Intellectually, assembler programming is the less demanding since its
> level of abstraction does not go any further than mapping a few binary
> numbers to a small set of usually well-chosen mnemonics.

This is the surface complexity - it is true that when you write an assembler
statement, you know exactly *what* it is going to do.  The *why*, however,
is not always as obvious, as it entails keeping far more *registers and memory
locations* alive in your mind as you go - and the temptation is great, for
efficiency's sake, to let a series of calls leave their answers *in place*,
ready
for the next call to use:

call this
jc error_handling
call that
jc error_handling
call thenextthing
jc error_handling
...

This kind of thing is in a way worse than spaghetti, and it is about
the hardest thing to understand that I know of.  It is also fragile,
as you are never sure if you change something, no matter how well
documented your individual routines are, what the effect of a change
somewhere will have somewhere further down the line, as the
parameters are not explicitly named before the calls.  I find higher
level languages a lot easier to read because of this.

You can do the same kind of thing in Python, using globals, and if
there are enough of them, it will be just as hard to follow.

> Unless it features a powerful macro-language that lets the apprentice
> create his own high-level patois on top of the assembler, that is.

This is the fun part of assembly programming - and here again, one
has to exercise restraint, or the "language" becomes baroque.
Used correctly, however, it allows you to generate a lot of
required boilerplate with very few keystrokes.

It is also very useful to create application specific virtual machines
with specialised *instruction sets* which can make solving some
problems a lot easier. - and that is a level of abstraction that is
in a sense orthogonal to the levels of abstraction brought to the
party by a high level language that has a simple von Neumann
machine as it's base assumption.

- Hendrik


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


Re: and [True,True] --> [True, True]?????

2009-04-20 Thread bdb112
THanks Gabriel,
Now I know about the zip function.

Your explanation of Boolean ops on lists was clear.
It leads to some intriguing results:

bool([False])
--> True

I wonder if python 3 changes any of this?

> A and B means: check the boolean value of A; if it's false, return A.  
> Else, return B.
> A non-empty list has a boolean value of true, so the second list is  
> returned.
>
> If you want an element-wise operation:
> A = [False,True]
> B = [True,True]
> result = [a and b for a,b in zip(A,B)]
> --
> Gabriel Genellina

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


Re: PEP 401

2009-04-20 Thread Steven D'Aprano
On Sun, 19 Apr 2009 11:02:35 -0700, alessiogiovanni.baroni wrote:

> Are 19 days that I read this PEP; it's all true?

For the benefit of people who are not aware of the tradition of "April 
Fools":

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

Look at the date of the PEP and the status.



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


Re: PEP 401

2009-04-20 Thread Chris Rebert
On Mon, Apr 20, 2009 at 1:22 AM, Steven D'Aprano
 wrote:
> On Sun, 19 Apr 2009 11:02:35 -0700, alessiogiovanni.baroni wrote:
>
>> Are 19 days that I read this PEP; it's all true?
>
> For the benefit of people who are not aware of the tradition of "April
> Fools":
>
> http://en.wikipedia.org/wiki/April_fool
>
> Look at the date of the PEP and the status.

Heck, just look at its number and mentally insert one slash or dash.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Python standard library and PEP8

2009-04-20 Thread Steven D'Aprano
On Mon, 20 Apr 2009 03:44:59 -0400, Terry Reedy wrote:

> Steven D'Aprano wrote:
>> On Mon, 20 Apr 2009 19:18:23 +1200, Lawrence D'Oliveiro wrote:
>> 
>>> In message , Aahz wrote:
>>>
 What kind of OO language allows you to do this:

 def square(x):
 return x*x

 for i in range(10):
 print square(x)
>>> Take out the "OO" qualifier, and the answer is still "none":
>>>
>>> Traceback (most recent call last):
>>>   File "", line 2, in 
>>> NameError: name 'x' is not defined
>> 
>> 
>> I can't replicate that error. Did you forget to initialize x before
>> running the code snippet?
> 
> The code as posted had a typo: 'x' instead of the instended 'i'.

Well duh, that's obvious :)

It's such an obvious typo that I wonder what point Lawrence thought he 
was making to show that it wouldn't run as given.



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


Re: The Python standard library and PEP8

2009-04-20 Thread Steven D'Aprano
On Mon, 20 Apr 2009 19:15:51 +1200, Lawrence D'Oliveiro wrote:

> In message ,
> Christian Heimes wrote:
> 
>> Neither Java nor Python are pure object oriented languages.
> 
> That's like saying the Soviet Union was never a pure communist country,
> or that the US is not a pure capitalist country. "Pure", it seems, can
> be endlessly redefined to exclude any example you might care to name,
> that you don't happen to like.

> In short, it's a meaningless adjective.

Not in the least.

There's an accepted definition for "objected oriented programming 
language": a language which provides "objects", which are constructs 
encapsulating both data and routines to operate on that data in a single 
item.

A "pure" OO language is clearly a language where *everything* is 
performed using OO techniques on objects. That's in contrast to impure OO 
languages like Java, which exposes ints and floats as machine primitives, 
and Python, which allows and encourages non-OO techniques. Purity in 
object-orientivity is not necessarily a good thing.

In fact, we don't even need to know what a "pure" OO language is to know 
that Python isn't one. All we need is one feature that all reasonable 
people agree isn't OO, and we know that Python isn't pure OO. Since 
Python includes such functional tools as map() and reduce(), and there is 
no such collection.map() method, we know that Python isn't purely OO.



Waiting-for-somebody-to-claim-that-map(alist)-is-object-oriented-ly y'rs,


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


Re: and [True,True] --> [True, True]?????

2009-04-20 Thread Peter Otten
bdb112 wrote:

> Your explanation of Boolean ops on lists was clear.
> It leads to some intriguing results:
> 
> bool([False])
> --> True
> 
> I wonder if python 3 changes any of this?

No. Tests like

if items:
   ...

to verify that items is a non-empty list are a widespread idiom in Python.
They rely on the behaviour you observe.

Peter

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


RE: Keyerror addhandler

2009-04-20 Thread Peter Otten
Steven Macintyre wrote:

Please don't top-post.

[Diez B. Roggisch]

> For me, that fails with

> NameError: name 'RotatingFileHandler' is not defined

[Steven Macintyre]

> I am using 2.4, could that be the cuase of your issue below.
> 
> Ideally, I would like to stay with the 2.4 version and based on two
> tutorials, this was what I came up with

It looks like 2.5 has the better error message, but the actual problem is
the same for both versions. Try changing mylogfileHandler's class to

[handler_mylogfileHandler]
class=handlers.RotatingFileHandler

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


Re: please include python26_d.lib in the installer

2009-04-20 Thread Compie
On 31 mrt, 22:53, Carl Banks  wrote:
> On Mar 31, 12:50 pm, Compie  wrote:
>
> > On 27 mrt, 17:01, Carl Banks  wrote:
>
> > > OTOH, it's possible that SWIG and Python just happen to use the same
> > > macro to indicate debugging mode.  So I think you raise a valid point
> > > that this can be problematic.  Perhaps something like _Py_DEBUG should
> > > be used instead.
>
> > This would be a good solution IMHO. I'm not the only one facing this
> > problem. The internet is full of people looking for this 
> > file...http://www.google.com/search?q=python25_d.lib+error+cannot
>
> > _DEBUG is automatically defined by Visual Studio when you build the
> > Debug version of a 
> > project.http://msdn.microsoft.com/en-us/library/0b98s6w8.aspx
>
> > So I'm proposing: please use _PYTHON_DEBUG for this purpose. Would
> > this cause any problems?
>
> Go to bugs.python.org and file a bug report with the conflict it is
> causing you.  (Well, first, make sure no one else has reported it.)  I
> advise you to stress the downfalls of the current approach in a
> professional, respectful manner.  You have been coming off as slightly
> whiny in this thread, and that'll hurt your chances of getting such a
> change approved.  In particular, don't ask for anything, or ask why it
> was implemented that way; just report the issue and suggest a fix.
>
> I suspect they used _DEBUG deliberately.  I disagree with that: a
> generic symbol like _DEBUG should be avoided in general, and should
> really be avoided when it entails a change in interface.
>
> Carl Banks

Yes you are right, whining here won't help, I will file a bug report.

But I really needed the discussion here before I could do that. I
didn't know all the pros and cons of the current approach.
I was just reporting a problem that I (and many others) have with
pyconfig.h and Debug mode. But I do recognize that my current approach
(how I reported this problem) is not the most effective one. Thanks
for the tip.

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


Re: and [True,True] --> [True, True]?????

2009-04-20 Thread Gerhard Häring
Peter Otten wrote:
> bdb112 wrote:
> 
>> Your explanation of Boolean ops on lists was clear.
>> It leads to some intriguing results:
>>
>> bool([False])
>> --> True
>>
>> I wonder if python 3 changes any of this?
> 
> No. Tests like
> 
> if items:
>...
> 
> to verify that items is a non-empty list are a widespread idiom in Python.
> They rely on the behaviour you observe.

Are they widespread? I haven't noticed, yet.

I prefer to write it explicitly:

if len(lst) > 0:
...

if item is None:
...

etc.

-- Gerhard

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


Re: The Python standard library and PEP8

2009-04-20 Thread Steven D'Aprano
On Mon, 20 Apr 2009 08:05:01 +0200, Emmanuel Surleau wrote:

> On Monday 20 April 2009 01:48:04 Steven D'Aprano wrote:
> 
>> It also depends on whether you see the length of a data structure as a
>> property of the data, or the result of an operation ("counting") on the
>> data structure. We often fall into the trap of saying such things as
>> "the string HAS A length of 42" when what we really mean is "if you
>> count the elements of the string we find 42 of them". I don't believe
>> that the relationship between strings and length is a has-a
>> relationship. I believe it is a property requiring a function
>> (counting) to emerge, and therefore under OO principles, length should
>> *not* be an attribute and Java et al are guilty of misuse of OO in
>> making length an attribute.
> 
> This didn't quite make sense. Methods are "abilities" an object has. Why
> shouldn't a string be able to compute its length?

Nothing. I'm not talking about methods, I'm talking about making length a 
property (or attribute if you prefer).

I must admit a mistake: Java does not treat the length of a string as an 
attribute, but uses a callable method, String.length(), so I withdraw my 
accusation of misuse of OO principles.

[...]
> As noted above, nothing would stop Fred from having the ability to
> "computeHeight()", though. I guess you could say that what I find silly
> is that String objects have a number of abilities, which: - are more
> complicated than retrieving their own length - most likely use len()
> internally anyway

Advantages of calling a length method:

- Consistency with other methods.

- Makes it easy to discover by introspection.

Disadvantages of calling a length method:

- In Python for built-in lists, tuples and strings, it requires at least 
one extra attribute lookup that the len() function doesn't need. (Java 
can avoid paying that cost at runtime by doing it at compile time -- this 
isn't available to Python.)

- It makes it more difficult to write functional code such as this:

map(len, [seq1, seq2, seq3])

where the various seq* are arbitrary sequences, not necessarily just 
strings. (Functional in the sense of functional-programming, not in the 
sense of "it works".)

- It makes it harder to intercept calls to len() for debugging. I can do 
this:

def len(obj):
print "called len with arg %r" % obj  # or log it somewhere
return __builtins__.len(obj)

and have all the calls to len go through that, without even knowing what 
type of object is being called. 

But note that because len() in turn calls obj.__len__ (unless obj is a 
known built-in like str), you keep all the advantages of OO methods like 
sub-classing, without any of the disadvantages.


> And yet, when asked, it's not able to do something as basic as tell its
> length. This seems inconsistent to me.

Well, you can do this:

>>> s = "abc"
>>> s.__len__()
3


but if you do it in public, be prepared to have other Python programmers 
laugh at you.

It's just a stylistic difference, it's not a functional difference. Even 
if there is a genuine, objective advantage to one approach over the other 
(and I believe that advantage goes to len() as a function), it's quite 
small and it won't really make that big a difference.



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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-20 Thread Marco Mariani

Michael Torrie wrote:


http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html

Somebody better tell the Linux kernel developers about that!  They
apparently haven't read that yet.  Better tell CPU makers too.  In
assembly it's all gotos.



I'm sure you are joking.
Using goto for error handling in C is a reasonable practice,
Avoiding that for the sake of it would be like, say, avoiding "raise" in 
python because "a procedure should only have one exit point".

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


Re: best "void" return of a member function

2009-04-20 Thread Andreas Otto
Andreas Otto wrote:

  well propable found the answer by my own ...

Py_RETURN_NONE

  should be the best

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


Re: PEP 401

2009-04-20 Thread Steven D'Aprano
On Mon, 20 Apr 2009 01:30:44 -0700, Chris Rebert wrote:


>> Look at the date of the PEP and the status.
> 
> Heck, just look at its number and mentally insert one slash or dash.

Fourth of January? What's special about 4th of Jan?



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


Re: PEP 401

2009-04-20 Thread Chris Rebert
On Mon, Apr 20, 2009 at 2:28 AM, Steven D'Aprano
 wrote:
> On Mon, 20 Apr 2009 01:30:44 -0700, Chris Rebert wrote:
>
>
>>> Look at the date of the PEP and the status.
>>
>> Heck, just look at its number and mentally insert one slash or dash.
>
> Fourth of January? What's special about 4th of Jan?

Curse you L10n!

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: compiler package vs parser

2009-04-20 Thread Robin Becker

Kay Schluehr wrote:

I realize that I probably ought to be trying this out with the newer ast stuff,
but currently I am supporting code back to 2.3 and there's not much hope of
doing it right there without using the compiler package.


You might consider using the *builtin* parser module and forget about
the compiler package if it is broken ( I take your word that it is )
or modern ast representations which aren't really necessary for Python
anyway.


import parser
tree = parser.suite("def foo():\n print 42}\n")
code = tree.compile()
exec code
foo()

42

This is also not 100% reliable ( at least not for all statements in
all Python versions ) but it uses the internal parser/compiler and not
a standard library compiler package that might not be that well
maintained.

...
thinking about it I just made the wrong decision back in 2004; we observed a 
semantic change caused by the new scoping rules and tried to fix using the wrong 
model; back then we were probably supporting 2.0 as well so the parser module 
probably wasn't available everywhere anyway; even today the ast stuff isn't 
available in 2.4. I prefer the ast approach as preppy is effectively indentation 
free which makes the tree harder to synthesize for the parser tree.

--
Robin Becker

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


Re: and [True,True] --> [True, True]?????

2009-04-20 Thread Chris Rebert
On Mon, Apr 20, 2009 at 1:54 AM, Gerhard Häring  wrote:
> Peter Otten wrote:
>> bdb112 wrote:
>>
>>> Your explanation of Boolean ops on lists was clear.
>>> It leads to some intriguing results:
>>>
>>> bool([False])
>>> --> True
>>>
>>> I wonder if python 3 changes any of this?
>>
>> No. Tests like
>>
>> if items:
>>    ...
>>
>> to verify that items is a non-empty list are a widespread idiom in Python.
>> They rely on the behaviour you observe.
>
> Are they widespread? I haven't noticed, yet.
>
> I prefer to write it explicitly:
>
> if len(lst) > 0:

Nope, that's not idiomatic. The simpler `if lst:` version is indeed widespread.

>    ...
>
> if item is None:

That's pretty common and accepted; comparison to None is something of
a special case.

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


RE: Keyerror addhandler

2009-04-20 Thread Steven Macintyre
Hi Peter,

> It looks like 2.5 has the better error message, but the actual problem is
> the same for both versions. Try changing mylogfileHandler's class to

[handler_mylogfileHandler]
class=handlers.RotatingFileHandler

Many thanks, this worked for me!

Steven

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


Re: and [True,True] --> [True, True]?????

2009-04-20 Thread Peter Otten
Gerhard Häring wrote:

> Peter Otten wrote:
>> bdb112 wrote:
>> 
>>> Your explanation of Boolean ops on lists was clear.
>>> It leads to some intriguing results:
>>>
>>> bool([False])
>>> --> True
>>>
>>> I wonder if python 3 changes any of this?
>> 
>> No. Tests like
>> 
>> if items:
>>...
>> 
>> to verify that items is a non-empty list are a widespread idiom in
>> Python. They rely on the behaviour you observe.
> 
> Are they widespread? I haven't noticed, yet.

That is my impression.
 
> I prefer to write it explicitly:
> 
> if len(lst) > 0:
> ...

Using google codesearch I get

matches  search expression
ca. 1000 lang:python "if items:"
216  lang:python "if len(items) > 0:"

This could of course mean that "people who like 'items' as a list name also
like the 'if items:...' idiom" or "'items' is a popular name for boolean
values" or "the search result is spammed by a gazillion zope versions"...

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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-20 Thread Marco Mariani

baykus wrote:


those "lines" as numbered steps or numbered bricks that are sitting on
eachother but I see them as timelines or like filmstrips. Anyways it
sounds like such a toy programming language does not exists except
Arnaud surprisingly efficient code.  and I will search my dream
somewhere else :)


Actually, your dreams have already been implemented in Python.

As an april fool's joke. Really.

It works, but is so silly and depraved that I'm not going to provide a link.

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


Re: PEP 401

2009-04-20 Thread Stefan Behnel
Chris Rebert wrote:
> On Mon, Apr 20, 2009 at 1:22 AM, Steven D'Aprano
>  wrote:
>> On Sun, 19 Apr 2009 11:02:35 -0700, alessiogiovanni.baroni wrote:
>>
>>> Are 19 days that I read this PEP; it's all true?
>> For the benefit of people who are not aware of the tradition of "April
>> Fools":
>>
>> http://en.wikipedia.org/wiki/April_fool
>>
>> Look at the date of the PEP and the status.
> 
> Heck, just look at its number and mentally insert one slash or dash.

My first thought was that the PEP number was referring to HTTP 401, i.e.
"unauthorized".

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


Re: and [True,True] --> [True, True]?????

2009-04-20 Thread Steven D'Aprano
On Mon, 20 Apr 2009 10:54:40 +0200, Gerhard Häring wrote:

> Peter Otten wrote:
>> bdb112 wrote:
>> 
>>> Your explanation of Boolean ops on lists was clear. It leads to some
>>> intriguing results:
>>>
>>> bool([False])
>>> --> True
>>>
>>> I wonder if python 3 changes any of this?
>> 
>> No. Tests like
>> 
>> if items:
>>...
>> 
>> to verify that items is a non-empty list are a widespread idiom in
>> Python. They rely on the behaviour you observe.
> 
> Are they widespread? I haven't noticed, yet.
> 
> I prefer to write it explicitly:
> 
> if len(lst) > 0:


Do you also count the length of a list explicitly?

n = 0
for item in lst:
n += 1
if n > 0:
...

No? Of course you don't. You understand that lists know how to calculate 
their own length, and you just ask the list for its length. Great.

Well, lists also know whether or not they are empty, without needing to 
concern yourself with the definition of "empty".

if lst:
# not empty
else:
# empty


All Python objects have an understanding of "empty" or "not empty", and 
the only time I've seen it cause problems is with iterators, because you 
can't tell if an iterator is empty until you actually try to access a 
value.



> if item is None:
> ...

That's a completely different test. That's testing whether item is the 
specific singleton None. It is very different from testing bool(item).



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


Re: best "void" return of a member function

2009-04-20 Thread Christian Heimes
Andreas Otto wrote:
> 
>   well propable found the answer by my own ...
> 
> Py_RETURN_NONE
> 
>   should be the best

You have found the correct answer to your query. :)

Christian

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


Re: Create standalone Windows program with simple graphics?

2009-04-20 Thread Poster28
>> I'd like to program and compile a simple graphics program (showing
>> something like a chess board, some numbers and buttons, mouse support)
>> ...
> 2d or 3d graphics? You could start by looking at pygame and pyopengl.
2D Graphics.

>> ... and provide it as a standalone binary for Windows users.
> py2exe, althought this is a bit of a PITA. I'd get your game working
> first and worry about this aspect of the project last.

Luckily its more of a simulations - not meant to be nice looking or
comfortable. I only need bitmaps positioned like a chess board and also
some mouse support. Hope it will work :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: best "void" return of a member function

2009-04-20 Thread Stefan Behnel
Andreas Otto writes:
>   I'm writing a native language binding for a library.
> 
> http://libmsgque.sourceforge.net/
> 
>   Every native method called by PYTHON have to return
>   a PyObject* even if the function itself does not
>   return anything.
>  [...]
>   Question: what is the best return statement for a "void" function ?

Hmmm, this sounds like your goal is to write an exact 1:1 wrapper of the C
library API (for which there are tools like SWIG&friends). If the library
happens to have a rather unusual, close-to object oriented, high-level C API,
that might work. Otherwise, you might want to try to wrap it in a more Pythonic
look&feel style, that wraps operations and use-cases rather than plain
functions. That should make it easier to hide things like memory allocation and
other C implementation details from users, and will generally increase the
performance of your binding, as it will require less calls for larger operations
in C space.

Stefan


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


Re: best "void" return of a member function

2009-04-20 Thread Stefan Behnel
Stefan Behnel wrote:
> you might want to try to wrap it in a more Pythonic
> look&feel style, that wraps operations and use-cases rather than plain
> functions. That should make it easier to hide things like memory allocation
> and other C implementation details from users, and will generally increase
> the performance of your binding, as it will require less calls for larger
> operations in C space.

Here is an example from your web page:

  Sending data is a sequence of commands to prepare a data-package
  and one command to send this package.
  
  // get the "send" object from the "msgque" object
  struct MqSendS * const send = msgque->send;
  // init the data-package
  MqSendSTART (send);
  // fill the data-package with data
  MqSendI (send, myInteger);
  MqSendC (send, "myString");
  // send the data-package to the server
  MqSendEND (send, "IDNT", NULL);

A first thought would be a class "Connection" and a method "send_package" that
takes an arbitrary number of positional arguments, such as

  connection = some_source.connect()
  connection.send_package(my_int, "myString", end_id="IDNT")

In case you do not know the required data type packing (which is explicit in the
C example), you can either wrap the types in some kind of typing construct
(which might degrade performance, unless you know that you do not need it in
most cases), or define message packing formats in advance in some way, e.g.
similar to Python's "array" module.

Just an idea. Since you appear to be the main author of that library, I assume
that you know best how to make it usable.

Stefan


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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-20 Thread Tim Rowe
2009/4/20 Steven D'Aprano :

> Sheesh. Talk about cherry-picking data. Go read my post in it's entirety,
> instead of quoting mining out of context. If you still think I'm unaware
> of the difference between unstructured GOTOs and structured jumps, or
> that I'm defending unstructured GOTOs, then you might have something
> useful to contribute.

I wasn't cherry picking data, and I did read the entire post. However,
looking back through the message base I see that exactly the same text
appears in another posting by you, and the /other/ post makes it clear
that you know the difference. Sorry for the confusion.

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


Re: best "void" return of a member function

2009-04-20 Thread Stefan Behnel
Stefan Behnel wrote:
> define message packing formats in advance in some way, e.g.
> similar to Python's "array" module.

I (obviously ;) meant the format identifiers in the "struct" module here.

http://docs.python.org/library/struct.html

Stefan


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


Re: any(), all() and empty iterable

2009-04-20 Thread Antoon Pardon
On 2009-04-15, John O'Hagan  wrote:
> On Tue, 14 Apr 2009, Mark Dickinson wrote:
>> On Apr 14, 7:21 pm, Luis Alberto Zarrabeitia Gomez 
>>
>> wrote:
>> > It's more than that. Python's following the rules here. Maybe it could be
>> > documented better, for those without a background in logic/discrete
>> > mathematics, but not changed.
>>
>> Agreed.
>>
>> I'd like to guess that in 93.7% of cases, when a programmer
>> has used all(seq) without having thought in advance about what the
>> right thing to do is when seq is empty, the current behaviour is
>> already the right one.  I tried to test this hypothesis, but a
>> Google code search for uses of all() turned up very little
>> besides definitions.  For example:
>>
>> if all(t.already_filed() for t in my_tax_forms):
>> go_to_bed_happy()
>> else:
>> file_for_extension()
>
>
> But what about this:
>   
> if all(evidence):
>   suspect_is_guilty
> else:
>   suspect_is_innocent

even if the evidence is not empty, the above wouldn't be
a good test, because you need enough evidence en enough
is not implied by all even if all is more than nothing.

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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-20 Thread david
When I was at Data General, writing C (and a little C++), we had a set
of internal coding conventions that mandated a single return point for
a function. Goto's were used during error checks to branch to the
function exit; something like this:

int
frodo() {
  int rval = 0;

  if (bilbo() != 0) {
rval = -1;
goto leave;
  }

  if (gandalf() != 0) {
rval = -1;
goto leave;
  }

  /* lot's of code here */

  leave:
return rval;
}

Made sense to me.

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


ANN: pyparsing 1.5.2 released!

2009-04-20 Thread Paul McGuire
Well, it has been about 6 months since the release of pyparsing 1.5.1,
and there have been no new functional enhancements to pyparsing.  I
take
this as a further sign that pyparsing is reaching a development/
maturity
plateau.

With the help of the pyparsing community, there are some
compatibility
upgrades, and few bug fixes.  The major news is compatibility with
Python 3 and IronPython 2.0.1.  Here is the high-level summary of
what's
new in pyparsing 1.5.2:

- Removed __slots__ declaration on ParseBaseException, for
  compatibility with IronPython 2.0.1.  Raised by David
  Lawler on the pyparsing wiki, thanks David!

- Added pyparsing_py3.py module, so that Python 3 users can use
  pyparsing by changing their pyparsing import statement to:

  import pyparsing_py3

  Thanks for help from Patrick Laban and his friend Geremy
  Condra on the pyparsing wiki.

- Fixed bug in SkipTo/failOn handling - caught by eagle eye
  cpennington on the pyparsing wiki!

- Fixed second bug in SkipTo when using the ignore constructor
  argument, reported by Catherine Devlin, thanks!

- Fixed obscure bug reported by Eike Welk when using a class
  as a ParseAction with an errant __getitem__ method.

- Simplified exception stack traces when reporting parse
  exceptions back to caller of parseString or parseFile - thanks
  to a tip from Peter Otten on comp.lang.python.

- Changed behavior of scanString to avoid infinitely looping on
  expressions that match zero-length strings.  Prompted by a
  question posted by ellisonbg on the wiki.

- Enhanced classes that take a list of expressions (And, Or,
  MatchFirst, and Each) to accept generator expressions also.
  This can be useful when generating lists of alternative
  expressions, as in this case, where the user wanted to match
  any repetitions of '+', '*', '#', or '.', but not mixtures
  of them (that is, match '+++', but not '+-+'):

  codes = "+*#."
  format = MatchFirst(Word(c) for c in codes)

  Based on a problem posed by Denis Spir on the Python tutor
  list.

- Added new example eval_arith.py, which extends the example
  simpleArith.py to actually evaluate the parsed expressions.


Download pyparsing 1.5.2 at http://sourceforge.net/projects/pyparsing/.
The pyparsing Wiki is at http://pyparsing.wikispaces.com

-- Paul


Pyparsing is a pure-Python class library for quickly developing
recursive-descent parsers.  Parser grammars are assembled directly in
the calling Python code, using classes such as Literal, Word,
OneOrMore, Optional, etc., combined with operators '+', '|', and '^'
for And, MatchFirst, and Or.  No separate code-generation or external
files are required.  Pyparsing can be used in many cases in place of
regular expressions, with shorter learning curve and greater
readability and maintainability.  Pyparsing comes with a number of
parsing examples, including:
- "Hello, World!" (English, Korean, Greek, and Spanish(new))
- chemical formulas
- configuration file parser
- web page URL extractor
- 5-function arithmetic expression parser
- subset of CORBA IDL
- chess portable game notation
- simple SQL parser
- Mozilla calendar file parser
- EBNF parser/compiler
- Python value string parser (lists, dicts, tuples, with nesting)
  (safe alternative to eval)
- HTML tag stripper
- S-expression parser
- macro substitution preprocessor
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Python standard library and PEP8

2009-04-20 Thread Aahz
In article ,
Steven D'Aprano   wrote:
>On Mon, 20 Apr 2009 03:44:59 -0400, Terry Reedy wrote:
>> Steven D'Aprano wrote:
>>> On Mon, 20 Apr 2009 19:18:23 +1200, Lawrence D'Oliveiro wrote:
 In message , Aahz wrote:
>
> What kind of OO language allows you to do this:
>
> def square(x):
> return x*x
>
> for i in range(10):
> print square(x)

 Take out the "OO" qualifier, and the answer is still "none":

 Traceback (most recent call last):
   File "", line 2, in 
 NameError: name 'x' is not defined
>>> 
>>> I can't replicate that error. Did you forget to initialize x before
>>> running the code snippet?
>> 
>> The code as posted had a typo: 'x' instead of the instended 'i'.
>
>Well duh, that's obvious :)
>
>It's such an obvious typo that I wonder what point Lawrence thought he 
>was making to show that it wouldn't run as given.

It's called "humor".
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 401

2009-04-20 Thread alessiogiovanni . baroni
On 20 Apr, 10:22, Steven D'Aprano
 wrote:
> On Sun, 19 Apr 2009 11:02:35 -0700, alessiogiovanni.baroni wrote:
> > Are 19 days that I read this PEP; it's all true?
>
> For the benefit of people who are not aware of the tradition of "April
> Fools":
>
> http://en.wikipedia.org/wiki/April_fool
>
> Look at the date of the PEP and the status.
>
> --
> Steven

Yes, yes, I know it; in Italy its name is "pesce d'aprile" ("April's
fish")
(we aren't so out of the world ); I haven't read simply the
status .

Hi to all!
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Python standard library and PEP8

2009-04-20 Thread Scott David Daniels

Steven D'Aprano wrote:
... There's an accepted definition for "objected oriented programming 
language": a language which provides "objects", which are constructs 
encapsulating both data and routines to operate on that data in a single 
item.

Says you. Roger King wrote a book entitled "My Cat is Object-Oriented."
His basic premise is that, while everyone understands what you mean
when you say something is object-oriented, everyone's understanding is
different.

--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Python standard library and PEP8

2009-04-20 Thread George Sakkis
On Apr 19, 6:01 pm, "Martin P. Hellwig"

> Besides, calling Python Object-Orientated is a bit of an insult :-). I
> would say that Python is Ego-Orientated, it allows me to do what I want.

+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


when can i expect libraries and third party tools to be updated for python 3 ?

2009-04-20 Thread Deep_Feelings
every one is telling "dont go with python 3 , 3rd party tools and
libraries have no compitability with python 3"

so from previous experience : when can i expect libraries and third
party tools to be updated for python 3 ? (especially libraries )
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a programming language that is combination of Python and Basic?

2009-04-20 Thread Tim Rowe
2009/4/20 david :
> When I was at Data General, writing C (and a little C++), we had a set
> of internal coding conventions that mandated a single return point for
> a function.

How long ago was that? Or, more relevant, how old was the rule? Or how
long earlier had the person who wrote the rule learned their craft?
One reason for mandating single exit points was that early flow graph
reducers couldn't handle them, but, because of the GOTO equivalents
that you give, graphs with multiple exit points /are/ reducible
without the exponential blowup that node splitting can cause, so
they've been able to handle multiple exits for many years.

Of course, your code is equivalent to:

int
frodo() {
 int rval = 0;

 if (bilbo() != 0) rval = -1
 else
 {
   if (gandalf() != 0) rval = -1
   else
   {
 /* lots of code here */
   }
 }
 return rval;
}

with not a GOTO in sight, and to my mind much clearer logic. If the
nesting meant that the indentation was marching off the side of the
page I'd refactor the "lots of code here" into an inline helper
function. And provided bilbo() and gandalf() don't have side effects,
I'd probably rewrite it as:

int
frodo()
{
 int rval = 0;

 if ((bilbo() == 0) || (gandalf() == 0)
 {
   /* lot's of code here */
 }
 else rval = -1;
 return rval;
}

I'd be inclined to do it that way even if multiple exits were allowed;
it just seems so much clearer.

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


Re: when can i expect libraries and third party tools to be updated for python 3 ?

2009-04-20 Thread alessiogiovanni . baroni
On 20 Apr, 15:47, Deep_Feelings  wrote:
> every one is telling "dont go with python 3 , 3rd party tools and
> libraries have no compitability with python 3"
>
> so from previous experience : when can i expect libraries and third
> party tools to be updated for python 3 ? (especially libraries )

When the authors of a every library wants update to 3 :-D.
--
http://mail.python.org/mailman/listinfo/python-list


How save clipboard data as bmp file

2009-04-20 Thread gopal mishra
Hi,

 

I am trying to save my clipboard data (format is CF_ENHMETAFILE) as BitMap
file (.BMP).

 

Can any on suggest how to do this.

 

 

Thanks & Regards,

Gopal

 

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


Re: when can i expect libraries and third party tools to be updated for python 3 ?

2009-04-20 Thread Stefan Behnel
alessiogiovanni.baroni wrote:
> On 20 Apr, 15:47, Deep_Feelings wrote:
> > every one is telling "dont go with python 3 , 3rd party tools and
> > libraries have no compitability with python 3"
> >
> > so from previous experience : when can i expect libraries and third
> > party tools to be updated for python 3 ? (especially libraries )
> 
> When the authors of a every library wants update to 3 :-D.

Yes, that is the correct answer. From what I read, I would say that in most
projects, work or at least discussion has started regarding Py3 compatibility,
but it's not always trivial to get there, so (wo)manpower will often be the
limiting factor.

This is specifically a problem in C extensions, where running the 2to3 tool is
not an option and adding a 'b' in selected places won't do the job.

Note, BTW, that you do not have to wait for *all* Python libraries to be ported.
Just check when the libraries you require or want to use get ported (or ask the
authors or the development communities), and try a switch when it looks like all
you need is there.

... or give a hand to the projects you need, if you don't want to sit and wait.

Stefan


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


Re: Help improve program for parsing simple rules

2009-04-20 Thread pruebauno
On Apr 17, 5:32 pm, Paul McGuire  wrote:
> On Apr 17, 2:40 pm, [email protected] wrote:
>
>
>
> > On Apr 17, 11:26 am, Paul McGuire  wrote:
>
> > > On Apr 16, 10:57 am, [email protected] wrote:
>
> > > > Another interesting task for those that are looking for some
> > > > interesting problem:
> > > > I inherited some rule system that checks for programmers program
> > > > outputs that to be ported: given some simple rules and the values it
> > > > has to determine if the program is still working correctly and give
> > > > the details of what the values are. If you have a better idea of how
> > > > to do this kind of parsing please chime in. I am using tokenize but
> > > > that might be more complex than it needs to be. This is what I have
> > > > come up so far:
>
> > > I've been meaning to expand on pyparsing's simpleArith.py example for
> > > a while, to include the evaluation of the parsed tokens.  Here is the
> > > online version,http://pyparsing.wikispaces.com/file/view/eval_arith.py,
> > > it will be included in version 1.5.2 (coming shortly).  I took the
> > > liberty of including your rule set as a list of embedded test cases.
>
> > > -- Paul
>
> > That is fine with me. I don't know how feasible it is for me to use
> > pyparsing for this project considering I don't have admin access on
> > the box that is eventually going to run this. To add insult to injury
> > Python is in the version 2->3 transition (I really would like to push
> > the admins to install 3.1 by the end of the year before the amount of
> > code written by us gets any bigger) meaning that any third party
> > library is an additional burden on the future upgrade. I can't
> > remember if pyparsing is pure Python. If it is I might be able to
> > include it alongside my code if it is not too big.- Hide quoted text -
>
> > - Show quoted text -
>
> It *is* pure Python, and consists of a single source file for the very
> purpose of ease-of-inclusion.  A number of projects include their own
> versions of pyparsing for version compatibility management, matplotlib
> is one that comes to mind.
>
> The upcoming version 1.5.2 download includes a pyparsing_py3.py file
> for Python 3 compatibility, I should have that ready for users to
> download *VERY SOON NOW*!
>
> -- Paul

Thanks,
I will consider it. I have to admit that although it looks like it is
a very good solution, it is also longer and more complex than my
current code. Having to explicitly define standard python evaluation
and semantics is a bit overkill.
--
http://mail.python.org/mailman/listinfo/python-list


Re: any(), all() and empty iterable

2009-04-20 Thread Jani Hakala
Raymond Hettinger  writes:

> FWIW, I wrote the docs.  The pure python forms were put in
> as an integral part of the documentation.  The first
> sentence of prose was not meant to stand alone.  It is a
> lead-in to the code which makes explicit the short-circuiting
> behavior and the behavior when the input is empty.
>
Someone else seems to have written "What's new in Python 2.5"
documention which states:

 "Two new built-in functions, any() and all(), evaluate whether an
  iterator contains any true or false values. any() returns True if any
  value returned by the iterator is true; otherwise it will return
  False. all() returns True only if all of the values returned by the
  iterator evaluate as true."

This description of all() doesn't seem to be correct.

> I will probably leave the lead-in sentence as-is but may
> add another sentence specifically covering the case for
> an empty iterable.
>
Does this change cover the documentation returned by help(all) and 
help(any)?

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


Re: best "void" return of a member function

2009-04-20 Thread Andreas Otto
Stefan Behnel wrote:

> Andreas Otto writes:
>>   I'm writing a native language binding for a library.
>> 
>> http://libmsgque.sourceforge.net/
>> 
>>   Every native method called by PYTHON have to return
>>   a PyObject* even if the function itself does not
>>   return anything.
>>  [...]
>>   Question: what is the best return statement for a "void" function ?
> 
> Hmmm, this sounds like your goal is to write an exact 1:1 wrapper of the C
> library API (for which there are tools like SWIG&friends). If the library
> happens to have a rather unusual, close-to object oriented, high-level C
> API, that might work. Otherwise, you might want to try to wrap it in a
> more Pythonic look&feel style, that wraps operations and use-cases rather
> than plain functions. That should make it easier to hide things like
> memory allocation and other C implementation details from users, and will
> generally increase the performance of your binding, as it will require
> less calls for larger operations in C space.
> 
> Stefan

Thanks for your help ..

  I'm almost finished ... it took me ~1week from a non Python developer to:
1. download, install python
2. learn how to use python, syntax, class, objects, protocol, ...
3. learn how to use the native interface, ~hundreds of C functions
4. finally create a project add my native code, compile, build ... test
-> I just add one extra type I call them "PyMqS_type"

  all the special tools are not necessary because
if you wrote one language interface you can write every language 
interface
-> the tasks are allways the same... just the language-specific-names
are changing


mfg

  Andreas Otto

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


Re: when can i expect libraries and third party tools to be updated for python 3 ?

2009-04-20 Thread pruebauno
On Apr 20, 9:47 am, Deep_Feelings  wrote:
> every one is telling "dont go with python 3 , 3rd party tools and
> libraries have no compitability with python 3"
>
> so from previous experience : when can i expect libraries and third
> party tools to be updated for python 3 ? (especially libraries )


I predict: one year.


(THIS PREDICTION IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE
AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM,
OUT OF OR IN CONNECTION WITH THE PREDICTION OR THE USE OR OTHER
DEALINGS IN
THE PREDICTION.)

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


Re: when can i expect libraries and third party tools to be updated for python 3 ?

2009-04-20 Thread Gerhard Häring
Deep_Feelings wrote:
> every one is telling "dont go with python 3 , 3rd party tools and
> libraries have no compitability with python 3"
> 
> so from previous experience : when can i expect libraries and third
> party tools to be updated for python 3 ? (especially libraries )

The problem is: there is no previous experience. At least not in
Python-land.

Despite its major number, Python 2.0 was not disruptive.

-- Gerhard

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


Re: How save clipboard data as bmp file

2009-04-20 Thread Tino Wildenhain

gopal mishra wrote:

Hi,

 

I am trying to save my clipboard data (format is CF_ENHMETAFILE) as 
BitMap file (.BMP).


Can any on suggest how to do this.


Sure. Open "Paint" press ctrl-v and the save as BMP.

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a programming language that is combination of Python and Basic?

2009-04-20 Thread david
I was at DG in the early nineties. A lot of very smart people devised
some of these conventions, from hard-earned experience in the kernel
and system-level software. I've never been one for "fascist-rules
documents", but in DG's case many of the rules made good sense. I'm
not advocating one approach over another; just wanted to show an
example where some careful thought went into the use of goto.

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


Re: How save clipboard data as bmp file

2009-04-20 Thread Tim Golden

gopal mishra wrote:

I am trying to save my clipboard data (format is CF_ENHMETAFILE) as BitMap
file (.BMP).


Have a look at PIL's ImageGrab module:

 http://www.pythonware.com/library/pil/handbook/imagegrab.htm

I'm not sure if the current version supports metafiles, but
it's easy enough to try.

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


Re: when can i expect libraries and third party tools to be updated for python 3 ?

2009-04-20 Thread Ben Finney
(Is there hope that you could set your ‘From’ field using your real name
so we can discuss with a real person instead of a pseudonym?)

Deep_Feelings  writes:

> every one is telling "dont go with python 3 , 3rd party tools and
> libraries have no compitability with python 3"

That's a situation that will change over time, of course; *entirely new*
code, with no external dependencies, is encouraged to use Python 3.x
where feasible, and the number of existing libraries ported to Python
3.x can be expected to increase.

> so from previous experience :

Whose previous experience? Python has never been in such a situation
before, so I'm not sure what previous experience you expect to apply.

> when can i expect libraries and third party tools to be updated for
> python 3 ? (especially libraries )

That will differ for each and every third party and library, of course.
Some will switch rapidly, others slowly, and still others will molder
unmaintained and never convert.

More to the point, you don't need to know when *every* party switches;
just the parties that produce the libraries in which you're interested.
Why not ask the parties themselves?

-- 
 \  “If we have to give up either religion or education, we should |
  `\  give up education.” —William Jennings Bryan, 1923-01 |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


out of memory with processing module

2009-04-20 Thread Brian
I'm using the third-party "processing" module in Python 2.5, which may
have become the "multiprocessing" module in Python 2.6, to speed up
the execution of a computation that takes over a week to run. The
relevant code may not be relevant, but it is:

q1, q2 = processing.Queue(), processing.Queue()
p1 = processing.Process(target=_findMaxMatch, args=
(reciprocal, user, clusters[1:(numClusters - 1)/2], questions,
copy.copy(maxMatch), q1))
p2 = processing.Process(target=_findMaxMatch, args=
(reciprocal, user, clusters[(numClusters - 1)/2:], questions, copy.copy
(maxMatch), q2))
p1.start()
p2.start()
maxMatch1 = q1.get()[0]
maxMatch2 = q2.get()[0]
p1.join()
p2.join()
if maxMatch1[1] > maxMatch2[1]:
maxMatch = maxMatch1
else:
maxMatch = maxMatch2

This code just splits up the calculation of the cluster that best
matches 'user' into two for loops, each in its own process, rather
than one. (It's not important what the cluster is.)

The error I get is:

[21661.903889] Out of memory: kill process 14888 (python) score 610654
or a child
[21661.903930] Killed process 14888 (python)
Traceback (most recent call last):
...etc. etc. ...

Running this process from tty1, rather than GNOME, on my Ubuntu Hardy
system allowed the execution to get a little further than under GNOME.

The error was surprising because with just 1 GB of memory and a single
for loop I didn't run into the error, but with 5 GB and two processes,
I do. I believe that in the 1 GB case there was just a lot of
painfully slow swapping going on that allowed it to continue.
'processing' appears to throw its hands up immediately, instead.

Why does the program fail with 'processing' but not without it? Do you
have any ideas for resolving the problem? Thanks for your help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: when can i expect libraries and third party tools to be updated for python 3 ?

2009-04-20 Thread Jeremiah Dodds
On Mon, Apr 20, 2009 at 3:40 PM, Stefan Behnel  wrote:

> alessiogiovanni.baroni wrote:
> > On 20 Apr, 15:47, Deep_Feelings wrote:
> > > every one is telling "dont go with python 3 , 3rd party tools and
> > > libraries have no compitability with python 3"
> > >
> > > so from previous experience : when can i expect libraries and third
> > > party tools to be updated for python 3 ? (especially libraries )
> >
> > When the authors of a every library wants update to 3 :-D.
>
>
> ... or give a hand to the projects you need, if you don't want to sit and
> wait.
>
> Stefan
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


I think this is the key, really. I see a lot of people asking about when
libraries will get ported to python 3, and it seems to me like a lot of
people could just do a little reading on the tools provided for migrating,
pull the dev version of the library, and take a crack at it.

I'm sure the various library authors would be appreciative.

Of course, it's probably hard for a lot of people to find time to do so
(this does not exclude the library authors), and a good amount of the people
asking probably aren't quite to the point that they could just dive in to an
unfamiliar codebase.

I would say that porting libraries to 3 would probably be a decent way of
improving ones python chops though.
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Python standard library and PEP8

2009-04-20 Thread Jeremiah Dodds
On Mon, Apr 20, 2009 at 2:18 PM, Scott David Daniels
wrote:

> Steven D'Aprano wrote:
>
>> ... There's an accepted definition for "objected oriented programming
>> language": a language which provides "objects", which are constructs
>> encapsulating both data and routines to operate on that data in a single
>> item.
>>
> Says you. Roger King wrote a book entitled "My Cat is Object-Oriented."
> His basic premise is that, while everyone understands what you mean
> when you say something is object-oriented, everyone's understanding is
> different.
>
> --Scott David Daniels
> [email protected]
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Also see  http://c2.com/cgi/wiki?NobodyAgreesOnWhatOoIs
--
http://mail.python.org/mailman/listinfo/python-list


What is a real name, round 668 (was Re: when can i expect libraries and third party tools to be updated for python 3 ?)

2009-04-20 Thread Aahz
In article <[email protected]>,
Ben Finney   wrote:
>
>(Is there hope that you could set your From field using your real name
>so we can discuss with a real person instead of a pseudonym?)

Could you define what a "real name" is?

(If you think the above sounds annoyed, you are certainly correct; I have
little patience for this nonsense.)
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: best "void" return of a member function

2009-04-20 Thread Andreas Otto

Propable you can help me with an other problem ...

the following code crash with:

==31431== Process terminating with default action of signal 11 (SIGSEGV)
==31431==  General Protection Fault
==31431==at 0x4EA5151: PyObject_GenericGetAttr (object.c:982)
==31431==by 0x4EF1FBD: PyEval_EvalFrameEx (ceval.c:1941)
==31431==by 0x4EF5261: PyEval_EvalCodeEx (ceval.c:2869)
==31431==by 0x4E91618: function_call (funcobject.c:628)
==31431==by 0x4E6C7AC: PyObject_Call (abstract.c:2161)
==31431==by 0x4E8055A: method_call (classobject.c:323)
==31431==by 0x4E6C7AC: PyObject_Call (abstract.c:2161)
==31431==by 0x4E6DFFE: PyObject_CallFunctionObjArgs (abstract.c:2392)
==31431==by 0x6B8A43B: Python_pymsgque_pCallVoidMethod (pymisc.c:36)
==31431==by 0x6B8991D: PythonChildCreate (pymsgque.c:89)
==31431==by 0x6D9E15F: pTokenCheckSystem (token.c:547)
==31431==by 0x6DA5110: pReadHDR (read.c:385)

with the following scenario

1. I have an object on an class
2. this object has a callable method context->config
3. I create an additional object of the same class
4. now I want to bind the context->config to the new object
5. I use: 
context->config = PyMethod_New(PyMethod_GET_FUNCTION(context->config),
(PyObject*)context->self);
6. but call this object with "PyObject_CallFunctionObjArgs" create a crash

this is my C code with some helper

  if (context->self == NULL) {
context->self = PyObject_New(PyMqS_Obj,(PyTypeObject*)context->class);
M0
printO(PyMethod_Function(context->config))
if (context->config != NULL)
  context->config = PyMethod_New(PyMethod_GET_FUNCTION(context->config),
(PyObject*)context->self);
M1
if (context->create != NULL)
  context->create = PyMethod_New(PyMethod_GET_FUNCTION(context->create),
(PyObject*)context->self);
M2
printO(context->config)
printO(PyObject_Type(context->config))
  }

  // 4. set the 'hdl'
  context->self->msgque = msgque;

  // 5. init the new object
M3
  if (msgque->config.server == MQ_YES && context->config != NULL) {
switch (NS(pCallVoidMethod)(msgque, context->config, NULL)) {
  case MQ_OK:   break;
  case MQ_CONTINUE:
  case MQ_ERROR:goto error;
}
  }
M4

this is the output:

output from the first object without error:
configO -> >
PyObject_Type(configO) -> 
PythonChildCreate(pymsgque.c:87) -> 3
PythonChildCreate(pymsgque.c:95) -> 4

output from the second object with the crash:
PythonChildCreate(pymsgque.c:71) -> 0
PyMethod_Function(context->config) -> 
PythonChildCreate(pymsgque.c:75) -> 1
PythonChildCreate(pymsgque.c:78) -> 2
context->config -> >
PyObject_Type(context->config) -> 
PythonChildCreate(pymsgque.c:87) -> 3

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


Re: best "void" return of a member function

2009-04-20 Thread Stefan Behnel
Andreas Otto wrote:
>if you wrote one language interface you can write every language interface

This is like saying: if you used one programming language, you can use every
programming language. "Use" is different from "master" or "appreciate".

> -> the tasks are allways the same... just the language-specific-names
>are changing

That's the typical SWIG problem: you can generate wrappers for tons of
languages, mostly automatically. But none of them will feel 'native' to the
users of each of the target languages (well, possibly excluding C and Java 
here).

As the author, you write a wrapper once (and maybe keep maintaining it), but
every user of the wrapper will have to get along with its API that was copied
into his/her language from another one. And there are usually a lot more users
than authors.

I'm not undervaluing your work. It's good to have many, many library bindings
for Python. But having a "good" one would be even nicer.

Stefan


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


Re: out of memory with processing module

2009-04-20 Thread alessiogiovanni . baroni
On 20 Apr, 17:03, Brian  wrote:
> I'm using the third-party "processing" module in Python 2.5, which may
> have become the "multiprocessing" module in Python 2.6, to speed up
> the execution of a computation that takes over a week to run. The
> relevant code may not be relevant, but it is:
>
>             q1, q2 = processing.Queue(), processing.Queue()
>             p1 = processing.Process(target=_findMaxMatch, args=
> (reciprocal, user, clusters[1:(numClusters - 1)/2], questions,
> copy.copy(maxMatch), q1))
>             p2 = processing.Process(target=_findMaxMatch, args=
> (reciprocal, user, clusters[(numClusters - 1)/2:], questions, copy.copy
> (maxMatch), q2))
>             p1.start()
>             p2.start()
>             maxMatch1 = q1.get()[0]
>             maxMatch2 = q2.get()[0]
>             p1.join()
>             p2.join()
>             if maxMatch1[1] > maxMatch2[1]:
>                 maxMatch = maxMatch1
>             else:
>                 maxMatch = maxMatch2
>
> This code just splits up the calculation of the cluster that best
> matches 'user' into two for loops, each in its own process, rather
> than one. (It's not important what the cluster is.)
>
> The error I get is:
>
> [21661.903889] Out of memory: kill process 14888 (python) score 610654
> or a child
> [21661.903930] Killed process 14888 (python)
> Traceback (most recent call last):
> ...etc. etc. ...
>
> Running this process from tty1, rather than GNOME, on my Ubuntu Hardy
> system allowed the execution to get a little further than under GNOME.
>
> The error was surprising because with just 1 GB of memory and a single
> for loop I didn't run into the error, but with 5 GB and two processes,
> I do. I believe that in the 1 GB case there was just a lot of
> painfully slow swapping going on that allowed it to continue.
> 'processing' appears to throw its hands up immediately, instead.
>
> Why does the program fail with 'processing' but not without it? Do you
> have any ideas for resolving the problem? Thanks for your help.

If your program crashes with more of one process, maybe you handle the
Queue objects
not properly? If you can, post the code of _findMaxMatch.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unpythonic use of property()?

2009-04-20 Thread J Kenneth King
Carl Banks  writes:

> On Apr 17, 4:00 pm, Scott David Daniels  wrote:
>> Carl Banks wrote:
>> > On Apr 17, 10:21 am, J Kenneth King  wrote:
>> >> Consider:
>>
>> >> code:
>> >> 
>>
>> >> class MyInterface(object):
>>
>> >>     def __get_id(self):
>> >>         return self.__id
>>
>> >>     id = property(fget=__get_id)
>>
>> >>     def __init__(self, id, foo):
>> >>         self.__id = id
>> >>         self.foo = foo
>>
>> >> class MyInterface2(object):
>>
>> >>     def __init__(self, id, foo):
>> >>         self._id = id
>> >>         self.foo = foo
>>
>> >>     @property
>> >>     def id(self):
>> >>         return self._id
>>
>> ...
>> >> I was recently informed that it was 'unpythonic' and have since been a
>> >> little confused by the term. I've heard it bandied about before but
>> >> never paid much attention. What is 'unpythonic'? What about this example
>> >> is unpythonic?
>>
>> > There are different reasons someone might have said it.
>> > ...
>> > Some people think attribute name-mangling is unpythonic.  It's true
>> > that people sometimes mistakenly treat it a solid information hiding
>> > mechanism, but I wouldn't call its usage unpythonic when used as
>> > intended: as a way to avoid name-collisions.  If you think it's
>> > worthwhile to protect an attribute from being overwritten, you might
>> > as well guard against accidental conflict with the underlying name.
>>
>> Here you are assuming that a user of your class could not possibly have a
>> valid reason for getting to the underlying variable.  Don't make those
>> decisions for someone else, in Python, "we are all adults here."
>
> They can use the demangled name of the internal variable if they want
> access to it.
>
>
>> > Finally, some people think read-only attributes are unpythonic.  I
>> > think that's ridiculous, although in general I'd advise against making
>> > attributes read-only willy-nilly.  But there's a time and place for
>> > it.
>>
>> Generally, properties are for doing some form of calculation, not
>> for making things read-only.
>
> That might be how properties are "generally" used, but if for some
> reason I wanted a read-only attribute, that's how I'd do it.
>
>
> [snip strawman stuff]
>> It is not
>> your job to protect those users who do not use your code properly from
>> themselves; that way lies madness.
>
> I'm sorry, but the universe is not as simple as you are making it out
> to be.  Blanket statements like the one you just gave here are not
> something that should ever be blindly adhered to.
>
> If, in my judgment, users would be prone to overwrite one of my
> attributes, and if I designed the system to rely on that attribute,
> and if the results of changing it are bad enough, then by golly I'm
> going to make the attribute harder than usual to modify.  And yes,
> that is my job.
>
> Users who want to change it anyway can curse me and then go demangle
> the name themselves.
>
>
> Carl Banks

Thanks for all the replies --

While greatly simplified, the reason for desiring read-only attributes
in this case is that the interface is to a remote server whose policy
relies on data objects represented by this class to have a few values
which never change or are managed by the server and not the end
user. Changing the ID value would break things on the server, so I
wanted to write the interface class to respect those conventions.

I'm well aware that if a developer really wanted to, they could get
around it no matter what I did, but I figure that if I at least make
it really difficult it will be obvious that they're really going into
dangerous territory.

Further (and this might just be a tad paranoid), user interface code
which might use this API might be dangerous. It's one thing for a
developer to break the rules when they need to, but a user shouldn't
be able to. By enforcing read-only on the API it ensure (at least in
my world view) that a developer writing a user interface against it
won't have to code defensively against malicious input.

However, since the difference between the two is simply attribute
name-mangling it's practically a pedantic issue. I guess there might
be some hyper-specific scenario where MyInterface would still be
useful, but this one might not be it.

Again, thanks. :)
--
http://mail.python.org/mailman/listinfo/python-list


Python and GMP.

2009-04-20 Thread alessiogiovanni . baroni
There are reasons why Python not used the GMP library for implementing
its long type?
--
http://mail.python.org/mailman/listinfo/python-list


Re: unpythonic use of property()?

2009-04-20 Thread Michele Simionato
On Apr 17, 7:21 pm, J Kenneth King  wrote:
> Consider:
>
> code:
> 
>
> class MyInterface(object):
>
>     def __get_id(self):
>         return self.__id
>
>     id = property(fget=__get_id)
>
>     def __init__(self, id, foo):
>         self.__id = id
>         self.foo = foo

I use the double underscore/name mangling mechanism only if I am sure
that the
__xxx attribute will be overridden in subclasses, and overriding
without
protection will cause issues. Otherwise I don't bother, I use a single
underscore.
In my mind it is obvious that a private attribute _xxx attribute
should not
be overridden in subclasses without care. The double underscore
instead says "you can override me freely, don't worry" and I reserve
it
for attributes which *should* be overridden.
--
http://mail.python.org/mailman/listinfo/python-list


Re: and [True,True] --> [True, True]?????

2009-04-20 Thread Peter Pearson
On 20 Apr 2009 09:26:34 GMT, Steven D'Aprano wrote:
> On Mon, 20 Apr 2009 10:54:40 +0200, Gerhard Häring wrote:
[snip]
>> I prefer to write it explicitly:
>> 
>> if len(lst) > 0:
>
> Do you also count the length of a list explicitly?
>
> n = 0
> for item in lst:
> n += 1
> if n > 0:
> ...
>
> No? Of course you don't. You understand that lists know how to calculate 
> their own length, and you just ask the list for its length. Great.
>
> Well, lists also know whether or not they are empty, without needing to 
> concern yourself with the definition of "empty".
>
> if lst:
> # not empty
> else:
> # empty
>
> All Python objects have an understanding of "empty" or "not empty", and 
> the only time I've seen it cause problems is with iterators, because you 
> can't tell if an iterator is empty until you actually try to access a 
> value.

Like Gerhard, I prefer the construction that explicitly
says, "This is a list, and this is what I'll do if it's not
empty."  To me, and I suspect to a great many programmers,
"if x:" does *not* mean "if x is not empty", it means "if
x is (in some sense) True, including the possibility that
x is an object from which a True or False value must be
extracted by means that might not be at all obvious."  For
an object lesson in the perils of said extraction, see the
recent thread on [False,True] and [True,True] == [True,True].

People much smarter than me will no doubt rush to point out
that if I were alert, I would know from the context that x
is a list, and if I were thoroughly familiar with Python, I
would know that when x is a list, "if x:" means not empty.
True, but this is all the brain I got, so when I come back
in two months, pathetically disoriented, to peer at this
line of code through my senescent blear, I hope I'll see,
"This, Peter, is a list, and this is what I'll do . . ."

The "not empty" interpretation is a cute shortcut.  But
somebody's gotta put up some resistance to cute shortcuts,
or we'll find ourselves back with Perl.

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


python-magic with python2.6

2009-04-20 Thread Gabriel
Is there any way to use 
python-magic(http://pypi.python.org/pypi/python-magic/0.1) with python2.6?

Or do somebody know something similar to this what is running on 2.6?

--
Gabriel

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


sorting two corresponding lists?

2009-04-20 Thread Esmail

Hello all,

I wonder if someone could help me with sorting two corresponding lists.

For instance the first list contains some items, and the second list
contains their value (higher is better)

items = [apple, car, town, phone]
values = [5, 2, 7, 1]

I would like to sort the 'items' list based on the 'values' list so
that I end up with the following two list:

items = [town, apple, car, phone]
values = [7, 5, 2, 1]

So I would like to keep the corresponding value still corresponding
after the sorting.

Is there an easy/nice/Pythonic way to do this?

Thanks,
Esmail

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


Re: any(), all() and empty iterable

2009-04-20 Thread John O'Hagan
On Mon, 20 Apr 2009, Antoon Pardon wrote:
> On 2009-04-15, John O'Hagan  wrote:
> > On Tue, 14 Apr 2009, Mark Dickinson wrote:

[...] 

> >> I'd like to guess that in 93.7% of cases, when a programmer
> >> has used all(seq) without having thought in advance about what the
> >> right thing to do is when seq is empty, the current behaviour is
> >> already the right one.  I tried to test this hypothesis, but a
> >> Google code search for uses of all() turned up very little
> >> besides definitions.  For example:
> >>
> >> if all(t.already_filed() for t in my_tax_forms):
> >> go_to_bed_happy()
> >> else:
> >> file_for_extension()
> >
> > But what about this:
> >
> > if all(evidence):
> > suspect_is_guilty
> > else:
> > suspect_is_innocent
>
> even if the evidence is not empty, the above wouldn't be
> a good test, because you need enough evidence en enough
> is not implied by all even if all is more than nothing.

One should probably file for an extension until one gets some new tax forms, 
too, for that matter. It was just a facetious way of suggesting that it could 
be seen as counter-intuitive to say that no evidence is all true (you trimmed 
my smiley). 

>>> evidence=()
>>> all(i is True for i in evidence)
True
>>> all(i is False for i in evidence)
True
>>> all(i is blue for i in evidence) 
True 

However don't worry, I've been thoroughly convinced that this behaviour is the 
way it is (and should be) done, if for no other reason than that the 
alternatives are even weirder!

John


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


Re: sorting two corresponding lists?

2009-04-20 Thread Diez B. Roggisch
Esmail wrote:

> Hello all,
> 
> I wonder if someone could help me with sorting two corresponding lists.
> 
> For instance the first list contains some items, and the second list
> contains their value (higher is better)
> 
> items = [apple, car, town, phone]
> values = [5, 2, 7, 1]
> 
> I would like to sort the 'items' list based on the 'values' list so
> that I end up with the following two list:
> 
> items = [town, apple, car, phone]
> values = [7, 5, 2, 1]
> 
> So I would like to keep the corresponding value still corresponding
> after the sorting.
> 
> Is there an easy/nice/Pythonic way to do this?

items = zip(*sorted(zip(values, items)))[1]

To better understand this please note that

a = [1, 2]
b = [3, 4]

zip(*zip(a, b)) == a, b

or, in other words, zip(*argument) is the inverse of an argument created by
zip (under the assumption the a and b have equal length)

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


Re: Python and GMP.

2009-04-20 Thread Diez B. Roggisch
[email protected] wrote:

> There are reasons why Python not used the GMP library for implementing
> its long type?

Any reason it should? I don't know GMP (only that it exists), but adding
binary dependencies is always a tricky and in need of careful weighting
thing to do.

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


Re: sorting two corresponding lists?

2009-04-20 Thread Saketh
On Apr 20, 12:10 pm, Esmail  wrote:
> Hello all,
>
> I wonder if someone could help me with sorting two corresponding lists.
>
> For instance the first list contains some items, and the second list
> contains their value (higher is better)
>
> items = [apple, car, town, phone]
> values = [5, 2, 7, 1]
>
> I would like to sort the 'items' list based on the 'values' list so
> that I end up with the following two list:
>
> items = [town, apple, car, phone]
> values = [7, 5, 2, 1]
>
> So I would like to keep the corresponding value still corresponding
> after the sorting.
>
> Is there an easy/nice/Pythonic way to do this?
>
> Thanks,
> Esmail

Why not use a dictionary instead of two lists? Then you can sort the
dictionary by value -- e.g.

d = dict(zip(items, values))
sorted_items = sorted(d.iteritems(), key=lambda (k,v): (v,k))

This produces a list of pairs, but demonstrates the general idea.
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Python standard library and PEP8

2009-04-20 Thread Colin J. Williams

Emmanuel Surleau wrote:

Hi there,

Exploring the Python standard library, I was surprised to see that several 
packages (ConfigParser, logging...) use mixed case for methods all over the 
place. I assume that they were written back when the Python styling 
guidelines were not well-defined.


Given that it's rather irritating (not to mention violating the principle of 
least surprise) to have this inconsistency, wouldn't it make sense to clean 
up the API by marking old-style, mixed-case methods as deprecated (but 
keep them around anyway) and add equivalent methods following the 
lowercase_with_underscores convention?


On an unrelated note, it would be *really* nice to have a length property on 
strings. Even Java has that!

Why not anySequence.len()?

Colin W.

PS Yes, I know this has been flogged before.


Cheers,

Emm

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


Re: and [True,True] --> [True, True]?????

2009-04-20 Thread Paul Rubin
Peter Pearson  writes:
> The "not empty" interpretation is a cute shortcut.  But
> somebody's gotta put up some resistance to cute shortcuts,
> or we'll find ourselves back with Perl.

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


Re: [ANN] pyxser-0.2r --- Python XML Serialization

2009-04-20 Thread Daniel Molina Wegener
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Stefan Behnel wrote:

> Daniel Molina Wegener wrote:
>>   Sorry, it appears that I've misunderstand your question. By /unicode
>> objects/ I mean /python unicode objects/ aka /python unicode strings/.
> 
> Yes, that's exactly what I'm talking about. Maybe you should read up on
> what Unicode is.

  OK, seems that the better option is to return both types in different 
functions, then it will allow the user to choice to fit the development
needs.

> 
> 
>> Most of them can be reencoded into /latin*/ strings and then /ascii/
>> strings if is that what you want. But for most communications, suchs as
>> Java systems, utf-8 encoding goes as default.
> 
> Well, then do not output a Python unicode string, but a UTF-8 encoded byte
> string as the default. Except for a couple of cases, Python unicode
> strings are very inconvenient for serialised XML.

  OK, good point, I must take a look on the implementation, and as I've 
said, I will implement both returns in different functions to allow a user
choice, and document the impact of using python unicode strings.

  Thanks for your feedback :D

> 
> Stefan

Best regards,
- -- 
.O.| Daniel Molina Wegener   | C/C++ Developer
..O| dmw [at] coder [dot] cl | FreeBSD & Linux
OOO| http://coder.cl/| Standards Basis
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (GNU/Linux)

iQIcBAEBAgAGBQJJ7KMSAAoJEHxqfq6Y4O5NxXcQALZCT+mpjXv2My2XV6VdNAdd
rd2W3q4ZLWdFdawvPwBWIzsoyAWIq1fU5tsZ4gywGesZFF2dbh6QJA7WvsqNaOXp
wraeN0A3uWIwxAQEtHXu/vmO68CskVBxKZOrwjFOFoH3CoDqj0cdltKtddNkjHjl
sxR91bK8lsBtYleQvng5oVjDouTvzSZEj9Lz2EbgjGIe+UKB8cQDLpT5CqF/whW7
kPmmbMJz195dyPTHstTy7BaZTJu/zgA3aNrbl4/QQ9B97dO5oMO3JEQgpTv4KSWn
prpFo447HxYCChd+3wYyEx4tjMfnFezreuWxymKU9BP9Bk6yAcBFfdIDqBvUTDIw
HF24n8NkesoHnoyQ1vf474fyIQ8NT28MQaBZXYntTTx1h015UB7vRMF0L3EttLRy
VdpoRvlVAp01Z+7fdUjIRszveC5OCp1a4ZRmptcrZmIQM83Z/HZDBwjRO0zVuIqM
5qFmhERvgHSEl3cpdANznHZBKEEB9dqmAv9/XV5n5lUMg5Hn6d8yBkiwr5lRJ9eK
0n0602EuiPxgaP5cAbYF0MJGs3c+YNK9eIAmZC9++Fcg6lOlDSwS3RTQMsCi+Rvo
k6gI0YNA9N19zbBfQippf1SGrmGrfPk141gNuXGW2HjIuTF9t3IAUZ/bgpWI74L/
69u5ugNM+ERRnxpgIHLV
=P88y
-END PGP SIGNATURE-

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


Re: out of memory with processing module

2009-04-20 Thread Brian
On Apr 20, 9:18 am, [email protected] wrote:
> On 20 Apr, 17:03, Brian  wrote:
>
>
>
> > I'm using the third-party "processing" module in Python 2.5, which may
> > have become the "multiprocessing" module in Python 2.6, to speed up
> > the execution of a computation that takes over a week to run. The
> > relevant code may not be relevant, but it is:
>
> >             q1, q2 = processing.Queue(), processing.Queue()
> >             p1 = processing.Process(target=_findMaxMatch, args=
> > (reciprocal, user, clusters[1:(numClusters - 1)/2], questions,
> > copy.copy(maxMatch), q1))
> >             p2 = processing.Process(target=_findMaxMatch, args=
> > (reciprocal, user, clusters[(numClusters - 1)/2:], questions, copy.copy
> > (maxMatch), q2))
> >             p1.start()
> >             p2.start()
> >             maxMatch1 = q1.get()[0]
> >             maxMatch2 = q2.get()[0]
> >             p1.join()
> >             p2.join()
> >             if maxMatch1[1] > maxMatch2[1]:
> >                 maxMatch = maxMatch1
> >             else:
> >                 maxMatch = maxMatch2
>
> > This code just splits up the calculation of the cluster that best
> > matches 'user' into two for loops, each in its own process, rather
> > than one. (It's not important what the cluster is.)
>
> > The error I get is:
>
> > [21661.903889] Out of memory: kill process 14888 (python) score 610654
> > or a child
> > [21661.903930] Killed process 14888 (python)
> > Traceback (most recent call last):
> > ...etc. etc. ...
>
> > Running this process from tty1, rather than GNOME, on my Ubuntu Hardy
> > system allowed the execution to get a little further than under GNOME.
>
> > The error was surprising because with just 1 GB of memory and a single
> > for loop I didn't run into the error, but with 5 GB and two processes,
> > I do. I believe that in the 1 GB case there was just a lot of
> > painfully slow swapping going on that allowed it to continue.
> > 'processing' appears to throw its hands up immediately, instead.
>
> > Why does the program fail with 'processing' but not without it? Do you
> > have any ideas for resolving the problem? Thanks for your help.
>
> If your program crashes with more of one process, maybe you handle the
> Queue objects
> not properly? If you can, post the code of _findMaxMatch.


Thanks for your interest. Here's _findMaxMatch:

def _findMaxMatch(reciprocal, user, clusters, sources, maxMatch,
queue):
for clusternumminusone, cluster in enumerate(clusters):
clusterFirstData, clusterSecondData = cluster.getData(sources)
aMatch = gum.calculateMatchGivenData(user.data, None, None,
None, user2data=clusterSecondData)[2]
if reciprocal:
maxMatchB = gum.calculateMatchGivenData(clusterFirstData,
None, None, None, user2data=user.secondUserData)[2]
aMatch = float(aMatch + maxMatchB) / 2
if aMatch > maxMatch[1]:
maxMatch = [clusternumminusone + 1, aMatch]
queue.put([maxMatch])

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


Re: out of memory with processing module

2009-04-20 Thread Brian
On Apr 20, 9:18 am, [email protected] wrote:
> On 20 Apr, 17:03, Brian  wrote:
>
>
>
> > I'm using the third-party "processing" module in Python 2.5, which may
> > have become the "multiprocessing" module in Python 2.6, to speed up
> > the execution of a computation that takes over a week to run. The
> > relevant code may not be relevant, but it is:
>
> >             q1, q2 = processing.Queue(), processing.Queue()
> >             p1 = processing.Process(target=_findMaxMatch, args=
> > (reciprocal, user, clusters[1:(numClusters - 1)/2], questions,
> > copy.copy(maxMatch), q1))
> >             p2 = processing.Process(target=_findMaxMatch, args=
> > (reciprocal, user, clusters[(numClusters - 1)/2:], questions, copy.copy
> > (maxMatch), q2))
> >             p1.start()
> >             p2.start()
> >             maxMatch1 = q1.get()[0]
> >             maxMatch2 = q2.get()[0]
> >             p1.join()
> >             p2.join()
> >             if maxMatch1[1] > maxMatch2[1]:
> >                 maxMatch = maxMatch1
> >             else:
> >                 maxMatch = maxMatch2
>
> > This code just splits up the calculation of the cluster that best
> > matches 'user' into two for loops, each in its own process, rather
> > than one. (It's not important what the cluster is.)
>
> > The error I get is:
>
> > [21661.903889] Out of memory: kill process 14888 (python) score 610654
> > or a child
> > [21661.903930] Killed process 14888 (python)
> > Traceback (most recent call last):
> > ...etc. etc. ...
>
> > Running this process from tty1, rather than GNOME, on my Ubuntu Hardy
> > system allowed the execution to get a little further than under GNOME.
>
> > The error was surprising because with just 1 GB of memory and a single
> > for loop I didn't run into the error, but with 5 GB and two processes,
> > I do. I believe that in the 1 GB case there was just a lot of
> > painfully slow swapping going on that allowed it to continue.
> > 'processing' appears to throw its hands up immediately, instead.
>
> > Why does the program fail with 'processing' but not without it? Do you
> > have any ideas for resolving the problem? Thanks for your help.
>
> If your program crashes with more of one process, maybe you handle the
> Queue objects
> not properly? If you can, post the code of _findMaxMatch.


Thanks for your interest. Here's _findMaxMatch:

def _findMaxMatch(reciprocal, user, clusters, sources, maxMatch,
queue):
for clusternumminusone, cluster in enumerate(clusters):
clusterFirstData, clusterSecondData = cluster.getData(sources)
aMatch = gum.calculateMatchGivenData(user.data, None, None,
None, user2data=clusterSecondData)[2]
if reciprocal:
maxMatchB = gum.calculateMatchGivenData(clusterFirstData,
None, None, None, user2data=user.secondUserData)[2]
aMatch = float(aMatch + maxMatchB) / 2
if aMatch > maxMatch[1]:
maxMatch = [clusternumminusone + 1, aMatch]
queue.put([maxMatch])

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


efficiently checking for string.maketrans conflicts?

2009-04-20 Thread Saketh
Hi everyone:

I'm using "translation" in the sense of string.maketrans here.

I am trying to efficiently compare if two string translations
"conflict" -- that is, either they differently translate the same
letter, or they translate two different letters to the same one. Here
are some examples:

# no conflict - equal
t1 = Translation('ab', 'cd')
t2 = Translation('ab', 'cd')

# no conflict - inverses
t1 = Translation('ab', 'cd')
t2 = Translation('cd', 'ab')

# conflict - same key, different value
t1 = Translation('ab', 'cd')
t2 = Translation('ab', 'ce')

# conflict - different key, same value
t1 = Translation('ab', 'cd')
t2 = Translation('xy', 'cd')

This conflict-checking is the bottleneck of my program, and the
obvious way to implement it -- looping through the translations and
explicitly checking for the above conditions -- is much slower than
I'd like.

Is there a more efficient, Pythonic way of checking if two
translations conflict?

Sincerely,
Saketh
--
http://mail.python.org/mailman/listinfo/python-list


Re: sorting two corresponding lists?

2009-04-20 Thread Luis Alberto Zarrabeitia Gomez



Quoting Esmail :

> items = [apple, car, town, phone]
> values = [5, 2, 7, 1]
> 
> I would like to sort the 'items' list based on the 'values' list so
> that I end up with the following two list:
> 
> items = [town, apple, car, phone]
> values = [7, 5, 2, 1]

I've used this sometimes:

=== [untested] ===
sorted_pairs = sorted(zip(values,items))
values = [value for value, _ in sorted_pairs]
items = [item for _, item in sorted_pairs]
===

You could also do something like this, if you don't mind the extra indirection:

=== [also untested] ===
indices = sorted(range(len(values)), key = lambda i: values[i])
# and then access the values as
print "first value", values[indices[0]]
print "first item", items[indices[0]]
===

Keep in mind that both cases keep the original lists unsorted. I guess you could
use "values[:] = " instead of "values = " on the first option to simulate a
sort_in_place. 

I usually prefer the first form.

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie



-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie


-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu

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


Re: Python and GMP.

2009-04-20 Thread Jean-Paul Calderone

On Mon, 20 Apr 2009 18:24:07 +0200, "Diez B. Roggisch"  
wrote:

[email protected] wrote:


There are reasons why Python not used the GMP library for implementing
its long type?


Any reason it should? I don't know GMP (only that it exists), but adding
binary dependencies is always a tricky and in need of careful weighting
thing to do.


This has been discussion in detail on python-dev (more than once, I think,
even).  Here's the top of one such thread:

 http://mail.python.org/pipermail/python-dev/2008-November/083315.html

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


Re: print as a function in 2.5 ?

2009-04-20 Thread Martin
Hi,

On Sun, Apr 19, 2009 at 7:13 PM, Stef Mientki  wrote:
> hello,
>
> For several reasons I still use Python version 2.5.
> I understand that the print-statement will be replaced in Python version
> 3.0.
>
> At the moment I want to extend the print statement with an optional
> traceback.
> So I've 2 options:
> 1- make a new function, like "eprint ()", where "e" stands for extended
> print
> 2- make a function "print()" that has the extended features

I usually have a tools module/package (depending on size of my
project, mostly a module) that defines an "emit([object, ...][, sep='
'][, end='\n'][, file=sys.stdout])" -- this corresponds
tohttp://docs.python.org/3.0/library/functions.html#print

I found that to be the handiest solution, however I'm too much of an
idiot to use it as a gobally available module right now :) (Yeah I
know DRY)

regards,
Martin

-- 
http://soup.alt.delete.co.at
http://www.xing.com/profile/Martin_Marcher
http://www.linkedin.com/in/martinmarcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: The Python standard library and PEP8

2009-04-20 Thread Emmanuel Surleau
On Monday 20 April 2009 10:55:19 Steven D'Aprano wrote:
> On Mon, 20 Apr 2009 08:05:01 +0200, Emmanuel Surleau wrote:
> > On Monday 20 April 2009 01:48:04 Steven D'Aprano wrote:
> >> It also depends on whether you see the length of a data structure as a
> >> property of the data, or the result of an operation ("counting") on the
> >> data structure. We often fall into the trap of saying such things as
> >> "the string HAS A length of 42" when what we really mean is "if you
> >> count the elements of the string we find 42 of them". I don't believe
> >> that the relationship between strings and length is a has-a
> >> relationship. I believe it is a property requiring a function
> >> (counting) to emerge, and therefore under OO principles, length 
should
> >> *not* be an attribute and Java et al are guilty of misuse of OO in
> >> making length an attribute.
> >
> > This didn't quite make sense. Methods are "abilities" an object has. Why
> > shouldn't a string be able to compute its length?
>
> Nothing. I'm not talking about methods, I'm talking about making length a
> property (or attribute if you prefer).
>
> I must admit a mistake: Java does not treat the length of a string as an
> attribute, but uses a callable method, String.length(), so I withdraw my
> accusation of misuse of OO principles.

Well, Java uses .length on arrays (but arrays are not really objects). But 
most constants are hidden behind accessors or "regular" methods.

> [...]
>
> > As noted above, nothing would stop Fred from having the ability to
> > "computeHeight()", though. I guess you could say that what I find silly
> > is that String objects have a number of abilities, which: - are more
> > complicated than retrieving their own length - most likely use len()
> > internally anyway
>
> Advantages of calling a length method:
>
> - Consistency with other methods.
>
> - Makes it easy to discover by introspection.
>
> Disadvantages of calling a length method:
>
> - In Python for built-in lists, tuples and strings, it requires at least
> one extra attribute lookup that the len() function doesn't need. (Java
> can avoid paying that cost at runtime by doing it at compile time -- this
> isn't available to Python.)

Someone on the list pointed out that that Python actually stores the length of 
a string in a field for performance reasons. I wouldn't be surprised to hear 
that the same is true for lists and tuples. Thoughts?

> - It makes it more difficult to write functional code such as this:
>
> map(len, [seq1, seq2, seq3])
>
> where the various seq* are arbitrary sequences, not necessarily just
> strings. (Functional in the sense of functional-programming, not in the
> sense of "it works".)

That's a good point.

> - It makes it harder to intercept calls to len() for debugging. I can do
> this:
>
> def len(obj):
> print "called len with arg %r" % obj  # or log it somewhere
> return __builtins__.len(obj)
>
> and have all the calls to len go through that, without even knowing what
> type of object is being called.
>
> But note that because len() in turn calls obj.__len__ (unless obj is a
> known built-in like str), you keep all the advantages of OO methods like
> sub-classing, without any of the disadvantages.

Both arguments hold true for any method, though.

> > And yet, when asked, it's not able to do something as basic as tell its
> > length. This seems inconsistent to me.
>
> Well, you can do this:
> >>> s = "abc"
> >>> s.__len__()
>
> 3
>
>
> but if you do it in public, be prepared to have other Python programmers
> laugh at you.

I do understand that you don't call __xxx__ without a good reason.

> It's just a stylistic difference, it's not a functional difference. Even
> if there is a genuine, objective advantage to one approach over the other
> (and I believe that advantage goes to len() as a function), it's quite
> small and it won't really make that big a difference.

Well, Aahz and Carl Banks managed to convince me that len() has legitimate 
reasons to exist, and I can live with that. Thanks for providing some 
examples of functional code where len() as a function is more interesting 
than len() as a method.

Cheers,

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


Re: sorting two corresponding lists?

2009-04-20 Thread Esmail

Hi Diez,

Thanks for this, I had seen zip() before but had no idea
really what it does, this will serve as good motivation to
find out more.

I'm amazed at what this language can do (and the helpfulness
of the people on the list here).

Best,
Esmail

Diez B. Roggisch wrote:


items = zip(*sorted(zip(values, items)))[1]

To better understand this please note that

a = [1, 2]
b = [3, 4]

zip(*zip(a, b)) == a, b

or, in other words, zip(*argument) is the inverse of an argument created by
zip (under the assumption the a and b have equal length)

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



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


Re: sorting two corresponding lists?

2009-04-20 Thread Esmail

Saketh wrote:



Why not use a dictionary instead of two lists? Then you can sort the
dictionary by value -- e.g.


thanks for the suggestion. I am not sure this is quite suitable for my
application (the example I provided was extremely simplified), but this
is a useful technique to know and has been stored away for future use.

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


getter and setter and list appends

2009-04-20 Thread dasacc22
Hi,

I seem to be having a problem with a list being share across multiple
instantiations of it and dont quite understand why this is happening.

My class looks like this,

class Widget(object):
_parent = None
_children = []

def __init__(self, parent=None):
self.parent = parent

@property
def children(self):
return self._children

@property
def parent(self):
return self._parent

@parent.setter
def parent(self, obj):
if obj:
obj._children.append(self)
self._parent = obj


now if i make instances and attach children like so

a = Widget()
b = Widget(a)
c = Widget(a)
d = Widget(c)

Basically all the objects end up sharing the _children list from `a`
instead of forming something like a tree. Any advice would be greatly
appreciated.

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


Re: sorting two corresponding lists?

2009-04-20 Thread Esmail

Thanks Luis, more code for me to study and learn from.

Esmail

Luis Alberto Zarrabeitia Gomez wrote:


I've used this sometimes:




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


Re: getter and setter and list appends

2009-04-20 Thread Diez B. Roggisch
dasacc22 wrote:

> Hi,
> 
> I seem to be having a problem with a list being share across multiple
> instantiations of it and dont quite understand why this is happening.
> 
> My class looks like this,
> 
> class Widget(object):
> _parent = None
> _children = []
> 
> def __init__(self, parent=None):
> self.parent = parent
> 
> @property
> def children(self):
> return self._children
> 
> @property
> def parent(self):
> return self._parent
> 
> @parent.setter
> def parent(self, obj):
> if obj:
> obj._children.append(self)
> self._parent = obj
> 
> 
> now if i make instances and attach children like so
> 
> a = Widget()
> b = Widget(a)
> c = Widget(a)
> d = Widget(c)
> 
> Basically all the objects end up sharing the _children list from `a`
> instead of forming something like a tree. Any advice would be greatly
> appreciated.

The problem stems from you confusing instance attributes with class
attributes. You use a latter, which is shared amongst *all* instances of a
given class.

If you want instance-attributes, use

def __init__(self, ..):
self.children = []

also, your use of properties for the children is pointless in Python. Just
use "children" as attribute name. Then, if at one fine day you want to do
something more than just returning that value, you can still do that witout
changing the interface by using a property - as you do so for parent.

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


Re: getter and setter and list appends

2009-04-20 Thread dasacc22
Ah thank you for clarifying, I did confuse instance and class
attributes from creating the list in the class def. I actually just
spiffed up that class to represent a portion of a much larger class
that needs getter and setter for children. Doing as you said fixed my
problem, heres the code as reference for w/e

class Widget(object):
_children = None
_parent = None

def __init__(self, parent=None):
self.children = []
self.parent = parent

@property
def children(self):
return self._children

@children.setter
def children(self, obj):
self._children = obj

@property
def parent(self):
return self._parent

@parent.setter
def parent(self, obj):
if obj:
print obj
obj.children.append(self)
self._parent = obj


On Apr 20, 1:05 pm, "Diez B. Roggisch"  wrote:
> dasacc22 wrote:
> > Hi,
>
> > I seem to be having a problem with a list being share across multiple
> > instantiations of it and dont quite understand why this is happening.
>
> > My class looks like this,
>
> > class Widget(object):
> >     _parent = None
> >     _children = []
>
> >     def __init__(self, parent=None):
> >         self.parent = parent
>
> >     @property
> >     def children(self):
> >         return self._children
>
> >     @property
> >     def parent(self):
> >         return self._parent
>
> >     @parent.setter
> >     def parent(self, obj):
> >         if obj:
> >             obj._children.append(self)
> >             self._parent = obj
>
> > now if i make instances and attach children like so
>
> > a = Widget()
> > b = Widget(a)
> > c = Widget(a)
> > d = Widget(c)
>
> > Basically all the objects end up sharing the _children list from `a`
> > instead of forming something like a tree. Any advice would be greatly
> > appreciated.
>
> The problem stems from you confusing instance attributes with class
> attributes. You use a latter, which is shared amongst *all* instances of a
> given class.
>
> If you want instance-attributes, use
>
> def __init__(self, ..):
>     self.children = []
>
> also, your use of properties for the children is pointless in Python. Just
> use "children" as attribute name. Then, if at one fine day you want to do
> something more than just returning that value, you can still do that witout
> changing the interface by using a property - as you do so for parent.
>
> Diez

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


  1   2   >