Re: python2.4 generator expression > python2.3 list expression

2005-02-20 Thread Michael Hoffman
snacktime wrote:
I need to convert a generator expression to a list expression so it
will work under python 2.3.
I rewrote this:
for c in range(128):
  even_odd = (sum(bool(c & 1<
As this:
for c in range(128):
  bo = [bool(c & 1<
Seems to work, is there a better way to do this?
If you want to keep it as a generator that doesn't build a list
in memory, you can use itertools:
import itertools
for c in range(128):
def _even_odd_func(b): return bool(c & 1<
The fact that you used range() instead of xrange() indicates that
you may not care about this, though. ;-)
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to Python from PHP - 3 questions

2005-02-20 Thread Michal Migurski
Thank you. My impression of Zope in the past has been that it does 
what I need, along with 10,000 other things I don't (built in WebDAV 
server?!), but clearly I owe it another chance. I've been initially 
attracted to mod_python because of its raw simplicity and its 
apparent similarity to mod_php and mod_perl, which I am familiar 
with. I'll give Zope a try.
I am moving my band's website from an antiquated and horrible PHPNuke 
site to a Python-based site, and so have done quite a bit of research 
about this (though I never considered myself a PHP expert).  Here's 
what I've come up with...
[snip]
This is awesome, quote a bit to chew on. Thank you Joe!
--
michal migurski- contact info, blog, and pgp key:
sf/cahttp://mike.teczno.com/contact.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode encoding usablilty problem

2005-02-20 Thread aurora
On Sun, 20 Feb 2005 15:01:09 +0100, Martin v. Löwis <[EMAIL PROTECTED]>  
wrote:

Nick Coghlan wrote:
Having "", u"", and r"" be immutable, while b"" was mutable would seem  
rather inconsistent.
Yes. However, this inconsistency might be desirable. It would, of  
course, mean that the literal cannot be a singleton. Instead, it has
to be a display (?), similar to list or dict displays: each execution
of the byte string literal creates a new object.

An alternative would be to have "bytestr" be the immutable type  
corresponding to the current str (with b"" literals producing  
bytestr's), while reserving the "bytes" name for a mutable byte  
sequence.
Indeed. This maze of options has caused the process to get stuck.
People also argue that with such an approach, we could as well
tell users to use array.array for the mutable type. But then,
people complain that it doesn't have all the library support that
strings have.
The main point being, the replacement for 'str' needs to be immutable  
or the upgrade process is going to be a serious PITA.
Somebody really needs to take this in his hands, completing the PEP,
writing a patch, checking applications to find out what breaks.
Regards,
Martin
What is the processing of getting a PEP work out? Does the work and  
discussion carry out in the python-dev mailing list? I would be glad to  
help out especially on this particular issue.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in email package?

2005-02-20 Thread Tim Roberts
Roman Suzi <[EMAIL PROTECTED]> wrote:
>
>I was playing with email package and discovrered this strange kind of 
>behaviour:
>
 import email.Message
 m = email.Message.Message()
 m['a'] = '123'
 print m
>>From nobody Mon Feb 21 00:12:27 2005
>a: 123
>
 for i in m: print i
>...
>Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/local/lib/python2.3/email/Message.py", line 304, in __getitem__
> return self.get(name)
>   File "/usr/local/lib/python2.3/email/Message.py", line 370, in get
> name = name.lower()
>AttributeError: 'int' object has no attribute 'lower'

Intuitively, what did you expect this to do?  I don't see why a single
message should be iterable.

>I think that if any object (from standard library at least) doesn't support
>iteration, it should clearly state so.

That's going a bit far.  Iteration is a relatively new addition to Python.
Those classes that DO support iteration generally say so.  If it isn't
mentioned, you probaby shouldn't assume it.

>Can this behaviour of email be considered a bug?

Not in my opinion, no.

>Is there a good case to iterate over something useful in a message?

Well, if you don't have an answer to that question, then why would you
expect it to support iteration?

>P.S. rfc822 has the same behaviour, at least on Python 2.3

Again, I'm not sure what, intuitively, it would mean to iterate over an
rfc822 object.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article on Hi-Fi Myths

2005-02-20 Thread Mike Meyer
Al Christians <[EMAIL PROTECTED]> writes:

> I learned Friday night that the hi-fi talk is our most popular tape.
> This page:
>
> http://www.belt.demon.co.uk/product/Cable_Controversy/Cable_Controversy.htm
>
> Gives a somewhat different take on the controversy, almost certainly
> bizarre.  It's a long page and the interesting part is near the end.
> The conclusion is:
>
>   "you just need to know what techniques to use to create a
>   'friendly', 'relaxing', energy pattern."


I find that playing back Python code over multi-stranded copper
produces the best results.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Fwd: Re: [Uuu-devel] languages] <-- Why Python

2005-02-20 Thread Mike Meyer
[EMAIL PROTECTED] (Paul Boddie) writes:

> Mike Meyer <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
>> Arich Chanachai <[EMAIL PROTECTED]> writes:
>> 
>> > When the CLR is integrated, it will allow a wide array of problem
>> > solving choices for uuu users.
>> 
>> You've missed the point. Allowing a wide array of problem solving
>> choices is a goal, not a means. Instead of concentrating on adding
>> langauges, you should be provding an infrastructure that makes adding
>> langauges simple.  The Plan 9 example does this best, as any language
>> that can do file I/O is supported.
>
> This discussion collides quite nicely with two of the more quoted
> articles on software development:
>
> http://primates.ximian.com/~miguel/bongo-bong.html

I've actually done some work on using CORBA as a COM for Unix (or, as
I think of it, an ARexx for Unix). After being exposed to Plan 9, I've
decided that's a better solution. CORBA has the advantage that you can
work on it without getting buy-in from kernel vendors.

> In contrast, the standard UNIX model of interprocess communication and
> introspection, extended substantially by Plan 9 and more
> conservatively by modern UNIX variants, is said to leave something to
> be desired, and those wishing more informative details about the
> interfaces exposed by programs and services usually end up putting
> something more complicated on top - see the emergence of Bonobo, DCOP
> and D-BUS.

The crucial question isn't whether the underlying mechanism is
complete, but whether it's sufficient. The underlying Unix facilities
provide byte streams - because that's what Unix does. What that leaves
to be desired is a standard high-level way for applications to
interact with each other, passing back and forth things that are more
complicated than byte streams. Having standars for these high-level
objects allows for code reuse and data sharing. This is a good thing,
and there's nothing inherently wrong with doing things this way.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recommended way of generating HTML from Python

2005-02-20 Thread Michele Simionato
The problem is a problem of standardization, indeed. There plenty of
recipes to
do the same job, I just would like to use a blessed one (I am teaching
a Python
course and I do not know what to recommend to my students).

FWIW, here is a my version of the recipe (stripped down to the bare
essentials)

.def makeattr(dict_or_list_of_pairs):
.dic = dict(dict_or_list_of_pairs)
.return " ".join("%s=%r" % (k, dic[k]) for k in dic)

.class HTMLTag(object):
.def __getattr__(self, name):
.def tag(value, **attr):
."""value can be a string or a sequence of strings."""
.if hasattr(value, "__iter__"): # is iterable
.value = " ".join(value)
.return "<%s %s>%s\n" % (name, makeattr(attr), value,
name)
.return tag

# example:
.html = HTMLTag()

.tableheader = ["field1", "field2"]
.tablebody = [["a1", "a2"],
. ["b1", "b2"]]

.html_header = [html.tr(html.th(el) for el in tableheader)]
.html_table = [html.tr(html.td(el) for el in row) for row in tablebody]
.print html.table(html_header + html_table)

  Michele Simionato

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


Re: questions concerning cgi.FieldStorage(keep_blank_values=1)

2005-02-20 Thread Michele Simionato
Jonas:
> in this application, i need keys to be delivered with the url, some
with
> and some without value (for example 'script.py?key1&key2=foo'.

You are missing an "=" sign after key1. Confront with this example:

from cgi import parse_qsl

QS = "x=1&y=2&x=3&z=&y=4"
print parse_qsl(QS)
print parse_qsl(QS, keep_blank_values=True)

which gives

[('x', '1'), ('y', '2'), ('x', '3'), ('y', '4')]
[('x', '1'), ('y', '2'), ('x', '3'), ('z', ''), ('y', '4')]

Here the blank value "z=" is converted into "z=''".


   Michele Simionato

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


Re: help please

2005-02-20 Thread Steven Bethard
Dennis Lee Bieber wrote:
On 20 Feb 2005 20:12:50 -0800, "gargonx" <[EMAIL PROTECTED]> declaimed
the following in comp.lang.python:
decode_replacements.update([(std[key], key) for key in std])
Traceback (most recent call last):
 File "", line 1, in ?
AttributeError: keys
	Did you read the reference manual?
Yes, actually.  But I generally check only the reference manual for the 
current version of Python:

http://docs.python.org/lib/typesmapping.html
which does support sequence arguments for dict.update.  As noted there, 
of course, this support was added for Python 2.4.

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


Re: [Fwd: Re: [Uuu-devel] languages] <-- Why Python

2005-02-20 Thread Mike Meyer
Nick Coghlan <[EMAIL PROTECTED]> writes:

> Mike Meyer wrote:
>> Arich Chanachai <[EMAIL PROTECTED]> writes:
>>
>>>Mike Meyer wrote:
>>>
Whatever the intentions may be, the *act* is one of dictation. Since
the point of the underlying OS is to increase the interconnections
between applications (assuming I've found the correct web page and
interpreted it correctly), the underlying architecture should be
language-neutral. That allows as many applications as possible to play
in the environment.
>
> *Allowing* other languages is one thing, but that shouldn't preclude
> having a 'default' language. On other OS's, the default language is
> some form of shell scripting (i.e. Unix shell scripts, or Windows
> batch files). It would be good to have a real language to fill that
> role.

Um - I'd say Unix has no default language. Traditional Eunices come
with a nice selection of languages (sh, awk, sed, C), and modern ones
include more (C++, Perl, Python, Ruby, Lua). Tagging one as the
"default" does a disservice to the other languages, and to the OS as a
whole.

For that matter, I'd say that these days the default on Windows is VB,
unless there are hooks to talk to COM from batch files, since COM is
the standard scripting mechanism on Windows. Note that by providing a
scripting mechanism instead of a scripting language, you can script
applications with Python as or more easily than you can script them
with the MS provided solution of VB.

>> You've missed the point. Allowing a wide array of problem solving
>> choices is a goal, not a means. Instead of concentrating on adding
>> langauges, you should be provding an infrastructure that makes adding
>> langauges simple.  The Plan 9 example does this best, as any language
>> that can do file I/O is supported.
> Still, the builtin shell is going to need *some* form of scripting
> support. And if that looks like IPython's shell mode, so much the
> better.

Scripting support shouldn't "look like" a language, it should look
like a mechanism for hooking languages up to the system being
scripted. Shells are a particularly easy hookup, as they have only
three types of objects to deal with - commands, command results, and
text streams. Any language which lets you invoke commands and
manipulate the results of those commands and text streams is
sufficient for shell scripting.

IPython's pysh seems a little clumsy for interactive use, as it
requires special characters to distinguish between commands to be
passed to the shell and commands to be passed to the scripting
language. This should be contrasted with languages designed for
working in a command environment, like Rexx, sh and rc.

> Anyway, the reason to prefer Python to LISP for something like this,
> is that Python reads much more naturally for most people, whereas LISP
> requires that you write things 'out of order'.

I'll say it again - if you're arguing about which language to use,
you're arguing about the wrong thing.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode encoding usablilty problem

2005-02-20 Thread aurora
On Sat, 19 Feb 2005 18:44:27 +0100, Fredrik Lundh <[EMAIL PROTECTED]>  
wrote:

"aurora" <[EMAIL PROTECTED]> wrote:
I don't want to mix them. But how could I find them? How do I know  
this  statement can be
potential problem

  if a==b:
where a and b can be instantiated individually far away from this line  
of  code that put them
together?
if you don't know what a and b comes from, how can you be sure that
your program works at all?  how can you be sure they're both strings?
("a op b" can fail in many ways, depending on what "a", "b", and "op"  
are)

a and b are both string. The issue is 8-bit string or unicode string.

Things works fine, unit tests pass, all until the first non-ASCII  
characters
come in and then the program breaks.
if you have unit tests, why don't they include Unicode tests?

How do I structure the test cases to guarantee coverage? It is not  
practical to test every combinations of unicode/8-bit strings. Adding  
non-ascii characters to test data probably make problem pop up earlier.  
But it is arduous and it is hard to spot if you left out any.

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


IDLE Problem: win98\Python2.4

2005-02-20 Thread kim kubik
This sure seems like it would have been
brought up but I checked Google Groups
(the dejanews replacement) and saw
nothing:  I installed Python2.4 in Win98
and IDLE doesn't work (neither does the
online manual even tho a 3.6KB Python24.chm
is there, but that's a story for another
day) - that is, clicking on the IDLE icon
in the Start menu just gives a brief hourglass
cursor and then nothing . . .

>From a DOS prompt (in C:\Python24) I can do
'python lib\idlelib\idle.py' and get a list
of errors, not being able to find tcl8.4 in
a number of paths, none of which exist in
the c:\python24 as installed. I moved tcl84.lib
into a directory it does search and got fewer
errors msg's, the last being like 'can't find
a usable init.tcl.'  Moved init.tcl to the same
dir as tcl84.lib, got even fewer errors, the
last being like
"_tkinter.TclError: invalid cmd name "tcl_findLibrary"

So I'm stuck. I uninstalled Py2.4, installed Py2.3.5,
again same thing . . . IDLE just does not come up
with the tcl paths of the standard install.

www.python.org gives answer to problems w/IDLE on Py1.5
from 1999 and shows adding tcl\bin to %PATH%.  OK . . .

What to try next? SOMEONE else must have seen this?
\kim


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


Re: python2.4 generator expression > python2.3 list expression

2005-02-20 Thread Steven Bethard
snacktime wrote:
I need to convert a generator expression to a list expression so it
will work under python 2.3.
I rewrote this:
for c in range(128):
  even_odd = (sum(bool(c & 1<
As this:
for c in range(128):
  bo = [bool(c & 1<
Seems to work, is there a better way to do this?
Well, if you were happy with your generator expression, you can use 
almost exactly the same syntax:

for c in range(128):
  even_odd = (sum([bool(c & 1<
No need for the 'bo' variable...
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: help please

2005-02-20 Thread Steven Bethard
gargonx wrote:
Even if i put it in exactly the way you did:
import re
charmatcher = re.compile(r' [A-Z] [\d]?')
ext = dict(D="V1", O="M1", G="S1")
std = dict(S="H")
decode_replacements ={}
decode_replacements.update([(std[key], key) for key in std])
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: keys
What version of Python are you using?  Here's what I get:
PythonWin 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)] 
on win32.
Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED]) - 
see 'Help/About PythonWin' for further copyright information.
py>
py> import re
py> charmatcher = re.compile(r' [A-Z] [\d]?')
py>
py> ext = dict(D="V1", O="M1", G="S1")
py> std = dict(S="H")
py>
py> decode_replacements = {}
py> decode_replacements.update([(std[key], key) for key in std])

As you can see, I'm using Python 2.4.  I'm guessing you're using an 
earlier version.  I just checked the docs for dict.update:

"update() accepts either another mapping object or an iterable of 
key/value pairs (as a tuple or other iterable of length two). If keyword 
arguments are specified, the mapping is then is updated with those 
key/value pairs: "d.update(red=1, blue=2)". Changed in version 2.4: 
Allowed the argument to be an iterable of key/value pairs and allowed 
keyword arguments."

So dict.update() only accepts a list of key/value pairs as of 2.4 I 
guess.  Try:

py> decode_replacements.update(dict([(std[key], key) for key in std]))
I believe that, unlike dict.update, the dict constructor allowed a list 
of key/value pairs previous to Python 2.4.  If that doesn't work either, 
you can do the more verbose version:

py> for key in std:
... decode_replacements[std[key]] = key
...
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-20 Thread Mike Meyer
"Carl Banks" <[EMAIL PROTECTED]> writes:

> Say you have a suite of functions, all of which are called by some main
> function and each other, and all of which need to access a lot of the
> same data.  The best, most straightforward way to do it is to have the
> common data be a local variable of the main function, and nest the
> suite inside it.  The other way to do it, passing around a common data
> structure, add complexity and hurts performance.

The third way to do it is to make the thing a class. Make all the
functions methods of the class, and all the data instance
variables. You may well want to make the main function the __call__
method of the class. In an OO environment, this may be a better, more
straightforward way than nesting fnctions.

See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 > for an
example of this.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


python2.4 generator expression > python2.3 list expression

2005-02-20 Thread snacktime
I need to convert a generator expression to a list expression so it
will work under python 2.3.

I rewrote this:

for c in range(128):
  even_odd = (sum(bool(c & 1

Re: intersection of 2 list of pairs

2005-02-20 Thread James Stroud
Learned list comprehension today, its cool:


>>> E1=[('a','g'),('r','s')]
>>> E2=[('g','a'),('r','q'),('f','h')]
>>> [x for x in E1 for y in E2 if x == y or (x[1],x[0])==y]
[('a', 'g')]




On Sunday 20 February 2005 09:24 am, [EMAIL PROTECTED] wrote:
> Hi,
> I have 2 lists of tuples that look like:
> E1=[('a','g'),('r','s')] and
> E2=[('g','a'),('r','q'),('f','h')].
> In this tuple, the ordering does not
> matter, i.e. (u,v) is the same as (v,u).
>
> What I want to do is the following:
> given 2 list of tuples, E1 and E2, I want to create another list with
> tuples that are common to both. So in the above example I would like
> to return ('a','g') as being common.
> So far I have the code below but it does not work out properly, I would
> be grateful if someone can help me out .
> thanks
>
> def list_of_tuples_intersect(E1,E2):
>
>   S1=Set()
>   S2=Set()
>   for e in E1:
>   S1.add((e[0],e[1]))
>   S1.add((e[1],e[0]))
>   for e in E2:
>   S2.add((e[0],e[1]))
>   S2.add((e[1],e[0]))
>   S= S1 & S2
>   SS=Set()
>   done=Set()
>
>   for e in S:
>   if ((e[0],e[1])  in done) or ((e[1],e[0])  in done):
>   continue
>   else:
>   SS.add((e[0],e[1]))
>   done.add((e[0],e[1]))
>   done.add((e[1],e[0]))
>   return SS

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
-- 
http://mail.python.org/mailman/listinfo/python-list


Python/Rexx Interface Now Available

2005-02-20 Thread les
A Python Rexx Interface is now available to allow Python scripting to access
REXX libraries and utilities.
See http://www.lestec.com.au for details

Regards,
Les


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


Re: help please

2005-02-20 Thread gargonx
Even if i put it in exactly the way you did:

>>> import re
>>> charmatcher = re.compile(r' [A-Z] [\d]?')
>>>
>>> ext = dict(D="V1", O="M1", G="S1")
>>> std = dict(S="H")
>>>
>>> decode_replacements ={}
>>> decode_replacements.update([(std[key], key) for key in std])
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: keys

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


PyEphem on Win32

2005-02-20 Thread David Flory
 
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Has anyone run the PyEphem ephemeris application under WinXP?  I have
compiled it with Visual Studio 6 and it crashes Python with a simple

>>> import ephem
>>> ephem.date('1994/7/16')

Identical code works fine under Linux. 

I am running ActivePython 2.3.5 Build 236 on a WinXP SP2 system with
Visual Studio 6 patched to sp6.
- ---
David Flory

-BEGIN PGP SIGNATURE-
Version: PGP 8.1

iQA/AwUBQhlQ31e2/rcN3lp8EQJElQCgjRVn5alvDdcCUIuPie5XAnyGJV8AoN5Z
HXZz9RD02fr1cKfh13BcIFNd
=RNWe
-END PGP SIGNATURE-

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


Re: How Do I get Know What Attributes/Functions In A Class?

2005-02-20 Thread George Sakkis
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Thank you Hans.   Could you give me a simple sample of using inspect?
>

http://www.python.org/doc/current/lib/module-inspect.html

George


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


Re: low-end persistence strategies?

2005-02-20 Thread Paul Rubin
"Michele Simionato" <[EMAIL PROTECTED]> writes:
> Ok, I have yet another question: what is the difference between
> fcntl.lockf and fcntl.flock? The man page of my Linux system says
> that flock is implemented independently of fcntl, however it does
> not say if I should use it in preference over fcntl or not.

It looks to me like flock is 4.2-BSD-style locking and fcntl.lockf is
Sys V style.  I'm not sure exactly what the differences are, but
generally speaking, BSD did this type of thing better than Sys V.  On
the other hand, it looks like lockf has more features, like the
ability to ask for a SIGIO notification if someone tries opening a
file that you have locked.  In Python, flock is certainly easier to
use, since you pass an integer mode flag instead of building up the
weird fcntl structure.

There's one subtlety, which is that I'm not sure locking your file
before updating it is guaranteed to do the right thing.  You may have
to use a second file as a lock.  E.g., suppose the data file is small,
like a few dozen bytes.  So maybe:
  1) process A opens the file.  The contents get read into a cache buffer.
  2) Process B opens the file, locks it, updates it, releases the lock.
  3) Process A locks and updates the file.  Is the cached stuff guaranteed
 to get invalidated even in some awful RFS environment?  Or could
 A clobber B's changes?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How Do I get Know What Attributes/Functions In A Class?

2005-02-20 Thread steven
Thank you Hans.   Could you give me a simple sample of using inspect?

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


Re: Tuple index

2005-02-20 Thread John Machin

Steve M wrote:
> Hello,
>
> I'm trying to figure out the index position of a tuple
member.
> I know the member name, but I need to know the members index
position.

Tuples, like lists, don't have members in the sense that they can be
"named" like t.foo. The only way of referring to them is by index,
t[4].

> I
> know that if I use the statement print tuple[4] that it will print
the
> contents of that location. What I don't understand is if I know that
foo is
> a member of tuple, how do I get foo's index position.

You *can't* "know that foo is a member of tuple".

Consider this:

>>> foo = 'carol'
>>> t = (123,456,789,'bob',foo,'ted')
>>> t[4]
'carol'

Is that what you mean by "foo is a member of t'? Well, it's not. foo is
a reference to the string 'carol'. t[4] is also a reference to the
string 'carol'.

Now read on ...

>>> foo = 'alice'
>>> t
(123, 456, 789, 'bob', 'carol', 'ted')
>>> t[4]
'carol'
>>>

Now foo is a reference to the string 'alice'. Nothing to do with t,
either before or now.

Have you read the tutorial found at http://docs.python.org/tut/tut.html
?

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


Re: recommended way of generating HTML from Python

2005-02-20 Thread has
xtian wrote:
> Stan (part of nevow, which is part of twisted) is a nice python
syntax
> for building HTML
[...]
> I don't know how detachable it is from the rest of nevow. I'd assume
it
> wouldn't be too difficult to implement in a standalone fashion.

FWIW I whipped up a simple self-contained Stan clone a while back:

http://freespace.virgin.net/hamish.sanderson/stanlite.py

It's a bit quick-n-dirty - I think ideally you'd want it to parse all
the HTML element information from a DTD and perform proper validation
of input data - but if anyone want to pick it up and run with it, or
just use it as-is, they're more than welcome to.

HTH

has

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


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Mark Lawrence

Nick Vargish wrote:
> "BrainDead" <[EMAIL PROTECTED]> writes:
>
> > I believe that you are wasting your time.  Looking at your email
> > address, this may well be relevant.
>   [ 4-line URL snipped ]
>
> Thanks for the historical reference. Please consider a visit to
> tinyurl.com before posting a monster like that... :^)
>
> Nick
>
> --
> #  sigmask  ||  0.2  ||  20030107  ||  public domain  ||  feed this
to a python
> print reduce(lambda x,y:x+chr(ord(y)-1),'
Ojdl!Wbshjti!=obwAcboefstobudi/psh?')

Nick,

Sorry about that, forgot to engage brain before doing cut and paste.
At least I can learn, unlike some well known people.:)

Regards.

Mark Lawrence.

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


Re: Tuple index

2005-02-20 Thread Erik Max Francis
Larry Bates wrote:
Tuples don't have all the nice methods that lists have
so convert it to a list.
tuple=('a','b','c','d')
l=list(tuple)
now you can do:
list.index('c')
which returns 2
Remember index returns -1 when nothing is found.
No, that's .find in strings that returns -1.  .index in lists raises a 
ValueError:

>>> [1, 2, 3].index(4)
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: list.index(x): x not in list
--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  The map is not the territory.
  -- Alfred Korzybski
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in email package?

2005-02-20 Thread Steven Bethard
Erik Max Francis wrote:
Roman Suzi wrote:
I think that if any object (from standard library at least) doesn't 
support
iteration, it should clearly state so.

My guess is that 'for' causes the use of 'm[0]', which is (rightfully) 
an error...

Can this behaviour of email be considered a bug?
Is there a good case to iterate over something useful in a message
Why would it be a bug if the documentation never stated that the object 
was iterable?
I think the bug is not that an error is produced, but that the _wrong_ 
error is produced.  Trying to iterate over something that is not 
iterable should produce a TypeError saying so (not an Attribute error):

py> class C(object):
... pass
...
py> iter(C())
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: iteration over non-sequence
I've actually seen something like this come up before (I think with 
email.Message even...)  I say call it a bug and submit a patch.  It's 
pretty easy to fix -- just add an __iter__ method to Message that raises 
a TypeError.  That makes it clear that Message doesn't intend to support 
the getitem protocol -- it just does so accidentally because it provides 
__getitem__.

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


Re: Tuple index

2005-02-20 Thread Larry Bates
Tuples don't have all the nice methods that lists have
so convert it to a list.

tuple=('a','b','c','d')
l=list(tuple)

now you can do:

list.index('c')

which returns 2

Remember index returns -1 when nothing is found.

Larry Bates


Steve M wrote:
> Hello,
> 
> I'm trying to figure out the index position of a tuple member. 
> I know the member name, but I need to know the members index position. I
> know that if I use the statement print tuple[4] that it will print the
> contents of that location. What I don't understand is if I know that foo is
> a member of tuple, how do I get foo's index position.
> Thanks-in-Advance
> Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


Tuple index

2005-02-20 Thread Steve M
Hello,

I'm trying to figure out the index position of a tuple member. 
I know the member name, but I need to know the members index position. I
know that if I use the statement print tuple[4] that it will print the
contents of that location. What I don't understand is if I know that foo is
a member of tuple, how do I get foo's index position.
Thanks-in-Advance
Steve
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exercise: partition a list by equivalence

2005-02-20 Thread Erik Max Francis
John Machin wrote:
Xah is asserting his right to be recognised as the author of his
artistic creations, line by line.
Not very well, however, since his usage doesn't constitute a valid 
copyright notice :-).

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  Wyrd has swept all my kin / all the brave chiefs away! / Now I must
  follow them! -- Beowulf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in email package?

2005-02-20 Thread Erik Max Francis
Roman Suzi wrote:
I think that if any object (from standard library at least) doesn't support
iteration, it should clearly state so.
My guess is that 'for' causes the use of 'm[0]', which is (rightfully) an 
error...

Can this behaviour of email be considered a bug?
Is there a good case to iterate over something useful in a message
Why would it be a bug if the documentation never stated that the object 
was iterable?

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  Wyrd has swept all my kin / all the brave chiefs away! / Now I must
  follow them! -- Beowulf
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pausing a program - poll/sleep/threads?

2005-02-20 Thread Simon John
Ah yes, that Informit article helped endlessly - I'm all done now - got
the backend to fetch the info from the server every 2secs using a
QThread, then it pass the data back to the GUI frontend by raising a
custom event!

Thanks for all the help folks, now I'm off to compile the new PyQt 3.14
;-)

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Nick Vargish
Ilias Lazaridis <[EMAIL PROTECTED]> writes:

> Now it's really time to close this thread.

I suspect this will fall of deaf ears, but I have to mention that you
do not get to "close threads" on Usenet. You can excuse yourself from
this one and stop replying to comments, but you don't get to
unilaterally declare a discussion over.

Just not how it works, though in this case an exception might be
welcomed...

Nick

-- 
#  sigmask  ||  0.2  ||  20030107  ||  public domain  ||  feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Neil Hodgson
Martin v. Löwis:

> So I have to guess what you could have meant. If you want
> to be understood, you might have phrased the question like
> this:
>
> "Should I take answers from people which do not respect coherence
> of writings serious?"

   The main grammatical problem with the question is the use of an adjective
("serious") rather than an adverb ("seriously") to modify the verb "take".

Should I take answers seriously?

   I'd also add in an article to point to the particular answers to be
disregarded.

Should I take these answers seriously?

   Next problem is the disagreement in number between "answers" and "answer"
which breaks the connection just as separating the questions does.

Answers from people which do not respect coherence of writings?

   There are more problems to fix but this is a start. Grammatical errors
are often perceived as rudeness.

> Perhaps the question was meant rhetoric.

   Aghhh! He's got you doing it too.

   Neil -- Aussie ear for the foreign guy


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


Re: [ANN] Python 2.4 Quick Reference available

2005-02-20 Thread Michael Hoffman
François Pinard wrote:
[Michael Hoffman]
To be honest I doubt open will be extended in this manner.
I did not read Guido's arguments for a while, so I may remember them
wrongly.
No, I think you remember them the same way I do.
So, take me with a grain of salt.  I would not think Guido is
arguing for the sole sake of arguing.  Maybe his plans or visions will
change, but until such changes are announced, I've no reason to doubt
them :-).
Well I'd hope they would. :)
All in all, `file' is now probably to be considered safer than
`open', despite Guido advises to prefer `open'.
Definitely. :)
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Python 2.4 Quick Reference available

2005-02-20 Thread Peter Hansen
Michael Hoffman wrote:
That said, I still use file() instead of open(). I think that:
for line in file("mytext.txt"):
makes a lot more sense than:
for line in open("mytext.txt"):
I guess it's because the first option sounds a lot more like English.
Call me a space-waster (or a "waste of space" ;-)  but I
still prefer this one to either of the above:
file = open('mytext.txt')
for line in file:
   ...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to Python from PHP - 3 questions

2005-02-20 Thread Joe Francia
Michal Migurski wrote:
Thank you. My impression of Zope in the past has been that it does what 
I need, along with 10,000 other things I don't (built in WebDAV 
server?!), but clearly I owe it another chance. I've been initially 
attracted to mod_python because of its raw simplicity and its apparent 
similarity to mod_php and mod_perl, which I am familiar with. I'll give 
Zope a try.

I am moving my band's website from an antiquated and horrible PHPNuke 
site to a Python-based site, and so have done quite a bit of research 
about this (though I never considered myself a PHP expert).  Here's what 
I've come up with...

Zope is excellent (especially with Plone), but if you are not building 
applications that require lots of levels of access and permissions and 
collaborations, as well as the 10,000 other things you speak of, you 
probably would like something simpler than Zope, such as CherryPy or 
Quixote.  Both are excellent and light-weight frameworks that give you 
session support and easy access to request variables (as well as full 
access to the entire Python language).  Conceptually, the two are very 
close, but I am slightly more biased towards CherryPy lately.  Quixote 
has better built in form support, but now that I've discovered FormKit, 
this seems to becoming a non-issue.  Also, both are pure Python so 
should run anywhere Python does (though Quixote has a C extension, it 
will fallback to a somewhat slower pure-Python version if your platform 
cannot compile the extension).

There are other good frameworks out there, like Nevow and Webware, but 
have a somewhat larger conceptual overhead which doesn't rest as easy 
with me.  You'll also want to probably look at some of the templating 
kits, of which Cheetah and/or ElementTree work best for me.  (Well, 
ElementTree isn't exactly a templating kit - it's a general-purpose XML 
tookit - but it is easily used for templating.)

General Python web programming:
http://www.python.org/topics/web/
Frameworks/toolkits:
[CherryPy] http://www.cherrypy.org/
[Quixote] http://www.mems-exchange.com/software/quixote
[FormKit] http://dalchemy.com/opensource/formkit/
[Cheetah] http://www.cheetahtemplate.org/
[ElementTree] http://effbot.org/zone/element-index.htm
[Nevow] http://nevow.com/
[Webware] http://www.webwareforpython.org/
For more comparisons of some of the various frameworks:
[PyWebOff] http://pyre.third-bit.com/pyweb/index.html
[Python Web Shootout (older)] http://www.colorstudy.com/docs/shootout.html
--
Soraia: http://www.soraia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: questions concerning cgi.FieldStorage(keep_blank_values=1)

2005-02-20 Thread Daniel Lichtenberger
Jonas Meurer wrote:
"key1" isn't a valid parameter, to supply an empty key you would write
script.py?key1=&key2=foo
Then cgi.FieldStorage also includes key1.
great, it works. but is there no way to use single keywords as GET
argument?
You could manually parse the request string (CGI stores the request 
string as an environment variable, you can retrieve it via 
os.environ["REQUEST_STRING"]), but why not add "=1" (or "=") to your 
keywords?

bye,
Daniel
--
http://perplex.schmumpf.de/
[visit for regular email address]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Test for structure

2005-02-20 Thread Steven Bethard
Terry Hancock wrote:
> But you probably shouldn't do that. You should probably just test to
> see if the object is iterable --- does it have an __iter__ method?
>
> Which might look like this:
>
> if hasattr(a, '__iter__'):
> print "'a' quacks like a duck"
Martin Miller top-posted:
I don't believe you can use the test for a __iter__ attribute in this
case, for the following reason:
c1 = 'abc'
c2 = ['de', 'fgh', 'ijkl']
hasattr(c1, '__iter__')
False
hasattr(c2, '__iter__')
True
Right.  str and unicode objects support iteration through the old 
__getitem__ protocol, not the __iter__ protocol.  If you want to use 
something as an iterable, just use it and catch the exception:

try:
itr = iter(a)
except TypeError:
# 'a' is not iterable
else:
# 'a' is iterable
Another lesson in why EAPF is often better than LBYL in Python[1].
STeVe
[1] http://www.python.org/moin/PythonGlossary
--
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to Python from PHP - 3 questions

2005-02-20 Thread Brian Beck
Maybe this can help you get it working on OS X:
http://thread.gmane.org/gmane.comp.python.mod-python/4039
But as stated in my other post, you may want to take a look at your 
other options first. Web development with Python is really nothing like 
PHP, unless you really want it to be.

--
Brian Beck
Adventurer of the First Order
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie CGI problem

2005-02-20 Thread Rory Campbell-Lange
On 18/02/05, Peter Otten ([EMAIL PROTECTED]) wrote:
> Rory Campbell-Lange wrote:
> 
> > #!/usr/bin/python
> > import cgi
> > print "Content-type: text/html\n\n"
> > print "hi"
> > 
> > Gives me the following in my browser:
> > 
> > '''
> > hi
> > Content-type: text/html
> > 
> > 
> > hi
> > '''
> > 
> > Why are there two 'hi's?
> 
> You have chosen a bad name for your script: cgi.py.
> It is now self-importing. Rename it to something that doesn't clash with the
> standard library, and all should be OK.

Thanks very much. Ouch!
Rory

-- 
Rory Campbell-Lange 
<[EMAIL PROTECTED]>

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


Re: Moving to Python from PHP - 3 questions

2005-02-20 Thread Brian Beck
Michal Migurski wrote:
Thank you. My impression of Zope in the past has been that it does what 
I need, along with 10,000 other things I don't (built in WebDAV 
server?!), but clearly I owe it another chance. I've been initially 
attracted to mod_python because of its raw simplicity and its apparent 
similarity to mod_php and mod_perl, which I am familiar with. I'll give 
Zope a try.
Personally, I'd have to say that your impression was right. Once you 
start using Zope, you'll start to feel locked in. Sure, it does a lot 
for you, but it's also a big investment.

I can't really help you to get mod_python working on OS X, but 
concerning your other two points, did you notice these two sections in 
the documentation?

http://modpython.org/live/current/doc-html/pyapi-sess.html
http://modpython.org/live/current/doc-html/pyapi-mprequest.html
mod_python and Zope are not your only options by far. In fact, they're 
at completely opposite ends of the spectrum; mod_python being low-level 
in that you are in control of everything and have the necessary tools to 
build a framework, and Zope being the highest-level in that it does tons 
of stuff for you. There are dozens of frameworks in between.

If you do manage to get mod_python working, I suggest taking a look at 
Vampire as well: http://www.dscpl.com.au/projects/vampire/
I have had good experience with it. Once you start using mod_python 
you'll realize you can really go anywhere you want; and that's not 
necessarily a good thing. Vampire points you in a nice direction (I 
don't want to say 'the right' direction).

--
Brian Beck
Adventurer of the First Order
--
http://mail.python.org/mailman/listinfo/python-list


Re: Test for structure

2005-02-20 Thread Martin Miller
I don't believe you can use the test for a __iter__ attribute in this
case, for the following reason:
>>> c1 = 'abc'
>>> c2 = ['de', 'fgh', 'ijkl']
>>> hasattr(c1, '__iter__')
False
>>> hasattr(c2, '__iter__')
True
>>> for i in c1: print "i=%s is an element of c1" % repr(i)
...
i='a' is an element of c1
i='b' is an element of c1
i='c' is an element of c1

In other words, even though the c1 single string variable does not have
an __iter__ attribute, it can still be used in a for loop. I think the
right answer would depend on what exactly the OP intends to do with the
argument when it is a list (or is list-like in some way) -- i.e. he
didn't say specifically that he wanted use it in a for loop.

-Martin



Terry Hancock wrote:
> On Wednesday 16 February 2005 09:08 am, alex wrote:
> > how can I check if a variable is a structure (i.e. a list)? For my
> > special problem the variable is either a character string OR a list
of
> > character strings line ['word1', 'word2',...]
> >
> > So how can I test if a variable 'a' is either a single character
string
> > or a list?
>
> The literally correct but actually wrong answer is:
>
> if type(a) == type([]):
> print "'a' is a duck"
>
> But you probably shouldn't do that. You should probably just test to
> see if the object is iterable --- does it have an __iter__ method?
>
> Which might look like this:
>
> if hasattr(a, '__iter__'):
> print "'a' quacks like a duck"
>
> That way your function will also work if a happens to be a tuple,
> a dictionary, or a user-defined class instance which is happens to
> be  iterable.
>
> Being "iterable" means that code like:
>
> for i in a:
>print "i=%s is an element of a" % repr(i)
>
> works.  Which is probably why you wanted to know, right?
>
> Cheers,
> Terry
>
> --
> --
> Terry Hancock ( hancock at anansispaceworks.com )
> Anansi Spaceworks  http://www.anansispaceworks.com

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


ANNOUNCE: KirbyBase 1.8

2005-02-20 Thread Jamey Cribbs
KirbyBase is a simple, plain-text, database management system written in 
Python.  It can be used either embedded in a python script or in a 
client/server, multi-user mode.  You use python code to express your 
queries instead of having to use another language such as SQL.  
KirbyBase is disk-based, not memory-based.  Database changes are 
immediately written to disk.

You can find more information on KirbyBase at:
http://www.netpromi.com/kirbybase.html
You can download KirbyBase for Python at:
http://www.netpromi.com/files/KirbyBase_Python_1.8.zip
The most noticeable things about this release are (1) the ability to 
sort the result set by multiple fields, (2) the ability to have the 
result set returned as a nicely formatted report, suitable for printing, 
and (3) the ability to do an insert or an update using a record object 
(thanks, Fred Pacquier, for the suggestion).

The manual has also been updated to reflect the new features.
Also, for those of you who have asked how Kirby is doing, I have a 
couple of new pictures of him on the website.  :-)

I would like to thank everyone who has emailed me with comments, bug 
reports, and enhancement requests/ideas.  Hearing from people who 
actually use KirbyBase is what makes working on it worthwhile.  Please 
keep the emails coming!

Changes in Version 1.8:
   IMPORTANT - Method Interface Changes   
   -Added the ability to sort the result set of a select by multiple
fields and to specify whether each field should be sorted
ascending or descending.  This necessitated a change to the
interface of the select method.  I moved the position of sortField
in the argument list and also changed it to be a list instead of a
string.  I also changed the name of sortField to sortFields. I
also moved sortDesc in the arguement list and also made it a list.
**
   -Added another allowable value, 'report',  to the keyword
parameter, returnType in the select method.  This returns the
result set in a pretty print format.  Along with this, added
another keyword parameter called rptSettings to the select method.
This is only used if rptType is 'report'.  It is a 2 element list.
The first element specifies the number of records to print on a
page.  The second element is boolean specifying whether to print
a dashed line between records.
   -Added ability to pass field values to update and insert using an
object with attributes set equal to the field names.
   -Fixed a bug in _getMatches.  If a field of type int or float had
a blank value in the table (i.e. ''), the code was attempting to
convert it to it's proper type (i.e. int or float) before
doing the match comparison.  This would cause an exception to
occur.  Now, if the field is an int,float,date or datetime and it
is blank, I convert it to None.  This allows the numeric
comparisons to work correctly for null fields.
   -Fixed a bug in select.  If a field in the result set was equal
to '', I was letting it stay that way, when I should really be
converting it to None before returning the result set.
   -Cleaned up the internals a bit.  Mainly, I tried to use functions
in the operator module like lt and ge instead of hardcoding < and
>= in an if statement.
Jamey Cribbs
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: [long] nested lists as arrays

2005-02-20 Thread [EMAIL PROTECTED]
great thanks

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


Re: Moving to Python from PHP - 3 questions

2005-02-20 Thread Diez B. Roggisch
> Thank you. My impression of Zope in the past has been that it does what
> I need, along with 10,000 other things I don't (built in WebDAV
> server?!), but clearly I owe it another chance. I've been initially

The apache has a built in webdav server too - is that a reason _not_ to use
it? If you don't want a feature, don't use it. You can turn them off, btw. 

But what you might not be aware of is that zope does not store its
templates, scripts and files in general in the filesystem as php does, but
as objects in the zodb database. So webdav and ftp are other views to that
objects that allow you to load and save these files using "normal" editors
and tools, not only the web-interface of zope. The advantage of this
approach is that versioning of content - regardless of it's type - is
built-in. Can be a life-saver sometimes :)

> attracted to mod_python because of its raw simplicity and its apparent
> similarity to mod_php and mod_perl, which I am familiar with. 

It certainly is the most simple way to create dynamic content. But there is
a big difference between python and php: php started as a web-developers
tool, and it's features are a direct consequence of that. python oth is a
general purpose programming language - it is certainly suited for web
development, but not limited to. There are people who also want to use php
as general purpose programming language - but nevertheless, its design has
been influenced by its main purpose. So you e.g. get session state handling
"for free"  - as more or less _all_ web-apps today need them.


-- 
Regards,

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


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Nick Vargish
"BrainDead" <[EMAIL PROTECTED]> writes:

> I believe that you are wasting your time.  Looking at your email
> address, this may well be relevant.
  [ 4-line URL snipped ]

Thanks for the historical reference. Please consider a visit to
tinyurl.com before posting a monster like that... :^)

Nick

-- 
#  sigmask  ||  0.2  ||  20030107  ||  public domain  ||  feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
-- 
http://mail.python.org/mailman/listinfo/python-list


Bug in email package?

2005-02-20 Thread Roman Suzi
I was playing with email package and discovrered this strange kind of 
behaviour:

import email.Message
m = email.Message.Message()
m['a'] = '123'
print m
From nobody Mon Feb 21 00:12:27 2005
a: 123

for i in m: print i
...
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/local/lib/python2.3/email/Message.py", line 304, in __getitem__
return self.get(name)
  File "/usr/local/lib/python2.3/email/Message.py", line 370, in get
name = name.lower()
AttributeError: 'int' object has no attribute 'lower'
I think that if any object (from standard library at least) doesn't support
iteration, it should clearly state so.
My guess is that 'for' causes the use of 'm[0]', which is (rightfully) an 
error...

Can this behaviour of email be considered a bug?
Is there a good case to iterate over something useful in a message?
P.S. rfc822 has the same behaviour, at least on Python 2.3
Sincerely yours, Roman Suzi
--
[EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3
--
http://mail.python.org/mailman/listinfo/python-list


Article on Hi-Fi Myths

2005-02-20 Thread Al Christians
I learned Friday night that the hi-fi talk is our most popular tape.
This page:
http://www.belt.demon.co.uk/product/Cable_Controversy/Cable_Controversy.htm
Gives a somewhat different take on the controversy, almost certainly 
bizarre.  It's a long page and the interesting part is near the end.
The conclusion is:

	"you just need to know what techniques to use to create a 		 
'friendly', 'relaxing', energy pattern."

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


Re: recommended way of generating HTML from Python

2005-02-20 Thread xtian
Stan (part of nevow, which is part of twisted) is a nice python syntax
for building HTML - I like the use of () and [] to separate attributes
from sub-elements.

For example:

class Greeter(rend.Page):
def greet(self, context, data):
return random.choice(["Hello", "Greetings", "Hi"]), " ", data

docFactory = loaders.stan(
tags.html[
tags.head[ tags.title[ "Greetings!" ]],
tags.body[
tags.h1(style="font-size: large")[ "Now I will greet you:" ],
greet
]
])

(From http://nevow.com/releases/0.3.0/nevow-intro.html)

I don't know how detachable it is from the rest of nevow. I'd assume it
wouldn't be too difficult to implement in a standalone fashion.

xtian

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


Re: Moving to Python from PHP - 3 questions

2005-02-20 Thread Michal Migurski
The python-based zope application server has session management. 
Togther
with a built-in user and access rights management.
...
This can be done in zope if you name a variable :list. That then 
will
give you the variable as list regardless of the number of occurences.
Thank you. My impression of Zope in the past has been that it does what 
I need, along with 10,000 other things I don't (built in WebDAV 
server?!), but clearly I owe it another chance. I've been initially 
attracted to mod_python because of its raw simplicity and its apparent 
similarity to mod_php and mod_perl, which I am familiar with. I'll give 
Zope a try.

--
michal migurski- contact info, blog, and pgp key:
sf/cahttp://mike.teczno.com/contact.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt Python Bindings for Qt v3.14 Released

2005-02-20 Thread Phil Thompson
On Sunday 20 February 2005 8:42 pm, Simon John wrote:
> All looks like good news, especially PyQt4 - one question, if it's
> statically linked with Qt4, will it still work with things like py2exe?

Should do.

> I guess it just won't need qt-mt4.dll?

The binary will be provided for the Windows GPL version just to make it as 
easy as possible for people to get started. Obviously the source will also be 
available to build it yourself if you need to.

> I'm getting a 404 on the new SIP:
>
> http://www.river-bank.demon.co.uk/download/QScintilla/qscintilla-1.61-gpl-1
>.5.tar.gz

Should be fixed now - thanks.

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


Re: Moving to Python from PHP - 3 questions

2005-02-20 Thread Diez B. Roggisch
Hi,

> 2) Session management. Cookie-based sessions in PHP are pretty
> transparent, with a small library of basic functions that do 95% of
> what anyone may need to store session data in serialized files and
> associate them with cookies. I've seen python code that accomplishes
> this, but so far no pre-built server-side session management modules.

The python-based zope application server has session management. Togther
with a built-in user and access rights management. 

> 3) Structured request variables. PHP has a really handy feature where
> request variables with name like "foo[]", "foo[bar]", or
> "foo[bar][baz]" are automatically structured into nested associative
> arrays. I can see that the python cgi module will make a list of
> MiniFieldStorage objects when more than one variable with the same name
> is provided, but that's about the extent of it that I've seen.

This can be done in zope if you name a variable :list. That then will
give you the variable as list regardless of the number of occurences.

> 
> An "RTFM" answer with a URL for the M would be great. :)

For zope: http://www.zope.org/

But there are plenty of other python http frameworks. The mod_python is
AFAIK the most basic and primitive one. But build on top of it or fully
python-based you have plenty of options. Google is your friend - this NG
features similar discussions every other week.


-- 
Regards,

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


Re: PyQt Python Bindings for Qt v3.14 Released

2005-02-20 Thread Simon John
All looks like good news, especially PyQt4 - one question, if it's
statically linked with Qt4, will it still work with things like py2exe?
I guess it just won't need qt-mt4.dll?

I'm getting a 404 on the new SIP:

http://www.river-bank.demon.co.uk/download/QScintilla/qscintilla-1.61-gpl-1.5.tar.gz

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


Re: recommended way of generating HTML from Python

2005-02-20 Thread Pierre Quentel
Here are a couple of pointers. I agree with Michele that it would be 
nice to have some kind of standardization. Maybe this would be worth a 
post to the Web-SIG ?

- I posted a 70-line recipe on the Python Cookbook, a sort of poor man's 
HTMLGen called HTMLTags
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366000
with a syntax like this :

# print HTML( HEAD(TITLE('Test document')) +
#BODY(H1('This is a test document')+
#TEXT('First line')+BR()+
#TEXT('Second line')))
The use of addition allows for shortcuts like
print Sum([ TR(TD(i)+TD(i*i)) for i in range(100) ])
where Sum works like the built-in sum, but sum only works for numbers 
apparently

- in the Cookbook someone mentioned the HyperText package, published in 
2000 by Andy Dustman : http://dustman.net/andy/python/HyperText/

It uses this syntax :
# print TABLE(
#TR((TH('SPAM'), TH('EGGS')),
#TR(TD('foo','bar', colspan=2))
# )
The package also handles XML, SGML etc.
- I wrote to Andy and he said there was also Living Logic's XIST :
http://www.livinglogic.de/Python/xist/index.html
An example taken from the site :
#node = xsc.Frag(
#  xml.XML10(),
#  html.DocTypeXHTML10transitional(),
#  html.html(
#  html.head(
# meta.contenttype(),
# html.title("Example page")
#  ),
#  html.body(
# html.h1("Welcome to the example page"),
# html.p(
#"This example page has a link to the ",
#html.a("Python home page", href="http://www.python.org/";),
#"."
# )
#  )
#   )
# )
#
# print node.conv().asBytes(encoding="us-ascii")
--
http://mail.python.org/mailman/listinfo/python-list


Re: exercise: partition a list by equivalence

2005-02-20 Thread John Machin

Eric Pederson wrote:
> > From: "Xah Lee" <[EMAIL PROTECTED]>
> > ©for group in interm:
> what do the funny little "©"s stand for?

...>>> import unicodedata as ucd; ucd.name('©'.decode('cp1252'))
'COPYRIGHT SIGN'

Xah is asserting his right to be recognised as the author of his
artistic creations, line by line.

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


Moving to Python from PHP - 3 questions

2005-02-20 Thread Michal Migurski
Hi everyone,
I've been planning to move to Python from PHP for some time now. I use 
PHP extensively for web scripting, with mod_php, Apache, and a DB (I 
would characterize my knowledge of PHP as advanced). Here are three 
stumbling blocks I've experienced, for which I couldn't seem to find 
any helpful information via Google:

1) Mod_python on OSX. I use a Mac as my primary development 
environment, so I need mod_python to get anything done. Compiling 
mod_python from source fails under OSX 10.3, and mod_python does not 
appear to be included in Fink. I've found plenty of other questions 
about this on other mailing lists, but so far no conclusive answers - 
is mod_python on OSX currently a dead-end?

2) Session management. Cookie-based sessions in PHP are pretty 
transparent, with a small library of basic functions that do 95% of 
what anyone may need to store session data in serialized files and 
associate them with cookies. I've seen python code that accomplishes 
this, but so far no pre-built server-side session management modules.

3) Structured request variables. PHP has a really handy feature where 
request variables with name like "foo[]", "foo[bar]", or 
"foo[bar][baz]" are automatically structured into nested associative 
arrays. I can see that the python cgi module will make a list of 
MiniFieldStorage objects when more than one variable with the same name 
is provided, but that's about the extent of it that I've seen.

2 & 3 are problems I can solve on my own, but they're so transparently 
automatic in PHP that it's a real pleasure to use them. I can probably 
implement my own fixes, but I'd rather not have to. Alternatively, are 
these just "PHP-isms" for which python has a more native, more 
appropriate response?

An "RTFM" answer with a URL for the M would be great. :)
Thank you,
-mike.
--
michal migurski- contact info, blog, and pgp key:
sf/cahttp://mike.teczno.com/contact.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: exercise: partition a list by equivalence

2005-02-20 Thread John Machin

Reinhold Birkenfeld wrote:
> Reinhold Birkenfeld wrote:
>
> > My solution (which may not be the fastest or most effective, but
till
> > now is the shortest  and it works):

[snip RB]
>
> A recursive solution (around twice as fast as the above, though very
> slow still...)
>
[snip RB2]
>
> Another one:
>

[snip RB3]

Dunno what data you are using for timing, but my tests suggest that RB
is fast enough, RB3 is slightly faster, but RB2 is a real dog and
appears to be quadratic [hint: it has that same for-for-for-update
signature found in phase 2 of Xah's effort]. Not only that, but it
seems to be somewhat irregular. Below are some results on trivial test
data:

prototype input: python -m timeit -s "import
merge;n=3000;inp=((x,x+1)for x in xrange(0,n,2))"
"merge.merge_RB3(inp)"
10 loops, best of 3: 3.98 usec per loop

n=3000;RB2  64.9 msec per loop
n=3000;RB3  3.98 usec per loop
n=3000;RB  3.06 usec per loop
n=3000;JM3  2.73 usec per loop

n=1000;RB2  4.92 usec per loop
n=1250;RB2  5.34 usec per loop
n=1500;RB2  20.4 usec per loop
n=1750;RB2  22.1 msec per loop
n=2000;RB2  28.8 msec per loop
n=2500;RB2  44.9 msec per loop
n=3000;RB2  64.9 msec per loop

[background: Python 2.4, Win2000, 1.4GHz Athlon chip, 768Mb memory]

Here's a function to generate some serious timing data:
!def mktimedata(n,lev):
!res = []
!d = 1
!for k in range(lev):
!res.extend(zip(xrange(0, n, 2*d), xrange(d, n, 2*d)))
!d *= 2
!return res

Try that with n=3000 and lev=5 ...

Cheers,
John

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


Re: recommended way of generating HTML from Python

2005-02-20 Thread Fernando Perez
Michele Simionato wrote:

> What is the recommended way of generating HTML from Python? I know of
> HTMLGen and of
> few recipes in the Cookbook, but is there something which is more or
> less standard?

I'm also an htmlgen user, but it's getting a bit long in the tooth, and the
installation is not very clean (pre-distutils).  I keep an eye out for
alternatives, here's one (which I haven't looked at yet):

##
htmldata 1.0.6 is available.

http://oregonstate.edu/~barnesc/htmldata/

The htmldata module allows one to translate HTML
documents back and forth to list data structures.
This allows for programmatic reading and writing
of HTML documents, with much flexibility.

##

I could swear that I also saw another recent email announcing an htmlgen
alternative, but no amount of googling or digging through my email could turn
it up.  I think it was in the last month or so, and probably on the
python-announce list, but looking through the archives I can't find it.  Maybe
my memory is playing tricks on me.

> Also, are there plans to include a module for HTML generation in the
> standard library?
> I really would like to see some standardization in this area.

I would too.  The HTMLgen model is quite nice and clean (at least for my simple
uses), but I'd use anything, as long as it's included by default and supported.

Cheers,

f

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


Re: How to wrap a class's methods?

2005-02-20 Thread Steven Bethard
rbt wrote:
Jeff Shannon wrote:
You could probably also do this as a factory function, rather than as 
a class (also untested!):

def Wrapper(func):
def wrapped(self, *args, **kwargs):
s, r = func(self, *args, **kwargs)
if s != 'OK':
raise NotOK((s,r))
return r
return wrapped
I believe that this will be semantically almost equivalent, but 
conceptually slightly simpler.

Jeff Shannon
This is a nice example. I have used sub-functions (functions within 
functions) recently with some code, but I've wondered how proper it is 
to do this. Is this type of thing frowned upon?
Nope.  If it was frowned upon, Python wouldn't support it. ;)  Sometimes 
it's even faster:

 test.py 
def wrapper(func):
def wrapped(*args, **kwargs):
return bool(func(*args, **kwargs))
return wrapped
class Wrapper(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return bool(self.func(*args, **kwargs))
-
$ python -m timeit -s "import test; w = test.wrapper(sum)" "w([]); w([1,2])"
10 loops, best of 3: 4.77 usec per loop
$ python -m timeit -s "import test; w = test.Wrapper(sum)" "w([]); w([1,2])"
10 loops, best of 3: 6.52 usec per loop
Personally, I still tend towards the class-based version, but I'm sure 
in many cases the nested function version would work just as well.

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


Re: help please

2005-02-20 Thread Steven Bethard
gargonx wrote:
I think there's a problem with the code:
 py> decode_replacements.update([(std[key], key) for key in std])
 py> decode_replacements.update([(ext[key], key) for key in ext])
when i run this i get an error:
 AttributeError: keys
I can't get that figured out
Can you show the part of your code in which you do this?  As you can see 
from the interactive Python session I posted, I didn't get an 
AttributeError...

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Ilias Lazaridis
Summarized Suggestions for the Python Team, PSF, Community):
-
-
-
An automated-build-process-system should allow community-members to add 
their targets (e.g. MinGW) into an special "incubation section", which 
does not in any way affect the "main section" (which contains the 
official production targets, e.g. MSVC).

If an "incubation section" target proves over time as stable and 
supported (by community contributions), it is moved to the 
"official-auto-build".

-
The python-team should
 * detect any efforts made within the community to support different 
build-targets
 * attract/engourage the authors/teams to include the patches/sources 
into the main build-system
 * attract/engourage the authors/teams to have open projects with an 
collaboration infrastructure.

-
The python-community and the PSF should support the python-team to 
fulfill the above tasks, thus the python-teams effort is limited to 
provide the infrastructure (incubation-build-targets).

-
-
-
Practical example:
Engourage the current pyMinGW project to become a open collaborative 
project:

http://jove.prohosting.com/iwave/ipython/pyMinGW.html
  * as a first step, setup a pyMinGW mailinglist
* intrested people can come together an communicate
  * as a second step, setup an SVN
* intrested projects could get your patch via SVN
  * as a third step, find intrested contributors
* which would help testing
* which would help you with coding
The python-team setups a build-target, which the collaborative pyMinGW 
project tries to make valid.

-
-
-
Now it's really time to close this thread.
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-20 Thread Dirk Thierbach
Ted Lilley <[EMAIL PROTECTED]> wrote:
> As a side note, I'm familiar with the term currying from a friend who
> learned ML and Scheme quite some time ago.  Not sure if that's the true
> origin, but it was a sufficiently different context from Python (or at
> least I thought) that I didn't want to rely on its meaning.  I was also
> sufficiently unsure of it's _exact_ meaning, 

The exact meaning is reasonably well explained, together with the
origins, on Wikipedia:

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

That meaning shouldn't change if applied to different computer languages.
I can understand the temptation to confuse partial application with
currying (for languages like Python which take tuples of arguments
by default, currying is one way to make partial application possible;
supplying default arguments is another), but nonetheless they are different 
things.

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


Re: BaseHTTPServer threading using SocketServer.ThreadingMixIn

2005-02-20 Thread Tortelini
It's not that, here is definition that I use:
class myWebServer(SocketServer.ThreadingMixIn,
BaseHTTPServer.HTTPServer):
  pass

code that runs server:
server = myWebServer(('', 80), myWebHTTPHandler)
LOG("Web Server starting")
server.serve_forever()

and here is shortened version of myWebHTTPHandler:
class myWebHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
sys_version=""
server_version=versionString

def log_request(self, code='-', size='-'):
pass

def do_GET(self):
my GET code...

def do_POST(self):
my POST code...

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


Re: Trouble with mysql-python 1.2.0 on Solaris 8 sparc

2005-02-20 Thread Andy Dustman
Did you build your own MySQL, or did you use a pre-built version? And
what version? It's not clear if you're using 4.0 or 4.1. If
mysql_config is returning the wrong flags, then that's a bug with
MySQL.

You should be able to work around this by doing this in setup.py before
the call to setup():

extra_compile_args.remove('-m64')

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


Re: introspection inquiry

2005-02-20 Thread Michael Hoffman
Robin Becker wrote:
import inspect
class A:
  _class_name=inspect.currentframe().f_code.co_name
  def __init__(self,text,_defining_class_name=_class_name):
print 'text=',text,'_defining_class_name=',_defining_class_name
class B(A):
  pass
b=B('aaa')
That won't work, if you, say, wanted to print out the name of the
class the constructor was defined in for a whole chain of
constructors. Which is about the only case I can think of where
this would be useful.
could work as well, but if we only need the local name why not just 
insert directly.
To be honest, that is what I have done every time I have needed
something like this.
I've only used metaclasses in production code once and I still debate
whether that case is a good idea or not.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Python 2.4 Quick Reference available

2005-02-20 Thread François Pinard
[Michael Hoffman]

> To be honest I doubt open will be extended in this manner.

I did not read Guido's arguments for a while, so I may remember them
wrongly.  So, take me with a grain of salt.  I would not think Guido is
arguing for the sole sake of arguing.  Maybe his plans or visions will
change, but until such changes are announced, I've no reason to doubt
them :-). All in all, `file' is now probably to be considered safer than
`open', despite Guido advises to prefer `open'.

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: intersection of 2 list of pairs

2005-02-20 Thread John Machin

[EMAIL PROTECTED] wrote:
> Hi,
> I have 2 lists of tuples that look like:
> E1=[('a','g'),('r','s')] and
> E2=[('g','a'),('r','q'),('f','h')].
> In this tuple, the ordering does not
> matter, i.e. (u,v) is the same as (v,u).
>
> What I want to do is the following:
> given 2 list of tuples, E1 and E2, I want to create another list with
> tuples that are common to both. So in the above example I would like
> to return ('a','g') as being common.
> So far I have the code below but it does not work out properly, I
would
> be grateful if someone can help me out .
[snip]

This is likely to do what you want, provided the types of the objects
in your tuples define an ordering. The idea is to change the
representation of the tuples to a canonical form (a, b) where a <= b.
By the way, have you considered that there might be duplicates *within*
each list?

>>> E1=[('a','g'),('r','s')]
>>> E2=[('g','a'),('r','q'),('f','h')]
>>> s1 = set((min(x,y),max(x,y)) for x, y in E1)
>>> s1
set([('a', 'g'), ('r', 's')])
>>> s2 = set((min(x,y),max(x,y)) for x, y in E2)
>>> s2
set([('a', 'g'), ('q', 'r'), ('f', 'h')])
>>> answer = s1 & s2
>>> answer
set([('a', 'g')])
>>>

Here's a hint: when you find yourself typing stuff like (x[0],x[1])
 (x[1],x[0]) more than minimally, the 'wrong way, go back' sign
should flash up.

HTH,

John

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Ilias Lazaridis
Martin v. Löwis wrote:
Ilias Lazaridis wrote:
Should I take answers serious?
[...]
Answer from people which do not respect coherence of writings?
[...]
I still detect the coherence.
As most people in this group will detect the coherence.
I don't. The second fragment is not even correct English
[...] - (limits of AI)
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread BrainDead
[Snip]

Martin,

I believe that you are wasting your time.  Looking at your email
address, this may well be relevant.

http://groups-beta.google.com/group/de.admin.net-abuse.news/browse_frm/thread/8914399857641c05/4163a4fb8a624349?q=Ilias&_done=%2Fgroup%2Fde.admin.net-abuse.news%2Fsearch%3Fgroup%3Dde.admin.net-abuse.news%26q%3DIlias%26qt_g%3D1%26searchnow%3DSearch+this+group%26&_doneTitle=Back+to+Search&&d#4163a4fb8a624349

Regards.

Mark Lawrence.

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


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Pat
Nick Coghlan wrote:
> Pat wrote:
> > On Windows, most users are used to installing precompiled binary
> > packages, rather than compiling from source.  When you do have to
> > compile from source, it often requires you to fiddle with nitty
gritty
> > details about which you'd rather remain ignorant.  The less
fiddling
> > required, the happier the user will be, and the easier it will be
for
> > that product to get adopted on that platform.  No psychic abilities
are
> > required.  No Python abilities are required, either, for that
matter.
> > ;-)
>
> And the fact that building *any* Windows native program without
commercial
> software is a PITA is the py-dev crew's fault, how?

I don't recall saying that it was their fault, but if I gave that
impression I apologize.  I'm mainly reacting to those individuals who
keep claiming that things couldn't be any simpler and that there is no
problem.  Based on the quality of the rest of your reply, you clearly
on not one of those individuals.  In fact, you have given some great
information here.  So thank you.  It is greatly appreciated.

> The python.org releases provide pre-built binaries for Windows,
support for
> compiling Windows extensions with various compilers (including
MinGW), and
> autoconf/automake support for POSIX-ish platforms (including Cygwin).

True, and I've always been glad that Tim Peters went through all the
trouble of creating and supporting the Windows binaries because I was
on the Windows platform when I first got introduced to Python.  Thank
you, Tim!

> For native Windows compilation of the interpreter, they support MSVC6
and MSVC7.1.
>
> If you're a serious commercial Windows shop, you will have one of the
Microsoft
> compiler suites installed *somewhere*. At that point, building your
own version
> of Python is trivial.

True, but see my reply to your subsequent points.

> Which leaves the hobbyists, and those companies which, for whatever
reason,
> choose not to use Visual Studio to build C/C++ code on Windows.

Exactly.  And how big is that group, really?  It might be quite large.

> If it meets your needs, the easiest solution is to build a non-native
version
> using Cygwin (./configure, make, make altinstall). That's what I
currently do,
> as the easiest free way to hack Python on a Windows box.

Yeah, but Cygwin is a bit scary for Windows folks who aren't familiar
with Linux or Unix.

> Which means our target group is now only those who want to build a
Windows
> Python binary, and don't want to use Visual Studio, and don't want to
use Cygwin
> (hmm, the group under discussion must be getting rather small by
now).

Actually, I think this group is potentially huge in comparison to the
current users of Python.  It's just that they aren't currently
represented in the Python community.  Look at the PythonCard project.
I was involved in the early stages of its formation (that was when I
wrote PyCrust, which was incorporated into PythonCard).  A great deal
of the interest in PythonCard was from hobbyists, VBers, old HyperCard
developers, etc.  These folks were not your typical Python programmers.
 They just wanted a simple tool that they could use to create simple
applications.

Now what if PythonCard started using some C source code as part of
their project?  They would either have to provide binaries, or they
would have to make it easy for their developer community, many of whom
are on Windows, to be able to compile C extensions for Python.  If they
couldn't make it easy, they would risk alienating many of their
supporters.

So my only point is that by making it easier to use C extensions, we
have an opportunity to make Python more attractive to a broader
audience that includes hobbyists and folks that do not want to pay for
commercial C compilers.  And I think there may very well be more C code
in typical projects with all the cool tools getting used, like Pyrex
and such.

[snip]

The rest of your message provided great information.  Thank you very
much.

--
Patrick K. O'Brien
Orbtechhttp://www.orbtech.com
Schevo http://www.schevo.org
Pypersyst  http://www.pypersyst.org

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


help wanted: poser to ogre 3d python script

2005-02-20 Thread verizon account


a community of online 3d developers is 
looking for a python script writer to write a script to export from poser to 
ogre3d .mesh/.skeleton formats, using the poser python script interpretor. 
please reply to [EMAIL PROTECTED]thanks!! 
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Grant Edwards
On 2005-02-20, Ilias Lazaridis <[EMAIL PROTECTED]> wrote:

>> If you would have written:
>> 
>> """
>> Should I take answers serious? Answer from people which do not respect 
>> coherence of writings?
>> """
>> 
>> it would have been much more coherent.
>
> I understand.

I doubt it.

> I still detect the coherence.
>
> As most people in this group will detect the coherence.

You, sir, are a loon.

I've detected little coherence in _any_ of your postings.

-- 
Grant Edwards   grante Yow!  I want to TAKE IT
  at   HOME and DRESS IT UP in
   visi.comHOT PANTS!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: introspection inquiry

2005-02-20 Thread Robin Becker
Michael Hoffman wrote:
Robin Becker wrote:
self.__class__.__name__

Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.
Here's a way to do that using metaclasses and Python's magic
double-underscore attribute-mangling feature:
"""
class SelfKnowledge(type):
def __init__(cls, name, bases, dict):
setattr(cls, "_%s__%s" % (name, "class_name"), name)
type.__init__(cls, name, bases, dict)
class Nietzsche(object):
__metaclass__ = SelfKnowledge
def __init__(self, text):
self.spam = text
print "In the constructor of the %s class" % self.__class_name
class Kierkegaard(Nietzsche):
def __init__(self, text):
print "Now in the constructor of %s" % self.__class_name
Nietzsche.__init__(self, text)
Nietzsche("Thus Spake Zarathustra")
print
Kierkegaard("Fear and Trembling")
"""
$ python test1.py
In the constructor of the Nietzsche class
Now in the constructor of Kierkegaard
In the constructor of the Nietzsche class
I guess if you're right something along the lines of
import inspect
class A:
  _class_name=inspect.currentframe().f_code.co_name
  def __init__(self,text,_defining_class_name=_class_name):
print 'text=',text,'_defining_class_name=',_defining_class_name
class B(A):
  pass
b=B('aaa')
==>text= aaa _defining_class_name= A
could work as well, but if we only need the local name why not just 
insert directly.
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-20 Thread jfj
Carl Banks wrote:
Say you want to calculate a list of points of an iterated fractal.
Here's the idea: you have a set of linear transformations.  You take
the origin (0,0) as the first point, and then apply each transformation
in turn to get a new point.  You recursively apply each transformation
at each additional point, up to a certain depth.
I like these kind of things. Ahhh, the best use out of one's computer.
What's the best way to write such a function?  Using a nested function,
it's easy as pie.  (Details may be a little wrong)
. def ifs(transformations, maxdepth):
. def add_point(x,y,angle,depth):
. ifspoints.append((x,y,angle))
. if depth < maxdepth:
. for t in transformations:
. nx = x + t.x*cos(angle) - t.y*sin(angle)
. ny = y + t.x*sin(angle) * t.y*cos(angle)
. nangle = angle + t.angle
. add_point(nx,ny,nangle,depth+1)
. ifspoints = []
. add_point(0.0, 0.0, 0.0, 0)
. return ifspoints
If you didn't have the nested function, you'd have to pass not only
depth, but also maxdepth, transformations, and ifspoints around.
I see. Some people complained that you have to use "self." all the
time in methods:)  If that was lifted the above would be done with
a class then?
The costly extra feature is this:
###
 def foo():
def f():
   print x
x=1
f()
x=2
f()
return f
foo()()
#
which prints '1 2 2'
The fractal code runs a little _slower_ because of this ability.
Although the specific program does not take advantage of it!
If you had something a little more complex than this, with more than
one nested function and more complex pieces of data you'd need to pass
around, the savings you get from not having to pass a data structure
around and referncing all that data though the structure can be quite a
lot.
Generally, I believe OOP is a superset of nested functions (as a
feature).  Nested functions make sense to me as primary python
def statements which ``create new code objects with arbitary constants''
When I see :
###
def foo(x):
 def bar():
 print x
 return bar
###
and the call:
 xx = foo(1)
I imagine that python runs:
 def bar():
print 1
 xx=bar
But alas, it doesn't:(
No. It carries around a silly cell object for the
rest of its lifetime.  see xx.func_closure.
At least, I think this is what happens...
jfj
--
http://mail.python.org/mailman/listinfo/python-list


Re: intersection of 2 list of pairs

2005-02-20 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> I have 2 lists of tuples that look like:
> E1=[('a','g'),('r','s')] and
> E2=[('g','a'),('r','q'),('f','h')].
> In this tuple, the ordering does not
> matter, i.e. (u,v) is the same as (v,u).
> 
> What I want to do is the following:
> given 2 list of tuples, E1 and E2, I want to create another list with
> tuples that are common to both. So in the above example I would like
> to return ('a','g') as being common.
> 

How about

>>> e1 = [('a', 'g'), ('r', 's')]
>>> e2 = [('g', 'a'), ('r', 'q'), ('f', 'h')]
>>> s2 = set(e2)
>>> s2.update((b, a) for (a, b) in e2)
>>> list(set(e1) & s2)
[('a', 'g')]

If you are on 2.3, continue to use Set instead of set and modify the update
line to use a list comprehension:

s2.update([(b, a) for (a, b) in e2])

Peter

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


Re: help please

2005-02-20 Thread gargonx
I think there's a problem with the code:

 py> decode_replacements.update([(std[key], key) for key in std])
 py> decode_replacements.update([(ext[key], key) for key in ext])

when i run this i get an error:
 AttributeError: keys

I can't get that figured out

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread "Martin v. Löwis"
Ilias Lazaridis wrote:
Should I take answers serious?
.
.
.
.
Answer from people which do not respect coherence of writings?
-
-
-
I still detect the coherence.
As most people in this group will detect the coherence.
I don't. The second fragment is not even correct English
(it does not have a verb in the main phrase, and Answer
is lacking an article).
So I have to guess what you could have meant. If you want
to be understood, you might have phrased the question like
this:
"Should I take answers from people which do not respect coherence
of writings serious?"
Or, if this splits the adjective too much from the verb, you
could also write
"Should I take answers serious if they come from people which
do not respect coherence of writings?"
This *still* would not have meant that I had understood the
question, since I still don't know what coherence of
writings is (as you failed to give a definition when I
last asked), but atleast I would have realized that I
don't understand the question, and refrained from answering
it. Perhaps the question was meant rhetoric.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Fredrik Lundh
Ilias Lazaridis wrote:

> I understand.

no.

 



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


intersection of 2 list of pairs

2005-02-20 Thread les_ander
Hi,
I have 2 lists of tuples that look like:
E1=[('a','g'),('r','s')] and
E2=[('g','a'),('r','q'),('f','h')].
In this tuple, the ordering does not
matter, i.e. (u,v) is the same as (v,u).

What I want to do is the following:
given 2 list of tuples, E1 and E2, I want to create another list with
tuples that are common to both. So in the above example I would like
to return ('a','g') as being common.
So far I have the code below but it does not work out properly, I would
be grateful if someone can help me out .
thanks

def list_of_tuples_intersect(E1,E2):

S1=Set()
S2=Set()
for e in E1:
S1.add((e[0],e[1]))
S1.add((e[1],e[0]))
for e in E2:
S2.add((e[0],e[1]))
S2.add((e[1],e[0]))
S= S1 & S2
SS=Set()
done=Set()

for e in S:
if ((e[0],e[1])  in done) or ((e[1],e[0])  in done):
continue
else:
SS.add((e[0],e[1]))
done.add((e[0],e[1]))
done.add((e[1],e[0]))
return SS

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


Re: questions concerning cgi.FieldStorage(keep_blank_values=1)

2005-02-20 Thread Jonas Meurer
On 20/02/2005 Daniel Lichtenberger wrote:
> > any suggestions about how to make form.keys() contain the blank keys
> > as well?
> 
> "key1" isn't a valid parameter, to supply an empty key you would write
> script.py?key1=&key2=foo
> 
> Then cgi.FieldStorage also includes key1.

great, it works. but is there no way to use single keywords as GET
argument?

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Ilias Lazaridis
Jan Dries wrote:
Ilias Lazaridis wrote:
[...] - (things which justify inability of coherence-detection)
If you would have written:
"""
Should I take answers serious? Answer from people which do not respect 
coherence of writings?
"""

it would have been much more coherent.
I understand.
Let's see:
-
Should I take answers serious?
.
.
.
.
Answer from people which do not respect coherence of writings?
-
-
-
I still detect the coherence.
As most people in this group will detect the coherence.
[Except if you want to ignore it, thus you can get at least _one_ 
'points' ins this discussion]

Regards,
Jan
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: questions concerning cgi.FieldStorage(keep_blank_values=1)

2005-02-20 Thread Daniel Lichtenberger
Hi,

Jonas Meurer wrote:

> if i request the script with script.py?key1&key2=foo, it will output:
> list keys with form.keys():
> key2
> 
> any suggestions about how to make form.keys() contain the blank keys
> as well?

"key1" isn't a valid parameter, to supply an empty key you would write
script.py?key1=&key2=foo

Then cgi.FieldStorage also includes key1.

bye,
Daniel

-- 
For mail replies please use my address from 
http://perplex.schmumpf.de/
http://www.gametective.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Jan Dries
Ilias Lazaridis wrote:
they above 2 questions are coherent, thus answering isolated [as you've 
done] makes not much sense.

"
 >> Should I take answers serious?
 >> Answer from people which do not respect coherence of writings?
"
Except that the quote here above is NOT what was in your original 
posting. Here is the *real* quote (also note that Python uses """ 
instead of " for delimiting a multi-line string:

"""
Should I take answers serious?
Answer from people which do not respect coherence of writings?
"""
If you insert a blank line between two sentences most people in this 
newsgroup (and in the western world in general) will interprete that as 
the start of a new paragraph, as an indication that what follows is 
something different than what precedes the blank line.
If you want to obtain "coherence of writing" between two sentences, then 
maybe you shouldn't type them as different paragraphs.

If you would have written:
"""
Should I take answers serious? Answer from people which do not respect 
coherence of writings?
"""

it would have been much more coherent.
Regards,
Jan
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Fwd: Re: [Uuu-devel] languages] <-- Why Python

2005-02-20 Thread Ville Vainio
> "Donn" == Donn Cave <[EMAIL PROTECTED]> writes:

Donn> I don't know what the Windows version is like, but for all
Donn> the UNIX shell's weaknesses, it's very well suited to its
Donn> role.  The Plan 9

I don't know about that - I don't see anything in shell that couldn't
be done better in Python (well, launching subshells perhaps, and the
smaller size == faster launch). The Windows incarnation is obviously
so horrible that it hardly deserves mention, but the scripts done with
unix shell also always have this "hackish" flavour.

(I'm aware that this is an unpopular opinion that is likely to collect
some flames, but some people never learn ;-).


Donn> shell (rc) is similar with much improved syntax, and has a
Donn> distant relative "es" that I think is the closest thing I've
Donn> ever seen to a 1st class language that works as a shell

I assume you've tried IPython ('ipython -p pysh')? I just apt-getted
es and it seems to be like ipython, only for scheme.

Donn> Well, honestly I think that's stretching it.  Your order
Donn> issue here seems to apply only to operators, and they don't
Donn> really figure that heavily in the kinds of things we
Donn> normally do with the OS.  The only

I think they do - summing sets of files, adding extensions to
filenames, etc. 

Donn> Now, we Python users know very well that's not true, Python's as clear
Donn> as could be.  But theoretically, if you wanted to talk about order
Donn> issues, for example ... is it really easier to understand when a 
language
Donn> sometimes expresses a function f over x and y this way
Donn> f(x, y)
Donn> sometimes this way (+ is a function, really)
Donn> x f y
Donn> and sometimes this way
Donn> x.f(y)
Donn> ?

Yes - operators like + and - are very intuitive to everybody. Having
only one way to call functions is more orthogonal and "cleaner" in a
theoretical sense, but noi in practical sense.

Donn> I don't know, I'm just thinking that while Python's notation
Donn> might be just fine for people who've gotten here the way
Donn> most of us have, it's not obvious from this that it's just
Donn> fine 4 everyone.

Perhaps not for everyone but for the majority I guess the python
notation would be more suitable.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


questions concerning cgi.FieldStorage(keep_blank_values=1)

2005-02-20 Thread Jonas Meurer
hello,

i'm quite new to python. currently i try to write a web application with
python cgi scripts.

in this application, i need keys to be delivered with the url, some with
and some without value (for example 'script.py?key1&key2=foo'.

i've searched the internet, and already figured out that i need to give
non-empty keep_blank_values as argument to cgi.FieldStorage, to make it
not cut all the empty keywords.

anyway, this still doesn't work really good:

---snip---
form = cgi.FieldStorage(keep_blank_values=1)

print 'list keys with form.keys():'
keys = form.keys()
keys.sort()
for key in keys:
print key
---snip---

if i request the script with script.py?key1&key2=foo, it will output:
list keys with form.keys():
key2

any suggestions about how to make form.keys() contain the blank keys as
well?

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


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread BrainDead
[snip, Ilias would not understand it]

> P.S. if Ilias volunteers, or offers to pay someone to do this,
instead of just
> complaining, will hell freeze over?)

Nick,

There is about as much chance of hell freezing over as there is of
England beating Australia in the cricket this summer. [I'am a
half-caste, English father, Welsh mother.  Makes it worse when you are
watching rugby :)]

To get back to Ilias, people on c.l.py have already pointed out that he
has been banned from other mailing lists, responds to 99% of assistance
with "not relevant", "off topic", or some similar garbage, and
obviously has no intention of actually delivering anything to anybody.
See c.l.clipper.visual-objects amognst other ngs for their opinion on
this megastar.

Me, I use Python to write simple programs to suit my own needs.  I have
never in the last three/four years needed to ask a question because the
documentation provided is perfectly adequate for me, failing which
Google this ng for an answer.

Ilias,

If you can't stand the heat, get out of the server room.

Kindest regards.

Mark Lawrence.

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-20 Thread Ilias Lazaridis
Martin v. Löwis wrote:
Ilias Lazaridis wrote:
Should I take answers serious?
If not, why are you asking questions in the first place?
simply read the next question, which limits the scope of the first one.
Answer from people which do not respect coherence of writings?
Coherence of writings?
An example:
they above 2 questions are coherent, thus answering isolated [as you've 
done] makes not much sense.

"
>> Should I take answers serious?
>> Answer from people which do not respect coherence of writings?
"
[answering here makes sense]
Should a professional developer take python serious?
Yes.
I mean, if the team does not manage at least the foundation of a 
multi-target automated-build-process?
If the team *would* not manage at least the foundation of a
multi-target automated-build-process, a professional developer
*should* not take python serious.
Very nice.
At this point, we agree very much.
However, since the team *does* manage at least the foundation of
a multi-target automated-build-process, a professional developer
*might* take python serious.
here our disagreement:
=> {"managing the foundation of a multi-target automated-build-process"}
What are the requirements for fulfilling this?
[a false premise can imply anything]
again you ignore coherent writings.
-
You have omitted the following part of my writings:
"[targets need not to be supported directly by the python team. They 
could be added/managed/maintained by community members]"

in which I essentially define a few requirements for "managing the 
foundation of a multi-target automated-build-process".

-
The python team should provide the fundamental infrastructure for the 
community, thus it can add/manage/maintain build targets.

Additionally:
  * The python-team should detect any efforts made for different 
build-targets
  * The python-team should attract/engourage the authors to include 
them in the main build-system [incubation section].

The python-community and the PSF supports the python-team to take the 
above actions.

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


Re: Real-Time Fluid Dynamics for Games...

2005-02-20 Thread bearophileHUGS
Your two email addresses bouce emails back, so I post a shortened
version of my comment here.
I haven't installed:
PyOpenGL-2.0.2.01.py2.4-numpy23
glut-3.7.6
Therefore at the moment I cannot try your interesting code.
What's the speed of this Python code on your computer?
I'd like to see a screenshoot of the running Python Program...

Some people are doing in Python some things that require lots of
computations, like:
http://www.joachim-bauch.de/projects/python/pytrace

Bye,
Bearophile

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


Re: introspection inquiry

2005-02-20 Thread Michael Hoffman
John Roth wrote:
If that's the case, then the inspect module should give
the tools to do it without a great deal of angst. Unfortunately,
it doesn't give you the class that defined the method, just
the class that invoked it.
Are you saying that the inspect module *should* give you the
tools to do it but does not?
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: introspection inquiry

2005-02-20 Thread Michael Hoffman
Diez B. Roggisch wrote:
>[Michael Hoffman]:
Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.
Where is the difference? The method is defined in a class - and an instance
is created from that class.
This works as expected:
class ExistentialCrisis:
def __init__(self, text):
self.spam = text
print 'In the constructor of the %s class' % self.__class__.__name__
ExistentialCrisis("egal")
Yes, but this doesn't work if you have a subclass:
"""
class ExistentialCrisisSubclass(ExistentialCrisis):
def __init__(self, text):
print "New constructor"
ExistentialCrisis.__init__(self, text)
ExistentialCrisisSubclass("whoa")
"""
gives you:
New constructor
In the constructor of the ExistentialCrisisSubclass class
But the second line is *not* in the constructor of
ExistentialCrisisSubclass, it is in the constructor of ExistentialCrisis.
while I read the original post as saying that he wanted
"ExistentialCrisis" there instead. Indeed this example
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: introspection inquiry

2005-02-20 Thread John Roth
"Michael Hoffman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Robin Becker wrote:
self.__class__.__name__
Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.
If that's the case, then the inspect module should give
the tools to do it without a great deal of angst. Unfortunately,
it doesn't give you the class that defined the method, just
the class that invoked it.
John Roth
--
http://mail.python.org/mailman/listinfo/python-list


Re: introspection inquiry

2005-02-20 Thread Diez B. Roggisch
> Unless I misunderstood the question, that won't work. That will
> give you the name of the class the object is an instance is of.
> I think he wants the name of the class the method was defined in.

Where is the difference? The method is defined in a class - and an instance
is created from that class.

This works as expected:

class ExistentialCrisis:
def __init__(self, text):
self.spam = text
print 'In the constructor of the %s class' % self.__class__.__name__


ExistentialCrisis("egal")


-- 
Regards,

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


Re: introspection inquiry

2005-02-20 Thread Michael Hoffman
Robin Becker wrote:
self.__class__.__name__
Unless I misunderstood the question, that won't work. That will
give you the name of the class the object is an instance is of.
I think he wants the name of the class the method was defined in.
Here's a way to do that using metaclasses and Python's magic
double-underscore attribute-mangling feature:
"""
class SelfKnowledge(type):
def __init__(cls, name, bases, dict):
setattr(cls, "_%s__%s" % (name, "class_name"), name)
type.__init__(cls, name, bases, dict)
class Nietzsche(object):
__metaclass__ = SelfKnowledge
def __init__(self, text):
self.spam = text
print "In the constructor of the %s class" % self.__class_name
class Kierkegaard(Nietzsche):
def __init__(self, text):
print "Now in the constructor of %s" % self.__class_name
Nietzsche.__init__(self, text)
Nietzsche("Thus Spake Zarathustra")
print
Kierkegaard("Fear and Trembling")
"""
$ python test1.py
In the constructor of the Nietzsche class
Now in the constructor of Kierkegaard
In the constructor of the Nietzsche class
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: segfault when calling Python from C thread

2005-02-20 Thread Fredrik Lundh
Greg Chapman wrote:

> Your callback function needs to hold the Python GIL (and have a vaild
> threadstate) before it calls any Python C-API functions.  Change the
> last part of it to:
>
>PyGILState_STATE state;
>
>/* ... */
>
>/* Time to call the callback */
>
>state = PyGILState_Ensure();
>
>arglist = Py_BuildValue("(s)", str);
>result = PyEval_CallObject(my_callback, arglist);
>Py_DECREF(arglist);
>if(result == NULL)
>return;
>Py_DECREF(result);
>
>PyGILState_Release(state);
> }

you might wish to make sure you release the GIL even if the callback
raises an exception...

 



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


Re: BaseHTTPServer threading using SocketServer.ThreadingMixIn

2005-02-20 Thread Paul Rubin
"Tortelini" <[EMAIL PROTECTED]> writes:
> I am making custom web server using HTTPServer and want to be able to
> access it simultaneously from different computers. To achieve
> multithreading, I have been experimenting with ThreadingMixIn from
> SocketServer, but it doesn't seem to work, 

One common error is to define your class as something like:

  class myServer(HTTPServer, ThreadingMixin): ...

You have to put ThreadingMixin first, since it overrides methods of
TCPServer:

  class myServer(ThreadingMixin, HTTPServer): ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: segfault when calling Python from C thread

2005-02-20 Thread Greg Chapman
Travis Berg wrote:

> 
> I'm running into a problem when trying to perform a callback to a
> Python function from a C extension.  Specifically, the callback is
> being made by a pthread that seems to cause the problem.  If I call
> the callback from the parent process, it works fine.  The PyObject is
> static, and holds the same value in both Parent and thread, so I'm at
> a loss as to what would be different in the pthread from the parent
> that would cause a segfault on the callback.  The machine specifics
> are an x86 intel processor with RedHat linux.
> 
> 
> /* calling callback */
> void callback(char * str) {
> PyObject *arglist;
> PyObject *result;
> if(str == NULL)
> return;
> 
> if(my_callback == NULL) {
> printf("no callback function provided, returning...\n");
> return;
> }
> 
> /* Time to call the callback */
> arglist = Py_BuildValue("(s)", str);
> result = PyEval_CallObject(my_callback, arglist);
> Py_DECREF(arglist);
> if(result == NULL)
> return;
> Py_DECREF(result);
> }

Your callback function needs to hold the Python GIL (and have a vaild
threadstate) before it calls any Python C-API functions.  Change the
last part of it to:

PyGILState_STATE state;

/* ... */

/* Time to call the callback */

state = PyGILState_Ensure();

arglist = Py_BuildValue("(s)", str);
result = PyEval_CallObject(my_callback, arglist);
Py_DECREF(arglist);
if(result == NULL)
return;
Py_DECREF(result);

PyGILState_Release(state);
}

Also, somewhere in your main thread you should call PyEval_InitThreads
before any of the callback threads execute.  (This call is made
automatically if you are creating new threads using Python's thread
module, but if the new threads are created by some C code, you need to
call it yourself.)

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


Re: [ANN] Python 2.4 Quick Reference available

2005-02-20 Thread Michael Hoffman
François Pinard wrote:
[Nick Coghlan]

George Sakkis wrote:

Still the word "open" sounds too general if the meaning is "open
a file-like object"; OTOH this could be a good thing if in some
future version "open('http://www.python.org')" was e.g. an alias to
urllib2.urlopen.

Exactly the reason the BDFL gave for preferring 'open' - it may be extended 
to opening other types of objects than files.

So, when we *know* we are opening a file, `file' cannot be a bad choice! :-)
Moreover, practically, most of the times, we know we are opening a file.
`open' is opened (sic!) for some future magic.  I prefer to protect my
programs against future magic, until this magic is precisely specified.
I agree. I don't want users to be able to specify URLs instead of
filenames unless I explicitly allow it.
To be honest I doubt open will be extended in this manner. I can see
the Pythoneers adding, say, a keyword argument to open to allow a URL
instead, but just changing the current behavior would be too risky. Plus,
what happens if I have a file named "http://www.python.org/";?
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: introspection inquiry

2005-02-20 Thread Robin Becker
[EMAIL PROTECTED] wrote:
...
My question is this: what can be substituted for  that will
make the example above work?
self.__class__.__name__
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >