Re: usage of .encode('utf-8','xmlcharrefreplace')?

2008-02-18 Thread J Peyret
On Feb 18, 10:54 pm, 7stud <[EMAIL PROTECTED]> wrote:

> One last point: you can't display a unicode string.  The very act of
> trying to print a unicode string causes it to be converted to a
> regular string.  If you try to display a unicode string without
> explicitly encode()'ing it first, i.e. converting it to a regular
> string using a specified secret code--a so called 'codec', python will
> implicitly attempt to convert the unicode string to a regular string
> using the default codec, which is usually set to ascii.

Yes, the string above was obtained by printing, which got it into
ASCII format, as you picked up.
Something else to watch out for when posting unicode issues.

The solution I ended up with was

1) Find out the encoding in the data file.

In Ubuntu's gedit editor, menu 'Save As...' displays the encoding at
the bottom of the save prompt dialog.

ISO-8859-15 in my case.

2) Look up encoding corresponding to ISO-8859-15 at

http://docs.python.org/lib/standard-encodings.html

3) Applying the decode/encode recipe suggested previously, for which I
do understand the reason now.

#converting rawdescr
#from ISO-8859-15 (from the file)
#to UTF-8 (what postgresql wants)
#no error handler required.
decodeddescr = rawdescr.decode('iso8859_15').encode('utf-8')

postgresql insert is done using decodeddescr variable.

Postgresql is happy, I'm happy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Py_Finalize ERROR!

2008-02-18 Thread zaley
Py_Finalize ERROR!

In my C++ program ,python is embeded . I create one win thread to run
embedded Python code .
So at the begin of thread function I call "Py_Initialize" and at the
end of thread function call "Py_Finalize" .
But after I began thread several times,the program crashed  in
function  "Py_Finalize".
I can see the error occured at function "PyObject_ClearWeakRefs" when
"Py_Finalize" called "type_dealloc";

Note: the python25.dll(lib) is builded by VC6(SP6)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: average of PIL images

2008-02-18 Thread Gabriel Genellina
En Tue, 19 Feb 2008 04:01:04 -0200, vaneric <[EMAIL PROTECTED]>  
escribió:
> On Feb 19, 1:38 am, Robert Kern <[EMAIL PROTECTED]> wrote:

>> Averaging color
>> images is tricky; you really shouldn't do it in the RGB colorspace.
>
> hi,
> thanx for the guidance and detailed replies..I  tried  to pack the
> r,g,b into a single value like below(something a member posted in the
> past)
>
> def rgbTopixelvalue((r,g,b)):
>alpha=255
>return unpack("l", pack("", b, g, r, alpha))[0]

That's much worse than averaging the R,G,B components. First, you have to  
omit the alfa value (or set it at the end). Then, consider this example:  
(0,0,0)=black and (0,1,0)=almost black, average = (0,0,128) = dark blue, a  
total nonsense.

As said above, try to compute using another color space, try HSL. The  
colorsys module can transform from/to RGB.

-- 
Gabriel Genellina

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


Re: Threading the Python interpreter

2008-02-18 Thread Martin v. Löwis
MooJoo wrote:
> I've read that the Python interpreter is not thread-safe

Just to counter this misconception: the Python interpreter *is*
thread-safe. It's just that it won't run in parallel with itself
on multiple CPUs in a single process.

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


Re: usage of .encode('utf-8','xmlcharrefreplace')?

2008-02-18 Thread 7stud
To clarify a couple of points:

On Feb 18, 11:38 pm, 7stud <[EMAIL PROTECTED]> wrote:
> A unicode string looks like this:
>
> s = u'\u0041'
>
> but your string looks like this:
>
> s = 'he Company\xef\xbf\xbds ticker'
>
> Note that there is no 'u' in front of your string.  
>

That means your string is a regular string.


> If a python function requires a unicode string and a unicode string
> isn't provided..

For example: encode().


One last point: you can't display a unicode string.  The very act of
trying to print a unicode string causes it to be converted to a
regular string.  If you try to display a unicode string without
explicitly encode()'ing it first, i.e. converting it to a regular
string using a specified secret code--a so called 'codec', python will
implicitly attempt to convert the unicode string to a regular string
using the default codec, which is usually set to ascii.

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


Re: Why must implementing Python be hard unlike Scheme?

2008-02-18 Thread George Sakkis
On Feb 19, 1:15 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:

> I'm learning Scheme and I am amazed how easy it is to start building a
> half baked Scheme implementation that somewhat works.
>
> After knowing Python for *years* I have no idea how to actually
> implement the darn thing.

>From http://swiss.csail.mit.edu/projects/scheme/, "(Scheme) was
designed to have an exceptionally clear and simple semantics and few
different ways to form expressions". Apparently it did very well in
this department, but for most other programming languages minimality
is not the top priority. Python is not an exception.

> Does this have to be true?  Beneath the more complex syntax are there
> a few core design principles/objects/relationships to help in grokking
> the whole thing? Got any related links?

http://codespeak.net/pypy/dist/pypy/doc/getting-started.html#what-is-pypy

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


Re: usage of .encode('utf-8','xmlcharrefreplace')?

2008-02-18 Thread 7stud
On Feb 18, 10:52 pm, "Carsten Haese" <[EMAIL PROTECTED]> wrote:
> On Mon, 18 Feb 2008 21:36:17 -0800 (PST), J Peyret wrote
>
>
>
> > Well, as usual I am confused by unicode encoding errors.
>
> > I have a string with problematic characters in it which I'd like to
> > put into a postgresql table.
> > That results in a postgresql error so I am trying to fix things with
> > .encode
>
> > >>> s = 'he Company\xef\xbf\xbds ticker'
> > >>> print s
> > he [UTF-8?]Company�s ticker
>
> > Trying for an encode:
>
> > >>> print s.encode('utf-8')
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position
> > 10: ordinal not in range(128)
>
> > OK, that's pretty much as expected, I know this is not valid utf-8.
>
> Actually, the string *is* valid UTF-8, but you're confused about encoding and
> decoding. Encoding is the process of turning a Unicode object into a byte
> string. Decoding is the process of turning a byte string into a Unicode 
> object.
>

...or to put it more simply:  encode() is used to covert a unicode
string into a regular string.  A unicode string looks like this:

s = u'\u0041'

but your string looks like this:

s = 'he Company\xef\xbf\xbds ticker'

Note that there is no 'u' in front of your string.  Therefore, you
can't call encode() on that string.

> Also, why are the exceptions above complaining about the 'ascii'
> codec if I am asking for 'utf-8' conversion?

If a python function requires a unicode string and a unicode string
isn't provided, then python will implicitly try to convert the string
it was given into a unicode string.  In order to convert a given
string into a unicode string, python needs to know the secret code
that was used to produce the given string.  The secret code is
otherwise known as a 'codec'.  When python attempts an implicit
conversion of a given string into a unicode string, python uses the
default codec, which is normally set to 'ascii'.  Since your string
contains non-ascii characters, you get an error.  That all happens
long before your 'utf-8' argument ever comes into play.

decode() is used to convert a regular string into a unicode string
(the opposite of encode()).  Your error is a 'decode' error(rather
than an 'encode' error):

UnicodeDecodeError

because python is implicitly trying to convert the given regular
string into a unicode string with the default ascii codec, and python
is unable to do that.


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

Re: The big shots

2008-02-18 Thread George Sakkis
On Feb 19, 12:08 am, [EMAIL PROTECTED] wrote:

> The problem did not seem to be miscommunication, rather bias.

IMHO it's partly because of the obscurity of the ideas and the code
you suggest, and partly because of the poor job you do to explain
them.

By the way, you may have noticed that you have been mostly replying to
your own posts here in c.l.py, which indicates that the lack of
responses has nothing to do with the supposed snobbishness of the "big
shots".

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


Re: usage of .encode('utf-8','xmlcharrefreplace')?

2008-02-18 Thread J Peyret
OK, txs a lot.  I will have to think a bit more about you said, what I
am doing and how encode/decode fits in.

You are right, I am confused about unicode.  Guilty as charged.

I've seen the decode+encode chaining invoked in some of the examples,
but not the rationale for it.
Also doesn't help that I am not sure what encoding is used in the data
file that I'm using.

I didn't set out to "hide" the original error, just wanted to simplify
my error posting, after having researched enough to see that
encode/decode was part of the solution.
Adding the db aspect to the equation doesn't really help much and I
should have left it out entirely.

FWIW:

 
invalid byte sequence for encoding "UTF8": 0x92
HINT:  This error can also happen if the byte sequence does not match
the encoding expected by the server, which is controlled by
"client_encoding".

column is a varchar(2000) and the "guilty characters" are those used
in my posting.

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


Re: Understanding While Loop Execution

2008-02-18 Thread Tim Roberts
Gary Herron <[EMAIL PROTECTED]> wrote:
>
>So in the following code, the list named full does not have 3 copies of 
>sub in it, but rather it has 3 *references* to the single list named 
>sub.

Since we are being picky here, it's more accurate to say that the list
"full" contains 3 references to the list that is also referenced by the
name "sub".  I've found that it is more useful to think of Python objects
(like lists) as anonymous things living out in object memory (which is, no
doubt, a happy place), and all of the names in the program just refer to
those anonymous things.

>Any changes to the list named sub will be reflected anywhere that 
>list is referred to.

And vice versa.  "sub" is a reference to the list, exactly like "full[0]".
No difference.

