Re: regex question

2007-01-08 Thread proctor

Paul McGuire wrote:
> "proctor" <[EMAIL PROTECTED]> wrote in message
> news:<[EMAIL PROTECTED]>...
> > hello,
> >
> > i hope this is the correct place...
> >
> > i have an issue with some regex code i wonder if you have any insight:
> >
> > 
>
> There's nothing actually *wrong* wth your regex.  The problem is your
> misunderstanding of raw string notation.  In building up your regex, do not
> start the string with "r'" and end it with a "'".
>
> def makeRE(w):
> print w + " length = " + str(len(w))
> # reString = "r'" + w[:1]
> reString = w[:1]
> w = w[1:]
> if len(w) > 0:
> for c in (w):
> reString += "|" + c
> # reString += "'"
> print "reString = " + reString
> return reString
>
> Or even better:
>
> def makeRE(w):
> print w + " length = " + str(len(w))
> reString = "|".join(list(w))
> return reString
>
> Raw string notation is intended to be used when the string literal is in
> your Python code itself, for example, this is a typical use for raw strings:
>
> ipAddrRe = r'\d{1,3}(\.\d{1,3}){3}'
>
> If I didn't have raw string notation to use, I'd have to double up all the
> backslashes, as:
>
> ipAddrRe = '\\d{1,3}(\\.\\d{1,3}){3}'
>
> But no matter which way I create the string, it does not actually start with
> "r'" and end with "'", those are just notations for literals that are part
> of your Python source.
>
> Does this give you a better idea of what is happening?
>
> -- Paul

yes!  thanks so much.

it does work now...however, one more question:  when i type:

rx_a = re.compile(r'a|b|c')
it works correctly!

shouldn't:
rx_a = re.compile(makeRE(test))
give the same result since makeRE(test)) returns the string "r'a|b|c'"

are you saying that the "r'" and "'" are being interpreted differently
in the second case than in the first?  if so, how would i go about
using raw string notation in such a circumstance (perhaps if i need to
escape "\b" or the like)?  do i have to double up in this case?

proctor.

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


another SQL implement

2007-01-08 Thread Thinker
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

hello,

I have implement a SQL command generator for Python. It uses features
and syntax of Python to describe SQL schema & query. Following is a
example:

from pysqlite2 import dbapi2 as sqlite
from pysql import *

#
# define data source
# comprises tables and queries
#
class my_data_src(data_src):
def ds_definition():
class t1(pysql.table):
#
# define table 't1'
#
item = pysql.str_f()
count = pysql.int_f()
pass

class t2(pysql.table):
#
# define table 't2'
#
item = pysql.str_f()
money = pysql.float_f()
pass

#
# define a query 'get_count_and_money_of_item'
#
get_count_and_money_of_item = \
lambda: (t1 * t2) \
.fields(t1.item, t1.count * t2.money - 30) \
.where((t1.item == t2.item) & (t1.item != pysql._q))

return ds_define()
pass

cx = sqlite.connect('test
<http://heaven.branda.to/%7Ethinker/GinGin_CGI.py/show_kw_docs/test>.db')

db = my_data_src(cx) # create a instance of data source

db.init_db() # create tables

db.insert(db.t1, item='foo', count=100)
db.insert(db.t2, item='foo', money=3.2)
db.insert(db.t1, item='boo', count=50)
db.insert(db.t2, item='boo', money=3.0)

db.update(db.t1, count=140, where=~(db.t1.item == 'foo'))

cu = db.get_count_and_money_of_item('foo')
rows = cu.fetchall()
print rows

cu = db.get_count_and_money_of_item('cool')
rows = cu.fetchall()
print rows

db.commit()

pass

This is example code to define database schema and query.
get_count_and_money_of_item is initialized by a lambda expression. It
can also be a function. By inherit class data_src and defining method
ds_definition, my_data_src is acting as a wrapper of a database. It
includes two tables, t1 & t2, and a query,
get_count_and_money_of_item. Instantiate a instance of my_data_src
with a DB connection, you can create tables (init_db), insert records,
update records, and perform queries.

get_count_and_money_of_item = \
lambda: (t1 * t2) \
.fields(t1.item, t1.count * t2.money - 30) \
.where((t1.item == t2.item) & (t1.item != pysql._q))

(t1 * t2) means join tables t1 & t2, you can specify fields to be
return by query with *.fields(...). *.where() is just like WHERE
expression in SQL. get_count_and_money_of_item comprises a
free-variable; pysql._q stands as a free-variable waiting for caller
specified as parameter when calling get_count_and_money_of_item.

cu = db.get_count_and_money_of_item('foo')
rows = cu.fetchall()

It calls get_count_and_money_of_item() with 'foo' for free-variable.
A query returns a cursor defined in DBAPI.

Why another SQL ? Why not SQLObject?
RDBMS provides powerful query language, it provides performance by
reducing traffic between database & application and reducing memory
copy. A OR-mapping made RDBMS weak. DBMS is reduced as a indexed
storage. Relational algebra is so powerful & effective. Why don't
integrate it into Python language?

Downloads:
The implementation depend on pythk, so you need two modules, pysql & pythk
http://master.branda.to/downloads/pysql/pysql-20070108.tar.gz
http://master.branda.to/downloads/pythk/pythk-20070108.tar.gz


- --
Thinker Li - [EMAIL PROTECTED] [EMAIL PROTECTED]
http://heaven.branda.to/~thinker/GinGin_CGI.py
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (FreeBSD)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFFoflZ1LDUVnWfY8gRAqw9AJ9UQ5OAOIEWo+ovELQvcKohAkWJtwCfcloq
ecOxlrstOZ77Mr9qPxlkBj0=
=U12Y
-END PGP SIGNATURE-

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

Re: Recommendations (or best practices) to define functions (or methods)

2007-01-08 Thread Frank Millman

Martin v. Löwis wrote:
> vizcayno schrieb:
> > Need your help in the "correct" definition of the next function. If
> > necessary, I would like to know about a web site or documentation that
> > tells me about best practices in defining functions, especially for
> > those that consider the error exceptions management.
>
> I agree with George Sakkis' remarks. The best way to define this function is
>
> def ExecuteSQL(cmdSQL, cursor):
>   return cursor.execute(cmdSQL)
>
> If this raises an exception, it likely means there is something
> wrong with the SQL statement. The program should abort, and the
> developer should correct it.
>
> Regards,
> Martin

With respect, I can offer a counter-argument.

I have a multi-user server program, with a connection to a database,
servicing multiple requests from connected clients.

The clients are 'thin' - the business logic resides on the server - so
when a client selects an option, the server imports the appropriate
module and executes it. If that includes a SQL command, the server
connects to the database, executes the command, and returns the result
to the client.

If there is something wrong with the SQL statement, I do not want to
crash the server, I want to notify the client that there was something
wrong, so that the offending module can be corrected and reloaded.

Frank Millman

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

Re: regex question

2007-01-08 Thread Steven D'Aprano
On Sun, 07 Jan 2007 23:57:00 -0800, proctor wrote:

> it does work now...however, one more question:  when i type:
> 
> rx_a = re.compile(r'a|b|c')
> it works correctly!
> 
> shouldn't:
> rx_a = re.compile(makeRE(test))
> give the same result since makeRE(test)) returns the string "r'a|b|c'"

Those two strings are NOT the same.

>>> s1 = r'a|b|c'
>>> s2 = "r'a|b|c'"
>>> print s1, len(s1)
a|b|c 5
>>> print s2, len(s2)
r'a|b|c' 8

A string with a leading r *outside* the quotation marks is a raw-string.
The r is not part of the string, but part of the delimiter.

A string with a leading r *inside* the quotation marks is just a string
with a leading r. It has no special meaning.



-- 
Steven D'Aprano 

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


Re: regex question

2007-01-08 Thread proctor

Steven D'Aprano wrote:
> On Sun, 07 Jan 2007 23:57:00 -0800, proctor wrote:
>
> > it does work now...however, one more question:  when i type:
> >
> > rx_a = re.compile(r'a|b|c')
> > it works correctly!
> >
> > shouldn't:
> > rx_a = re.compile(makeRE(test))
> > give the same result since makeRE(test)) returns the string "r'a|b|c'"
>
> Those two strings are NOT the same.
>
> >>> s1 = r'a|b|c'
> >>> s2 = "r'a|b|c'"
> >>> print s1, len(s1)
> a|b|c 5
> >>> print s2, len(s2)
> r'a|b|c' 8
>
> A string with a leading r *outside* the quotation marks is a raw-string.
> The r is not part of the string, but part of the delimiter.
>
> A string with a leading r *inside* the quotation marks is just a string
> with a leading r. It has no special meaning.
>
>
>
> --
> Steven D'Aprano

thanks steven,

is there any way i would be successful then, in using raw string inside
my makeRE() function?

proctor.

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


Re: Recommendations (or best practices) to define functions (or methods)

2007-01-08 Thread Martin v. Löwis
Frank Millman schrieb:
> If there is something wrong with the SQL statement, I do not want to
> crash the server, I want to notify the client that there was something
> wrong, so that the offending module can be corrected and reloaded.

Right. In a distributed system, you should propagate the error (in some
form) to the client.

Then the question is what the best form is: IMO, you should keep as
much information as possible. This means you either return the Python
exception to the client, to be re-raised on the client side, or you
log the exception on the server side, and just return to the client
the information that the full error message has been logged.

In any case: this should happen on the middleware layer, i.e. the place
that does the communication. Wrt. the OP's code, I still maintain that
all of his approaches to "silence" the exception are flawed. Exception
handling should either recover from the error (e.g. by adjusting the
environment, then retrying) or abort the execution. In a distributed
case, "abort the execution" may not mean "terminate the program", but
instead "immediately abort execution of the current request and return
an error to the client".

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


Re: regex question

2007-01-08 Thread Mark Peters
> is there any way i would be successful then, in using raw string inside
> my makeRE() function?

Why do you think you even need a raw string?

Just build and return the string 'a|b|c' (NOTE: DON'T add the quotes to
the string)

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


Re: how to find the longst element list of lists

2007-01-08 Thread Peter Otten
Scott David Daniels wrote:

> Dan Sommers wrote:
>> ...
>> longest_list, longest_length = list_of_lists[ 0 ], len( longest_list
>> ) for a_list in list_of_lists[ 1 : ]:
>> a_length = len( a_list )
>> if a_length > longest_length:
>> longest_list, longest_length = a_list, a_length
>> will run faster than sorting the list just to pick off one element (O(n)
>> vs. O(n log n) for all of you Big-Oh notation fans out there; you know
>> who you are!).
> 
> Or, more succinctly, after:
>  list_of_lists = [["q", "e", "d"],
>   ["a", "b"],
>   ["a", "b", "c", "d"]]
> You can find the longest with:
>  maxlength, maxlist = max((len(lst), lst) for lst in list_of_lists)
> or (for those pre-2.5 people):

pre-2.4 

>  maxlength, maxlist = max([(len(lst), lst) for lst in list_of_lists])

With the caveat that if there are lists of equal length their items will be
compared:

>>> max((len(lst), lst) for lst in [[1], [1j]])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: no ordering relation is defined for complex numbers

So if you want the first out of the lists with equal length on a python
where Steve's enhancement is not yet available (pre-2.5):

>>> max_len, dummy, max_list = max((len(lst), -i, lst) for i, lst in
enumerate([[1], [1j]]))
>>> max_len, max_list
(1, [1])

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


Re: regex question

2007-01-08 Thread Paul McGuire

"proctor" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
>
> it does work now...however, one more question:  when i type:
>
> rx_a = re.compile(r'a|b|c')
> it works correctly!
>

Do you see the difference between:

rx_a = re.compile(r'a|b|c')

and

rx_a = re.compile("r'a|b|c'")

There is no difference in the variable datatype between "string" and "raw 
string".  Raw strings are just a notational helper when creating string 
literals that have lots of backslashes in them (as happens a lot with 
regexps).

r'a|b|c'  is the same as 'a|b|c'
r'\d' is the same as '\\d'

There is no reason to "add raw strings" to your makeRE method, since you 
don't have a single backslash anywhere.  And even if there were a backslash 
in the 'w' argument, it is just a string - no need to treat it differently.

-- Paul 


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


Re: regex question

2007-01-08 Thread proctor

Mark Peters wrote:
> > is there any way i would be successful then, in using raw string inside
> > my makeRE() function?
>
> Why do you think you even need a raw string?
>
> Just build and return the string 'a|b|c' (NOTE: DON'T add the quotes to
> the string)

yes, i suppose you are right.  i can't think of a reason i would NEED a
raw string in this situation.

all very helpful!  thanks very much.

sincerely,
proctor.

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


Re: regex question

2007-01-08 Thread proctor

Paul McGuire wrote:
> "proctor" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> >
> >
> > it does work now...however, one more question:  when i type:
> >
> > rx_a = re.compile(r'a|b|c')
> > it works correctly!
> >
>
> Do you see the difference between:
>
> rx_a = re.compile(r'a|b|c')
>
> and
>
> rx_a = re.compile("r'a|b|c'")
>
> There is no difference in the variable datatype between "string" and "raw
> string".  Raw strings are just a notational helper when creating string
> literals that have lots of backslashes in them (as happens a lot with
> regexps).
>
> r'a|b|c'  is the same as 'a|b|c'
> r'\d' is the same as '\\d'
>
> There is no reason to "add raw strings" to your makeRE method, since you
> don't have a single backslash anywhere.  And even if there were a backslash
> in the 'w' argument, it is just a string - no need to treat it differently.
> 
> -- Paul

thanks paul.  this helps.

proctor.

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


Re: regex question

2007-01-08 Thread Mark Peters
> yes, i suppose you are right.  i can't think of a reason i would NEED a
> raw string in this situation.
It looks from your code that you are trying to remove all occurances of
one string from the other.  a simple regex way would be to use re.sub()

>>> import re
>>> a = "abc"
>>> b = "debcabbde"
>>> re.sub("[" + a + "]","",b)
'dede'

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


Re: Just Getting Started with Python on MS XP Pro

2007-01-08 Thread Jussi Salmela
W. Watson kirjoitti:
> Gabriel Genellina wrote:
>> On 7 ene, 16:20, "W. Watson" <[EMAIL PROTECTED]> wrote:
>>
>>> We seem to be looping. I have the Python interpreter. I would like the
>>> pythonwin editor. The download link doesn't work on SourceForge. 
>>> Where can I
>>> get it? If not there, where? If it can't be obtained, then I'll go to 
>>> the
>>> default editor built into python-2.5.msi.
>>
>> It *does* work for me. Try
>> https://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063
>>  
>>
>>
> I can easily see the page you refer to, but where's the pythonwin editor?
> 
> 
>  Wayne T. Watson (Watson Adventures, Prop., Nevada City, CA)
>  (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>   Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
> 
> A road sign along many highways reads, "$1000
> fine for littering" I have yet to find any
> $1000 bills. WTW

The editor is only a part of pywin32, which is a handy package to do all 
kinds of Windows only stuff with Python. So download and install pywin32 
to get the editor and all that other nice stuff.

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


Walking The Right Path

2007-01-08 Thread Tim Daneliuk
Ah yes, moral philosophy and python all come together... Er, that is to day:

Imagine you have this situation on a *nix filesystem:

Symlink A:  /foo -> /usr/home
Symlink B:  /bar -> /foo/username


If I do this:

   import os
   print os.path.realpath("/bar")

I get this (as one would expect):

   /usr/home/username

However, what if I want to get back the result in this form:

   /foo/username


IOW, is there a way to return a symlink-based path which contains
the symlink pointer as is was *defined* not as it expands?


TIA,

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why less emphasis on private data?

2007-01-08 Thread Paul Boddie
Paul Rubin wrote:
>
> Right, the problem is if those methods start changing the "private"
> variable.  I should have been more explicit about that.
>
> class A:
>def __init__(self):
>   self.__x = 3
>def foo(self):
>   return self.__x
>
> class B(A): pass
>
> class A(B):
>def bar(self):
>  self.__x = 5   # clobbers private variable of earlier class named A

Has this ever been reported as a bug in Python? I could imagine more
sophisticated "name mangling": something to do with the identity of the
class might be sufficient, although that would make the tolerated
"subversive" access to private attributes rather difficult.

Paul

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


Re: Parallel Python

2007-01-08 Thread Laszlo Nagy
[EMAIL PROTECTED] wrote:
> Has anybody tried to run parallel python applications?
> It appears that if your application is computation-bound using 'thread'
> or 'threading' modules will not get you any speedup. That is because
> python interpreter uses GIL(Global Interpreter Lock) for internal
> bookkeeping. The later allows only one python byte-code instruction to
> be executed at a time even if you have a multiprocessor computer.
> To overcome this limitation, I've created ppsmp module:
> http://www.parallelpython.com
> It provides an easy way to run parallel python applications on smp
> computers.
> I would appreciate any comments/suggestions regarding it.
>   
I always thought that if you use multiple processes (e.g. os.fork) then 
Python can take advantage of multiple processors. I think the GIL locks 
one processor only. The problem is that one interpreted can be run on 
one processor only. Am I not right? Is your ppm module runs the same 
interpreter on multiple processors? That would be very interesting, and 
something new.


Or does it start multiple interpreters? Another way to do this is to 
start multiple processes and let them communicate through IPC or a local 
network.


  Laszlo

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


Re: Why less emphasis on private data?

2007-01-08 Thread Paul Rubin
"Paul Boddie" <[EMAIL PROTECTED]> writes:
> Has this ever been reported as a bug in Python? I could imagine more
> sophisticated "name mangling": something to do with the identity of the
> class might be sufficient, although that would make the tolerated
> "subversive" access to private attributes rather difficult.

If you mean the object id, I don't think you can use it for name
mangling, since the mangled names have to survive code marshalling
and you may end up with different object id's.

I've just never encountered any legitimate use for the "subversive"
access and if it's really necessary, it's better to do it through some
kind of well-designed reflection interface in the class, rather than
with a crock like name mangling.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommendations (or best practices) to define functions (or methods)

2007-01-08 Thread Diez B. Roggisch
vizcayno schrieb:
> Hello:
> Need your help in the "correct" definition of the next function. If
> necessary, I would like to know about a web site or documentation that
> tells me about best practices in defining functions, especially for
> those that consider the error exceptions management.
> I have the next alternatives but I think there are better:



IMHO none of them is good. Python has exceptions. Use them. There is no 
need to awkwardly communicate error conditions using return-values. Use 
return values to return values. Use exceptions in case of errors.

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


Stackless Python 2.5 for Nintendo DS

2007-01-08 Thread Richard Tew
Hi,

I have updated NDS Python from Python 2.4.3 to Python 2.5 (or rather
the Stackless version of it).

You can read more about it here if it might interest you:
http://www.disinterest.org/NDS/Python25.html

Cheers,
Richard.

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


Re: How to get file name on a remote server with ftplib?

2007-01-08 Thread alex
Thanks guys for the help! I used nlst().
The ftputil seems to be very helpfull, but getting a new library in an
organization like the one I work at  is big issue. Thanks anyway :)



[EMAIL PROTECTED] wrote:
> alex wrote:
> > Hello,
> >
> > My script is trying to get a file from a remote server, every day it
> > ftps from a directory. My code works perfect if I know the name of the
> > file in the remote directory.
> >
> > ftp.retrbinary('RETR ' + filename, handleDownload)
> >
> > The problem is that in the future the name of the file is going to be
> > aleatory. How can I get the file's name (only one file is in that
> > directory) and store it in a variable before executing ftp.retrbinary?
> >
> > Thanks a lot for your help,
> >
> > Alex
>
> You can use the nlst(dirname) method to retrieve a directory listing on
> the remote server. If the remote server doesn't support NLST command
> rhen you could do ftp.retrlines('LIST')  and parse the results to get a
> directory listing.

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


Re: Walking The Right Path

2007-01-08 Thread Jakub Stolarski
Tim Daneliuk napisal(a):
> Ah yes, moral philosophy and python all come together... Er, that is to day:
>
> Imagine you have this situation on a *nix filesystem:
>
> Symlink A:  /foo -> /usr/home
> Symlink B:  /bar -> /foo/username
>
>
> If I do this:
>
>import os
>print os.path.realpath("/bar")
>
> I get this (as one would expect):
>
>/usr/home/username
>
> However, what if I want to get back the result in this form:
>
>/foo/username
>
>
> IOW, is there a way to return a symlink-based path which contains
> the symlink pointer as is was *defined* not as it expands?
> 

One way (but very ugly):
print os.path._resolve_link('/bar')

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


Re: how to find the longst element list of lists

2007-01-08 Thread Steven D'Aprano
On Sun, 07 Jan 2007 20:55:19 -0500, Dan Sommers wrote:

> On Sun, 07 Jan 2007 22:23:22 +0100,
> "Michael M." <[EMAIL PROTECTED]> wrote:
> 
>> How to find the longst element list of lists?
>> I think, there should be an easier way then this:
> 
>>   s1 = ["q", "e", "d"]
>>   s2 = ["a", "b"]
>>   s3 = ["a", "b", "c", "d"]
> 
> [ snip ]
> 
> One more thing to think about:  if your list of lists grows (i.e., if
> you end up with thousands of lists instead of just three), then sorting
> may not be the way to go.  Assuming that list_of_lists is your list of
> lists, then something like this:
> 
> longest_list, longest_length = list_of_lists[ 0 ], len( longest_list )
> for a_list in list_of_lists[ 1 : ]:
> a_length = len( a_list )
> if a_length > longest_length:
> longest_list, longest_length = a_list, a_length
> 
> will run faster than sorting the list just to pick off one element (O(n)
> vs. O(n log n) for all of you Big-Oh notation fans out there; you know
> who you are!).

But your O(n) code is running in relatively slow Python, while the sort
method, while O(n log n), is some of the fastest, most highly optimized C
code out there. Unless your list is truly gigantic, chances are the sort
version will win.

Here's my timing code:


import timeit

def getlongest1(list_of_lists):
longest_list = list_of_lists[ 0 ]
longest_length = len( longest_list )
for a_list in list_of_lists[ 1 : ]:
a_length = len( a_list )
if a_length > longest_length:
longest_list, longest_length = a_list, a_length
return longest_list

def getlongest2(list_of_lists):
list_of_lists.sort(key=len)
return list_of_lists[0]

def make_list_of_lists(length):
return [[None]*i for i in xrange(length)]

t1 = timeit.Timer("getlongest1(L)", "from __main__ import getlongest1, L")
t2 = timeit.Timer("getlongest2(L)", "from __main__ import getlongest2, L")



Note that my test list_of_lists grows very big quite fast, like O(n**2).
Assuming Python pointers are eight bytes, a mere length=1 will
require over 760MB just for the pointers. More realistic data may allow
more extensive testing.

And here are my timing results:

>>> L = make_list_of_lists(1)
>>> print t1.timeit(1000), t2.timeit(1000)
0.00209903717041 0.00367403030396

>>> L = make_list_of_lists(10)
>>> print t1.timeit(1000), t2.timeit(1000)
0.00871086120605 0.00775289535522

>>> L = make_list_of_lists(100)
>>> print t1.timeit(1000), t2.timeit(1000)
0.121382951736 0.0518100261688

>>> L = make_list_of_lists(1000)
>>> print t1.timeit(1000), t2.timeit(1000)
0.809508085251 0.508343935013

>>> L = make_list_of_lists(1)
>>> print t1.timeit(100), t2.timeit(100)
0.906499147415 0.732254981995

>>> L = make_list_of_lists(2)
>>> print t1.timeit(100), t2.timeit(100)
1.83560800552 1.58732700348

For a list of 1 item, sorting is 1.8 times SLOWER; 
For a list of 10 items, sorting is 1.1 times FASTER;
For 100 items, sorting is 2.3 times faster;
For 1000 items, sorting is 1.6 times faster;
For 10,000 items, sorting is 1.2 times faster;
For 20,000 items, sorting is 1.1 times faster.


The precise results depend on the version of Python you're running, the
amount of memory you have, other processes running, and the details of
what's in the list you are trying to sort. But as my test shows, sort has
some overhead that makes it a trivial amount slower for sufficiently small
lists, but for everything else you're highly unlikely to beat it. 



-- 
Steven.

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


Re: Parallel Python

2007-01-08 Thread Duncan Booth
Laszlo Nagy <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] wrote:
>> Has anybody tried to run parallel python applications?
>> It appears that if your application is computation-bound using 'thread'
>> or 'threading' modules will not get you any speedup. That is because
>> python interpreter uses GIL(Global Interpreter Lock) for internal
>> bookkeeping. The later allows only one python byte-code instruction to
>> be executed at a time even if you have a multiprocessor computer.
>> To overcome this limitation, I've created ppsmp module:
>> http://www.parallelpython.com
>> It provides an easy way to run parallel python applications on smp
>> computers.
>> I would appreciate any comments/suggestions regarding it.
>>   
> I always thought that if you use multiple processes (e.g. os.fork) then 
> Python can take advantage of multiple processors. I think the GIL locks 
> one processor only. The problem is that one interpreted can be run on 
> one processor only. Am I not right? Is your ppm module runs the same 
> interpreter on multiple processors? That would be very interesting, and 
> something new.
> 
The GIL locks all processors, but just for one process. So, yes, if you 
spawn off multiple processes then Python will take advantage of this. For 
example we run Zope on a couple of dual processor dual core systems, so we 
use squid and pound to ensure that the requests are spread across 4 
instances of Zope on each machine. That way we do get a fairly even cpu 
usage.

For some applications it is much harder to split the tasks across separate 
processes rather than just separate threads, but there is a benefit once 
you've done it since you can then distribute the processing across cpus on 
separate machines.

The 'parallel python' site seems very sparse on the details of how it is 
implemented but it looks like all it is doing is spawning some subprocesses 
and using some simple ipc to pass details of the calls and results. I can't 
tell from reading it what it is supposed to add over any of the other 
systems which do the same.

Combined with the closed source 'no redistribution' license I can't really 
see anyone using it.
-- 
http://mail.python.org/mailman/listinfo/python-list


the free b2b website guide

2007-01-08 Thread haisge
the free b2b website guide

http://www.b2bbyte.com

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

Re: Why less emphasis on private data?

2007-01-08 Thread Duncan Booth
"Paul Boddie" <[EMAIL PROTECTED]> wrote:

> Paul Rubin wrote:
>>
>> Right, the problem is if those methods start changing the "private"
>> variable.  I should have been more explicit about that.
>>
>> class A:
>>def __init__(self):
>>   self.__x = 3
>>def foo(self):
>>   return self.__x
>>
>> class B(A): pass
>>
>> class A(B):
>>def bar(self):
>>  self.__x = 5   # clobbers private variable of earlier class named A
> 
> Has this ever been reported as a bug in Python? I could imagine more
> sophisticated "name mangling": something to do with the identity of the
> class might be sufficient, although that would make the tolerated
> "subversive" access to private attributes rather difficult.
> 
> Paul
> 
If it worries you then you can always check for it and disallow any 
hierarchies where it could be a problem. For that matter PyChecker ought to 
be able to catch this situation (maybe it already does, I haven't looked).

>>> class SafetyNet(type):
def __new__(cls, name, bases, dct):
print "new",name
c = type.__new__(cls, name, bases, dct)
assert not name in [b.__name__ for b in c.__mro__[1:]]
return c


>>> __metaclass__ = SafetyNet
>>> class A: pass

new A
>>> class B(A): pass

new B
>>> class A(B): pass

new A

Traceback (most recent call last):
  File "", line 1, in 
class A(B): pass
  File "", line 5, in __new__
assert not name in [b.__name__ for b in c.__mro__[1:]]
AssertionError

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


Re: Why less emphasis on private data?

2007-01-08 Thread Steven D'Aprano
On Sun, 07 Jan 2007 23:49:21 -0800, Paul Rubin wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> writes:
>> Just how often do you inherit from two identically-named classes
>> both of which use identically-named private attributes?
> 
> I have no idea how often if ever.

You've established that there's a name conflict when you do so, which
leads to bugs. So how often do you get bitten by that particular type of
bug?


> I inherit from library classes all
> the time, without trying to examine what superclasses they use.  If my
> subclass happens to have the same name as a superclass of some library
> class (say Tkinter) this could happen.  Whether it ever DOES happen, I
> don't know, I could only find out by examining the implementation
> details of every library class I ever use, and I could only prevent it
> by remembering those details.

class MySubClass(SomeSuperclass):
try:
__my_private_attribute
except AttributeError:
__my_private_attribute = some_value
else:
raise ValueError("Name conflict with private attribute!")

Problem solved.

*wink*


> That is an abstraction leak and is
> dangerous and unnecessary.  The name mangling scheme is a crock.  How
> often does anyone ever have a good reason for using it, 

Exactly. I never use it.

The truth of the matter is, MyClass.__private is not private at all. It is
still a public attribute with a slightly unexpected name. In other words,
if you want to code defensively, you should simply assume that Python has
no private attributes, and code accordingly.

Problem solved.



-- 
Steven.

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


General Question About Python

2007-01-08 Thread Enteng
To those who program in python, what programs do you do?
Also what community projects are you involved in(OSS probably)?
Will mastering the language land me a job?

I'm thinking about learning the language as a hobby. Just curious :)

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


Re: Module to read svg

2007-01-08 Thread Robert Kern
Martin v. Löwis wrote:
> [EMAIL PROTECTED] schrieb:
>> Does anyone know if there's an actual free implementation of this?
> 
> For the dom module in it, xml.dom.minidom should work. Depending on
> your processing needs, that might be sufficient.

I don't think it quite fits what the OP is asking for. SVG defines some non-XML
structure for some of its contents. For example:

  

The OP is asking for a module that would parse the "points" attribute into a 
list:

  [(100.0, 200.0), (100.0, 100.0)]

-- 
Robert Kern

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

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

Re: where is python on linux?

2007-01-08 Thread Hendrik van Rooyen
"rzed" <[EMAIL PROTECTED]> wrote:


>mmm... sloppy joes 
>
>-- 
>rzed
>
>"A sandwich is a sandwich, but a Manwich is a meal."

You eat people?

- Hendrik


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


Re: Why less emphasis on private data?

2007-01-08 Thread Paul Boddie
Steven D'Aprano wrote:
>
> The truth of the matter is, MyClass.__private is not private at all. It is
> still a public attribute with a slightly unexpected name. In other words,
> if you want to code defensively, you should simply assume that Python has
> no private attributes, and code accordingly.
>
> Problem solved.

Well, it isn't really solved - it's more avoided than anything else.
;-)

Still, if one deconstructs the use of private data in various
programming languages, one can identify the following roles (amongst
others):

 1. The prevention of access to data from program sections
not belonging to a particular component.
(The classic "keep out" mechanism.)
 2. The enforcement of distinct namespaces within components.
(Making sure that subclass attributes and superclass attributes
can co-exist.)
 3. To support stable storage layouts and binary compatibility.

Most Python adherents don't care too much about #1, and Python isn't
driven by the need for #3, mostly due to the way structures (modules,
classes, objects) are accessed by the virtual machine. However, one
thing which does worry some people is #2, and in a way it's the
forgotten but more significant benefit of private data.

Before I became completely aware of the significance of #2, I remember
using various standard library classes which are meant to be subclassed
and built upon, thinking that if I accidentally re-used an attribute
name then the operation of such classes would be likely to fail in
fairly bizarre ways. Of course, a quick browse of the source code for
sgmllib.SGMLParser informed me of the pitfalls, and I'm sure that
various tools could also be informative without the need to load
sgmllib.py into a text editor, but if I had been fully aware of the
benefits of private attributes and could have been sure that such
attributes had been used (again, a tool might have given such
assurances) then I wouldn't have needed to worry.

So I suppose that to "code accordingly" in the context of your advice
involves a manual inspection of the source code of superclasses or the
usage of additional tools. Yet I suppose that this isn't necessarily
unusual behaviour when working with large systems.

Paul

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


Re: Working with Excel inside Python

2007-01-08 Thread AleydisGP
Sorry for my little knowledge on Python. Actually my knowledge is
specific for automating geo-processing tasks within ESRI environment,
but sometimes I need to automate some other tasks (like this one) which
require more in-depth knowledge of this language.
Lots of documentation are of no use when you don't know exactly what to
look for or have a wrong idea of what to do.
Thanks for the guidance.

On 8 ene, 02:21, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On 7 Jan 2007 17:06:10 -0800, "John Machin" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
> > However I don't understand how a reasonable solution to the OP's
> > requirement (translate a tab-separated file to a DBF file with a bit of
> > slicing and dicing on the way) would have anything to do with .xls
> > files, or  Excel, or VB ...Only in that the original poster stated 
> > they were trying to
> translate an Excel VBA "macro" into Python, and the malformed (for
> Python) code appeared to be using Window's COM access to run all the
> work via Excel (I presume via importing the TSV, performing the edits,
> then exporting via some DBF compatible format -- ODBC?).
>
> I'd agree, however, that the specification of the task to be
> performed does not, it would seem, require any of the clumsiness of
> using Excel. Read the lines of the TSV file using proper specifications
> to the Python CSV file handling module, edit the lines as needed, and
> write them via an ODBC (or other) database adapter that generates the
> desired DBF format...
> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/

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


Proper way of handling "plug-in" methods

2007-01-08 Thread Franck PEREZ
All,

My application deals with strings formatting. I have built-in methods
but I also expect the user to add its methods in its own .py files
(some sort of plugin methods, all user methods should be exposed in my
application).

Here is the structure I have thought of :

formatting.py
_formattingDict = {} #a dict composed of all available methods, both
builtin and user
def expose(...) : #adds a method to the dict

builtinformatting.py
import myapp.formatting.expose
@expose
def builtinMethod(inputStr) : return someOutput

/home/user/.myapp/customformatting.py
import myapp.formatting.expose
@expose
def customMethod(inputStr) : return someOutput

model.py
#References all the methods, both builtin and custom
execfile("builtinformatting.py")
execfile("/home/user/.myapp/customformatting.py")

Expected result after the execfile : formatting._formattingDict
contains the 2 methods builtinMethod and customMethod

Is this a proper way of structuring my application ? Do you see
anything better ?

Moreover, I dislike execfile("builtinformatting.py") since classic
import would do the job. However I first wanted a united method for
both builtin and custom scripts since it is the same logic for me.

Thanks very much in advance for your advice.
Franck
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why less emphasis on private data?

2007-01-08 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> > I have no idea how often if ever.
> 
> You've established that there's a name conflict when you do so, which
> leads to bugs. So how often do you get bitten by that particular type of bug?

I don't know.  Likely zero, possibly not.  I'm sure I've written many
bugs that have never been detected by me or anyone else.  I've
probably written bugs that crashed an application for some user but
they just cursed me out and never bothered to tell me about the crash.
Maybe I've even written bugs that leaked a user's private data without
the user noticing, but discovered by some attacker intercepting the
data who is cackling about the bug while keeping it secret.  There's
no way for me to think I'll ever find out.

I'd much prefer to be able to say of any type of bug, "the number is
exactly zero as a known fact, because it's inherent in Python's design
that it's impossible to have that type of bug".  Language designs
should aim to let programmers say things like that as often as possible.

> class MySubClass(SomeSuperclass): ...
> raise ValueError("Name conflict with private attribute!") 
> Problem solved.

No good, Python allows creating classes and attributes on the fly.
The superclass could create its private variable after the subclass is created.

> The truth of the matter is, MyClass.__private is not private at all. It is
> still a public attribute with a slightly unexpected name. In other words,
> if you want to code defensively, you should simply assume that Python has
> no private attributes, and code accordingly.
> 
> Problem solved.

Well, "problem moved", not "problem solved".  Now you have the problem
of having to know the names of every attribute any related class might
use when you write your own class.  That is why other languages have
private variables and Python has name mangling--to solve a real problem.
Except Python's solution is a leaky kludge.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: General Question About Python

2007-01-08 Thread Sardaukary
Enteng wrote:
> To those who program in python, what programs do you do?
> Also what community projects are you involved in(OSS probably)?
> Will mastering the language land me a job?
>
> I'm thinking about learning the language as a hobby. Just curious :)

If you have any programming experience you'll be able to pick up
Python in an afternoon.   It's a very easy language to learn and
you'll be writing useful programs in no time.

Sadly I doubt learning it alone will land you a job (which is why I
forced myself to learn Java C++ and even PHP), but once you do have
that job, there's a 90% chance Python will help you get things done
in that job.  It's just a really fun and useful language with a huge
amount of well written libraries.

Check out www.pythonchallenge.com when you know the basics,  but be
warned it's quite addictive!

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


Re: how to find the longst element list of lists

2007-01-08 Thread Peter Otten
Steven D'Aprano wrote:

> On Sun, 07 Jan 2007 20:55:19 -0500, Dan Sommers wrote:
> 
>> On Sun, 07 Jan 2007 22:23:22 +0100,
>> "Michael M." <[EMAIL PROTECTED]> wrote:
>> 
>>> How to find the longst element list of lists?
>>> I think, there should be an easier way then this:
>> 
>>>   s1 = ["q", "e", "d"]
>>>   s2 = ["a", "b"]
>>>   s3 = ["a", "b", "c", "d"]
>> 
>> [ snip ]
>> 
>> One more thing to think about:  if your list of lists grows (i.e., if
>> you end up with thousands of lists instead of just three), then sorting
>> may not be the way to go.  Assuming that list_of_lists is your list of
>> lists, then something like this:
>> 
>> longest_list, longest_length = list_of_lists[ 0 ], len( longest_list
>> ) for a_list in list_of_lists[ 1 : ]:
>> a_length = len( a_list )
>> if a_length > longest_length:
>> longest_list, longest_length = a_list, a_length
>> 
>> will run faster than sorting the list just to pick off one element (O(n)
>> vs. O(n log n) for all of you Big-Oh notation fans out there; you know
>> who you are!).
> 
> But your O(n) code is running in relatively slow Python, while the sort
> method, while O(n log n), is some of the fastest, most highly optimized C
> code out there. Unless your list is truly gigantic, chances are the sort
> version will win.
> 
> Here's my timing code:
> 
> 
> import timeit
> 
> def getlongest1(list_of_lists):
> longest_list = list_of_lists[ 0 ]
> longest_length = len( longest_list )
> for a_list in list_of_lists[ 1 : ]:
> a_length = len( a_list )
> if a_length > longest_length:
> longest_list, longest_length = a_list, a_length
> return longest_list
> 
> def getlongest2(list_of_lists):
> list_of_lists.sort(key=len)
> return list_of_lists[0]
> 
> def make_list_of_lists(length):
> return [[None]*i for i in xrange(length)]
> 
> t1 = timeit.Timer("getlongest1(L)", "from __main__ import getlongest1, L")
> t2 = timeit.Timer("getlongest2(L)", "from __main__ import getlongest2, L")
> 
> 
> 
> Note that my test list_of_lists grows very big quite fast, like O(n**2).
> Assuming Python pointers are eight bytes, a mere length=1 will
> require over 760MB just for the pointers. More realistic data may allow
> more extensive testing.
> 
> And here are my timing results:
> 
 L = make_list_of_lists(1)
 print t1.timeit(1000), t2.timeit(1000)
> 0.00209903717041 0.00367403030396
> 
 L = make_list_of_lists(10)
 print t1.timeit(1000), t2.timeit(1000)
> 0.00871086120605 0.00775289535522
> 
 L = make_list_of_lists(100)
 print t1.timeit(1000), t2.timeit(1000)
> 0.121382951736 0.0518100261688
> 
 L = make_list_of_lists(1000)
 print t1.timeit(1000), t2.timeit(1000)
> 0.809508085251 0.508343935013
> 
 L = make_list_of_lists(1)
 print t1.timeit(100), t2.timeit(100)
> 0.906499147415 0.732254981995
> 
 L = make_list_of_lists(2)
 print t1.timeit(100), t2.timeit(100)
> 1.83560800552 1.58732700348
> 
> For a list of 1 item, sorting is 1.8 times SLOWER;
> For a list of 10 items, sorting is 1.1 times FASTER;
> For 100 items, sorting is 2.3 times faster;
> For 1000 items, sorting is 1.6 times faster;
> For 10,000 items, sorting is 1.2 times faster;
> For 20,000 items, sorting is 1.1 times faster.
> 
> 
> The precise results depend on the version of Python you're running, the
> amount of memory you have, other processes running, and the details of
> what's in the list you are trying to sort. But as my test shows, sort has
> some overhead that makes it a trivial amount slower for sufficiently small
> lists, but for everything else you're highly unlikely to beat it.

Try again with tN.timeit(1) and a second list that is random.shuffle()d and
copied to L before each measurement. list.sort() treats already sorted
lists specially.

Peter

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


Re: Recommendations (or best practices) to define functions (or methods)

2007-01-08 Thread vizcayno

Martin v. Löwis ha escrito:

> vizcayno schrieb:
> > Need your help in the "correct" definition of the next function. If
> > necessary, I would like to know about a web site or documentation that
> > tells me about best practices in defining functions, especially for
> > those that consider the error exceptions management.
>
> I agree with George Sakkis' remarks. The best way to define this function is
>
> def ExecuteSQL(cmdSQL, cursor):
>   return cursor.execute(cmdSQL)
>
> If this raises an exception, it likely means there is something
> wrong with the SQL statement. The program should abort, and the
> developer should correct it.
>
> Regards,
> Martin

Martin:
Thanks for your indications.
However, what happens when the error is due to data error. Or when the
program is reading many files to save data into a database and one or
two files have problems with data format. I would like to keep the
program running (using exception in a controlled way) for the remaining
good files and prepare a log about the failed files. How to keep the
same function for a program that runs in batch, or on-line or in  the
web? Giving the simple example I put, I would like to find more
guidelines.
Thanks.

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

Re: Recommendations (or best practices) to define functions (or methods)

2007-01-08 Thread vizcayno

Diez B. Roggisch ha escrito:

> vizcayno schrieb:
> > Hello:
> > Need your help in the "correct" definition of the next function. If
> > necessary, I would like to know about a web site or documentation that
> > tells me about best practices in defining functions, especially for
> > those that consider the error exceptions management.
> > I have the next alternatives but I think there are better:
>
> 
>
> IMHO none of them is good. Python has exceptions. Use them. There is no
> need to awkwardly communicate error conditions using return-values. Use
> return values to return values. Use exceptions in case of errors.
>
> Diez

Diez, in that case I woul prefer not to use exceptions and wait for
Python to abort itself and wait to see the message it issues.

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


Re: Recommendations (or best practices) to define functions (or methods)

2007-01-08 Thread vizcayno

Diez B. Roggisch ha escrito:

> vizcayno schrieb:
> > Hello:
> > Need your help in the "correct" definition of the next function. If
> > necessary, I would like to know about a web site or documentation that
> > tells me about best practices in defining functions, especially for
> > those that consider the error exceptions management.
> > I have the next alternatives but I think there are better:
>
> 
>
> IMHO none of them is good. Python has exceptions. Use them. There is no
> need to awkwardly communicate error conditions using return-values. Use
> return values to return values. Use exceptions in case of errors.
>
> Diez

Diez, in that case I woul prefer not to use exceptions and wait for
Python to abort itself and wait to see the message it issues.

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


Bizarre floating-point output

2007-01-08 Thread Nick Maclaren

x = (1.234567890125, 1.2345678901255)
print x
print x[0], x[1]

>>> (1.234567890124, 1.2345678901254999)
>>> 1.23456789012 1.23456789013

Is there a rational reason, or is that simply an artifact of the way
that the code has evolved?  It is clearly not a bug :-)


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


Re: where is python on linux?

2007-01-08 Thread Michael M.

$ whoami
cannibal

;-)


Hendrik van Rooyen wrote:

> "rzed" <[EMAIL PROTECTED]> wrote:
> 
> 
> 
>>mmm... sloppy joes 
>>
>>-- 
>>rzed
>>
>>"A sandwich is a sandwich, but a Manwich is a meal."
> 
> 
> You eat people?
> 
> - Hendrik
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Papers: Submission Deadline Imminent for Volume 2

2007-01-08 Thread Tennessee Leeuwenburg

Submission Deadline Imminent  To
those who have submitted content for The Python Papers, we salute you. To
the rest, we will be accepting zero-hour submissions up until the time of
publication. However, the closer the deadline gets, the less likely it is
that submissions will be processed in time. Submissions may be kept for the
next edition, however.

This edition will also be aimed to complement the upcoming PyCon 2007. As we
offer peer-review for academic publications, we hope to offer an opportunity
to participants who might regard this as an advantage.

We would still like to hear from anyone participating in any Python User's
Group to be a spokesperson. We will feature a series of articles covering
PUGs from around the world, and it would be fantastic to show people just
how diverse, wide-ranging and interesting the Python community really is.

Cheers,
-T
(Editor-In-Chief)
-- 
http://mail.python.org/mailman/listinfo/python-list

Finding the name of a class

2007-01-08 Thread tim mosher
Hello I'm looking for a Larry Bates that was in the Navy.  Could this be
you??   In CT in 1965???  In your 60's??
Please let me know I have been searching for over 10 yrs  thanks
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why less emphasis on private data?

2007-01-08 Thread Hendrik van Rooyen
"Paul Rubin"  wrote:

> If you want to write bug-free code, pessimism is the name of the game.

A healthy touch of paranoia does not come amiss either...

And even then things foul up in strange ways because your head
is never quite literal enough.

When you hear a programmer use the word "probability" -
then its time to fire him, as in programming even the lowest 
probability is a certainty when you are doing millions of 
things a second.

But this is off topic, really - I don't think that hiding things make 
much difference, especially as the python hiding is not absolute.

- Hendrik


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


Re: Bizarre floating-point output

2007-01-08 Thread Richard Brodie

"Nick Maclaren" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> x = (1.234567890125, 1.2345678901255)
> print x
> print x[0], x[1]
>
 (1.234567890124, 1.2345678901254999)
 1.23456789012 1.23456789013
>
> Is there a rational reason, or is that simply an artifact of the way
> that the code has evolved?  It is clearly not a bug :-)

print x[0] gives the same result as printing str(x[0]),
the value of x formatted as a string (rounded to a
sensible number of places).

x[0] at the command prompt gives the same result as
printing repr(x), the representation of the text value as
a string.

When you do print on a tuple it doesn't recursively
call str(), so you get the repr representations.

You can get similar results with anything where the
str() and repr() values are different.
e.g. x = ( u'a', u'b') 


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


recursive function

2007-01-08 Thread cesco
Hi,

I have a dictionary of lists of tuples like in the following example:
dict = {1: [(3, 4), (5, 8)],
2: [(5, 4), (21, 3), (19, 2)],
3: [(16, 1), (0, 2), (1, 2), (3, 4)]]

In this case I have three lists inside the dict but this number is
known only at runtime. I have to write a function that considers all
the possible combinations of tuples belonging to the different lists
and return a list of tuples of tuples for which the sum of the first
element of the most inner tuple is equal to N.

For example, assuming N = 24, in this case it should return:
[((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19,
2), (0, 2))]

A simple list comprehension would be enough if only I knew the number
of keys/lists beforehand but this is not the case. I guess I need a
recursive function. Can anyone help?

Thanks in advance
Francesco

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


Re: Table

2007-01-08 Thread skip

>> Someone know how do I get the collunm's number of a gkt.Table ?

This is probably better asked on the pygtk mailing list.  Your request seems
underspecified.  You want the column number given what input?  A child
widget of the Table?  If so, look at gtk.Container's child_get_property
method and the list of child properties for gtk.Table children:

http://www.pygtk.org/docs/pygtk/class-gtkcontainer.html
http://www.pygtk.org/docs/pygtk/class-gtktable.html

Skip

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


Re: Bizarre floating-point output

2007-01-08 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Richard Brodie" <[EMAIL PROTECTED]> writes:
|> 
|> When you do print on a tuple it doesn't recursively
|> call str(), so you get the repr representations.

Ah!  That explains it.  I would call that reason intermediate
between rational and an artifact of the way the code has evolved!


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


Re: Why less emphasis on private data?

2007-01-08 Thread hg
sturlamolden wrote:

> The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that
> if an object's 'internal' variables or states cannot be kept private,
> programmers get an irresistible temptation to mess with them in
> malicious ways. But if you are that stupid, should you be programming
> in any language? The most widely used language is still C, and there is
> no concept of private data in C either, nor is it needed.


void test(void)
{
  static int i;
}


Do you agree that i is "private" to test ?

hg

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


help: code formatter?

2007-01-08 Thread siggi
Hi all,

as a newbie I have problems with formatting code of downloaded programs,
because IDLE's reformatting capabilities are limited . Incorrect
indentation, mixing of TAB with BLANKs or eol are often very nasty to
correct.
Is there a simple code formatter that first removes all indentations and
then refomats correctly?

Please help!

Thank you,

siggi




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


Re: Why less emphasis on private data?

2007-01-08 Thread Neil Cerutti
On 2007-01-08, Paul Rubin  wrote:
> Dennis Lee Bieber <[EMAIL PROTECTED]> writes:
>> I'd be quite concerned about the design environment rather than the
>> immediate code... Probably need something ugly like...
>> 
>> from mod1 import B as B1
>> from mod2 import B as B2
>> class A(B1, B2):
>>  
>
> Interesting.  I just tried that.  mod1.py contains:
>
> class B:
> def foo(self): self.__x = 'mod1'
>
> mod2.py contains:
>
> class B:
> def bar(self): self.__x = 'mod2'
>
> And the test is:
>
> from mod1 import B as B1
> from mod2 import B as B2
>
> class A(B1, B2): pass
>
> a = A()
> a.foo()
> print a._B__x
> a.bar()
> print a._B__x
>
> Sure enough, mod2 messes up mod1's private variable.

When faced with this situation, is there any way to proceed
besides using composition instead?

-- 
Neil Cerutti
We've got to pause and ask ourselves: How much clean air do we really need?
--Lee Iacocca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursive function

2007-01-08 Thread Neil Cerutti
On 2007-01-08, cesco <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a dictionary of lists of tuples like in the following example:
> dict = {1: [(3, 4), (5, 8)],
> 2: [(5, 4), (21, 3), (19, 2)],
> 3: [(16, 1), (0, 2), (1, 2), (3, 4)]]
>
> In this case I have three lists inside the dict but this number
> is known only at runtime. I have to write a function that
> considers all the possible combinations of tuples belonging to
> the different lists and return a list of tuples of tuples for
> which the sum of the first element of the most inner tuple is
> equal to N.
>
> For example, assuming N = 24, in this case it should return:
> [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19,
> 2), (0, 2))]

What do you mean by "most inner tuple"?

> A simple list comprehension would be enough if only I knew the
> number of keys/lists beforehand

len(dict.keys()).

-- 
Neil Cerutti
Next Sunday Mrs. Vinson will be soloist for the morning service. The pastor
will then speak on "It's a Terrible Experience." --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module to read svg

2007-01-08 Thread Stefan Behnel
[EMAIL PROTECTED] wrote:
> I'm looking for a module to load an SVG document so that I can read out
> its contents in some graphics-centric way. For example, path elements
> store their vertices in a long attribute string you need to parse. An
> ideal module would get me these vertices in a list.
> 
> SVGdraw seems to only write, but not read.
> 
> I'm interested in a pretty simple subset of the actual spec, where SVG
> Tiny is sufficient. W3C's python spec seems just what I want:
> http://www.w3.org/TR/SVGMobile12/python-binding.html
> 
> Does anyone know if there's an actual free implementation of this?
> Before I start salvaging out code from Skencil, is there anything else
> I might look at?

Check out XIST, it seems to have some kind of SVG support.

http://www.livinglogic.de/Python/xist/
http://mail.python.org/pipermail/xml-sig/2004-June/010325.html

In case you still end up wanting to write something yourself, you might
consider lxml's namespace implementation feature a good starting point.

http://codespeak.net/lxml/element_classes.html

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


Re: Why less emphasis on private data?

2007-01-08 Thread Neil Cerutti
On 2007-01-08, hg <[EMAIL PROTECTED]> wrote:
> sturlamolden wrote:
>
>> The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that
>> if an object's 'internal' variables or states cannot be kept private,
>> programmers get an irresistible temptation to mess with them in
>> malicious ways. But if you are that stupid, should you be programming
>> in any language? The most widely used language is still C, and there is
>> no concept of private data in C either, nor is it needed.
>
>
> void test(void)
> {
>   static int i;
> }
>
>
> Do you agree that i is "private" to test ?

In C one uses the pointer to opaque struct idiom to hide data.
For example, the standard FILE pointer.

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


Re: lxml namespaces problem

2007-01-08 Thread Stefan Behnel
Maxim Sloyko wrote:
> I have a little problem with XML namespaces.
> In my application I have two XML processors, that process the same
> document, one after the other.  The first one looks for nodes in 'ns1'
> namespace, and substitutes them, according to some algorithm. After
> this processor is finished, it is guaranteed that there are no more
> 'ns1' nodes left in the tree. however 'ns1' namespace dclaration is
> still
> there, in the root node (well, I put it there manually). Now, when
> this namespace is no longer needed, I want to get rid of it, because
> it confuses some other processors (namely, my browser)
> 
> So, the question is, how do I do that?
> del tree.getroot().nsmap['ns1']
> does not seem to do the trick :(

Please ask this kind of questions on the lxml mailing list. You might also
want to consider searching the mail archive first.

First of all, lxml produces perfectly well-formed XML here. There is no reason
a document should not contain any unused namespace declarations. It's the
browser that's broken if it handles the namespace incorrectly.

Then: the thing is that lxml can't know that you removed all occurrences of
the respective namespace, so it can't just remove the declaration by itself.
lxml 1.2 will likely be able to handle these things a little (!) more
beautifully, but it's not there yet.

One way to get around this might be to reimplement the namespace replacement
in XSLT. You might also want to try to copy the elements to a newly created
document that does not have the original namespace declaration. Note, however,
that this is not guaranteed to work and might break depending on the lxml 
version.

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


Re: help: code formatter?

2007-01-08 Thread Bjoern Schliessmann
siggi wrote:

> as a newbie I have problems with formatting code of downloaded
> programs, because IDLE's reformatting capabilities are limited .
> Incorrect indentation, mixing of TAB with BLANKs or eol are often
> very nasty to correct.
> Is there a simple code formatter that first removes all
> indentations and then refomats correctly?

Why don't you just write one? :)

Seriously: Try.

BTW: Guessing to what amount of space TABs must be converted in
mixed source can be non-trivial.

Regards,


Björn

-- 
BOFH excuse #289:

Interference between the keyboard and the chair.

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


Maybe a little bug of ipython 0.7.3 ?

2007-01-08 Thread [EMAIL PROTECTED]
I'm new to ipython, and i found it a very cool product.

$ ipython
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.

IPython 0.7.3 -- An enhanced Interactive Python.


In [8]: a = range(1000)

In [9]: a?
Type:   list
Base Class: 
String Form:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 <...> 0, 981, 98
2, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 
997, 998, 999]
Namespace:  Interactive
Length: 1000
Docstring:
list() -> new list
list(sequence) -> new list initialized from sequence's items

*Please note that there is an extra "0" after "**26 <...>", which 
doesn't appear for the followling cases:*

In [10]: b = range(100)

In [11]: b?
Type:   list
Base Class: 
String Form:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 <...> , 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 
96, 97, 98, 99]


In [12]: c = range(1)

In [13]: c?
Type:   list
Base Class: 
String Form:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 <...> , 9984, 99
85, 9986, 9987, 9988, 9989, 9990, 9991, 9992, 9993, 9994, 9995, 9996, 
9997, 9998, ]



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


Re: Bizarre floating-point output

2007-01-08 Thread Bjoern Schliessmann
Nick Maclaren wrote:

> Ah!  That explains it.  I would call that reason intermediate
> between rational and an artifact of the way the code has evolved!

Which code has evolved? Those precision problems are inherent
problems of the way floats are stored in memory.

Regards,


Björn

-- 
BOFH excuse #292:

We ran out of dial tone and we're and waiting for the phone company
to deliver another bottle.

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


Re: multi-threaded webcam with SimpleAsyncHTTPServer.py

2007-01-08 Thread Bjoern Schliessmann
Ray Schumacher wrote:

> I'll be trying implementing some streaming next.
> Question, though: how can I unblock asyncore.loop(),

Not at all. That's the way event loops work.

> or at least be able to interrupt it?

Sorry for the stupid question, but why would you want to do that?

> Other suggestions?

Yes, why do you call it multithreaded when it's multiplexing? (or
isn't it?)

Regards,


Björn

-- 
BOFH excuse #10:

hardware stress fractures

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



Re: help: code formatter?

2007-01-08 Thread Thomas Heller
siggi schrieb:
> Hi all,
> 
> as a newbie I have problems with formatting code of downloaded programs,
> because IDLE's reformatting capabilities are limited . Incorrect
> indentation, mixing of TAB with BLANKs or eol are often very nasty to
> correct.
> Is there a simple code formatter that first removes all indentations and
> then refomats correctly?
> 
> Please help!


Tools\scripts\reindent.py in your Python distribution.

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


Books,resources..

2007-01-08 Thread Tarique
Hi all!
i am new to this group and starting out with python as well.i have
programming experience in 'c'
so can you please suggest some standard references for python
considering that i have some programming experience (though c is quite
unrelated i guess)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Xah's Edu Corner: Introduction to 3D Graphics Programing

2007-01-08 Thread ajsiegel
Xah Lee wrote:
> Here's their license:
> http://www.vpython.org/webdoc/visual/license.txt
>
> I read it wrong before.
> Thanks for correction.
>
> This is superb! I'll be looking into vpython!
>
>  Xah

Of course it does what it does by resort to OpenGL and C++, so is part
of the problem ;)

I am looking forward to your tutorial efforts, and hoping those efforts
can be accessed without exposure to too much polemics.  Though if that
is the price of admission, that is the price of admission.

BTW, VPython is most of the way through a 4.xxx release which provides
some nice additional functionality to the 3.xx series core - like
transparency and texturing.  Problem being the the lead developer has
graduated and moved on, and the NSF funding that had supported the
effort has run out.

And the core folks around the project are either science educators or
Python folks - there is little C++ expertise currently involved with
the project.

The project is looking for help.

Anyone willing to jump in should perhaps reply here or at:


[EMAIL PROTECTED]

Art

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


Re: PDF rendering toolkit?

2007-01-08 Thread Chris Mellon
On 1/5/07, Jorge Vargas <[EMAIL PROTECTED]> wrote:
> Hi
>
> I'm looking for a tool to take an actual .pdf file and display it in a
> window (I'm using wxwidgets at the moment)
>
> I have found several project but none seem to do what I need.
>
> http://sourceforge.net/projects/pdfplayground seems like a nice
> toolkit to edit pdf files with python code, but nothing about
> rendering.
>
> I have find out http://poppler.freedesktop.org/ but there seems to be
> no python bindings for it.
>
> there is also an example at http://www.daniweb.com/code/snippet618.html
> using wx.lib.pdfwin but that is windows only, I need at least Linux
> support better if it's platform independant as python *should* be
>
> and the reportlabs BSD packages can't do this.
> http://www.reportlab.org/devfaq.html#2.1.5
>
> anyone knows of a toolkit to do this? bonus points if's it is already
> integrated into wxpython
> --

Rendering PDF is quite hard, much harder than writing it. There are
relatively few PDF rendering solutions for any platform, and it's
non-trivial to merge one with a specific UI solution. So I'm not aware
of any cross-platform solution. Most PDF usage either embeds the Adobe
ActiveX control (on windows) or just shunts it off the user to find a
working PDF viewer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Suitability for long-running text processing?

2007-01-08 Thread tsuraan

I have a pair of python programs that parse and index files on my computer
to make them searchable.  The problem that I have is that they continually
grow until my system is out of memory, and then things get ugly.  I
remember, when I was first learning python, reading that the python
interpreter doesn't gc small strings, but I assumed that was outdated and
sort of forgot about it.  Unfortunately, it seems this is still the case.  A
sample program (to type/copy and paste into the python REPL):

a=[]
for i in xrange(33,127):
for j in xrange(33,127):
 for k in xrange(33,127):
  for l in xrange(33, 127):
   a.append(chr(i)+chr(j)+chr(k)+chr(l))

del(a)
import gc
gc.collect()

The loop is deep enough that I always interrupt it once python's size is
around 250 MB.  Once the gc.collect() call is finished, python's size has
not changed a bit.  Even though there are no locals, no references at all to
all the strings that were created, python will not reduce its size.  This
example is obviously artificial, but I am getting the exact same behaviour
in my real programs.  Is there some way to convince python to get rid of all
the data that is no longer referenced, or do I need to use a different
language?

This has been tried under python 2.4.3 in gentoo linux and python 2.3 under
OS X.3.  Any suggestions/work arounds would be much appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PDF rendering toolkit?

2007-01-08 Thread Jorge Vargas
On 1/6/07, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> > I'm looking for a tool to take an actual .pdf file and display it in a
> > window (I'm using wxwidgets at the moment)
>
> No idea if there is a one-shot-kills-them-all solution out there - but
> if you have a way to go for windows, you might checkout PyQt and PyKDE
> to embed a kpfd-view in a window of yours.
>
> I agree that it is less than desirable to switch toolkits - but if you
> _have_ to...
>
yes indeed the problem with that is I want my code to be portable that
is the reason I'm working on top of wx.

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


Re: PDF rendering toolkit?

2007-01-08 Thread Jorge Vargas
On 1/8/07, Chris Mellon <[EMAIL PROTECTED]> wrote:
> On 1/5/07, Jorge Vargas <[EMAIL PROTECTED]> wrote:
> > Hi
> >
> > I'm looking for a tool to take an actual .pdf file and display it in a
> > window (I'm using wxwidgets at the moment)
> >
> > I have found several project but none seem to do what I need.
> >
> > http://sourceforge.net/projects/pdfplayground seems like a nice
> > toolkit to edit pdf files with python code, but nothing about
> > rendering.
> >
> > I have find out http://poppler.freedesktop.org/ but there seems to be
> > no python bindings for it.
> >
> > there is also an example at http://www.daniweb.com/code/snippet618.html
> > using wx.lib.pdfwin but that is windows only, I need at least Linux
> > support better if it's platform independant as python *should* be
> >
> > and the reportlabs BSD packages can't do this.
> > http://www.reportlab.org/devfaq.html#2.1.5
> >
> > anyone knows of a toolkit to do this? bonus points if's it is already
> > integrated into wxpython
> > --
>
> Rendering PDF is quite hard, much harder than writing it.
yes indeed
> There are
> relatively few PDF rendering solutions for any platform, and it's
> non-trivial to merge one with a specific UI solution. So I'm not aware
> of any cross-platform solution. Most PDF usage either embeds the Adobe
> ActiveX control (on windows) or just shunts it off the user to find a
> working PDF viewer.
I guess for now I'll use the ActiveX code on windows and try out
Martin's suggestion on embedding a window of acrobat reader on the
linux part.

On the other hard I'm going to email the poppler guys to see if they
are interested in some python and/or wxwidgets integration.


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


Re: Suitability for long-running text processing?

2007-01-08 Thread tsuraan

After reading
http://www.python.org/doc/faq/general/#how-does-python-manage-memory, I
tried modifying this program as below:

a=[]

for i in xrange(33,127):
 for j in xrange(33,127):
  for k in xrange(33,127):
   for l in xrange(33, 127):
a.append(chr(i)+chr(j)+chr(k)+chr(l))



import sys
sys.exc_clear()
sys.exc_traceback = sys.last_traceback = None

del(a)

import gc
gc.collect()



And it still never frees up its memory.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Bizarre floating-point output

2007-01-08 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Bjoern Schliessmann <[EMAIL PROTECTED]> writes:
|> Nick Maclaren wrote:
|> 
|> > Ah!  That explains it.  I would call that reason intermediate
|> > between rational and an artifact of the way the code has evolved!
|> 
|> Which code has evolved? Those precision problems are inherent
|> problems of the way floats are stored in memory.

The use of different precisions for the two cases is not, however,
and it is that I was and am referring to.


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


Re: Maybe a little bug of ipython 0.7.3 ?

2007-01-08 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:

> In [8]: a = range(1000)
> 
> In [9]: a?
> Type:   list
> Base Class: 
> String Form:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 
> 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 <...> 0, 981, 98
> 2, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 
> 997, 998, 999]
> Namespace:  Interactive
> Length: 1000
> Docstring:
> list() -> new list
> list(sequence) -> new list initialized from sequence's items
> 
> *Please note that there is an extra "0" after "**26 <...>", which 
> doesn't appear for the followling cases:*

This 0 is the last digit of `980`.  If the string form is very long the
string itself is shortened by leaving out the middle part.  It's
irrelevant which object it was before the conversion to a string.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suitability for long-running text processing?

2007-01-08 Thread Felipe Almeida Lessa
On 1/8/07, tsuraan <[EMAIL PROTECTED]> wrote:
[snip]
> The loop is deep enough that I always interrupt it once python's size is
> around 250 MB.  Once the gc.collect() call is finished, python's size has
> not changed a bit.
[snip]
> This has been tried under python 2.4.3 in gentoo linux and python 2.3 under
> OS X.3.  Any suggestions/work arounds would be much appreciated.

I just tried on my system

(Python is using 2.9 MiB)
>>> a = ['a' * (1 << 20) for i in xrange(300)]
(Python is using 304.1 MiB)
>>> del a
(Python is using 2.9 MiB -- as before)

And I didn't even need to tell the garbage collector to do its job. Some info:

$ cat /etc/issue
Ubuntu 6.10 \n \l

$ uname -r
2.6.19-ck2

$ python -V
Python 2.4.4c1

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


sys.exit versus raise SystemExit

2007-01-08 Thread Will McGugan
Hi,

Is there any difference between calling sys.exit() and raise SystemExit? 
Should I prefer one over the other?

Regards,

Will McGugan
-- 
blog: http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


creating simple Python scripting interfaces via C++

2007-01-08 Thread Ben Sizer
I have Python embedded in a C++ application (yes, yes, I know, I'd
prefer it the other way around too) and essentially need to expose some
read-only values and functions to Python so it can be used to script
the host application.

When scripting a similar app in TCL, it's possible to associate each
command with some client data, so that the command can be written in
the script as a free function but it actually executes in some sort of
context, accessed via the client data pointer in C++. In Python, there
doesn't appear to be this mechanism, so I think I'd have to inject the
context in another way, either as some sort of module-level global, or
as an object, implementing the previously free functions as methods.

Is this correct? If so, what is the simplest way of implementing the
former method - inserting the pointer to the required context as a long
(via PyDict_SetItemString(globals, "context", PyInt_FromLong(pointer))
or similar) and then converting it back in the bound function? And for
the latter method, is it possible to make an arbitrary object and then
attach methods and the context data? Or will I have to create a whole
Python class for this (as in
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/54352)?

I'm not interested in wrapping whole C++ objects at this stage, and
libraries like Boost::Python aren't currently an option. I just need a
few pointers on doing it the low-level way for now.

-- 
Ben Sizer

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


popen, Pipes with programs that expect user input

2007-01-08 Thread Alex
Hello everyone,


I am writing a terminal server client-server application, that offers
the client the ability to run commands on the server and read their
output.

So far everything works fine, but I encounter a problem with commands
which require some sort of user input; i.e. they don't return
immediately.

This is my setup:
Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)]
on win32  


-
import os

def myExecEx(command):
"""Executes a command and returns a tuple (stdin,
stdout_stderr)"""  
outErrFile, inFile = os.popen4(command)

return (inFile, outErrFile)


fouterr, fin = myExecEx('date')   # try 'date /t' as well
#fin.write('\n')

try:
data=fouterr.read()
print data
except:
print "an exception occurred"
-

On Windows, the 'date' command will show the current date, and then
prompt me to enter a new one (thus waiting for something to come to
STDIN)

I am reading the output with:
  data=fouterr.read()

but data is empty (also, I must mention that "an exception occurred"
is not shown)

If I execute
   myExecEx('date /t')

(the /t parameter tells the date tool that it has to print the current
date and not wait for user input), then the program works as
expected).

Also, I noticed that if I uncomment the line in which I wrote to
STDIN:
  fin.write('\n')

then I can read STDOUT without problems (but this is counter-intuitive
to me; I don't know what to write to STDIN before I see what STDOUT
has to say). 


I have tried other commands from the popen family, but in either case
the behaviour was the same.


Could someone point out the cause of this?  It seems to me that the
interpreter is stuck at this line
  data=fouterr.read()

and it won't go forward unless popen returns. If so, how should the
objective be achieved?


Thank you

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


Re: Bizarre floating-point output

2007-01-08 Thread Fredrik Lundh
Nick Maclaren wrote:

> The use of different precisions for the two cases is not, however,
> and it is that I was and am referring to.

that's by design, of course.  maybe you should look "repr" up in the 
documentation ?



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


Re: Suitability for long-running text processing?

2007-01-08 Thread tsuraan

I just tried on my system

(Python is using 2.9 MiB)
>>> a = ['a' * (1 << 20) for i in xrange(300)]
(Python is using 304.1 MiB)
>>> del a
(Python is using 2.9 MiB -- as before)

And I didn't even need to tell the garbage collector to do its job. Some
info:



It looks like the big difference between our two programs is that you have
one huge string repeated 300 times, whereas I have thousands of
four-character strings.  Are small strings ever collected by python?
-- 
http://mail.python.org/mailman/listinfo/python-list

closed issue

2007-01-08 Thread Imbaud Pierre
I submitted a bug, to sourceforge. Was answered (pretty fast) the file
I dealt with was the buggy part. I then submitted a bug to the file
author, who agreed, and fixed. End of the story.
All I could complain about, with the xml.dom library, is how obscure
the exception context was: I did violate SOME xml rule, ideally the
exception should show the rule, and the faulty piece of data. But I
know this has a cost, both runtime cost and developper-s time cost.

Imbaud Pierre a écrit :
> I am using the standard xml library to create another library able to 
> read, and maybe write,
> xmp files.
> Then an xml library bug popped out:
> xml.dom.minidom was unable to parse an xml file that came from an 
> example provided by an official organism.(http://www.iptc.org/IPTC4XMP)
> The parsed file was somewhat hairy, but I have been able to reproduce 
> the bug with a simplified
> version, that goes:
> 
> 
> 
>  xmlns:iX='http://ns.adobe.com/iX/1.0/'>
> 
> xmlns:xmpPLUS='XMP Photographic Licensing Universal System (xmpPLUS, 
> http://ns.adobe.com/xap/1.0/PLUS/)'>
>   False
>   False
>  
> 
> 
> 
> 
> 
> The offending part is the one that goes: xmpPLUS=''
> it triggers an exception: ValueError: too many values to unpack,
> in  _parse_ns_name. Some debugging showed an obvious mistake
> in the scanning of the name argument, that goes beyond the closing
> " ' ".
> 
> Im aware I dont give here enough matter to allow full understanding
> of the bug. But thats not the place for this, and thats not my point.
> 
> Now my points are:
> - how do I spot the version of a given library? There is a __version__
>   attribute of the module, is that it?
> - How do I access to a given library buglist? Maybe this one is known,
>   about to be fixed, it would then be useless to report it.
> - How do I report bugs, on a standard lib?
> - I tried to copy the lib somewhere, put it BEFORE the official lib in
>   "the path" (that is:sys.path), the stack shown by the traceback
>   still shows the original files being used. Is there a special
>   mechanism bypassing the sys.path search, for standard libs? (I may
>   be wrong on this, it seems hard to believe...)
> 
> - does someone know a good tool to validate an xml file?
> 
> 
> btw, my code:
> 
> from nxml.dom import minidom
> ...
> class whatever:
> def __init__(self, inStream):
> xmldoc = minidom.parse(inStream)
> 
> 
> 
> Thanks for any help...

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


Re: sys.exit versus raise SystemExit

2007-01-08 Thread [EMAIL PROTECTED]

Will McGugan wrote:
> Hi,
>
> Is there any difference between calling sys.exit() and raise SystemExit?
> Should I prefer one over the other?
>
> Regards,
>
> Will McGugan
> --
> blog: http://www.willmcgugan.com

sys.exit() raises a SystemExit, see
http://docs.python.org/lib/module-sys.html

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


Re: Parallel Python

2007-01-08 Thread robert
Duncan Booth wrote:
> Laszlo Nagy <[EMAIL PROTECTED]> wrote:
> 
> 
> The 'parallel python' site seems very sparse on the details of how it is 
> implemented but it looks like all it is doing is spawning some subprocesses 
> and using some simple ipc to pass details of the calls and results. I can't 
> tell from reading it what it is supposed to add over any of the other 
> systems which do the same.
> 
> Combined with the closed source 'no redistribution' license I can't really 
> see anyone using it.


Thats true. IPC through sockets or (somewhat faster) shared memory -  cPickle 
at least - is usually the maximum of such approaches.
See 
http://groups.google.de/group/comp.lang.python/browse_frm/thread/f822ec289f30b26a

For tasks really requiring threading one can consider IronPython.
Most advanced technique I've see for CPython ist posh : 
http://poshmodule.sourceforge.net/ 

I'd say Py3K should just do the locking job for dicts / collections, obmalloc 
and refcount (or drop the refcount mechanism) and do the other minor things in 
order to enable free threading. Or at least enable careful sharing of 
Py-Objects between multiple separated Interpreter instances of one process.
.NET and Java have shown that the speed costs for this technique are no so 
extreme. I guess less than 10%. 
And Python is a VHLL with less focus on speed anyway.
Also see discussions in 
http://groups.google.de/group/comp.lang.python/browse_frm/thread/f822ec289f30b26a
 .


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


Re: help: code formatter?

2007-01-08 Thread Chuck Rhode
siggi wrote this on Mon, Jan 08, 2007 at 03:33:21PM +0100.  My reply is below.

> Is there a simple code formatter that first removes all indentations
> and then refomats correctly?

Why, yes, there is:

  http://lacusveris.com/PythonTidy/PythonTidy.python

-- 
.. Chuck Rhode, Sheboygan, WI, USA
.. 1979 Honda Goldwing GL1000 (Geraldine)
.. Weather:  http://LacusVeris.com/WX
.. 26° — Wind W 17 mph

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

Re: Walking The Right Path

2007-01-08 Thread Tim Daneliuk
Jakub Stolarski wrote:
> Tim Daneliuk napisal(a):
>> Ah yes, moral philosophy and python all come together... Er, that is to day:
>>
>> Imagine you have this situation on a *nix filesystem:
>>
>> Symlink A:  /foo -> /usr/home
>> Symlink B:  /bar -> /foo/username
>>
>>
>> If I do this:
>>
>>import os
>>print os.path.realpath("/bar")
>>
>> I get this (as one would expect):
>>
>>/usr/home/username
>>
>> However, what if I want to get back the result in this form:
>>
>>/foo/username
>>
>>
>> IOW, is there a way to return a symlink-based path which contains
>> the symlink pointer as is was *defined* not as it expands?
>>
> 
> One way (but very ugly):
> print os.path._resolve_link('/bar')
> 

Yup, that does just what I want.  By why, pray tell, do you consider it
ugly ...?


-- 

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suitability for long-running text processing?

2007-01-08 Thread Felipe Almeida Lessa
On 1/8/07, tsuraan <[EMAIL PROTECTED]> wrote:
>
>
> > I just tried on my system
> >
> > (Python is using 2.9 MiB)
> > >>> a = ['a' * (1 << 20) for i in xrange(300)]
> > (Python is using 304.1 MiB)
> > >>> del a
> > (Python is using 2.9 MiB -- as before)
> >
> > And I didn't even need to tell the garbage collector to do its job. Some
> info:
>
> It looks like the big difference between our two programs is that you have
> one huge string repeated 300 times, whereas I have thousands of
> four-character strings.  Are small strings ever collected by python?

In my test there are 300 strings of 1 MiB, not a huge string repeated. However:

$ python
Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
[GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> # Python is using 2.7 MiB
... a = ['1234' for i in xrange(10 << 20)]
>>> # Python is using 42.9 MiB
... del a
>>> # Python is using 2.9 MiB

With 10,485,760 strings of 4 chars, it still works as expected.

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


Re: Suitability for long-running text processing?

2007-01-08 Thread Chris Mellon
On 1/8/07, Felipe Almeida Lessa <[EMAIL PROTECTED]> wrote:
> On 1/8/07, tsuraan <[EMAIL PROTECTED]> wrote:
> >
> >
> > > I just tried on my system
> > >
> > > (Python is using 2.9 MiB)
> > > >>> a = ['a' * (1 << 20) for i in xrange(300)]
> > > (Python is using 304.1 MiB)
> > > >>> del a
> > > (Python is using 2.9 MiB -- as before)
> > >
> > > And I didn't even need to tell the garbage collector to do its job. Some
> > info:
> >
> > It looks like the big difference between our two programs is that you have
> > one huge string repeated 300 times, whereas I have thousands of
> > four-character strings.  Are small strings ever collected by python?
>
> In my test there are 300 strings of 1 MiB, not a huge string repeated. 
> However:
>
> $ python
> Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
> [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> # Python is using 2.7 MiB
> ... a = ['1234' for i in xrange(10 << 20)]
> >>> # Python is using 42.9 MiB
> ... del a
> >>> # Python is using 2.9 MiB
>
> With 10,485,760 strings of 4 chars, it still works as expected.
>
> --
> Felipe.
> --

Have you actually ran the OPs code? It has clearly different behavior
than what you are posting, and the OPs code, to me at least, seems
much more representative of real-world code. In your second case, you
have the *same* string 10,485,760 times, in the OPs case each string
is different.

My first thought was that interned strings were causing the growth,
but that doesn't seem to be the case. Regardless, what he's posting is
clearly different, and has different behavior, than what he is
posting. If you don't see the memory leak when you run the code he
posted (the *same* code) that'd be important information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Walking The Right Path

2007-01-08 Thread Tim Daneliuk
Tim Daneliuk wrote:
> Jakub Stolarski wrote:
>> Tim Daneliuk napisal(a):

>>> IOW, is there a way to return a symlink-based path which contains
>>> the symlink pointer as is was *defined* not as it expands?
>>>
>>
>> One way (but very ugly):
>> print os.path._resolve_link('/bar')
>>
> 
> Yup, that does just what I want.  By why, pray tell, do you consider it
> ugly ...?
> 
> 

Whoops - that doesn't do it either.  If I have this:

/foo -> /usr/bar
/usr/bar -> /usr1/bar

Then realpath or _resolve_link both return "/usr1/bar" when given "/foo"
(when what I want is "/usr/bar").  There is obviously some underlying
OS support to do this (in this case FreeBSD 4.x) because 'ls' shows
things as I prefer them - i.e. Links are shown as assigned not how they
actually resolve...
-- 

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suitability for long-running text processing?

2007-01-08 Thread tsuraan

$ python
Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
[GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> # Python is using 2.7 MiB
... a = ['1234' for i in xrange(10 << 20)]
>>> # Python is using 42.9 MiB
... del a
>>> # Python is using 2.9 MiB

With 10,485,760 strings of 4 chars, it still works as expected.



Have you tried running the code I posted?  Is there any explanation as to
why the code I posted fails to ever be cleaned up?
In your specific example, you have a huge array of pointers to a single
string.  Try doing "a[0] is a[1]".  You'll get True.  Try "a[0] is
'1'+'2'+'3'+'4'".  You'll get False.  Every element of a is a pointer to the
exact same string.  When you delete a, you're getting rid of a huge array of
pointers, but probably not actually losing the four-byte (plus gc overhead)
string '1234'.

So, does anybody know how to get python to free up _all_ of its allocated
strings?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: AES256 in PyCrypto

2007-01-08 Thread Gabriel Genellina

At Sunday 7/1/2007 18:23, [EMAIL PROTECTED] wrote:


Is a docstring is the text between the three consecutive quote
characters in a .py file?  The reason for the question is that I looked


See section 4.6 in the Python Tutorial - I strongly suggest you read 
it (or any other introductory text like diveintopython)



Can docstrings be embedded within the .pyd extension modules as well?


Yes - if the original module writer has provided it.


>>> x = AES.new(
As soon as I type the '(' character, the IDE displays:
new(key, [mode], [IV]): Return a new AES encryption object [...]
I'm guessing that what the IDE is displaying is the first line of what
may be multiple-line docstring that is embedded within the .pyd
extension module?  Might there be more lines in the docstring?


I don't know which IDE are you using, but try typing "help(AES.new)" 
or simply "help" (without quotes) in the interpreter.



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

xmlrpc an auth-diget

2007-01-08 Thread Thomas Liesner
Hi all,

this may have been asked before, but as a newbie with xmlrpc i can't
find any suitable info on that. Sorry.
I am trying to write a simple xmlrpc-client in python and the server i
am trying to receive data from requires http auth digest.
The info on xmlrpclib covers auth basic thrugh url econding such as
"user:[EMAIL PROTECTED]", but no auth digest.

Is there any other library i could use for that or can i write some sort
of wrapper around this using a differnt library like urllib?

TIA,
Tom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bizarre floating-point output

2007-01-08 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>, Fredrik Lundh <[EMAIL PROTECTED]> writes:
|> Nick Maclaren wrote:
|> 
|> > The use of different precisions for the two cases is not, however,
|> > and it is that I was and am referring to.
|> 
|> that's by design, of course.  maybe you should look "repr" up in the 
|> documentation ?

I think that you should.  Where does it say that tuple's __str__ is
the same as its __repr__?

The obvious interpretation of the documentation is that a sequence
type's __str__ would call __str__ on each sub-object, and its __repr__
would call __repr__.


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


xmlrpc and auth-digest

2007-01-08 Thread Thomas Liesner
Hi all,

this may have been asked before, but as a newbie with xmlrpc i can't
find any suitable info on that. Sorry.
I am trying to write a simple xmlrpc-client in python and the server i
am trying to receive data from requires http auth digest.
The info on xmlrpclib covers auth basic thrugh url econding such as
"user:[EMAIL PROTECTED]", but no auth digest.

Is there any other library i could use for that or can i write some sort
of wrapper around this using a differnt library like urllib?

TIA,
Tom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suitability for long-running text processing?

2007-01-08 Thread tsuraan

My first thought was that interned strings were causing the growth,
but that doesn't seem to be the case.



Interned strings, as of 2.3, are no longer immortal, right?  The intern doc
says you have to keep a reference around to the string now, anyhow.  I
really wish I could find that thing I read a year and a half ago about
python never collecting small strings, but I just can't find it anymore.
Maybe it's time for me to go source diving...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Walking The Right Path

2007-01-08 Thread Peter Otten
Tim Daneliuk wrote:

> IOW, is there a way to return a symlink-based path which contains
> the symlink pointer as is was *defined* not as it expands?

os.readlink()

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


Re: Recommendations (or best practices) to define functions (or methods)

2007-01-08 Thread Gabriel Genellina

At Monday 8/1/2007 10:25, vizcayno wrote:


However, what happens when the error is due to data error. Or when the
program is reading many files to save data into a database and one or
two files have problems with data format. I would like to keep the
program running (using exception in a controlled way) for the remaining
good files and prepare a log about the failed files. How to keep the
same function for a program that runs in batch, or on-line or in  the
web? Giving the simple example I put, I would like to find more
guidelines.


Deal with the exception at a higher level. In your example, you have 
some files to be processed:


for fname in filenames:
   do_something_with(fname)

==>

for fname in filenames:
try:
do_something_with(fname)
except StandardError, E:
log_error(E)


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

A Good Intro to wxpython/PostgreSQL Applications?

2007-01-08 Thread PAllen
Hi all,

I am trying to get rid of a few of my old MS Access applications and
move them to PostgreSQL and Python/wxpython.  Does anyone have any
suggestions on the easiest way to learn to program small database
applications with python & wxpython?  Does anyone have a few small
examples at least?

I will mainly need forms with/without subforms for viewing and
inserting data into the database.  Nothing too complicated to get
started.

thanks,

Phillip Allen

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


Re: Suitability for long-running text processing?

2007-01-08 Thread Chris Mellon
On 1/8/07, tsuraan <[EMAIL PROTECTED]> wrote:
>
>
> > My first thought was that interned strings were causing the growth,
> > but that doesn't seem to be the case.
>
> Interned strings, as of 2.3, are no longer immortal, right?  The intern doc
> says you have to keep a reference around to the string now, anyhow.  I
> really wish I could find that thing I read a year and a half ago about
> python never collecting small strings, but I just can't find it anymore.
> Maybe it's time for me to go source diving...
>
>

I remember something about it coming up in some of the discussions of
free lists and better behavior in this regard in 2.5, but I don't
remember the details.

Interned strings aren't supposed to be immortal, these strings
shouldn't be automatically interned anyway (and my brief testing
seemed to bear that out) and calling _Py_ReleaseInternedStrings didn't
recover any memory, so I'm pretty sure interning is not the culprit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Books,resources..

2007-01-08 Thread Bjoern Schliessmann
Tarique wrote:

> so can you please suggest some standard references for python
> considering that i have some programming experience 

I like "Learning Python" by Mark Lutz and David Ascher. They refer
to C/C++ many times.

Also try "Dive into Python" for a more fast-paced introduction
and "Python in a Nutshell" for a good reference.

Regards,


Björn

-- 
BOFH excuse #380:

Operators killed when huge stack of backup tapes fell over.

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


Re: sys.exit versus raise SystemExit

2007-01-08 Thread Will McGugan
[EMAIL PROTECTED] wrote:
> 
> sys.exit() raises a SystemExit, see
> http://docs.python.org/lib/module-sys.html
> 
Oh I know. I was just wondering if there was some sort of subtle 'best 
practice' recommendation that I wasnt aware of for using sys.exit over 
raising the exception manually. In the same way that 'open' is prefered 
over 'file', even though they appear to do the same thing.

Will
--
blog: http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursive function

2007-01-08 Thread cesco

Neil Cerutti wrote:
> On 2007-01-08, cesco <[EMAIL PROTECTED]> wrote:
> > Hi,
> >
> > I have a dictionary of lists of tuples like in the following example:
> > dict = {1: [(3, 4), (5, 8)],
> > 2: [(5, 4), (21, 3), (19, 2)],
> > 3: [(16, 1), (0, 2), (1, 2), (3, 4)]]
> >
> > In this case I have three lists inside the dict but this number
> > is known only at runtime. I have to write a function that
> > considers all the possible combinations of tuples belonging to
> > the different lists and return a list of tuples of tuples for
> > which the sum of the first element of the most inner tuple is
> > equal to N.
> >
> > For example, assuming N = 24, in this case it should return:
> > [((3, 4), (5, 4), (16, 1)), ((3, 4), (21, 3), (0, 2)), ((5, 8), (19,
> > 2), (0, 2))]
>
> What do you mean by "most inner tuple"?
>
> > A simple list comprehension would be enough if only I knew the
> > number of keys/lists beforehand
>
> len(dict.keys()).

What I mean is that the number of keys/lists is not known until runtime
and it changes randomly from time to time which means I would have to
write every time a different list comprehension (or a different number
of nested loops) to accomplish the same thing.
In the example the result of the search should be a list containing
three tuples each of which contains again three tuple (the most inner
tuples). If you consider the first element of each tuple the sum is 24
(like in 3+5+16, or 3+21+0 or 5+19+0).

Any other help will be appreciated

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


Re: Bizarre floating-point output

2007-01-08 Thread Bjoern Schliessmann
Nick Maclaren wrote:

> I think that you should.

Big words.

> Where does it say that tuple's __str__ is the same as its
> __repr__? 

Where does it say that a tuple's __str__ does not call its contents'
__repr__?

> The obvious interpretation of the documentation is that a sequence
> type's __str__ would call __str__ on each sub-object,

Where do you read that? BTW, that makes absolutely no sense to me.
Also, lists of Strings would quickly get messed up when displaying
them using __str__.

Regards,


Björn

-- 
BOFH excuse #359:

YOU HAVE AN I/O ERROR -> Incompetent Operator error

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


Re: Bizarre floating-point output

2007-01-08 Thread Bjoern Schliessmann
Nick Maclaren wrote:

> The use of different precisions for the two cases is not, however,
> and it is that I was and am referring to.

You mistake "precision" with "display". 

Regards,


Björn

-- 
BOFH excuse #12:

dry joints on cable plug

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


Re: multi-threaded webcam with SimpleAsyncHTTPServer.py

2007-01-08 Thread Gabriel Genellina

At Monday 8/1/2007 02:44, Ray Schumacher wrote:

Question, though: how can I unblock asyncore.loop(), or at least be 
able to interrupt it? To kill this server I need to hit CNTRL-C and 
then attempt to GET an image from Firefox, Python then throws 
KetboardInterrupt.


Why do you want to do that? (The usual reason is to have a place to 
do *other* things besides serving the channels). Anyway, you can use 
the count argument to asyncore.loop().
Ctrl-C gets recognised after the timeout expires; the default is 
30sec so you may have to wait up to 30 sec before the 
KeyboardInterrupt. You can lower it.



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Bizarre floating-point output

2007-01-08 Thread Ziga Seilnacht
Nick Maclaren wrote:

> I think that you should.  Where does it say that tuple's __str__ is
> the same as its __repr__?
>
> The obvious interpretation of the documentation is that a sequence
> type's __str__ would call __str__ on each sub-object, and its __repr__
> would call __repr__.

How would you distinguish ['3', '2', '1'] from [3, 2, 1] in that case?

Ziga

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


Re: Why less emphasis on private data?

2007-01-08 Thread Jussi Salmela
Neil Cerutti kirjoitti:
> On 2007-01-08, hg <[EMAIL PROTECTED]> wrote:
>> sturlamolden wrote:
>>
>>> The designers of Java, C++, C#, Ada95, Delphi, etc. seem to think that
>>> if an object's 'internal' variables or states cannot be kept private,
>>> programmers get an irresistible temptation to mess with them in
>>> malicious ways. But if you are that stupid, should you be programming
>>> in any language? The most widely used language is still C, and there is
>>> no concept of private data in C either, nor is it needed.
>>
>> void test(void)
>> {
>>   static int i;
>> }
>>
>>
>> Do you agree that i is "private" to test ?
> 
> In C one uses the pointer to opaque struct idiom to hide data.
> For example, the standard FILE pointer.
> 

To surlamolden: I don't know how you define private, but if one defines 
in C an external static variable i.e. a variable outside any functions, 
on the file level, the scope of the variable is that file only.

To hg: One does not need in C the static keyword to make a variable 
defined inside a function i.e. a so called 'automatic variable' private 
to that test. Automatic variables are private to their function by 
definition. The static keyword makes the variable permanent i.e. it 
keeps its value between calls but it is of course private also.

To Neil Cerutti: If a programmer in C has got a pointer to some piece of 
memory, that piece is at the mercy of the programmer. There's no data 
hiding at all in this case.

To whom it may concern: please stop comparing C and Python with regard 
to privacy and safety. They are two different worlds altogether. Believe 
me: I've been in this world for 2.5 years now after spending 19 years in 
the C world.

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


  1   2   3   >