> >>> sub = [1,2,3]
> >>> full = [sub,sub,sub]
> >>> full
>[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
> >>> sub[0] = 123
> >>> full
>[[123, 2, 3], [123, 2, 3], [123, 2, 3]]

And:

>>> full[0][2] = 99
>>> sub
[123, 2, 99]
>>> full
[[123, 2, 99], [123, 2, 99], [123, 2, 99]]
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Why must implementing Python be hard unlike Scheme?

2008-02-18 Thread [EMAIL PROTECTED]
I'm learning Scheme and I am amazed how easy it is to start building a
half baked Scheme implementation that somewhat works.

After knowing Python for *years* I have no idea how to actually
implement the darn thing.

Does this have to be true?  Beneath the more complex syntax are there
a few core design principles/objects/relationships to help in grokking
the whole thing? Got any related links?

Certainly, "(almost) everything is an object" is a good start.  Are
there any other axiom like statements one can hang their hat on when
trying to wrap their brain around Python's architecture?

Chris

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


Re: The big shots

2008-02-18 Thread Gabriel Genellina
En Tue, 19 Feb 2008 01:14:10 -0200, <[EMAIL PROTECTED]> escribió:

> I'm a little dissatisfied, and just thinking aloud.
>
> Some of the ideas that have been proposed on Python-ideas as well as
> Python, have received partial evaluation from the alphas.

(Note that I'm not a Python alpha, I don't vote, approve nor reject  
anything).

I skip your posts lately. Not because I have anything against you, not at  
all. Just because it takes too much time for me to make any sense of what  
you write, and I can't spend so much time in a single message.

This may or may not be related to your English skills (I'm not a native  
English speaker, as several others in this group). Perhaps you just write  
the first thing that comes to your mind at any time; but when I read that,  
it looks like a random collection of phrases to me. My ex-neighbor spoke  
in that way too; it was too difficult for me to follow him sometimes. The  
same happened with an old girlfriend of mine; after a long speech about  
the benefits of hydratation on the human being, how important is not to  
forget it on winter, and how she broke a cup last Thursday, I had to  
deduce: it *is* winter now, she likes tea, It must be Lipton (remember the  
brand!!), her favourite cup is broken and I must find a clone... Saying "I  
want a cup of tea" was not an option: too simple for her :)

I think the same happens with you. Maybe your thoughts are crystal clear  
in your mind, but I'm unable to understand you, sorry.

-- 
Gabriel Genellina

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


Re: average of PIL images

2008-02-18 Thread vaneric
On Feb 19, 1:38 am, Robert Kern <[EMAIL PROTECTED]> wrote:
>Averaging color
> images is tricky; you really shouldn't do it in the RGB colorspace.

hi,
thanx for the guidance and detailed replies..I  tried  to pack the
r,g,b into a single value like below(something a member posted in the
past)

def rgbTopixelvalue((r,g,b)):
   alpha=255
   return unpack("l", pack("", b, g, r, alpha))[0]

if i apply this for all images i can represent each image as an array
of longs instead of tuples.then for a pixel i can calculate the
average value
after this if i do the casting as you advised and create the avg
image
 avgface = avgface.astype(numpy.uint8)

here if i use these pixelvalues to create an imag
 img =Image.fromstring('RGB', (width, height), avgface.tostring())
it will fail because of -'not enough image data'..is there an
alternative to create average rgb color image ?(i want to keep the rgb
so can't convert to greyscale)

is there something wrong with my approach? I am a newbie in PIL/
imageprocessing ..so i would greately appreciate feedback
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: usage of .encode('utf-8','xmlcharrefreplace')?

2008-02-18 Thread Carsten Haese
On Mon, 18 Feb 2008 21:36:17 -0800 (PST), J Peyret wrote
> Well, as usual I am confused by unicode encoding errors.
> 
> I have a string with problematic characters in it which I'd like to
> put into a postgresql table.
> That results in a postgresql error so I am trying to fix things with
> .encode
> 
> >>> s = 'he Company\xef\xbf\xbds ticker'
> >>> print s
> he [UTF-8?]Company�s ticker
> >>>
> 
> Trying for an encode:
> 
> >>> print s.encode('utf-8')
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position
> 10: ordinal not in range(128)
> 
> OK, that's pretty much as expected, I know this is not valid utf-8.

Actually, the string *is* valid UTF-8, but you're confused about encoding and
decoding. Encoding is the process of turning a Unicode object into a byte
string. Decoding is the process of turning a byte string into a Unicode object.

You need to decode your byte string into a Unicode object, and then encode the
result to a byte string in a different encoding. For example:

>>> s = 'he Company\xef\xbf\xbds ticker'
>>> s.decode("utf-8").encode("ascii", "xmlcharrefreplace")
'he Company�s ticker'

By the way, whether this is the correct fix for your PostgreSQL error is not
clear, since you kept that error message a secret for some reason. There could
be a better solution than transcoding the string in this way, but we won't
know until you show us the actual error you're trying to fix. At the moment,
it's like showing you the best way to inflate a tire with a hammer.

Hope this helps,

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Terry Reedy

"Asun Friere" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| So was that a yes or no?  I mean is it even possible for the identity
| behaviour of mutables to vary between implementations?  I can't see
| how they can possibly be interned, but is there some other factor I'm
| missing in regard to identity behaviour which could in fact vary
| between implementations?

Not that I can think of,  so 'No'.  The semantics of creation, rebinding, 
and copying are well defined and the behavior is predictable once one 
understands the rules.  The problem some new Pythoneers have is mistakenly 
thinking that binding statements ('=') make copies, or that assignments in 
the body of a class statement or function header (default values) are made 
more than once (per class or function definition execution) or that 
somelist*n copies the contents.  Id() can help elucidate the rules even if 
it is not so useful in running code.

The difference between mutables and immutables is that the interpreter may 
optionally not create a new immutable when it would have created a new 
mutable, but may instead return a reference to an existing immutable of the 
same value.  I call this an application of the 'as if' rule because (except 
for calls to id() and use of 'is') the future behavior of the program is 
the same as if the interpreter has created the new immutable.  (The other 
exception to 'the same' is that the program may run instead of crash due 
the the space saving. ;-)

tjr



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


Re: name of client module

2008-02-18 Thread Jeff Schwab
Ben Finney wrote:
> Nick Stinemates <[EMAIL PROTECTED]> writes:
> 
>> Ah, I snipped because I was only replying to that specific part and
>> thought there was an archive of the rest. If that is unconventional
>> I'll stop.
> 
> Please continue snipping the parts that aren't relevant to your reply.
> The convention in this forum is trimmed-quote, inline-reply.
> 
> I think the complaint in this case might have been the "you snipped
> bits that *were* relevant" failure mode :-)

What he said.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: name of client module

2008-02-18 Thread Ben Finney
Nick Stinemates <[EMAIL PROTECTED]> writes:

> Ah, I snipped because I was only replying to that specific part and
> thought there was an archive of the rest. If that is unconventional
> I'll stop.

Please continue snipping the parts that aren't relevant to your reply.
The convention in this forum is trimmed-quote, inline-reply.

I think the complaint in this case might have been the "you snipped
bits that *were* relevant" failure mode :-)

-- 
 \"Madness is rare in individuals, but in groups, parties, |
  `\ nations and ages it is the rule."  -- Friedrich Nietzsche |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Double underscores -- ugly?

2008-02-18 Thread benhoyt

> [Terry Jan Reedy]
> No, the reservered special names are supposed to be ugly ;-) -- or at least
> to stand out.  However, since special methods are almost always called
> indirectly by syntax and not directly, only the class writer or reader, but
> not users, generally see them.

Fair enough, but my problem is that class writers are users too. :-)

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


usage of .encode('utf-8','xmlcharrefreplace')?

2008-02-18 Thread J Peyret
Well, as usual I am confused by unicode encoding errors.

I have a string with problematic characters in it which I'd like to
put into a postgresql table.
That results in a postgresql error so I am trying to fix things with
.encode

>>> s = 'he Company\xef\xbf\xbds ticker'
>>> print s
he Company�s ticker
>>>

Trying for an encode:

>>> print s.encode('utf-8')
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position
10: ordinal not in range(128)

OK, that's pretty much as expected, I know this is not valid utf-8.
But I should be able to fix this with the errors parameter of the
encode method.

>>> error_replace = 'xmlcharrefreplace'

>>> print s.encode('utf-8',error_replace)
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position
10: ordinal not in range(128)

Same exact error I got without the errors parameter.

Did I mistype the error handler name?  Nope.

>>> codecs.lookup_error(error_replace)


Same results with 'ignore' as an error handler.

>>> print s.encode('utf-8','ignore')
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position
10: ordinal not in range(128)

And with a bogus error handler:

print s.encode('utf-8','bogus')
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position
10: ordinal not in range(128)

This all looks unusually complicated for Python.
Am I missing something incredibly obvious?
How does one use the errors parameter on strings' encode method?

Also, why are the exceptions above complaining about the 'ascii' codec
if I am asking for 'utf-8' conversion?

Version and environment below.  Should I try to update my python from
somewhere?

./$ python
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2

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

Re: How to get current module object

2008-02-18 Thread Alex
Gabriel Genellina wrote:
> En Mon, 18 Feb 2008 14:49:02 -0200, Alex <[EMAIL PROTECTED]> escribió:
>> That's what I've been searching for, thanks. By the way, I know it might
>> be trivial question... but function and class namespaces have __name__
>> attribute too. Why is global one always returned?
> I don't understand the question (even with the later correction  
> namespaces->objects)
There's no question anymore, I just failed to distinguish function local 
variables (which don't include __name__) and function object's attributes
>>> Why do you want to get the module object? globals() returns the module
>>> namespace, its __dict__, perhaps its only useful attribute...
>>>   
>> To pass it as a parameter to a function (in another module), so it can
>> work with several modules ("plugins" for main program) in a similar  
>> manner.
>> 
>
> The function could receive a namespace to work with (a dictionary). Then  
> you just call it with globals() == the namespace of the calling module.
Yes, but access to module seems more verbose:

 >>> module_dict['x']()
xxx

Instead of just:

 >>> module.x()
xxx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The big shots

2008-02-18 Thread castironpi
On Feb 18, 11:22 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Feb 18, 10:26 pm, [EMAIL PROTECTED] (Aahz) wrote:
> >> In article <[EMAIL PROTECTED]>,
> >> Paul Rubin   wrote:
>
> >>> [EMAIL PROTECTED] (Aahz) writes:
>  [EMAIL PROTECTED]:
> > Some of the ideas that have been proposed on Python-ideas as well as
> > Python, have received partial evaluation from the alphas.
>  What do you mean by "alphas"?
> >>> Alpha test releases are the round of test distributions before the
> >>> beta tests, which come before the release candidates which come before
> >>> the final release.  
> >> Interesting, but I would bet that castironpi actually is referring to
> >> "alpha males" (particularly in the context of "big shots"); however, your
> >> confusion is precisely why I called it out.  Incoherent writing rarely
> >> flies well in this community (which is one reason why I love Python!).
> >> --
> >> Aahz ([EMAIL PROTECTED])           <*>        http://www.pythoncraft.com/
>
> >> "All problems in computer science can be solved by another level of    
> >> indirection."  --Butler Lampson
>
> > Who you callin' denigrates?  Ahem.  You think your ships don't
> > sink?  ;)
>
> Humor. Arf arf.
>
> > The problem did not seem to be miscommunication, rather bias.
>
> > What part of, "No one took the train before it was invented," do you
> > not understand?
>
> The problem with this complaint is you simply seem to be saying "there's
> a better language out there somewhere". No clue as to where it is, no
> clue as to how it might be approached. Merely a suggestion that adding
> randomly suggested features to Python, that are currently rejected for
> what appear to me to be mostly sound reasons, will somehow lead us to
> these undiscovered treasures.
>
> > No one climbed Mount Everest before it was discovered, and it wasn't
> > the tallest mountain until then either.
>
> It *was* the tallest mountain - it existed before its discovery, and its
> "discovery" wasn't news to the Sherpas who had been living on it for
> hundreds of years.

They hadn't discovered it -ei-ther!  What is Mount Everest!?

Anyway, I am saying, "there's a good feature out there."

As I've said before: library additions are one thing; syntax changes
are another.

What, in terms of the former, do the gurus rule -out- point blank?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The big shots

2008-02-18 Thread Carsten Haese
On Mon, 18 Feb 2008 21:08:42 -0800 (PST), castironpi wrote
> What part of, "No one took the train before it was invented," do you
> not understand?

Actually, no one took the train before it was built. And no one built the
train before it was feasible to do so.

To take this analogy back into the world of software development, software
features only get built if it's feasible to build them. Unless you want to
contribute by building those features yourself, you're relinquishing the
decision of what's feasible to the "big shots". You get what you pay for.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: The big shots

2008-02-18 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> On Feb 18, 10:26 pm, [EMAIL PROTECTED] (Aahz) wrote:
>> In article <[EMAIL PROTECTED]>,
>> Paul Rubin   wrote:
>>
>>> [EMAIL PROTECTED] (Aahz) writes:
 [EMAIL PROTECTED]:
> Some of the ideas that have been proposed on Python-ideas as well as
> Python, have received partial evaluation from the alphas.
 What do you mean by "alphas"?
>>> Alpha test releases are the round of test distributions before the
>>> beta tests, which come before the release candidates which come before
>>> the final release.  
>> Interesting, but I would bet that castironpi actually is referring to
>> "alpha males" (particularly in the context of "big shots"); however, your
>> confusion is precisely why I called it out.  Incoherent writing rarely
>> flies well in this community (which is one reason why I love Python!).
>> --
>> Aahz ([EMAIL PROTECTED])   <*>http://www.pythoncraft.com/
>>
>> "All problems in computer science can be solved by another level of
>> indirection."  --Butler Lampson
> 
> Who you callin' denigrates?  Ahem.  You think your ships don't
> sink?  ;)
> 
Humor. Arf arf.

> The problem did not seem to be miscommunication, rather bias.
> 
> What part of, "No one took the train before it was invented," do you
> not understand?
> 
The problem with this complaint is you simply seem to be saying "there's 
a better language out there somewhere". No clue as to where it is, no 
clue as to how it might be approached. Merely a suggestion that adding 
randomly suggested features to Python, that are currently rejected for 
what appear to me to be mostly sound reasons, will somehow lead us to 
these undiscovered treasures.

> No one climbed Mount Everest before it was discovered, and it wasn't
> the tallest mountain until then either.

It *was* the tallest mountain - it existed before its discovery, and its 
"discovery" wasn't news to the Sherpas who had been living on it for 
hundreds of years.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: pyinstall and matplotlib

2008-02-18 Thread John Henry
On Feb 18, 8:04 pm, John Henry <[EMAIL PROTECTED]> wrote:
> On Feb 18, 7:34 pm, John Henry <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Feb 17, 11:50 am, Stef Mientki <[EMAIL PROTECTED]> wrote:
>
> > > hi John,
>
> > > John Henry wrote:
> > > > Anybody willing to help?
>
> > > I struggled the past few days with the same problem,
> > > and with the help of Werner Bruhin (wxPython list) I found a solution.
> > > I had 2 problems:
> > >   - not finding mpl datapath
> > >   - matplotlib insisted on installing backends that were distorted on my
> > > system
>
> > > The first problem was solved with the following script:
> > > it has some special parts
> > > - remove the distro and build directories before running setup
> > > - a special matplot part, ensuring mpl-data is copied and installed
> > > - a lot of excludes for matplotlib ( which doesn't seem to work :-( )
>
> > > Kill_Distro = True
> > > MatPlotLib_Wanted = True
>
> > > from distutils.core import setup
> > > import py2exe
> > > import sys
> > > subdirs = [ '..\\P24_support', '..\\P24_pictures',
> > > '..\\P24_Lib_Extensions' ]
> > > for subdir in subdirs:
> > >   if not ( subdir in sys.path) : sys.path.append ( subdir )
>
> > > from file_support import *
>
> > > import shutil
> > > import glob
>
> > > # ***
> > > # Some suggests that old build/dist should be cleared
> > > # ***
> > > dist_paths =  [ 'D:\\Data_Python\\P24_PyLab_Works\\build',
> > > 'D:\\Data_Python\\P24_PyLab_Works\\dist' ]
> > > for path in dist_paths :
> > >   if File_Exists ( path ) :
> > > shutil.rmtree ( path )
> > > # ***
>
> > > # ***
> > > # ***
> > > data_files = []
> > > packages = []
> > > includes = []
> > > excludes = []
> > > dll_excludes = []
> > > data_files.append ( ( '', glob.glob ( 'templates_*.*' ) ) )
>
> > > # ***
> > > # For MatPlotLib
> > > # ***
> > > if MatPlotLib_Wanted :
> > >   import matplotlib
>
> > >   includes.append ( 'matplotlib.numerix.random_array' )
>
> > >   packages.append ( 'matplotlib' )
> > >   packages.append ( 'pytz' )
>
> > >   data_files.append ( ( r'mpl-data', glob.glob (
> > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\*.*' )))
> > >   data_files.append ( ( r'mpl-data', glob.glob (
>
> > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc' )))
> > >   data_files.append ( ( r'mpl-data\\images', glob.glob (
> > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\images\\*.*' 
> > > )))
> > >   data_files.append ( ( r'mpl-data\\fonts\\afm', glob.glob (
>
> > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\afm\\*.*' 
> > > )))
> > >   data_files.append ( ( r'mpl-data\\fonts\\pdfcorefonts', glob.glob (
>
> > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\pdfcorefonts\\*.*'
> > > )))
> > >   data_files.append ( ( r'mpl-data\\fonts\\ttf', glob.glob (
>
> > > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\*.*' 
> > > )))
>
> > >   excludes.append ( '_gtkagg')
> > >   excludes.append ( '_tkagg' )
> > >   excludes.append ( '_agg2'  )
> > >   excludes.append ( '_cairo' )
> > >   excludes.append ( '_cocoaagg' )
> > >   excludes.append ( '_fltkagg' )
> > >   excludes.append ( '_gtk' )
> > >   excludes.append ( '_gtkcairo')
> > >   excludes.append ( 'backend_qt' )
> > >   excludes.append ( 'backend_qt4')
> > >   excludes.append ( 'backend_qt4agg' )
> > >   excludes.append ( 'backend_qtagg' )
> > >   excludes.append ( 'backend_cairo' )
> > >   excludes.append ( 'backend_cocoaagg' )
> > >   excludes.append ( 'Tkconstants' )
> > >   excludes.append ( 'Tkinter' )
> > >   excludes.append ( 'tcl' )
> > >   excludes.append ( "_imagingtk" )
> > >   excludes.append ( "PIL._imagingtk" )
> > >   excludes.append ( "ImageTk" )
> > >   excludes.append ( "PIL.ImageTk" )
> > >   excludes.append ( "FixTk" )
>
> > >   dll_excludes.append ( 'libgdk-win32-2.0-0.dll' )
> > >   dll_excludes.append ( 'libgdk_pixbuf-2.0-0.dll' )
> > >   dll_excludes.append ( 'libgobject-2.0-0.dll')
> > >   dll_excludes.append ( 'tcl84.dll' )
> > >   dll_excludes.append ( 'tk84.dll' )
> > >   dll_excludes.append ( 'tclpip84.dll' )
> > > # ***
>
> > > # seems not to be found (imported in brick.py)
> > > includes.append ( 'PyLab_Works_properties' )
>
> > > # ***
> > > # ***
>
> > > # If run without args, build e

Re: The big shots

2008-02-18 Thread castironpi
On Feb 18, 10:26 pm, [EMAIL PROTECTED] (Aahz) wrote:
> In article <[EMAIL PROTECTED]>,
> Paul Rubin   wrote:
>
> >[EMAIL PROTECTED] (Aahz) writes:
> >>[EMAIL PROTECTED]:
>
> >>>Some of the ideas that have been proposed on Python-ideas as well as
> >>>Python, have received partial evaluation from the alphas.
>
> >> What do you mean by "alphas"?
>
> >Alpha test releases are the round of test distributions before the
> >beta tests, which come before the release candidates which come before
> >the final release.  
>
> Interesting, but I would bet that castironpi actually is referring to
> "alpha males" (particularly in the context of "big shots"); however, your
> confusion is precisely why I called it out.  Incoherent writing rarely
> flies well in this community (which is one reason why I love Python!).
> --
> Aahz ([EMAIL PROTECTED])           <*>        http://www.pythoncraft.com/
>
> "All problems in computer science can be solved by another level of    
> indirection."  --Butler Lampson

Who you callin' denigrates?  Ahem.  You think your ships don't
sink?  ;)

The problem did not seem to be miscommunication, rather bias.

What part of, "No one took the train before it was invented," do you
not understand?

No one climbed Mount Everest before it was discovered, and it wasn't
the tallest mountain until then either.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ROUNDING???

2008-02-18 Thread Asun Friere
On Feb 19, 2:05 pm, 7stud <[EMAIL PROTECTED]> wrote:

> An integer divided by an integer produces an integer.  In computer
> programming, that's called 'integer arithmetic', and any fractional
> part of the result is chopped off(not rounded).

In case you care, the "chopped off" bit is given by the modulo
operator '%'.  So integer division x/y is really like the everyday y
goes into x, p times, remainder q, for example:

>>> 10/3, 10%3
(3, 1)

> If your arithmetic
> involves at least one float, then you will get a float as an asnwer:
>
> print 255/494
> print 255.0/494
> print (255 * 1.0)/494

or indeed "print float(255)/494"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: average of PIL images

2008-02-18 Thread vaneric
On Feb 19, 1:38 am, Robert Kern <[EMAIL PROTECTED]> wrote:
>Averaging color
> images is tricky; you really shouldn't do it in the RGB colorspace.
hi,
thanx for the guidance and detailed replies..I  tried  to pack the
r,g,b into a single value like below(something a member posted in the
past)

def rgbTopixelvalue((r,g,b)):
   alpha=255
   return unpack("l", pack("", b, g, r, alpha))[0]


if i apply this for all images i can represent each image as an array
of longs instead of tuples.then for a pixel i can calculate the
average value
after this if i do the casting as you advised and create the avg
image
 avgface = avgface.astype(numpy.uint8)
 img = Image.fromstring('L', (width, height), avgface.tostring())

is there something wrong with my approach? I am a newbie in PIL/
imageprocessing ..so i would greately appreciate feedback
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The big shots

2008-02-18 Thread Aahz
In article <[EMAIL PROTECTED]>,
Paul Rubin   wrote:
>[EMAIL PROTECTED] (Aahz) writes:
>>[EMAIL PROTECTED]:
>>>
>>>Some of the ideas that have been proposed on Python-ideas as well as
>>>Python, have received partial evaluation from the alphas.
>> 
>> What do you mean by "alphas"?
>
>Alpha test releases are the round of test distributions before the
>beta tests, which come before the release candidates which come before
>the final release.  

Interesting, but I would bet that castironpi actually is referring to
"alpha males" (particularly in the context of "big shots"); however, your
confusion is precisely why I called it out.  Incoherent writing rarely
flies well in this community (which is one reason why I love Python!).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ROUNDING???

2008-02-18 Thread subeen
You can use the round() function. And if you want to print, use %0.2f


regards,
Subeen.
http://love-python.blogspot.com/


On Feb 19, 9:36 am, [EMAIL PROTECTED] (Aahz) wrote:
> In article <[EMAIL PROTECTED]>,
> katie smith  <[EMAIL PROTECTED]> wrote:
>
>
>
> >in python im doing the problem 255/494
>
> >it keeps giving me 0 instead of .51
> >what am i doing wrong?
> >>> from __future__ import division
> >>> 2/5
>
> 0.40002
>
> In addition:
>
> >>> division
>
> _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
>
> Therefore this works in Python 2.2 and higher.
> --
> Aahz ([EMAIL PROTECTED])   <*>http://www.pythoncraft.com/
>
> "All problems in computer science can be solved by another level of
> indirection."  --Butler Lampson

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


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Asun Friere
On Feb 19, 1:45 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Asun Friere" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]

> | The advice not to identity test strings and numbers (since they are
> | interred in the main implementation),
>
> They may or may not be.

Obviously, and that is the problem.  The behaviour will appear
inconsistent unless one is familiar with the conditions under which
they are or are not.  So since the numbers and strings are interned
(under certain conditions), it is probably best not to identity test
them.

>
> Ditto for tuples, unless possibly when they have mutable members.
>

Which is the reason that they are never interned in CPython, no?  So I
was wrong, the categorical avoidance of identity testing is probably
_not_ sound advice with regard to tuples.

> |  But given the nature of
> | immutables, is the identity of these even potentially implementation
> | dependant (ie. they couldn't be interred could they)?
>
> The word is 'interned', not 'interred' (buried).
>

Sorry I'm a goth, so you can understand my mistake ;=

So was that a yes or no?  I mean is it even possible for the identity
behaviour of mutables to vary between implementations?  I can't see
how they can possibly be interned, but is there some other factor I'm
missing in regard to identity behaviour which could in fact vary
between implementations?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyinstall and matplotlib

2008-02-18 Thread John Henry
On Feb 18, 7:34 pm, John Henry <[EMAIL PROTECTED]> wrote:
> On Feb 17, 11:50 am, Stef Mientki <[EMAIL PROTECTED]> wrote:
>
>
>
> > hi John,
>
> > John Henry wrote:
> > > Anybody willing to help?
>
> > I struggled the past few days with the same problem,
> > and with the help of Werner Bruhin (wxPython list) I found a solution.
> > I had 2 problems:
> >   - not finding mpl datapath
> >   - matplotlib insisted on installing backends that were distorted on my
> > system
>
> > The first problem was solved with the following script:
> > it has some special parts
> > - remove the distro and build directories before running setup
> > - a special matplot part, ensuring mpl-data is copied and installed
> > - a lot of excludes for matplotlib ( which doesn't seem to work :-( )
>
> > Kill_Distro = True
> > MatPlotLib_Wanted = True
>
> > from distutils.core import setup
> > import py2exe
> > import sys
> > subdirs = [ '..\\P24_support', '..\\P24_pictures',
> > '..\\P24_Lib_Extensions' ]
> > for subdir in subdirs:
> >   if not ( subdir in sys.path) : sys.path.append ( subdir )
>
> > from file_support import *
>
> > import shutil
> > import glob
>
> > # ***
> > # Some suggests that old build/dist should be cleared
> > # ***
> > dist_paths =  [ 'D:\\Data_Python\\P24_PyLab_Works\\build',
> > 'D:\\Data_Python\\P24_PyLab_Works\\dist' ]
> > for path in dist_paths :
> >   if File_Exists ( path ) :
> > shutil.rmtree ( path )
> > # ***
>
> > # ***
> > # ***
> > data_files = []
> > packages = []
> > includes = []
> > excludes = []
> > dll_excludes = []
> > data_files.append ( ( '', glob.glob ( 'templates_*.*' ) ) )
>
> > # ***
> > # For MatPlotLib
> > # ***
> > if MatPlotLib_Wanted :
> >   import matplotlib
>
> >   includes.append ( 'matplotlib.numerix.random_array' )
>
> >   packages.append ( 'matplotlib' )
> >   packages.append ( 'pytz' )
>
> >   data_files.append ( ( r'mpl-data', glob.glob (
> > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\*.*' )))
> >   data_files.append ( ( r'mpl-data', glob.glob (
>
> > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc' )))
> >   data_files.append ( ( r'mpl-data\\images', glob.glob (
> > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\images\\*.*' )))
> >   data_files.append ( ( r'mpl-data\\fonts\\afm', glob.glob (
>
> > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\afm\\*.*' )))
> >   data_files.append ( ( r'mpl-data\\fonts\\pdfcorefonts', glob.glob (
>
> > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\pdfcorefonts\\*.*'
> > )))
> >   data_files.append ( ( r'mpl-data\\fonts\\ttf', glob.glob (
>
> > r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\*.*' )))
>
> >   excludes.append ( '_gtkagg')
> >   excludes.append ( '_tkagg' )
> >   excludes.append ( '_agg2'  )
> >   excludes.append ( '_cairo' )
> >   excludes.append ( '_cocoaagg' )
> >   excludes.append ( '_fltkagg' )
> >   excludes.append ( '_gtk' )
> >   excludes.append ( '_gtkcairo')
> >   excludes.append ( 'backend_qt' )
> >   excludes.append ( 'backend_qt4')
> >   excludes.append ( 'backend_qt4agg' )
> >   excludes.append ( 'backend_qtagg' )
> >   excludes.append ( 'backend_cairo' )
> >   excludes.append ( 'backend_cocoaagg' )
> >   excludes.append ( 'Tkconstants' )
> >   excludes.append ( 'Tkinter' )
> >   excludes.append ( 'tcl' )
> >   excludes.append ( "_imagingtk" )
> >   excludes.append ( "PIL._imagingtk" )
> >   excludes.append ( "ImageTk" )
> >   excludes.append ( "PIL.ImageTk" )
> >   excludes.append ( "FixTk" )
>
> >   dll_excludes.append ( 'libgdk-win32-2.0-0.dll' )
> >   dll_excludes.append ( 'libgdk_pixbuf-2.0-0.dll' )
> >   dll_excludes.append ( 'libgobject-2.0-0.dll')
> >   dll_excludes.append ( 'tcl84.dll' )
> >   dll_excludes.append ( 'tk84.dll' )
> >   dll_excludes.append ( 'tclpip84.dll' )
> > # ***
>
> > # seems not to be found (imported in brick.py)
> > includes.append ( 'PyLab_Works_properties' )
>
> > # ***
> > # ***
>
> > # If run without args, build executables, in quiet mode.
> > if len(sys.argv) == 1:
> > sys.argv.append("py2exe")
>
> > setup (
> >   windows = ['PyLab_Works.py']  ,
> >   options = {
> >'py2exe' : {
> >   'includes' : includes,
> >   'excludes' : excludes,
> >   'dll_excludes' : dl

Re: The big shots

2008-02-18 Thread Paul Rubin
[EMAIL PROTECTED] (Aahz) writes:
> >Some of the ideas that have been proposed on Python-ideas as well as
> >Python, have received partial evaluation from the alphas.
> 
> What do you mean by "alphas"?

Alpha test releases are the round of test distributions before the
beta tests, which come before the release candidates which come before
the final release.  Ever since Python 2.4, Python's functools module
has supported partial evaluation, bundling up some of the arguments to
a function into a closure (also called currying).  See:

  http://python.org/doc/lib/module-functools

Apparently some stuff from python-ideas has been curried into closures
using the version of that module from some early Python test releases.

I couldn't understand the rest of the post you're replying to either.
The above was the only part I could make any sense of.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The big shots

2008-02-18 Thread Aahz
In article <[EMAIL PROTECTED]>,
 <[EMAIL PROTECTED]> wrote:
>
>I'm a little dissatisfied, and just thinking aloud.

What exactly are you dissatisfied with?  This post reminds me of one
reason why your ideas have not been well received: it is difficult to
understand what your point is.

Perhaps English is not your native language; if that is the case, you may
wish to either improve your proficiency or find someone else that you can
use your native language with to act as your champion.  (I'm not
denigrating you for not knowing English; it is simply a fact that most
Python core development takes place in English, and many of the core
developers -- including Guido himself, MaL, and MvL -- are not native
speakers, either.)

>Some of the ideas that have been proposed on Python-ideas as well as
>Python, have received partial evaluation from the alphas.

What do you mean by "alphas"?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The big shots

2008-02-18 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> I'm a little dissatisfied, and just thinking aloud.
> 
> Some of the ideas that have been proposed on Python-ideas as well as
> Python, have received partial evaluation from the alphas.
> 
> Lesser individuals than they could not have invented Python, and would
> be liable to ban me merely for this post.  Notwithstanding.
> 
> The reason they have cited is, "It is not in prevalent use."
> 
> The printing press, rail, automobiles, and Python, were not in
> prevalent use before their invention.  I.e., they -can't- come if one
> doesn't build it.  However, there were writing, transportation, and
> programming before these respectively; does it merely suffice to
> answer, "Yes it is?"
> 
> The Python gurus' combined professional judgement results in Python.
> 
> Looking through http://www.python.org/dev/peps/ , their own proposals
> don't meet their own criteria.  Start there.
> 
> It is neither necessary nor sufficient that an expansion is or would
> be used.

Well it isn't a democracy, that's true. The "big shots" are the people 
who have proven themselves capable not only of *having* good ideas but 
also seeing them through into implementation.

I don't believe anyone would argue that Python is the best language for 
absolutely every purpose, but it's pretty damned good for most of the 
tings I want to do, so I guess I am in favor of letting "the big shots" 
continue to ignore half-baked ideas :)

No process is perfect. If you want to change the python development 
process you'll have to join the developers.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: ROUNDING???

2008-02-18 Thread Aahz
In article <[EMAIL PROTECTED]>,
katie smith  <[EMAIL PROTECTED]> wrote:
>
>in python im doing the problem 255/494
>
>it keeps giving me 0 instead of .51
>what am i doing wrong?

>>> from __future__ import division
>>> 2/5
0.40002

In addition:

>>> division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

Therefore this works in Python 2.2 and higher.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyinstall and matplotlib

2008-02-18 Thread John Henry
On Feb 17, 11:50 am, Stef Mientki <[EMAIL PROTECTED]> wrote:
> hi John,
>
> John Henry wrote:
> > Anybody willing to help?
>
> I struggled the past few days with the same problem,
> and with the help of Werner Bruhin (wxPython list) I found a solution.
> I had 2 problems:
>   - not finding mpl datapath
>   - matplotlib insisted on installing backends that were distorted on my
> system
>
> The first problem was solved with the following script:
> it has some special parts
> - remove the distro and build directories before running setup
> - a special matplot part, ensuring mpl-data is copied and installed
> - a lot of excludes for matplotlib ( which doesn't seem to work :-( )
>
> Kill_Distro = True
> MatPlotLib_Wanted = True
>
> from distutils.core import setup
> import py2exe
> import sys
> subdirs = [ '..\\P24_support', '..\\P24_pictures',
> '..\\P24_Lib_Extensions' ]
> for subdir in subdirs:
>   if not ( subdir in sys.path) : sys.path.append ( subdir )
>
> from file_support import *
>
> import shutil
> import glob
>
> # ***
> # Some suggests that old build/dist should be cleared
> # ***
> dist_paths =  [ 'D:\\Data_Python\\P24_PyLab_Works\\build',
> 'D:\\Data_Python\\P24_PyLab_Works\\dist' ]
> for path in dist_paths :
>   if File_Exists ( path ) :
> shutil.rmtree ( path )
> # ***
>
> # ***
> # ***
> data_files = []
> packages = []
> includes = []
> excludes = []
> dll_excludes = []
> data_files.append ( ( '', glob.glob ( 'templates_*.*' ) ) )
>
> # ***
> # For MatPlotLib
> # ***
> if MatPlotLib_Wanted :
>   import matplotlib
>
>   includes.append ( 'matplotlib.numerix.random_array' )
>
>   packages.append ( 'matplotlib' )
>   packages.append ( 'pytz' )
>
>   data_files.append ( ( r'mpl-data', glob.glob (
> r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\*.*' )))
>   data_files.append ( ( r'mpl-data', glob.glob (
>
> r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc' )))
>   data_files.append ( ( r'mpl-data\\images', glob.glob (
> r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\images\\*.*' )))
>   data_files.append ( ( r'mpl-data\\fonts\\afm', glob.glob (
>
> r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\afm\\*.*' )))
>   data_files.append ( ( r'mpl-data\\fonts\\pdfcorefonts', glob.glob (
>
> r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\pdfcorefonts\\*.*'
> )))
>   data_files.append ( ( r'mpl-data\\fonts\\ttf', glob.glob (
>
> r'P:\\Python\\Lib\\site-packages\\matplotlib\\mpl-data\\fonts\\ttf\\*.*' )))
>
>   excludes.append ( '_gtkagg')
>   excludes.append ( '_tkagg' )
>   excludes.append ( '_agg2'  )
>   excludes.append ( '_cairo' )
>   excludes.append ( '_cocoaagg' )
>   excludes.append ( '_fltkagg' )
>   excludes.append ( '_gtk' )
>   excludes.append ( '_gtkcairo')
>   excludes.append ( 'backend_qt' )
>   excludes.append ( 'backend_qt4')
>   excludes.append ( 'backend_qt4agg' )
>   excludes.append ( 'backend_qtagg' )
>   excludes.append ( 'backend_cairo' )
>   excludes.append ( 'backend_cocoaagg' )
>   excludes.append ( 'Tkconstants' )
>   excludes.append ( 'Tkinter' )
>   excludes.append ( 'tcl' )
>   excludes.append ( "_imagingtk" )
>   excludes.append ( "PIL._imagingtk" )
>   excludes.append ( "ImageTk" )
>   excludes.append ( "PIL.ImageTk" )
>   excludes.append ( "FixTk" )
>
>   dll_excludes.append ( 'libgdk-win32-2.0-0.dll' )
>   dll_excludes.append ( 'libgdk_pixbuf-2.0-0.dll' )
>   dll_excludes.append ( 'libgobject-2.0-0.dll')
>   dll_excludes.append ( 'tcl84.dll' )
>   dll_excludes.append ( 'tk84.dll' )
>   dll_excludes.append ( 'tclpip84.dll' )
> # ***
>
> # seems not to be found (imported in brick.py)
> includes.append ( 'PyLab_Works_properties' )
>
> # ***
> # ***
>
> # If run without args, build executables, in quiet mode.
> if len(sys.argv) == 1:
> sys.argv.append("py2exe")
>
> setup (
>   windows = ['PyLab_Works.py']  ,
>   options = {
>'py2exe' : {
>   'includes' : includes,
>   'excludes' : excludes,
>   'dll_excludes' : dll_excludes,
>   'packages' : packages,
>}},
>   data_files = data_files
>   )
>
> import subprocess
> result = subprocess.call (
>   [ 'P:\Program Files\Inno Setup 4\ISCC.exe',
> 'D:\Data_Python\P24_PyLab_Works\PyLab_Works.iss'])
>
> if (result==0)

Re: name of client module

2008-02-18 Thread Jeff Schwab
Nick Stinemates wrote:
> Jeff Schwab wrote:
>> Nick Stinemates wrote:
>>   
 I'm not saying I don't want to do that.  I'm saying that, in addition to 
 what you've written, I want foo to know it's being imported, and by whom.
   
>> Please don't snip so much.
>>
>>   
>>> You're still not explaining a real example of what this could be used for.
>>> 
>> Why would you say something like that?  I told you *exactly* what I 
>> wanted to use it for.  See Berwyn's post on the recent thread "Double 
>> underscores -- ugly?"  He suggests that a suitable replacement for "if 
>> __name__ == '__main__'" might be "if sys.main()".  I was looking for a 
>> way to implement that kind of function.  Just like I told you when you 
>> asked me.  You snipped it, along with most of the post.
>>
>>   
>>> Oh well, here's an example of an implementation of what you want to do.
>>> 
>> Thanks.
>>   
> Ah, I snipped because I was only replying to that specific part and
> thought there was an archive of the rest. If that is unconventional I'll
> stop.
> 
> I suppose I did get a bit carried away. It seems people always want to
> know 'who is calling my object' but I think writing a design around that is:
> 
> a) Really hard to follow, much like GoTo statements
> b) Poorly thought out
> and, probably much more importantly
> c) Grouping code together like that really limits what you can do
> with it..
> 
> I'm sorry if I offended.

No problem!  In general, I agree with those points completely.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a callable object to Thread

2008-02-18 Thread castironpi
>  a= object()
>  (a,) is a
> > False
>
> (a,) is not identical with a.
>
>  (a,) is (a,)
> > False
>
> The tuple on the left is not identical with the tuple on the right, even
> though they are equivalent.
>
>  a is a
> > True
>
> The variable on the left is identical with the one on the right.  This
> is not the same comparison as "(a,) is (a,)", which actually contains
> the construction of two distinct objects.  The moral equivalent of "a is
> a" would be:
>
>  >>> b = (a,)
>  >>> b is b
> True
>
> An interesting thing about Python is that numbers of built-in types are
> flyweights.  Unlike literals of non-flyweight types, distinct instances
> of a given numeric literal actually refer to the same object:
>
>  >>> 5 is 5
> True
>  >>> 99 is 99
> True
>  >>> 3.5 is 3.5
> True
>
> I wonder, will this be true of the upcoming Fraction class?
>
>  (a,) == (a,)
> > True
>
> The two tuples are equivalent (though not identical).
>
>  a= []
>  a.append( a )
>  a
> > [[...]]
>
> That's cool.  I don't think would have known off the top of my head how
> the interactive interpreter would display something like that.  Talk
> about a cyclic reference...
>
>  tuple(a) is tuple(a)
> > False
>
> The tuple on the left is not identical with the tuple on the right, even
> though they are equivalent.  This is the sample as one of your earlier
> examples, just with slightly different syntax.
>
> > hasVanilla= True
> > hasStrawberry= True
> > hasChocolate= True
> > if hasVanilla:
> >   print "Vanilla"
> > if hasVanilla and not hasChocolate:
> >   print "and"
> > if hasStrawberry:
> >   print "Strawberry"
> > if hasVanilla or hasStrawberry and hasChocolate:
> >   print "and"
> > if hasChocolate:
> >   print "Chocolate."
>
> You've tried to implement a set using a set of flags to indicate whether
> various items have membership in that set.  See how an object
> representing a given flavor would have to be distinct from the object
> (boolean flag) indicating its set membership?  Btw, your formatting
> could use some work. :)  Some flavor combinations cause extra "ands" to
> be printed. Here's a little test harness, with PEP-friendly variable
> names, and showing how your booleans corresponding directly with
> traditional bit-bucket flag sets:
>
> def print_flavors(flags):
>
>      print flags
>
>      vanilla = flags & 1
>      strawberry = flags & 2
>      chocolate = flags & 4
>
>      if vanilla:
>          print "Vanilla"
>      if vanilla and not chocolate:
>          print "and"
>      if strawberry:
>          print "Strawberry"
>      if vanilla or strawberry and chocolate:
>          print "and"
>      if chocolate:
>          print "Chocolate."
>
> if __name__ == '__main__':
>      for flavor_flags in range(8):
>          print_flavors(flavor_flags)- Hide quoted text -
>
> - Show quoted text -

while True:
   "No, it's the element."
   "No, it's a tuple with one element."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Phatch = PHoto bATCH processor and renamer based on PIL

2008-02-18 Thread Daniel Fetchinson
On 2/18/08, SPE - Stani's Python Editor <[EMAIL PROTECTED]> wrote:
> I'm pleased to announce the release of Phatch which is a
> powerful batch processor and renamer. Phatch exposes a big part of the
> Python Imaging Library through an user friendly GUI. (It is using
> python-pyexiv2 to offer more extensive EXIF and IPTC support.) Phatch
> is not targeted at manipulating individual pictures (such as with
> Gimp), but repeating the same actions on hundreds or thousands of
> images.
>
> If you know PIL and have some nice recipes laying around, it is very
> easy to write plugins as Phatch generates the corresponding GUI
> automagically just like in Django. Any existings PIL scripts can be
> added very easily. Let me know if you want to contribute or have any
> questions.
>
> Homepage: http://photobatch.stani.be (free download link below)
> Tutorials: http://photobatch.wikidot.com/tutorials
> Translations: https://translations.launchpad.net/phatch/trunk/+pots/phatch
> License: GPLv3
> Screenshot:
> http://photobatch.wikidot.com/local--files/start/Screenshot-Phatch3d.jpg
> (the perspective and reflection is produced by Phatch itself)
>
> Phatch has many features, like:
> - EXIF information inspector with thumbnail
> - limit jpeg file size when saving
> - tons of actions organized by tags (including perspective, round
> corners, shadow, reflection, ...)
> - console version (Phatch can now run without a gui on servers)
> - batch rename and copy files based on exif metadata
> - data stamping (http://photobatch.wikidot.com)
> - online documentation wiki (http://photobatch.wikidot.com)
>
> Linux only features:
> - desktop or panel droplets on which images or folders can be dropped
> (will be ported to Windows & Mac)
> - Nautilus and desktop integration (with its own mime type and
> nautilus extension)
> - manpage with examples
>
> With python-pyexiv2 the following featues are added:
> - embedding the original EXIF and IPTC tags in the image
>
> All actions mostly have a separate pil function in their source code,
> so they could be read as a recipe book for PIL:
> * Auto Contrast - Maximize image contrast
> * Background - Put colour under transparent image
> * Border - Crop or add border to all sides
> * Brightness - Adjust brightness from black to white
> * Canvas - Crop the image or enlarge canvas without resizing the image
> * Colorize - Colorize grayscale image
> * Common - Copies the most common pixel value
> * Contrast - Adjust from grey to black & white
> * Convert Mode - Convert the color mode of an image (grayscale, RGB,
> RGBA or CMYK)
> * Copy - Copy image file
> * Effect - Blur, Sharpen, Emboss, Smooth, ...
> * Equalize - Equalize the image histogram
> * Fit - Downsize and crop image with fixed ratio
> * Grayscale - Fade all colours to gray
> * Invert - Invert the colors of the image (negative)
> * Maximum - Copies the maximum pixel value
> * Mask - Apply a transparency mask
> * Median - Copies the median pixel value
> * Minimum - Copies the minimum pixel value
> * Offset - Offset by distance and wrap around
> * Posterize - Reduce the number of bits of colour channel
> * Perspective - Shear 2d or 3d
> * Rank - Copies the rank'th pixel value
> * Reflect - Drops a reflection
> * Rename - Rename image file
> * Rotate - Rotate with random angle
> * Round - Round or crossed corners with variable radius and corners
> * Saturation - Adjust saturation from grayscale to high
> * Save - Save an image with variable compression in different types
> * Scale - Scale an image with different resample filters.
> * Shadow - Drop a blurred shadow under a photo with variable position,
> blur and color
> * Solarize - Invert all pixel values above threshold
> * Text - Write text at a given position
> * Transpose - Flip or rotate an image by 90 degrees
> * Watermark - Apply a watermark image with variable placement (offset,
> scaling, tiling) and opacity
>
> I develop Phatch on Ubuntu/Linux, but I have tested and polished it
> regularly on Windows and Mac Os X. (Only the droplet functionality
> needs to be ported.) Phatch is submitted to Debian unstable and
> Ubuntu Hardy. Packagers for other platforms are welcome.
>
> Requirements:
> - PIL 1.1.5 or higher
> - wxPython 2.6 or higher
> - pyexiv2 (optional)
> - python nautilus bindings (optional)


This is pretty cool! I have one question about the equally cool
website: what tool did you use for creating this image:

http://photobatch.wikidot.com/local--files/start/Screenshot-Phatch3d.jpg


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


Re: Double underscores -- ugly?

2008-02-18 Thread Raymond Hettinger
[benhoyt]
> Is it just me that thinks "__init__" is rather ugly?

I also find it unattractive and unpleasant to type.

In Py3.0, I would support a single underscore convention, _init_ or
somesuch.

I'm not sure what the aesthetic reasons are, but somehow the change
from double underscores to single underscores makes the result a lot
less offensive to my eyes.

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


Re: name of client module

2008-02-18 Thread Nick Stinemates
Jeff Schwab wrote:
> Nick Stinemates wrote:
>   
>>> I'm not saying I don't want to do that.  I'm saying that, in addition to 
>>> what you've written, I want foo to know it's being imported, and by whom.
>>>   
>
> Please don't snip so much.
>
>   
>> You're still not explaining a real example of what this could be used for.
>> 
>
> Why would you say something like that?  I told you *exactly* what I 
> wanted to use it for.  See Berwyn's post on the recent thread "Double 
> underscores -- ugly?"  He suggests that a suitable replacement for "if 
> __name__ == '__main__'" might be "if sys.main()".  I was looking for a 
> way to implement that kind of function.  Just like I told you when you 
> asked me.  You snipped it, along with most of the post.
>
>   
>> Oh well, here's an example of an implementation of what you want to do.
>> 
>
> Thanks.
>   
Ah, I snipped because I was only replying to that specific part and
thought there was an archive of the rest. If that is unconventional I'll
stop.

I suppose I did get a bit carried away. It seems people always want to
know 'who is calling my object' but I think writing a design around that is:

a) Really hard to follow, much like GoTo statements
b) Poorly thought out
and, probably much more importantly
c) Grouping code together like that really limits what you can do
with it..

I'm sorry if I offended.

-- 
==
Nick Stinemates ([EMAIL PROTECTED])
http://nick.stinemates.org

AIM: Nick Stinemates
MSN: [EMAIL PROTECTED]
Yahoo: [EMAIL PROTECTED]
==


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


The big shots

2008-02-18 Thread castironpi
I'm a little dissatisfied, and just thinking aloud.

Some of the ideas that have been proposed on Python-ideas as well as
Python, have received partial evaluation from the alphas.

Lesser individuals than they could not have invented Python, and would
be liable to ban me merely for this post.  Notwithstanding.

The reason they have cited is, "It is not in prevalent use."

The printing press, rail, automobiles, and Python, were not in
prevalent use before their invention.  I.e., they -can't- come if one
doesn't build it.  However, there were writing, transportation, and
programming before these respectively; does it merely suffice to
answer, "Yes it is?"

The Python gurus' combined professional judgement results in Python.

Looking through http://www.python.org/dev/peps/ , their own proposals
don't meet their own criteria.  Start there.

It is neither necessary nor sufficient that an expansion is or would
be used.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ROUNDING???

2008-02-18 Thread Jeff Schwab
7stud wrote:
> On Feb 18, 7:57 pm, katie smith <[EMAIL PROTECTED]> wrote:
>> in python im doing the problem 255/494
>>
>> it keeps giving me 0 instead of .51
>> what am i doing wrong?
>>
>> please help me I have been looking for hours
>>
>>   
>> ___ 
>> _
>> Never miss a thing.  Make Yahoo your home page.http://www.yahoo.com/r/hs
> 
> An integer divided by an integer produces an integer.  In computer
> programming, that's called 'integer arithmetic', and any fractional
> part of the result is chopped off(not rounded).  If your arithmetic
> involves at least one float, then you will get a float as an asnwer:
> 
> 
> print 255/494
> print 255.0/494
> print (255 * 1.0)/494
> 
> --output:--
> 0
> 0.516194331984
> 0.516194331984

Not that this behavior is expected to change in the future, such that 
255 / 494 will actually perform floating-point division.  The way to 
achieve flooring division will be 255 // 494.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ROUNDING???

2008-02-18 Thread Daniel Fetchinson
> in python im doing the problem 255/494

Try this:

>>> 255.0/494.0
0.51619433198380571
>>> float(255)/float(494)
0.51619433198380571


> it keeps giving me 0 instead of .51
> what am i doing wrong?

Nothing, integer division is not wrong :)

> please help me I have been looking for hours






>
> 
> Never miss a thing.  Make Yahoo your home page.
> http://www.yahoo.com/r/hs
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: name of client module

2008-02-18 Thread Jeff Schwab
Nick Stinemates wrote:
>> I'm not saying I don't want to do that.  I'm saying that, in addition to 
>> what you've written, I want foo to know it's being imported, and by whom.

Please don't snip so much.

> You're still not explaining a real example of what this could be used for.

Why would you say something like that?  I told you *exactly* what I 
wanted to use it for.  See Berwyn's post on the recent thread "Double 
underscores -- ugly?"  He suggests that a suitable replacement for "if 
__name__ == '__main__'" might be "if sys.main()".  I was looking for a 
way to implement that kind of function.  Just like I told you when you 
asked me.  You snipped it, along with most of the post.

> Oh well, here's an example of an implementation of what you want to do.

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


Re: ROUNDING???

2008-02-18 Thread 7stud
On Feb 18, 7:57 pm, katie smith <[EMAIL PROTECTED]> wrote:
> in python im doing the problem 255/494
>
> it keeps giving me 0 instead of .51
> what am i doing wrong?
>
> please help me I have been looking for hours
>
>       
> ___ 
> _
> Never miss a thing.  Make Yahoo your home page.http://www.yahoo.com/r/hs

An integer divided by an integer produces an integer.  In computer
programming, that's called 'integer arithmetic', and any fractional
part of the result is chopped off(not rounded).  If your arithmetic
involves at least one float, then you will get a float as an asnwer:


print 255/494
print 255.0/494
print (255 * 1.0)/494

--output:--
0
0.516194331984
0.516194331984
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding While Loop Execution

2008-02-18 Thread 7stud
On Feb 18, 4:53 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
> Brad wrote:
> > Hi folks,
>
> > I'm still fairly new to programming in python and programming in
> > general.

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

a[0] = 100
print a
print b

--output:--
[1, 2, 3]
[1, 2, 3]

[100, 2, 3]
[100, 2, 3]
-- 
http://mail.python.org/mailman/listinfo/python-list


ROUNDING???

2008-02-18 Thread katie smith
in python im doing the problem 255/494

it keeps giving me 0 instead of .51
what am i doing wrong?

please help me I have been looking for hours


  

Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs

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


Re: Passing a callable object to Thread

2008-02-18 Thread castironpi
On Feb 18, 5:23 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Feb 18, 4:26 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> >> Lie wrote:
> >>> On Feb 16, 12:29 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>  Paul Rubin wrote:
> > Jeff Schwab <[EMAIL PROTECTED]> writes:
> >> Why not?  They seem intuitive to me.  I would find it weird if you
> >> couldn't have 0-tuple, and even weirder if you couldn't have a
> >> 1-tuple.   Maybe my brain has been warped by too much C++ code.
> > The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a
> > 3-tuple is three numbers, and a 1-tuple is one number.  That would
> > mean a number and a 1-tuple of numbers are the same thing, not
> > separate types.
>  No, that doesn't follow.  A set with one element is not the same thing
>  as that element, a sequence of one element is not the same thing as that
>  element, and a tuple with one element is not the same thing as that 
>  element.
> >>> Probably the analogue of tuples in human language would be like this:
> >>> A: What ice-cream flavour do you have?
> >>> B: "Vanilla", "Chocolate", and "Strawberry"
> >>> If, for example, he only have Vanilla:
> >>> A: What ice-cream flavour do you have?
> >>> B: "Vanilla"
> >>> This way of thinking makes 1-tuple the same as the element itself.
> >> Yes.  I first heard the term "tuple" in a physics class, where it was
> >> used to mean that a mathematical function took an arbitrary number of
> >> objects.  It was by analog with "triple, quadruple, quintuple...
> >> n-tuple."  That's a different context than computer science, though,
> >> which is a specific branch of mathematics with its own terminology.  In
> >> CS, a tuple is a kind of data structure that is specifically not
> >> identical with any of its elements.  That's the sort of tuple used in
> >> Python.- Hide quoted text -
>
>  a= object()
>  (a,) is a
> > False
>
> (a,) is not identical with a.
>
>  (a,) is (a,)
> > False
>
> The tuple on the left is not identical with the tuple on the right, even
> though they are equivalent.
>
>  a is a
> > True
>
> The variable on the left is identical with the one on the right.  This
> is not the same comparison as "(a,) is (a,)", which actually contains
> the construction of two distinct objects.  The moral equivalent of "a is
> a" would be:
>
>  >>> b = (a,)
>  >>> b is b
> True
>
> An interesting thing about Python is that numbers of built-in types are
> flyweights.  Unlike literals of non-flyweight types, distinct instances
> of a given numeric literal actually refer to the same object:
>
>  >>> 5 is 5
> True
>  >>> 99 is 99
> True
>  >>> 3.5 is 3.5
> True
>
> I wonder, will this be true of the upcoming Fraction class?
>
>  (a,) == (a,)
> > True
>
> The two tuples are equivalent (though not identical).
>
>  a= []
>  a.append( a )
>  a
> > [[...]]
>
> That's cool.  I don't think would have known off the top of my head how
> the interactive interpreter would display something like that.  Talk
> about a cyclic reference...
>
>  tuple(a) is tuple(a)
> > False
>
> The tuple on the left is not identical with the tuple on the right, even
> though they are equivalent.  This is the sample as one of your earlier
> examples, just with slightly different syntax.
>
> > hasVanilla= True
> > hasStrawberry= True
> > hasChocolate= True
> > if hasVanilla:
> >   print "Vanilla"
> > if hasVanilla and not hasChocolate:
> >   print "and"
> > if hasStrawberry:
> >   print "Strawberry"
> > if hasVanilla or hasStrawberry and hasChocolate:
> >   print "and"
> > if hasChocolate:
> >   print "Chocolate."
>
> You've tried to implement a set using a set of flags to indicate whether
> various items have membership in that set.  See how an object
> representing a given flavor would have to be distinct from the object
> (boolean flag) indicating its set membership?  Btw, your formatting
> could use some work. :)  Some flavor combinations cause extra "ands" to
> be printed. Here's a little test harness, with PEP-friendly variable
> names, and showing how your booleans corresponding directly with
> traditional bit-bucket flag sets:
>
> def print_flavors(flags):
>
>      print flags
>
>      vanilla = flags & 1
>      strawberry = flags & 2
>      chocolate = flags & 4
>
>      if vanilla:
>          print "Vanilla"
>      if vanilla and not chocolate:
>          print "and"
>      if strawberry:
>          print "Strawberry"
>      if vanilla or strawberry and chocolate:
>          print "and"
>      if chocolate:
>          print "Chocolate."
>
> if __name__ == '__main__':
>      for flavor_flags in range(8):
>          print_flavors(flavor_flags)- Hide quoted text -
>
> - Show quoted text -

a= set( 'Vanilla', 'Chocolate', 'Strawberry' )
flavors= [ Flavors( i ) for i in a ]
b= list( a )
if len( b )> 1:
   b[-1]= "and "+ b[-1]
return ", ".

Re: name of client module

2008-02-18 Thread Nick Stinemates

> I'm not saying I don't want to do that.  I'm saying that, in addition to 
> what you've written, I want foo to know it's being imported, and by whom.
>   

You're still not explaining a real example of what this could be used for.

Oh well, here's an example of an implementation of what you want to do.

Import.py

#!/usr/bin/python

class Importer:
def __init__(self):
pass
def __import__(self, module):
exec "import %s" % module
exec "a = %s" % module
a.setImported(self)

i = Importer()
i.__import__("Imported")


Imported.py

#!/usr/bin/python

def setImported(importer):
print "I've been imported by %s" %importer



-- 
==
Nick Stinemates ([EMAIL PROTECTED])
http://nick.stinemates.org

AIM: Nick Stinemates
MSN: [EMAIL PROTECTED]
Yahoo: [EMAIL PROTECTED]
==


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


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Terry Reedy

"Asun Friere" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| On Feb 19, 9:44 am, Steven D'Aprano <[EMAIL PROTECTED]
| cybersource.com.au> wrote:
|
| > Except for documented singletons such as modules and None, which 
objects
| > have the same identity is platform dependent, version dependent, and 
even
| > dependent on the execution history of your code.
|
| The advice not to identity test strings and numbers (since they are
| interred in the main implementation),

They may or may not be.  But for almost all purposes, that is irrelevant.

| or tuples, since they  potentially could be, seems sound enough.

Ditto for tuples, unless possibly when they have mutable members.

|  But given the nature of
| immutables, is the identity of these even potentially implementation
| dependant (ie. they couldn't be interred could they)?

The word is 'interned', not 'interred' (buried).

| One might
| conceivably want to know that a list into which one is about to stuff
| something is the same (or perhaps not the same) list as that pointed
| to by another name, which operation, hopefully, remains possible
| across the range of potential implementations.

Lists are mutable, and identity is often important.  Id(list) can be used 
to debug or solve puzzling behavior.

tjr



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


Re: Threading the Python interpreter

2008-02-18 Thread Gabriel Genellina
En Mon, 18 Feb 2008 22:47:40 -0200, MooJoo <[EMAIL PROTECTED]>  
escribió:

> I've read that the Python interpreter is not thread-safe but are there
> any issues in creating threads that create new processes (not threads)
> that run new instantiations of python? What I'm doing is subclassing the
> threading.Thread and, in the run method, I'm making a call to os.system,
> passing to it another python script which then processes a file. When

You don't want multiple threads, you just want concurrent processes. Use  
the subprocess module instead. You get the same results with much less  
work.

-- 
Gabriel Genellina

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


Re: name of client module

2008-02-18 Thread Jeff Schwab
Nick Stinemates wrote:
> Jeff Schwab wrote:
>> Q1: When a module is imported, is there any way for the module to 
>> determine the name of the client code's module?
>>   
> Why would you ever want to do this?
>> Q2: My understanding is that the code in a module is executed only on 
>> the first import of that module.  Is there any way to have a hook 
>> invoked on subsequent imports, and for that hook (as in Q1) to determine 
>> the name of the client module?
>>   
> Why would you ever want to do this?

So that the imported module can implement functions that return 
information about the client module, as a form of introspection. 
Suppose I want to know whether I'm the main module, and I don't want to 
write __name__ == '__main__'; it would be nice if I could import a 
module and call a method to tell me whether I'm __main__:

 import modinfo

 if modinfo.main():
 print("Hello, world")

> I don't really understand why you wouldn't want to do the following:
> 
> import foo
> foo.exec()

I'm not saying I don't want to do that.  I'm saying that, in addition to 
what you've written, I want foo to know it's being imported, and by whom.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python ASP Error

2008-02-18 Thread Nick Stinemates
NoName wrote:
> I want continuie this topic
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/6cc8f4154369abf2/df299ebaa5a2144c?hl=ru&lnk=st&q=Python+ASP+HTTP%2F1.1+500+Server+Error#df299ebaa5a2144c
>
> I have same problem
>
> Pythonwin's "Tools->Remote Trace Collector" show me:
>
> IOError: [Errno 13] Permission denied: 'C:\\WINDOWS\\TEMP\\gen_py\\2.5\
> \__init__.py'
> pythoncom error: ERROR: server.policy could not create an instance.
>
>
> how solve this problem?
>   

Give the service running IIS/whatever webserver you're running read
access to

C:\\WINDOWS\\TEMP\\gen_py\\2.5\\__init__.py


-- 
==
Nick Stinemates ([EMAIL PROTECTED])
http://nick.stinemates.org

AIM: Nick Stinemates
MSN: [EMAIL PROTECTED]
Yahoo: [EMAIL PROTECTED]
==


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


Re: Double underscores -- ugly?

2008-02-18 Thread Terry Reedy

"benhoyt" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi guys,
|
| I've been using Python for some time now, and am very impressed with
| its lack of red tape and its clean syntax -- both probably due to the
| BDFL's ability to know when to say "no".
|
| Most of the things that "got me" initially have been addressed in
| recent versions of Python, or are being addressed in Python 3000. But
| it looks like the double underscores are staying as is. This is
| probably a good thing unless there are better alternatives, but ...
|
| Is it just me that thinks "__init__" is rather ugly?

No, the reservered special names are supposed to be ugly ;-) -- or at least 
to stand out.  However, since special methods are almost always called 
indirectly by syntax and not directly, only the class writer or reader, but 
not users, generally see them.

| Not to mention  "if __name__ == '__main__': ..."?

Someone (perhaps me) once suggested on pydev using 'main' instead, but a 
couple of people piped back that they regularly name their main module (as 
opposed to the startup script) 'main'.  So much for that idea.  'main__' 
might not look as bad, but anything other that '__main__' introduces an 
inconsistency with the reserved name rule.  Changing '__name__' has the 
same pair of problems (conflict with user names and consistency).  So I 
decided to live with the current incantation.

Terry Jan Reedy



| 



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


Re: name of client module

2008-02-18 Thread Nick Stinemates
Jeff Schwab wrote:
> Q1: When a module is imported, is there any way for the module to 
> determine the name of the client code's module?
>   
Why would you ever want to do this?
> Q2: My understanding is that the code in a module is executed only on 
> the first import of that module.  Is there any way to have a hook 
> invoked on subsequent imports, and for that hook (as in Q1) to determine 
> the name of the client module?
>   
Why would you ever want to do this?

I don't really understand why you wouldn't want to do the following:

import foo
foo.exec()



-- 
==
Nick Stinemates ([EMAIL PROTECTED])
http://nick.stinemates.org

AIM: Nick Stinemates
MSN: [EMAIL PROTECTED]
Yahoo: [EMAIL PROTECTED]
==


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


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Asun Friere
On Feb 19, 9:44 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:

> Except for documented singletons such as modules and None, which objects
> have the same identity is platform dependent, version dependent, and even
> dependent on the execution history of your code.

The advice not to identity test strings and numbers (since they are
interred in the main implementation), or tuples, since they
potentially could be, seems sound enough.  But given the nature of
mutables, is the identity of these even potentially implementation
dependant (ie. they couldn't be interred could they)?  One might
conceivably want to know that a list into which one is about to stuff
something is the same (or perhaps not the same) list as that pointed
to by another name, which operation, hopefully, remains possible
across the range of potential implementations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading the Python interpreter

2008-02-18 Thread Nick Stinemates
MooJoo wrote:
> I've read that the Python interpreter is not thread-safe but are there 
> any issues in creating threads that create new processes (not threads) 
> that run new instantiations of python? What I'm doing is subclassing the 
> threading.Thread and, in the run method, I'm making a call to os.system, 
> passing to it another python script which then processes a file. When 
> the call to os.system completes, the thread is finished. Here is a 
> simplified fragment of code for what I'm doing.
>
> from threading import Thread
> import os
>
> class MyThread(Thread):
>def __init__(self, fn):
>   Thread.__init__(self)
>   self.fn = fn
>
>def run(self):
>   pyscript = '/usr/bin/env python script.py %s'%self.fn
>   status = os.system(pyscript)
>
> thr = MyThread('test.dat')
> thr.start()
> thr.join()
>
> Since I'm running each python instance in a new process, I don't believe 
> that there is a problem and, in my testing so far, I haven't encountered 
> anything that would lead me to believe there is a potential time bomb 
> here. Am I correct in my assumption this is OK or just lucky so far?
>   
FYI -- That's not multi threading that's multiprocessing. You're safe.

-- 
==
Nick Stinemates ([EMAIL PROTECTED])
http://nick.stinemates.org

AIM: Nick Stinemates
MSN: [EMAIL PROTECTED]
Yahoo: [EMAIL PROTECTED]
==


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


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Asun Friere
On Feb 19, 12:27 pm, Asun Friere <[EMAIL PROTECTED]> wrote:
> But given the nature of immutables

I meant to write "given the nature of mutables" of course ... :/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XML pickle

2008-02-18 Thread castironpi
> from lxml import etree
>
> class XMLable:
>         cname= ''
>         Text= object()
>         class CTor:
>                 def __init__( self, *ar ):
>                         self.ar, self.kwar= ar, dict( ar )
>         ctor= CTor()
>         FTor= dict
>         ftor= {}
>         def __init__( self, par= None, *ar, **kwar ):
>                 nsmap= kwar.pop( 'nsmap', None )
>                 if par is None:
>                         self.node= etree.Element( self.cname or 
> self.__class__.__name__,
> nsmap= nsmap )
>                 else:
>                         self.node= etree.SubElement( par.node, self.cname or
> self.__class__.__name__, nsmap= nsmap )
>                 for a, ca in zip( ar, self.ctor.ar ):
>                         if ca[0] in self.ftor:
>                                 a= self.ftor[ ca[0] ]( a )
>                         if ca[1] is XMLable.Text:
>                                 self.node.text= a
>                         else:
>                                 self.node.set( ca[1], a )
>                 for k, v in kwar.items():
>                         if k in self.ftor:
>                                 v= self.ftor[ k ]( v )
>                         if self.ctor.kwar[ k ] is XMLable.Text:
>                                 self.node.text= v
>                         else:
>                                 self.node.set( self.ctor.kwar[ k ], str( v ) )
>
> SS= '{urn:schemas-microsoft-com:office:spreadsheet}'
> X= '{urn:schemas-microsoft-com:office:excel}'
>
> class Workbook( XMLable ):
>         #jtor= JTor( 'xmlns', req= 'urn:schemas-microsoft-
> com:office:spreadsheet' )
>         def __init__( self ):
>                 nns= { 'x': 'urn:schemas-microsoft-com:office:excel',
>                         'ss': 'urn:schemas-microsoft-com:office:spreadsheet' }
>                 XMLable.__init__( self, nsmap= nns )
>                 self.node.set( 'xmlns', 'urn:schemas-microsoft-
> com:office:spreadsheet' )
>                 self.styles= Styles( self )
> class Worksheet( XMLable ):
>         ctor= XMLable.CTor( ( 'name', SS+ 'Name' ) )
> class Table( XMLable ): pass
> class Row( XMLable ):
>         ctor= XMLable.CTor( ( 'index', SS+ 'Index' ) )
> class Cell( XMLable ):
>         ctor= XMLable.CTor( ( 'index', SS+ 'Index' ), ( 'style', SS+
> 'StyleID' ) )
>         ftor= XMLable.FTor( { 'style': lambda x: x.styleid } )
> class Data( XMLable ):
>         ctor= XMLable.CTor( ( 'type', SS+ 'Type' ), ( 'data',
> XMLable.Text ) )
> class Styles( XMLable ): pass
> class Font( XMLable ):
>         #jtor= JTor( 'family', X+ 'Family', req='Swiss' ), Jtor( 'bold', SS+
> 'Bold', lambda x: str( int( x ) ) )
>         ctor= XMLable.CTor( ( 'family', X+ 'Family' ), ( 'bold', SS+
> 'Bold' ) )
>         ftor= XMLable.FTor( { 'bold': lambda x: str( int( x ) ) } )
> class Style( XMLable ):
>         styles= {}
>         ctor= XMLable.CTor( ( 'styleid', SS+ 'ID' ) )
>         def __init__( self, par= None, *ar, **kwar ):
>                 self.styleid= 's%i'% ( 21+ len( Style.styles ) )
>                 Style.styles[ self.styleid ]= self
>                 XMLable.__init__( self, par.styles, self.styleid )
>                 Font( self, *ar, **kwar )
>
> book= Workbook()
> sheet= Worksheet( book, 'WSheet1' )
> table= Table( sheet )
> row= Row( table, index= '2' )
> style= Style( book, 'Swiss', True )
> celli= Cell( row, style= style )
> datai= Data( celli, 'Number', '123' )
> cellj= Cell( row, index= 3 )
> dataj= Data( cellj, 'String', 'abc' )
>
> out= etree.tostring( book.node, pretty_print= True,
> xml_declaration=True )
> print( out )
> open( 'xl.xml', 'w' ).write( out )
> new= etree.XML( out )
> etree.XML( etree.tostring( book.node ) )
> out= etree.tostring( new, pretty_print= True, xml_declaration=True )
> print( out )

This is one way of eliminating a particular redundancy that showed up
in the first implementation.  I've already excluded some potential
uses of XMLable.  I've, in other words, made assumptions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading the Python interpreter

2008-02-18 Thread Steve Holden
MooJoo wrote:
> I've read that the Python interpreter is not thread-safe but are there 
> any issues in creating threads that create new processes (not threads) 
> that run new instantiations of python? What I'm doing is subclassing the 
> threading.Thread and, in the run method, I'm making a call to os.system, 
> passing to it another python script which then processes a file. When 
> the call to os.system completes, the thread is finished. Here is a 
> simplified fragment of code for what I'm doing.
> 
> from threading import Thread
> import os
> 
> class MyThread(Thread):
>def __init__(self, fn):
>   Thread.__init__(self)
>   self.fn = fn
> 
>def run(self):
>   pyscript = '/usr/bin/env python script.py %s'%self.fn
>   status = os.system(pyscript)
> 
> thr = MyThread('test.dat')
> thr.start()
> thr.join()
> 
> Since I'm running each python instance in a new process, I don't believe 
> that there is a problem and, in my testing so far, I haven't encountered 
> anything that would lead me to believe there is a potential time bomb 
> here. Am I correct in my assumption this is OK or just lucky so far?

You're fine. The interpreters running in separate processes share only 
the pure code (that is the compiled interpreter itself). The Python 
namespaces of the two processes are entirely separate from each other.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Double underscores -- ugly?

2008-02-18 Thread Asun Friere

benhoyt wrote:
> Is it just me that thinks "__init__" is rather ugly?

I used to hate looking at and having the type out all those
underscores (surely two leading or one on either side would do?), but
I've gotten so used to it by now the eyes don't see and the fingers
work by themselves.

> Not to mention
> "if __name__ == '__main__': ..."?

Which ugliness is only trumped by the use of 'main' as a function name
thus:

if __name__ == '__main__' : main()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Asun Friere
On Feb 19, 9:44 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:

> Except for documented singletons such as modules and None, which objects
> have the same identity is platform dependent, version dependent, and even
> dependent on the execution history of your code.

The advice not to identity test strings and numbers (since they are
interred in the main implementation), or tuples, since they
potentially could be, seems sound enough.  But given the nature of
immutables, is the identity of these even potentially implementation
dependant (ie. they couldn't be interred could they)?  One might
conceivably want to know that a list into which one is about to stuff
something is the same (or perhaps not the same) list as that pointed
to by another name, which operation, hopefully, remains possible
across the range of potential implementations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Garbage collection

2008-02-18 Thread Aahz
In article <[EMAIL PROTECTED]>,
Ken  <[EMAIL PROTECTED]> wrote:
>Simon Pickles wrote:
>>
>> For instance, I have a manager looking after many objects in a dict. 
>> When those objects are no longer needed, I use del manager[objectid], 
>> hoping to force the garbage collector to perform the delete.
>>
>> However, this doesn't trigger my overloaded __del__ destructor. Can I 
>> simply rely on the python garbage collector to take it from here?
>   
>Objects are deleted at some undefined time after there are no references 
>to the object.

Assuming we're talking about CPython, objects are deleted immediately
when there are no references to the object.  The problem is that it's
not always obvious when the refcount goes to zero.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)

2008-02-18 Thread George Sakkis
On Feb 18, 6:56 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
> > Dear Ilias,
>
> > Post in a single reply.
>
> He has to, in hopes to gain the traction he desires
  

Was the pun intended ? ;-)

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


Threading the Python interpreter

2008-02-18 Thread MooJoo
I've read that the Python interpreter is not thread-safe but are there 
any issues in creating threads that create new processes (not threads) 
that run new instantiations of python? What I'm doing is subclassing the 
threading.Thread and, in the run method, I'm making a call to os.system, 
passing to it another python script which then processes a file. When 
the call to os.system completes, the thread is finished. Here is a 
simplified fragment of code for what I'm doing.

from threading import Thread
import os

class MyThread(Thread):
   def __init__(self, fn):
  Thread.__init__(self)
  self.fn = fn

   def run(self):
  pyscript = '/usr/bin/env python script.py %s'%self.fn
  status = os.system(pyscript)

thr = MyThread('test.dat')
thr.start()
thr.join()

Since I'm running each python instance in a new process, I don't believe 
that there is a problem and, in my testing so far, I haven't encountered 
anything that would lead me to believe there is a potential time bomb 
here. Am I correct in my assumption this is OK or just lucky so far?
-- 
http://mail.python.org/mailman/listinfo/python-list


name of client module

2008-02-18 Thread Jeff Schwab
Q1: When a module is imported, is there any way for the module to 
determine the name of the client code's module?

Q2: My understanding is that the code in a module is executed only on 
the first import of that module.  Is there any way to have a hook 
invoked on subsequent imports, and for that hook (as in Q1) to determine 
the name of the client module?
-- 
http://mail.python.org/mailman/listinfo/python-list


The __name__ == '__main__' hack (was: Double underscores -- ugly?)

2008-02-18 Thread Ben Finney
benhoyt <[EMAIL PROTECTED]> writes:

> Not to mention "if __name__ == '__main__': ..."?

Unlike the double-underscore attribute names for signalling "special
meaning", that particular hack is IMO unnecessarily ugly.

I don't, however, think it's likely to go away any time soon. If
that's the ugliest convention people can find in Python (as opposed to
the limitless *non*-conventional ugliness that programmers are capable
of in any language), then Python is doing pretty well.

-- 
 \   “An idea isn't responsible for the people who believe in it.” |
  `\  —Donald Robert Perry Marquis |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Passing a callable object to Thread

2008-02-18 Thread Jeff Schwab
Paul Rubin wrote:
> Jeff Schwab <[EMAIL PROTECTED]> writes:
>> I think you're a little confused about the meaning of "numeric
>> literal." (5+1) is not a numeric literal.  Neither is
>> (99+1).
>>
>> The flyweight pattern does not guarantee that all equivalent instances
>> of an object type will be identical.  
> 
> I don't think there's any Python language rule that says multiple uses
> of the same numeric literal turn into the same object.  It's just an
> optimization (constant folding) that the CPython implementation
> happens to perform.  Other implementations might not do it, or CPython
> might do it differently in some future version.

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


Re: Passing a callable object to Thread

2008-02-18 Thread Paul Rubin
Jeff Schwab <[EMAIL PROTECTED]> writes:
> I think you're a little confused about the meaning of "numeric
> literal." (5+1) is not a numeric literal.  Neither is
> (99+1).
> 
> The flyweight pattern does not guarantee that all equivalent instances
> of an object type will be identical.  

I don't think there's any Python language rule that says multiple uses
of the same numeric literal turn into the same object.  It's just an
optimization (constant folding) that the CPython implementation
happens to perform.  Other implementations might not do it, or CPython
might do it differently in some future version.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python ASP Error

2008-02-18 Thread NoName
I want continuie this topic
http://groups.google.com/group/comp.lang.python/browse_thread/thread/6cc8f4154369abf2/df299ebaa5a2144c?hl=ru&lnk=st&q=Python+ASP+HTTP%2F1.1+500+Server+Error#df299ebaa5a2144c

I have same problem

Pythonwin's "Tools->Remote Trace Collector" show me:

IOError: [Errno 13] Permission denied: 'C:\\WINDOWS\\TEMP\\gen_py\\2.5\
\__init__.py'
pythoncom error: ERROR: server.policy could not create an instance.


how solve this problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Double underscores -- ugly?

2008-02-18 Thread Berwyn
> Is it just me that thinks "__init__" is rather ugly? Not to mention
> "if __name__ == '__main__': ..."?

That ugliness has long been my biggest bugbear with python, too.  The
__name__ == '__main__' thing is something I always have to look up,
every time I use it, too ... awkward.

I'd settle for:

hidden def init(self):  # which could be extended to work
for everything "hidden x=3"
...

And for __name__ == '__main__' how about:

if sys.main():
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a callable object to Thread

2008-02-18 Thread Jeff Schwab
Paul Rubin wrote:
> Jeff Schwab <[EMAIL PROTECTED]> writes:
 In CS, a tuple is a kind of data structure that is specifically not
 identical with any of its elements.  That's the sort of tuple used in
 Python.
> 
> The usual CS meaning of "tuple" is more like the physics meaning than
> like the Python meaning, I think.  

That has not been my experience.

>> (a,) is (a,)
>>> False
>> The tuple on the left is not identical with the tuple on the right,
>> even though they are equivalent.
> 
> Implementation artifact.  It could be constant folded.
>x = (a,)
>y = x
>x is y
> should print True.

I gave a similar example, but you snipped it.

>> An interesting thing about Python is that numbers of built-in types
>> are flyweights.  Unlike literals of non-flyweight types, distinct
>> instances of a given numeric literal actually refer to the same object:
>>
>>  >>> 5 is 5
>> True
>>  >>> 99 is 99
>> True
>>  >>> 3.5 is 3.5
>> True
> 
> Again an implementation artifact, not guaranteed by the language.  Try:
>   (5+1) is (5+1)

True

> then try
>   (99+1) is (99+1)

False

I think you're a little confused about the meaning of "numeric literal." 
  (5+1) is not a numeric literal.  Neither is 
(99+1).

The flyweight pattern does not guarantee that all equivalent instances 
of an object type will be identical.  Maybe I should have said that 
*some* distinct instances of a given numeric literal actually refer to 
the same object, so as not to imply that *all* of them did.  I don't 
know whether 5 is always guaranteed to be the same object as any other 5 
in a given Python session.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a callable object to Thread

2008-02-18 Thread Paul Rubin
Jeff Schwab <[EMAIL PROTECTED]> writes:
> >> In CS, a tuple is a kind of data structure that is specifically not
> >> identical with any of its elements.  That's the sort of tuple used in
> >> Python.

The usual CS meaning of "tuple" is more like the physics meaning than
like the Python meaning, I think.  

>  (a,) is (a,)
> > False
> 
> The tuple on the left is not identical with the tuple on the right,
> even though they are equivalent.

Implementation artifact.  It could be constant folded.
   x = (a,)
   y = x
   x is y
should print True.

> An interesting thing about Python is that numbers of built-in types
> are flyweights.  Unlike literals of non-flyweight types, distinct
> instances of a given numeric literal actually refer to the same object:
> 
>  >>> 5 is 5
> True
>  >>> 99 is 99
> True
>  >>> 3.5 is 3.5
> True

Again an implementation artifact, not guaranteed by the language.  Try:
  (5+1) is (5+1)
then try
  (99+1) is (99+1)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)

2008-02-18 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> Dear Ilias,
> 
> Post in a single reply.

He has to, in hopes to gain the traction he desires - as otherwise he's 
pretty much ignored these days. Which is a good thing of course...

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


Re: Understanding While Loop Execution

2008-02-18 Thread Gary Herron
Brad wrote:
> Hi folks,
>
> I'm still fairly new to programming in python and programming in
> general. A friend of mine is in a CompSci 101 course and was working
> on a slider game when he encountered a problem. We eventually figured
> out what the problem was and built a test case to help solve it, but I
> can't for the life of me figure out the why behind it. I tried
> googling it and searching the list but didn't find anything that
> really explained it. I'm sure it's probably just both of us
> misunderstanding what the "while" statement does. So I hoped to ask
> for some clarification here. So here is what we worked out was going
> on with his code.
>
> from random import shuffle
>
> mylist=[2,1,3]
> baselist=[1,2,3]
> newlist=[]
> count=0
> while mylist!=baselist:
> count+=1
> shuffle(mylist)
> newlist.append(mylist)
> print count, mylist, newlist
>
> Output:
>   
> 1 [3, 1, 2] [[3, 1, 2]]
> 2 [1, 2, 3] [[1, 2, 3], [1, 2, 3]]
>   
>
> What he wanted was a list of lists to use later as a replay. What we
> expected newlist.append(mylist) to do was to save a copy of mylist
> into the collection for each iteration of the while statement.
> However, what struck us as odd is that for each time the while loop
> executes it changes all the lists in the list. What I found even
> exasperating was if I created yet another list.
>
> from random import shuffle
>
> mylist=[2,1,3]
> baselist=[1,2,3]
> newlist=[]
> saved_shufs=[]
> count=0
>
> while mylist!=baselist:
> count+=1
> shuffle(mylist)
> newlist.append(mylist)
> saved_shufs.append(newlist[0])
> print count, mylist, newlist[0], saved_shufs
>
> Output:
>   
> 1 [1, 3, 2] [1, 3, 2] [[1, 3, 2]]
> 2 [3, 2, 1] [3, 2, 1] [[3, 2, 1], [3, 2, 1]]
> 3 [1, 2, 3] [1, 2, 3] [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>   
>
> newlist[0] printed out correctly but when appending it into
> saved_shufs it still overwrote everything.
>
> Eventually, after plinking about I remembered that tuples were
> immutable and wound up creating a variable like
> tuple_of_mylist=tuple(mylist) then appending that into newlist. That
> kept the list of tuples fine. I'm still wondering though what I'm not
> grasping about "while" that made it do that to the lists? Or is it not
> even while, is it something else I'm not getting?
>
> Thanks in advance,
> B
>   
First of all, it's got nothing to do with the while loop.  The Python 
feature that's biting you here is the fact that lists are not *copied* 
when you work with them.

So in the following code, the list named full does not have 3 copies of 
sub in it, but rather it has 3 *references* to the single list named 
sub.  Any changes to the list named sub will be reflected anywhere that 
list is referred to.


 >>> sub = [1,2,3]
 >>> full = [sub,sub,sub]
 >>> full
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
 >>> sub[0] = 123
 >>> full
[[123, 2, 3], [123, 2, 3], [123, 2, 3]]


So in you code, the single list mylist is shuffled each time, and 
newlist keeps growing my more references to it.  If you want a *copy* of 
the list, you have to explicitly ask for one.  The easiest way to do 
that is mylist[:].  (This is a shorthand for copying out any sublist of 
mylist via the syntax mylist[a:b], with a and b defaulting to whole list.)

Gary Herron



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


Re: Double underscores -- ugly?

2008-02-18 Thread Ben Finney
benhoyt <[EMAIL PROTECTED]> writes:

> I realise that double underscores make the language conceptually
> cleaner in many ways (because fancy syntax and operator overloading
> are just handled by methods), but they don't *look* nice.

That's a good thing, in that it draws attention to the names. The
convention is by design: these names will be treated specially, so
they should stand out visually to the reader.

> A solution could be as simple as syntactic sugar that converted to
> double underscores behind the scenes. A couple of ideas that come to
> my mind (though these have their problems too):
> 
> def ~init(self):  # shows it's special, but too like a C++ destructor
> def +init(self):  # a bit too additive :-)
> defop add(self, other):  # or this, equivalent to "def __add__"
> def operator add(self, other):  # new keyword, and a bit wordy

None of these, IMO, meet the "needs to stand out" requirement met by
double-underscore names.

They also introduce special cases for the language parser (and thus
for the reader to understand how the language will be parsed), whereas
double-underscore names work without any special syntax handling.

-- 
 \   “Holy contributing to the delinquency of minors, Batman!” |
  `\—Robin |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: flattening a dict

2008-02-18 Thread Jeff Schwab
Arnaud Delobelle wrote:
> On Feb 18, 10:22 pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
> [...]
>> The problem with lambdas comes from people trying to hammer multi-
>> expression functions into a single-expression lambda, hence obfuscating
>> the algorithm. That's no different from people who obfuscate multi-
>> expression functions by writing them as a generator expression.
> 
> I'm sorry if my Python is difficult to understand.  That's because
> I've got a bit of a Lisp...

That may be the first lambda-related humor I've ever heard.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a callable object to Thread

2008-02-18 Thread Jeff Schwab
[EMAIL PROTECTED] wrote:
> On Feb 18, 4:26 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>> Lie wrote:
>>> On Feb 16, 12:29 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
 Paul Rubin wrote:
> Jeff Schwab <[EMAIL PROTECTED]> writes:
>> Why not?  They seem intuitive to me.  I would find it weird if you
>> couldn't have 0-tuple, and even weirder if you couldn't have a
>> 1-tuple.   Maybe my brain has been warped by too much C++ code.
> The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a
> 3-tuple is three numbers, and a 1-tuple is one number.  That would
> mean a number and a 1-tuple of numbers are the same thing, not
> separate types.
 No, that doesn't follow.  A set with one element is not the same thing
 as that element, a sequence of one element is not the same thing as that
 element, and a tuple with one element is not the same thing as that 
 element.
>>> Probably the analogue of tuples in human language would be like this:
>>> A: What ice-cream flavour do you have?
>>> B: "Vanilla", "Chocolate", and "Strawberry"
>>> If, for example, he only have Vanilla:
>>> A: What ice-cream flavour do you have?
>>> B: "Vanilla"
>>> This way of thinking makes 1-tuple the same as the element itself.
>> Yes.  I first heard the term "tuple" in a physics class, where it was
>> used to mean that a mathematical function took an arbitrary number of
>> objects.  It was by analog with "triple, quadruple, quintuple...
>> n-tuple."  That's a different context than computer science, though,
>> which is a specific branch of mathematics with its own terminology.  In
>> CS, a tuple is a kind of data structure that is specifically not
>> identical with any of its elements.  That's the sort of tuple used in
>> Python.- Hide quoted text -
> 
 a= object()
 (a,) is a
> False

(a,) is not identical with a.

 (a,) is (a,)
> False

The tuple on the left is not identical with the tuple on the right, even 
though they are equivalent.

 a is a
> True

The variable on the left is identical with the one on the right.  This 
is not the same comparison as "(a,) is (a,)", which actually contains 
the construction of two distinct objects.  The moral equivalent of "a is 
a" would be:

 >>> b = (a,)
 >>> b is b
True

An interesting thing about Python is that numbers of built-in types are 
flyweights.  Unlike literals of non-flyweight types, distinct instances 
of a given numeric literal actually refer to the same object:

 >>> 5 is 5
True
 >>> 99 is 99
True
 >>> 3.5 is 3.5
True

I wonder, will this be true of the upcoming Fraction class?

 (a,) == (a,)
> True

The two tuples are equivalent (though not identical).

 a= []
 a.append( a )
 a
> [[...]]

That's cool.  I don't think would have known off the top of my head how 
the interactive interpreter would display something like that.  Talk 
about a cyclic reference...

 tuple(a) is tuple(a)
> False

The tuple on the left is not identical with the tuple on the right, even 
though they are equivalent.  This is the sample as one of your earlier 
examples, just with slightly different syntax.

> hasVanilla= True
> hasStrawberry= True
> hasChocolate= True
> if hasVanilla:
>   print "Vanilla"
> if hasVanilla and not hasChocolate:
>   print "and"
> if hasStrawberry:
>   print "Strawberry"
> if hasVanilla or hasStrawberry and hasChocolate:
>   print "and"
> if hasChocolate:
>   print "Chocolate."

You've tried to implement a set using a set of flags to indicate whether 
various items have membership in that set.  See how an object 
representing a given flavor would have to be distinct from the object 
(boolean flag) indicating its set membership?  Btw, your formatting 
could use some work. :)  Some flavor combinations cause extra "ands" to 
be printed. Here's a little test harness, with PEP-friendly variable 
names, and showing how your booleans corresponding directly with 
traditional bit-bucket flag sets:

def print_flavors(flags):

 print flags

 vanilla = flags & 1
 strawberry = flags & 2
 chocolate = flags & 4

 if vanilla:
 print "Vanilla"
 if vanilla and not chocolate:
 print "and"
 if strawberry:
 print "Strawberry"
 if vanilla or strawberry and chocolate:
 print "and"
 if chocolate:
 print "Chocolate."

if __name__ == '__main__':
 for flavor_flags in range(8):
 print_flavors(flavor_flags)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flattening a dict

2008-02-18 Thread Arnaud Delobelle
On Feb 18, 10:22 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
[...]
> The problem with lambdas comes from people trying to hammer multi-
> expression functions into a single-expression lambda, hence obfuscating
> the algorithm. That's no different from people who obfuscate multi-
> expression functions by writing them as a generator expression.

I'm sorry if my Python is difficult to understand.  That's because
I've got a bit of a Lisp...

--
Arnaud

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


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Steven D'Aprano
On Mon, 18 Feb 2008 14:11:53 +0100, Christian Heimes wrote:

> Tobiah wrote:
> print float(3.0) is float(3.0)
>> True
> print float(3.0 * 1.0) is float(3.0)
>> False
> 
> 
> Thumb rule: Never compare strings, numbers or tuples with "is". Only
> compare an object with a singleton like a type or None. "is" is not a
> comparison operator.


I know why you're saying it, I agree with your reasons, but I wouldn't 
say it that way.

Never use "is" when you want to test for EQUALITY, regardless of whether 
the objects are strings, numbers, tuples, or anything else. To test for 
equality, use "==".

Always use "is" when you wish to compare objects for IDENTITY, such as 
testing to see whether an object IS None (as opposed to some random 
object which just happens to compare equal to None).

"is" is a comparison operator: it compares identity, not equality. It is 
more or less equivalent to the expression id(x) == id(y).

Except for documented singletons such as modules and None, which objects 
have the same identity is platform dependent, version dependent, and even 
dependent on the execution history of your code.



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


Re: Passing a callable object to Thread

2008-02-18 Thread castironpi
On Feb 18, 4:26 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> > On Feb 16, 12:29 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> >> Paul Rubin wrote:
> >>> Jeff Schwab <[EMAIL PROTECTED]> writes:
>  Why not?  They seem intuitive to me.  I would find it weird if you
>  couldn't have 0-tuple, and even weirder if you couldn't have a
>  1-tuple.   Maybe my brain has been warped by too much C++ code.
> >>> The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a
> >>> 3-tuple is three numbers, and a 1-tuple is one number.  That would
> >>> mean a number and a 1-tuple of numbers are the same thing, not
> >>> separate types.
> >> No, that doesn't follow.  A set with one element is not the same thing
> >> as that element, a sequence of one element is not the same thing as that
> >> element, and a tuple with one element is not the same thing as that 
> >> element.
>
> > Probably the analogue of tuples in human language would be like this:
> > A: What ice-cream flavour do you have?
> > B: "Vanilla", "Chocolate", and "Strawberry"
>
> > If, for example, he only have Vanilla:
> > A: What ice-cream flavour do you have?
> > B: "Vanilla"
>
> > This way of thinking makes 1-tuple the same as the element itself.
>
> Yes.  I first heard the term "tuple" in a physics class, where it was
> used to mean that a mathematical function took an arbitrary number of
> objects.  It was by analog with "triple, quadruple, quintuple...
> n-tuple."  That's a different context than computer science, though,
> which is a specific branch of mathematics with its own terminology.  In
> CS, a tuple is a kind of data structure that is specifically not
> identical with any of its elements.  That's the sort of tuple used in
> Python.- Hide quoted text -

>>> a= object()
>>> (a,) is a
False
>>> (a,) is (a,)
False
>>> a is a
True
>>> (a,) == (a,)
True
>>> a= []
>>> a.append( a )
>>> a
[[...]]
>>> tuple(a) is tuple(a)
False

hasVanilla= True
hasStrawberry= True
hasChocolate= True
if hasVanilla:
  print "Vanilla"
if hasVanilla and not hasChocolate:
  print "and"
if hasStrawberry:
  print "Strawberry"
if hasVanilla or hasStrawberry and hasChocolate:
  print "and"
if hasChocolate:
  print "Chocolate."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linux/Python Issues

2008-02-18 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> 
> [EMAIL PROTECTED] wrote:
>> IOW: all this is assumed to be
>> common *n*x knowledge.
> 
> Both GNOME and KDE put Windows to shame. An old Windows guy, like me,
> can just start using either one without needing 'common *n*x
> knowledge.' Too bad the *n*x community isn't more welcoming to
> outsiders. Linspire's CNR puts Windows DLs to shame, but Python2.5
> isn't there. Ugh.

I might destroying pink dreams of windows cozyness, but to my knowledge 
*compiling* something under windows is at least as hard, if not harder, 
than under linux.

As I said - I use ubuntu, and do issue an

apt-get install python2.5

and afterwards I end up with a python2.5 including Tkinter and whatnot.

You deliberately chose to do otherwise, goind the hard way - don't 
expect to be your hands being hold.

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


Double underscores -- ugly?

2008-02-18 Thread benhoyt
Hi guys,

I've been using Python for some time now, and am very impressed with
its lack of red tape and its clean syntax -- both probably due to the
BDFL's ability to know when to say "no".

Most of the things that "got me" initially have been addressed in
recent versions of Python, or are being addressed in Python 3000. But
it looks like the double underscores are staying as is. This is
probably a good thing unless there are better alternatives, but ...

Is it just me that thinks "__init__" is rather ugly? Not to mention
"if __name__ == '__main__': ..."?

I realise that double underscores make the language conceptually
cleaner in many ways (because fancy syntax and operator overloading
are just handled by methods), but they don't *look* nice.

A solution could be as simple as syntactic sugar that converted to
double underscores behind the scenes. A couple of ideas that come to
my mind (though these have their problems too):

def ~init(self):  # shows it's special, but too like a C++ destructor
def +init(self):  # a bit too additive :-)
defop add(self, other):  # or this, equivalent to "def __add__"
def operator add(self, other):  # new keyword, and a bit wordy

Has anyone thought about alternatives? Is there a previous discussion
on this I can look up?

Cheers,
Ben.

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


Re: Python Memory Manager

2008-02-18 Thread Jeff Schwab
[EMAIL PROTECTED] wrote:
> 
> Paul Rubin wrote:
>> The problem here is with a high allocation rate, you have to GC a lot
>> more often, which typically involves copying live data.
> 
> This is last century's issue. Copying data, RAM to RAM, is nearly free
> using the Intel architecture.

What's "the Intel architecture?"  Do you mean the x86_64 architecture 
that was actually developed by AMD, or x86 for x > some number, or do 
you actually mean IA64?

> 
> This short article, http://www.martinrinehart.com/articles/repz.html
> explains why.
> 
> I'd use one int per clock as a rule of thumb for the current copy rate
> in a single-core CPU.
-- 
http://mail.python.org/mailman/listinfo/python-list


Understanding While Loop Execution

2008-02-18 Thread Brad
Hi folks,

I'm still fairly new to programming in python and programming in
general. A friend of mine is in a CompSci 101 course and was working
on a slider game when he encountered a problem. We eventually figured
out what the problem was and built a test case to help solve it, but I
can't for the life of me figure out the why behind it. I tried
googling it and searching the list but didn't find anything that
really explained it. I'm sure it's probably just both of us
misunderstanding what the "while" statement does. So I hoped to ask
for some clarification here. So here is what we worked out was going
on with his code.

from random import shuffle

mylist=[2,1,3]
baselist=[1,2,3]
newlist=[]
count=0
while mylist!=baselist:
count+=1
shuffle(mylist)
newlist.append(mylist)
print count, mylist, newlist

Output:
>>>
1 [3, 1, 2] [[3, 1, 2]]
2 [1, 2, 3] [[1, 2, 3], [1, 2, 3]]
>>>

What he wanted was a list of lists to use later as a replay. What we
expected newlist.append(mylist) to do was to save a copy of mylist
into the collection for each iteration of the while statement.
However, what struck us as odd is that for each time the while loop
executes it changes all the lists in the list. What I found even
exasperating was if I created yet another list.

from random import shuffle

mylist=[2,1,3]
baselist=[1,2,3]
newlist=[]
saved_shufs=[]
count=0

while mylist!=baselist:
count+=1
shuffle(mylist)
newlist.append(mylist)
saved_shufs.append(newlist[0])
print count, mylist, newlist[0], saved_shufs

Output:
>>>
1 [1, 3, 2] [1, 3, 2] [[1, 3, 2]]
2 [3, 2, 1] [3, 2, 1] [[3, 2, 1], [3, 2, 1]]
3 [1, 2, 3] [1, 2, 3] [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>>

newlist[0] printed out correctly but when appending it into
saved_shufs it still overwrote everything.

Eventually, after plinking about I remembered that tuples were
immutable and wound up creating a variable like
tuple_of_mylist=tuple(mylist) then appending that into newlist. That
kept the list of tuples fine. I'm still wondering though what I'm not
grasping about "while" that made it do that to the lists? Or is it not
even while, is it something else I'm not getting?

Thanks in advance,
B
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a callable object to Thread

2008-02-18 Thread Jeff Schwab
Lie wrote:
> On Feb 16, 12:29 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>> Paul Rubin wrote:
>>> Jeff Schwab <[EMAIL PROTECTED]> writes:
 Why not?  They seem intuitive to me.  I would find it weird if you
 couldn't have 0-tuple, and even weirder if you couldn't have a
 1-tuple.   Maybe my brain has been warped by too much C++ code.
>>> The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a
>>> 3-tuple is three numbers, and a 1-tuple is one number.  That would
>>> mean a number and a 1-tuple of numbers are the same thing, not
>>> separate types.
>> No, that doesn't follow.  A set with one element is not the same thing
>> as that element, a sequence of one element is not the same thing as that
>> element, and a tuple with one element is not the same thing as that element.
> 
> Probably the analogue of tuples in human language would be like this:
> A: What ice-cream flavour do you have?
> B: "Vanilla", "Chocolate", and "Strawberry"
> 
> If, for example, he only have Vanilla:
> A: What ice-cream flavour do you have?
> B: "Vanilla"
> 
> This way of thinking makes 1-tuple the same as the element itself.

Yes.  I first heard the term "tuple" in a physics class, where it was 
used to mean that a mathematical function took an arbitrary number of 
objects.  It was by analog with "triple, quadruple, quintuple... 
n-tuple."  That's a different context than computer science, though, 
which is a specific branch of mathematics with its own terminology.  In 
CS, a tuple is a kind of data structure that is specifically not 
identical with any of its elements.  That's the sort of tuple used in 
Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Question

2008-02-18 Thread Blubaugh, David A.
I have already solved that problem.  Sorry for not alerting you as to me
of solving this issue.  Thank you very much for the help.  I was
wondering if you would be interested in helping in the development of a
Scipy / MyHDL hybrid.  The advantage of this would be to develop FPGA
logic with the ease of Python programming.  This would especially be
helpful in the development of a rapid DSP development system for FPGAS.
The rapid speed one could possibly obtain with this system might well be
a great deal faster that FPGA development with MATLAB.  Thank you for
your help.

David Blubaugh




-Original Message-
From: Gabriel Genellina [mailto:[EMAIL PROTECTED] 
Sent: Monday, February 18, 2008 4:24 PM
To: python-list@python.org
Subject: Re: Question

En Mon, 18 Feb 2008 17:48:57 -0200, Blubaugh, David A.  
<[EMAIL PROTECTED]> escribi :

> Dan,
> I have been working with examples within the Scipy and Numpy
framework.
> Those are the examples that I have been working with at this time, 
> including the FFT example.  The following command:
> python setup.py  install.
>
> Is what I did within the Python IDLE environment.  However, python was

> not able to see this script file.  Under directory should the MyHDL 
> folder be located??  What I mean by this, should the MyHDL folder be 
> installed in the same directory as where the Scipy folder is located??
> If I am not making any sense, please inform me as soon as possible.

Don't do that from inside IDLE. These are some step by step generic
instructions to install a new package; they don't assume much about your
previous knowledge.

1) Open a command prompt window (or system prompt, or console, or...).
Go to the Start menu, click on Run, type "cmd" (without the quotes),
press Enter.

2) See if you can invoke Python directly; type at the command prompt:

   C:\doesntmatter> python -V

   (use a capital V, press Enter at the end. Don't type the text at the
left of the > sign). You should get a response like this:

   Python 2.5.1

   If you get a similar response (maybe a different Python version),
skip to step 5.
   If you get an error message telling that "python" isn't recognized as
a command or something, continue on step 3.

3) Let's try to find where Python is located. As you appear to have IDLE
installed and working, open it, and execute these two lines:

   >>> import sys
   >>> print sys.executable
   c:\python25\pythonw.exe

Take note of the response, but omit the last "w". We will call this "the
full path to python.exe". In the example above, the full path to
python.exe would be c:\python25\python.exe

4) Repeat step 2 above, using the full path to python.exe instead of the
bare word python:

   C:\doesntmatter> c:\python25\python.exe -V  [press Enter]
   Python 2.5.1

You should get the installed Python version number, not an error.

5) Decompress the package you want to install into any temporary folder
-it doesn't matter where- using your favorite tool (WinRar, WinZip,
7zip, the Zip file handler built into WinXP...). Probably you've already
done that. Take note of the temporary folder (should contain the
setup.py
script)

6) Come back to the command prompt and make that temporary folder your
current directory, using the "cd" command. E.g. if it were
c:\temp\mypackage-3.2, type:

   C:\doesntmatter> cd c:\temp\mypackage-3.2 [press Enter]
   c:\temp\mypackage-3.2>

7) Now execute:

   c:\temp\mypackage-3.2> python setup.py install [press Enter]

(If you had to go thru steps 3 and 4 above, replace the word python with
the full path to python.exe) This should start the package installation;
read its documentation for further details.

-- 
Gabriel Genellina



This e-mail transmission contains information that is confidential and may be 
privileged. It is intended only for the addressee(s) named above. If you 
receive 
this e-mail in error, please do not read, copy or disseminate it in any manner. 
If you are not the intended recipient, any disclosure, copying, distribution or 
use of the contents of this information is prohibited. Please reply to the 
message immediately by informing the sender that the message was misdirected. 
After replying, please erase it from your computer system. Your assistance in 
correcting this error is appreciated.

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


Re: flattening a dict

2008-02-18 Thread Steven D'Aprano
On Mon, 18 Feb 2008 14:03:20 +, Duncan Booth wrote:

> Why, why, why, why are you using lambda here? It only makes the code
> harder to read (and it is bad enough without that). A lambda which is
> assigned directly to a variable is a bad code smell.

Oh come on. I don't get this allergy to lambda that so many people have. 
Look at the example given:


def flattendict(d) :
gen = lambda L : (x for M in exp(L) for x in rec(M))
exp = lambda L : (L+list(kv) for kv in L.pop().iteritems())
rec = lambda M : gen(M) if isinstance(M[-1],dict) else [M]
return dict((tuple(L[:-1]),L[-1]) for L in gen([d]))


The hard-to-read doesn't come from the lambda (which only adds a keyword 
and a name to each function), but the algorithm, which combines 
recursion, generator expressions, and tight coupling between three 
functions. Would the function be any easier to read written like this?

# Untested
def flattendict(d):
def gen(L):
return (x for M in exp(L) for x in rec(M))
def exp(L):
return (L+list(kv) for kv in L.pop().iteritems())
def rec(M):
return gen(M) if isinstance(M[-1],dict) else [M]
return dict((tuple(L[:-1]),L[-1]) for L in gen([d]))

No. The function is hard to read, not because it uses lambdas, but 
because it is obfuscated Python. The lambda syntax doesn't contribute to 
the obfuscation.

And as for your point about bad code smells, no, I don't agree. If your 
function consists of a single expression, and you don't expect 
func.__name__ to have a meaningful value, then there's nothing wrong with 
using a "named lambda". Anonymous functions are first-class objects in 
Python, just as classes and modules and named functions are, and people 
shouldn't make up superstitious rules about not assigning them to names.

def foo(x):
return x+1

foo = lambda x: x+1

The first case uses TWO keywords, a name, a declared argument and an 
expression; the lambda form uses ONE keyword, a name, a declared argument 
and an expression. 

The problem with lambdas comes from people trying to hammer multi-
expression functions into a single-expression lambda, hence obfuscating 
the algorithm. That's no different from people who obfuscate multi-
expression functions by writing them as a generator expression.



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


Re: Is there any Generic RSS/ATOM generator in Python?

2008-02-18 Thread Christopher Arndt
On 11 Feb., 15:47, js <[EMAIL PROTECTED]> wrote:
> I'm looking for RSS/ATOM generator I can use in Python.
> I searched on pypi and the other places but I couldn't find any
> options on this. (I found many parsers, though)
> Is there any de-fact standard RSS/ATOM generator? (especially, I'd
> like to create Atom's)
> Do I have to do it myself from scratch?

You didn't specify your use case very much. If you just want to add
support for generating Atom/RSS feeds to your app and the format (i.e.
which elements and attributes are used) isn't too dynamic, you could
just an XML-templating language like Kid or Genshi.

The feed generator included in TurboGears uses this approach. I
recently packaged this as a separate module:

   http://chrisarndt.de/projects/turbofeeds/

The module still only makes sense in a TurboGears context but you may
want to look at the Kid templates used, they could be used by any app
that wants to generate Atom/RSS:

http://trac.turbogears.org/browser/projects/TurboFeeds/trunk/turbofeeds/templates

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


Re: Python Memory Manager

2008-02-18 Thread rbossy
Quoting Steve Holden <[EMAIL PROTECTED]>:

> [...]
> Not only that, but all pointers to an object have to be updated when it
> is relocated.

"Any problem in computer science can be solved by another level of indirection"
-- David John Wheeler

;-)

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


Re: Garbage collection

2008-02-18 Thread Ken
Simon Pickles wrote:
> Hi,
>
> I'm building a server with python, but coming from a c++ background, 
> garbage collection seems strange.
>
> For instance, I have a manager looking after many objects in a dict. 
> When those objects are no longer needed, I use del manager[objectid], 
> hoping to force the garbage collector to perform the delete.
>
> However, this doesn't trigger my overloaded __del__ destructor. Can I 
> simply rely on the python garbage collector to take it from here?
>   
Objects are deleted at some undefined time after there are no references 
to the object.

You will need to change your thinking about how destructors work.  It is 
very different from C++.

The good news is that you almost never have to do anything to clean up.  
My guess is that you might not even need to overload __del__ at all.  
People from a C++ background often mistakenly think that they have to 
write destructors when in fact they do not.  What is your __del__ method 
doing?
> Is there a way to find how many references exist for an object?
>   
yes:

  from sys import getrefcount
  print getrefcount(x)


> Thanks
>
> Simon
>
>   

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


Re: Passing a callable object to Thread

2008-02-18 Thread Lie
On Feb 16, 12:29 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Paul Rubin wrote:
> > Jeff Schwab <[EMAIL PROTECTED]> writes:
> >> Why not?  They seem intuitive to me.  I would find it weird if you
> >> couldn't have 0-tuple, and even weirder if you couldn't have a
> >> 1-tuple.   Maybe my brain has been warped by too much C++ code.
>
> > The idea is that a 2-tuple (of numbers, say) is a pair of numbers, a
> > 3-tuple is three numbers, and a 1-tuple is one number.  That would
> > mean a number and a 1-tuple of numbers are the same thing, not
> > separate types.
>
> No, that doesn't follow.  A set with one element is not the same thing
> as that element, a sequence of one element is not the same thing as that
> element, and a tuple with one element is not the same thing as that element.

Probably the analogue of tuples in human language would be like this:
A: What ice-cream flavour do you have?
B: "Vanilla", "Chocolate", and "Strawberry"

If, for example, he only have Vanilla:
A: What ice-cream flavour do you have?
B: "Vanilla"

This way of thinking makes 1-tuple the same as the element itself.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Memory Manager

2008-02-18 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> 
> Paul Rubin wrote:
>> The problem here is with a high allocation rate, you have to GC a lot
>> more often, which typically involves copying live data.
> 
> This is last century's issue. Copying data, RAM to RAM, is nearly free
> using the Intel architecture.
> 
> This short article, http://www.martinrinehart.com/articles/repz.html
> explains why.
> 
> I'd use one int per clock as a rule of thumb for the current copy rate
> in a single-core CPU.

You have a strange idea of "nearly free", and I find your analysis a 
little simplistic. You may take advantage of direct memory access, but 
cycles are still consumed. I presume also (though here my knowledge of 
present-day Intel and AMD architectures gets a little sketchy) that many 
data cache lines could still be invalidated by these moves, and that 
also has a significant effect on performance.

Extending an integer array from 100 to 150 items is a pretty puny 
operation when you compare it with the amount of data that might need to 
be moved during a compactifying garbage collection of a 20MB Python 
program image.

Not only that, but all pointers to an object have to be updated when it 
is relocated.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Garbage collection

2008-02-18 Thread Simon Pickles
Hi,

I'm building a server with python, but coming from a c++ background, 
garbage collection seems strange.

For instance, I have a manager looking after many objects in a dict. 
When those objects are no longer needed, I use del manager[objectid], 
hoping to force the garbage collector to perform the delete.

However, this doesn't trigger my overloaded __del__ destructor. Can I 
simply rely on the python garbage collector to take it from here?

Is there a way to find how many references exist for an object?

Thanks

Simon

-- 
Linux user #458601 - http://counter.li.org.



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


Re: Linux/Python Issues

2008-02-18 Thread MartinRinehart


Paul Boddie wrote:
> The whole CNR stuff and the
> proprietary software slant of Linspire obscures the solution, in my
> opinion.

Thanks for all your help, Paul.

CNR, which is now free, is absolutely marvelous when it's got what you
need. If Python2.5 were in the warehouse, I'd have clicked, gone to
make a cup of coffee and the appropriate icon would be on my desktop
when I came back. If I were Python.org I'd not consider anything ready
for release until it was in the warehouse.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question

2008-02-18 Thread Gabriel Genellina
En Mon, 18 Feb 2008 17:48:57 -0200, Blubaugh, David A.  
<[EMAIL PROTECTED]> escribi�:

> Dan,
> I have been working with examples within the Scipy and Numpy framework.
> Those are the examples that I have been working with at this time,
> including the FFT example.  The following command:
> python setup.py  install.
>
> Is what I did within the Python IDLE environment.  However, python was
> not able to see this script file.  Under directory should the MyHDL
> folder be located??  What I mean by this, should the MyHDL folder be
> installed in the same directory as where the Scipy folder is located??
> If I am not making any sense, please inform me as soon as possible.

Don't do that from inside IDLE. These are some step by step generic  
instructions to install a new package; they don't assume much about your  
previous knowledge.

1) Open a command prompt window (or system prompt, or console, or...). Go  
to the Start menu, click on Run, type "cmd" (without the quotes), press  
Enter.

2) See if you can invoke Python directly; type at the command prompt:

   C:\doesntmatter> python -V

   (use a capital V, press Enter at the end. Don't type the text at the  
left of the > sign). You should get a response like this:

   Python 2.5.1

   If you get a similar response (maybe a different Python version), skip  
to step 5.
   If you get an error message telling that "python" isn't recognized as a  
command or something, continue on step 3.

3) Let's try to find where Python is located. As you appear to have IDLE  
installed and working, open it, and execute these two lines:

   >>> import sys
   >>> print sys.executable
   c:\python25\pythonw.exe

Take note of the response, but omit the last "w". We will call this "the  
full path to python.exe". In the example above, the full path to  
python.exe would be c:\python25\python.exe

4) Repeat step 2 above, using the full path to python.exe instead of the  
bare word python:

   C:\doesntmatter> c:\python25\python.exe -V  [press Enter]
   Python 2.5.1

You should get the installed Python version number, not an error.

5) Decompress the package you want to install into any temporary folder  
-it doesn't matter where- using your favorite tool (WinRar, WinZip, 7zip,  
the Zip file handler built into WinXP...). Probably you've already done  
that. Take note of the temporary folder (should contain the setup.py  
script)

6) Come back to the command prompt and make that temporary folder your  
current directory, using the "cd" command. E.g. if it were  
c:\temp\mypackage-3.2, type:

   C:\doesntmatter> cd c:\temp\mypackage-3.2 [press Enter]
   c:\temp\mypackage-3.2>

7) Now execute:

   c:\temp\mypackage-3.2> python setup.py install [press Enter]

(If you had to go thru steps 3 and 4 above, replace the word python with  
the full path to python.exe)
This should start the package installation; read its documentation for  
further details.

-- 
Gabriel Genellina

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

Re: Python Memory Manager

2008-02-18 Thread MartinRinehart


Paul Rubin wrote:
> The problem here is with a high allocation rate, you have to GC a lot
> more often, which typically involves copying live data.

This is last century's issue. Copying data, RAM to RAM, is nearly free
using the Intel architecture.

This short article, http://www.martinrinehart.com/articles/repz.html
explains why.

I'd use one int per clock as a rule of thumb for the current copy rate
in a single-core CPU.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: average of PIL images

2008-02-18 Thread 7stud
On Feb 18, 2:05 pm, 7stud <[EMAIL PROTECTED]> wrote:
> num = arr[1:, 2:]
>
> That says to get all elements from row 1 to the bottom that are in
> from column 2 to the end of the row.

err..

That says to get all elements from row 1 to the last row which are in
column 2, column 3, etc. to the end of the row.

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


Re: average of PIL images

2008-02-18 Thread 7stud
On Feb 18, 1:58 pm, 7stud <[EMAIL PROTECTED]> wrote:
> On Feb 18, 10:18 am, vaneric <[EMAIL PROTECTED]> wrote:
>
>
>
> > hi
> > i have a set of RGB images of diff faces (of people )as a 2 dim
> > numpyarray
> > ..something like
> > threefaces=array([[xa1,xa2,xa3],
> >        [xb1,xb2,xb3],
> >        [xc1,xc2,xc3]])
> > where xa1,xa2,xa3 are  tuples each representing rgb values of a pixel
> > of first image ..
>
> > i need to create the average face image and display it.problem is i
> > need to calculate (xa1+xb1+xc1)/3  etc to calculate avearge value of
> > each pixel.how can i do this calculation.do i need to convert the
> > r,g,b in to a single value for each pixel? the average value of a
> > pixel will be a float isn't it? how can i create a PIL image from
> > this?
> > any help,directive greatly appreciated
> > eric
>
> import Numeric
>
> arr = Numeric.array([
>     [1, 2, 3],
>     [4, 5, 6],
>     [7, 8, 9],
>     [10, 11, 12]
> ])
>
> col1 = arr[0:,0]
> print col1
>
> sum = 0
> count = 0
> for num in col1:
>     sum += num
>     count += 1
>
> avg = (sum * 1.0)/count   #convert one term to a float to get float
> result
> print avg
> print round(avg)
> print int(round(avg))
>
> print arr[0]
>
> size = len(arr[0])
> for i in range(size):
>     col = arr[0:, i]
>     sum = 0
>     count = 0
>
>     for num in col:
>         sum += num
>         count += 1
>
>     result = (sum * 1.0) /count
>     print result,
>     result = int(round(result))
>     print result
>
> --output:--
> [ 1  4  7 10]
> 5.5
> 6.0
> 6
> [1 2 3]
> 5.5 6
> 6.5 7
> 7.5 8

In this statement:

> col1 = arr[0:,0]

the first term is the row or row range, and the second term is the
column or column range.  If you write this:

num = arr[0,0]

you get the element in row 0, column 0.  But you can also specify
ranges for each col or row:

num = arr[1:, 2:]

That says to get all elements from row 1 to the bottom that are in
from column 2 to the end of the row.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >