Re: image processing

2007-03-07 Thread edurand
On Mar 7, 5:54 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Tue, 06 Mar 2007 10:16:21 -0300, edurand <[EMAIL PROTECTED]>
> escribió:
>
> > On Mar 6, 9:57 am, Paul Rubin  wrote:
> >> "edurand" <[EMAIL PROTECTED]> writes:
> >> > Have a look at :http://filters.sourceforge.net/
> > It's a DLL, so yes, it run on Windows.
> > If someone would like to port it on other OS, why not.
>
> Could you please update the project attributes then? Operating System,
> Language... They appear not to have the right values.
>
> --
> Gabriel Genellina

You are right. I have changed "Operating System" to "All 32-bit MS
Windows (95/98/NT/2000/XP)".
For the "Programming Language", we don't have to change anything,
because Filters can be used in C, C++, C#, Delphi, Java, Python, .NET

Thanks for your comment
Emmanuel Durand

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


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-07 Thread Nick Vatamaniuc
On Mar 7, 3:49 pm, "John" <[EMAIL PROTECTED]> wrote:
> Then is there anyway to sort the numeric keys and avoid future implemetation
> confusion?
>
> "Ant" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > On Mar 7, 8:18 pm, "John" <[EMAIL PROTECTED]> wrote:
> > ...
> >> However, I am not sure whether it is always like this. Can anybody
> >> confirm
> >> my finding?
>
> >>From the standard library docs:
>
> > "Keys and values are listed in an arbitrary order which is non-random,
> > varies across Python implementations, and depends on the dictionary's
> > history of insertions and deletions."
>
> > i.e. the behaviour you have discovered is an implementation detail,
> > and could change in future versions.

I would consider that a bad choice. In the dictionary the keys are a
set i.e. you might as well get a set() when you do d.keys() but the
set() came later so you just get a list. The problem with a list is
that somehow people want to make sense of it's order, just like in
this case. So if instead of asking, he could have just written the
application based on the fact that the keys will always be sorted in
some way. But then one day his application maybe run a different
platform and all of the sudden the keys are not sorted as before and
then disaster strikes.

I hope that dictionary.keys() would return a set to emphasize that
keys are unordered.

You suggested to just set a sort order and keep it consistent, but the
problem is that then you _have to_ maintain the sort order in addition
to the regular dictionary implementation (now it might just be a
byproduct), that is extra work that will have to be done on every
single insertion or deletion just for that rare use case where someone
will want the keys to be sorted.

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


Re: how can I find out the value of an environment variable?

2007-03-07 Thread Tim Roberts
"ken" <[EMAIL PROTECTED]> wrote:
>
>how can I find out the value of an environment variable in my pythong
>script?

 C:\Apps\Python24>python
 Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on
win32
 Type "help", "copyright", "credits" or "license" for more information.
 >>> import os
 >>> os.environ['PATH']

'C:\\WINDOWS\\system32;c:\\WINDOWS;c:\\WINDOWS\\System32\\Wbem;c:\\bin;e:\\bin'
 >>>
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2007-03-07 Thread Brian Adkins
Ken Tilton wrote:
> John Nagle wrote:
>> Brian Adkins wrote:
>>> John Nagle wrote:
>>> If you want to restart a debate, please go back and reply to some 
>>> serious post in the thread - don't hijack mine for your own evil 
>>> purposes and cut out the good parts - did you even see the movie?
>>
>>
>>If you want to post jokes...
> 
> fer chrissakes, it was the OP of "means what you think it means" who was 
> obviously doing Princess Bride and being reasonably funny,

Turns out John is having quite a tough time with Python web hosting (the 
thread has split off to a c.l.p only fork), so I'm going to cut him some 
slack. Maybe with some lovin' we can woo him over to c.l.l ;)

> Brian just 
> missed that it was deliberate.

D'oh!

> , try ...
> 
> comp.lang.lisp. All the SBCL bug reports are starting to drag down 
> the mood of this NG.
> 
> kt
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2007-03-07 Thread Paul Rubin
Brian Adkins <[EMAIL PROTECTED]> writes:
> This may sound like I'm baiting you, but it's a sincere question. If
> your experience with Perl was so good, why did you decide to pursue
> Python? Trouble free hosting and no problems in development - sounds
> like it worked out well for you.

Er, because the Perl language itself is up there with Vogon poetry in
bletcherousness?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2007-03-07 Thread Ken Tilton


John Nagle wrote:
> Brian Adkins wrote:
> 
>> John Nagle wrote:
> 
> 
>> If you want to restart a debate, please go back and reply to some 
>> serious post in the thread - don't hijack mine for your own evil 
>> purposes and cut out the good parts - did you even see the movie?
> 
> 
>If you want to post jokes...

fer chrissakes, it was the OP of "means what you think it means" who was 
obviously doing Princess Bride and being reasonably funny, Brian just 
missed that it was deliberate.

, try ...

comp.lang.lisp. All the SBCL bug reports are starting to drag down 
the mood of this NG.

kt

-- 
Well, I've wrestled with reality for 35 years, Doctor, and
I'm happy to state I finally won out over it.
   -- Elwood P. Dowd

In this world, you must be oh so smart or oh so pleasant.
   -- Elwood's Mom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2007-03-07 Thread Brian Adkins
John Nagle wrote:
> Paul Rubin wrote:
>> Brian Adkins <[EMAIL PROTECTED]> writes:
>>
>>> With prices of dedicated servers and virtual private servers so cheap,
>>> why would anyone get a hosting account without root access? 
>>
>> Because it turns you into a sysadmin instead of letting specialists
>> handle all the OS stuff so you can concentrate on your application.
> 
>Exactly.  I want to outsource these headaches to someone who's
> doing it for a thousand servers and has a standardized "just works"
> configuration that's Python-friendly.  It's inefficient to work
> through all these issues for a single server.  I have better things
> to do with my time.
> 
>When starting out with this project, I'd made the assumption that
> Python was a stable, working, well-supported technology, like Perl
> hosting.  It isn't.
> 
>It's really amazing how stable Perl hosting is.  I have a site,
> "downside.com", that's been running a Perl application since 2000,
> with essentially no attention since 2002.  It's been migrated to new
> servers twice by the hosting provider, without my having had to change
> anything.  Or even do anything.  It's talking to a MySQL database,
> going out and retrieving files from the SEC, parsing complex documents,
> gettting a feed from NASDAQ, responding to queries, and doing
> quite a bit of work.  When developing that, I had no serious problems 
> with Perl.

This may sound like I'm baiting you, but it's a sincere question. If 
your experience with Perl was so good, why did you decide to pursue 
Python? Trouble free hosting and no problems in development - sounds 
like it worked out well for you.

I do think that "hosting for the masses" is geared toward PHP, Perl, 
.NET, etc.

I primarily develop in Ruby on Rails (I'm here 'cause the original 
thread was posted to c.l.p and c.l.l) and I admit that trying that in a 
shared hosting environment will probably lead to frustration, but once I 
bit the bullet and got a VPS, and later a dedicated server, it was 
smooth sailing, and the performance is *so* much better.

A bit of a learning curve getting Apache, Mongrel, MySQL, etc. up and 
running (which was a fixed amount of time), then it just runs. In my 
case, the productivity gains over my previous environment 
(Java/Spring/Hibernate) was enough to justify a little pain for long 
term gains. Switching from the VPS to the dedicated server with a 
different company was easy because I already had the recipe to get a 
server setup.

> 
>Python, on the other hand, is uphill all the way.  Constant trouble
> with version issues, especially with C components called from Python.
> MySQLdb, M2Crypto, SSL - they all have platform/version
> incompatibility problems.  I just spent three days making M2Crypto
> work on a new Linux server with a different Red Hat version.
> Neither Python's packaging tools nor the platform's packaging
> tools deal adequately with these issues.

Now I understand your original post a bit better. Sounds like you've had 
a fair amount of frustration.

>The language is fine.  It's those weakly-supported packages out
> there in the cold that are the problem.  (I definitely agree with
> Guido that SWIG is a bad idea.  I've been combing through the 24,000
> lines of C generated by SWIG for M2Crypto, figuring out the compile
> errors and what caused them.  This is neither fun nor desirable.)
> 
>I get the feeling that Python isn't used much for general web hosting
> any more.  Only about two messages per month on this newsgroup mention
> a hosting-related issue.

It could be that the web folks are concentrated elsewhere - maybe a 
TurboGears or Django forum? Are you just using Python with CGI, or with 
a web framework? If the latter, I expect the framework folks could be 
quite helpful.

> 
>One wonders how many people try and give up.
> 
> John Nagle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: persistent fifo queue class

2007-03-07 Thread Hendrik van Rooyen
"David Bear" <[EMAIL PROTECTED]> wrote:
> Diez B. Roggisch wrote:

> > Why don't you use a DB for that? If you want pickles, use a  blob
> > column. But all the rest - a defined protocol, stable server,
> > transactions - you get for free.
> > 
> > Diez
> 
> Thanks for the suggestion. I did think of this. Indeed the final destination
> of the data is in a db. However, the postsgresql server is on a separate
> box. It will be connected via a private lan. I was worried that possible
> network disruptions would cause either the web application to hang -- or
> data to just get lost. I was thinking along the lines is a message queue
> architecture, where the web app would push data directly onto a queue --
> and then a worker app would dequeue the data and handle it by sending it to
> the db server or otherwise.
> 
Have you looked at Pyro?

I think it could help to tie the boxes on the local LAN together,
with a 'Pusher' on the first box and a 'Popper' on the box where the 
final DB lives.  And Diez' DB could provide the persistence on the first
box.
The 'push' and 'pop' above are a bit of a misnomer, as Pyro will allow 
you to have a 'puller' on the final DB box to front end the DB.
I think a "double DB" architecture like that will be very robust as
Diez' DB can provide a "transactions queued, in process, and 
completed" log.

- Hendrik 



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


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread Bjoern Schliessmann
John Nagle wrote:

> True.  It would make sense to disallow mutable values as
> initial values for optional arguments.  The present behavior
> is silly.

Why? You're free to only use immutables.

Regards,


Björn

-- 
BOFH excuse #42:

spaghetti cable cause packet failure

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


Re: merits of Lisp vs Python

2007-03-07 Thread John Nagle
Paul Rubin wrote:
> Brian Adkins <[EMAIL PROTECTED]> writes:
> 
>>With prices of dedicated servers and virtual private servers so cheap,
>>why would anyone get a hosting account without root access? 
> 
> Because it turns you into a sysadmin instead of letting specialists
> handle all the OS stuff so you can concentrate on your application.

Exactly.  I want to outsource these headaches to someone who's
doing it for a thousand servers and has a standardized "just works"
configuration that's Python-friendly.  It's inefficient to work
through all these issues for a single server.  I have better things
to do with my time.

When starting out with this project, I'd made the assumption that
Python was a stable, working, well-supported technology, like Perl
hosting.  It isn't.

It's really amazing how stable Perl hosting is.  I have a site,
"downside.com", that's been running a Perl application since 2000,
with essentially no attention since 2002.  It's been migrated to new
servers twice by the hosting provider, without my having had to change
anything.  Or even do anything.  It's talking to a MySQL database,
going out and retrieving files from the SEC, parsing complex documents,
gettting a feed from NASDAQ, responding to queries, and doing
quite a bit of work.  When developing that, I had no serious problems with Perl.

Python, on the other hand, is uphill all the way.  Constant trouble
with version issues, especially with C components called from Python.
MySQLdb, M2Crypto, SSL - they all have platform/version
incompatibility problems.  I just spent three days making M2Crypto
work on a new Linux server with a different Red Hat version.
Neither Python's packaging tools nor the platform's packaging
tools deal adequately with these issues.

The language is fine.  It's those weakly-supported packages out
there in the cold that are the problem.  (I definitely agree with
Guido that SWIG is a bad idea.  I've been combing through the 24,000
lines of C generated by SWIG for M2Crypto, figuring out the compile
errors and what caused them.  This is neither fun nor desirable.)

I get the feeling that Python isn't used much for general web hosting
any more.  Only about two messages per month on this newsgroup mention
a hosting-related issue.

One wonders how many people try and give up.

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


Re: Problem with Packages

2007-03-07 Thread Gabriel Genellina
En Thu, 08 Mar 2007 02:37:51 -0300, Srikanth <[EMAIL PROTECTED]> escribió:

> I am learning about Python packages and I am getting an ImportError
> but I can't figure out the reason why.

It appears that you forgot the basic rule: a package is a directory with  
an __init__.py file (even if empty).

> I have three modules and they are stored in a directory hierarchy as:
>
> my_apps
> |
> |--> mod3.py
> |--> dir1/dir1_1/mod1.py
> |--> dir2/dir2_2/mod2.py

You need 4 of such files here.

> And the directory my_apps is included in PYTHONPATH environment
> variable, what am I doing wrong? I executed this code under PyDev and
> it's working perfectly but when I run it outside of PyDev, it fails.

Maybe PyDev plays some tricks with PYTHONPATH or something...

-- 
Gabriel Genellina

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


Exception

2007-03-07 Thread Navid Parvini
Dear All,
   
  When an exception occurs in a Python Qt application and it is not caught,
an error message is printed to stderr and the control is given back
to the event handler (similar to the interactive Python session).
The resources allocated before the error occurred is not flushed, but
rather kept with the traceback information. The only way to release
these is to call sys.exc_clear(). Is there a way to force sys.exc_clear()
to be called automatically upon writing the error message?

  Thank you in advance.
  Navid

 
-
Never miss an email again!
Yahoo! Toolbar alerts you the instant new Mail arrives. Check it out.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: merits of Lisp vs Python

2007-03-07 Thread Brian Adkins
Paul Rubin wrote:
> Brian Adkins <[EMAIL PROTECTED]> writes:
>> With prices of dedicated servers and virtual private servers so cheap,
>> why would anyone get a hosting account without root access? 
> 
> Because it turns you into a sysadmin instead of letting specialists
> handle all the OS stuff so you can concentrate on your application.

I'm not sure what "OS stuff" you're referring to, but my interactions 
with my dedicated host are quite similar to when I had a shared hosting 
account (except I never have to contact the hosting company like I used 
to with a shared account - it just keeps humming along).

Besides, this whole thing got started with John resurrecting the 
"industrial strength" argument. I hardly think a shared hosting account 
would be considered "industrial strength". If you're not willing to deal 
with a dedicated server, then I don't think you're serious about 
"industrial strength", right? Not to mention the fact that none of this 
has anything to do with the "industrial strengthness" of the language.

> 
> Also, no VPS where you have to run your own httpd instance (and
> usually your own database if you're using one) can possibly be as
> cheap as a virtual host where you're sharing the same httpd with
> thousands of other sites.

And you *want* to share the same httpd with thousands of other sites?

I can relate to what you're saying. I tried the shared hosting thing 
originally, but the saying, "you get what you pay for" holds some truth 
here.

Maybe y'all should change the thread to "Why don't shared hosting 
companies treat Python customers better?" or something along those 
lines. We seem to have drifted from "Princess Bride" quotes and the 
merits of Lisp vs. Python ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2007-03-07 Thread Paul Rubin
Brian Adkins <[EMAIL PROTECTED]> writes:
> With prices of dedicated servers and virtual private servers so cheap,
> why would anyone get a hosting account without root access? 

Because it turns you into a sysadmin instead of letting specialists
handle all the OS stuff so you can concentrate on your application.

Also, no VPS where you have to run your own httpd instance (and
usually your own database if you're using one) can possibly be as
cheap as a virtual host where you're sharing the same httpd with
thousands of other sites.
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with Packages

2007-03-07 Thread Srikanth
Hi,

I am learning about Python packages and I am getting an ImportError
but I can't figure out the reason why.

I have three modules and they are stored in a directory hierarchy as:

my_apps
|
|--> mod3.py
|--> dir1/dir1_1/mod1.py
|--> dir2/dir2_2/mod2.py

mod1.py defines a function called add(num1, num2) and mod2.py defines
a function called multiply(num1, num2) and mod3.py makes use of the
two functions defined in mod1.py and mod2.py and mod3.py's contents is
as follows:

---
from dir1.dir1_1 import mod1
from dir2.dir2_2 import mod2

def main():
print mod1.add(10, 34)
print mod2.multiply(3, 6)

if __name__ == "__main__":
main()
--

And the directory my_apps is included in PYTHONPATH environment
variable, what am I doing wrong? I executed this code under PyDev and
it's working perfectly but when I run it outside of PyDev, it fails.

This is command I used to execute mod3.py:

C:\> python C:\my_apps\mod3.py

But I get the following error:
Traceback (most recent call last):
  File "c:\my_apps\mod3.py", line 1, in ?
from dir1.dir1_1 import mod1
ImportError: No module named dir1.dir1_1

Thanks,
Srikanth

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


Re: merits of Lisp vs Python

2007-03-07 Thread Brian Adkins
John Nagle wrote:
> Brian Adkins wrote:
>> alex23 wrote:
>>
>>> John Nagle wrote:
>>>
 Hosting providers and distro
 makers aren't concerned over whether Python works.  They
 care if C, C++, Java, PHP, and Perl work, but not Python or LISP.
 Ask them.
>>>
>>>
>>> Do you have any real experience with recent linux distros? Or with any
>>> _real_ hosting providers?
> 
>Do you?  You're writing from a gmail account, not your own site.
> 
>I have four hosting accounts with EZpublishing and a dedicated server
> at Aplus.net.  I spent weeks trying to find a hosting provider that
> would provide a Python environment that "just works", like everyone
> does for Perl.  What you typically get is a basic Python 2.4,
> and a refusal to install more packages, because it's so time-consuming.
> Or a quote of $50 to $150 per hour to install Python packages.
> 
>There are a very few hosting providers that actually want to provide
> Python hosting, such as Hard Hat Hosting.  But most don't.
>>>
>>> Because what you've said is clearly not true. Just because the
>>> situation isn't as easy _for you_ as you would like, doesn't mean that
>>> Python is being ignored to the extent you're trying to claim.
> 
>I don't see any evidence to back up this unsubstantiated claim.
> 
> John Nagle

Ok, since you provided some details you appear less troll-like, so I'll 
ignore my own advice.

With prices of dedicated servers and virtual private servers so cheap, 
why would anyone get a hosting account without root access? Once you 
have root, just install whatever you want. It shouldn't take more than a 
few minutes to install Python or whatever language you desire.

If "apt-get install" doesn't give you a recent enough version, just 
download the source and compile it.

Brian

P.S. very cool rag doll physics by the way...
-- 
http://mail.python.org/mailman/listinfo/python-list


Exception

2007-03-07 Thread Navid Parvini
Dear All,
   
  When an exception occurs in a Python Qt application and it is not caught,
an error message is printed to stderr and the control is given back
to the event handler (similar to the interactive Python session).
The resources allocated before the error occurred is not flushed, but
rather kept with the traceback information. The only way to release
these is to call sys.exc_clear(). Is there a way to force sys.exc_clear()
to be called automatically upon writing the error message?

  Thank you in advance.
  Navid

 
-
The fish are biting.
 Get more visitors on your site using Yahoo! Search Marketing.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: merits of Lisp vs Python

2007-03-07 Thread John Nagle
Brian Adkins wrote:
> alex23 wrote:
> 
>> John Nagle wrote:
>>
>>> Hosting providers and distro
>>> makers aren't concerned over whether Python works.  They
>>> care if C, C++, Java, PHP, and Perl work, but not Python or LISP.
>>> Ask them.
>>
>>
>> Do you have any real experience with recent linux distros? Or with any
>> _real_ hosting providers?

Do you?  You're writing from a gmail account, not your own site.

I have four hosting accounts with EZpublishing and a dedicated server
at Aplus.net.  I spent weeks trying to find a hosting provider that
would provide a Python environment that "just works", like everyone
does for Perl.  What you typically get is a basic Python 2.4,
and a refusal to install more packages, because it's so time-consuming.
Or a quote of $50 to $150 per hour to install Python packages.

There are a very few hosting providers that actually want to provide
Python hosting, such as Hard Hat Hosting.  But most don't.
>>
>> Because what you've said is clearly not true. Just because the
>> situation isn't as easy _for you_ as you would like, doesn't mean that
>> Python is being ignored to the extent you're trying to claim.

I don't see any evidence to back up this unsubstantiated claim.

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


Re: merits of Lisp vs Python

2007-03-07 Thread Brian Adkins
alex23 wrote:
> John Nagle wrote:
>> Hosting providers and distro
>> makers aren't concerned over whether Python works.  They
>> care if C, C++, Java, PHP, and Perl work, but not Python or LISP.
>> Ask them.
> 
> Do you have any real experience with recent linux distros? Or with any
> _real_ hosting providers?
> 
> Because what you've said is clearly not true. Just because the
> situation isn't as easy _for you_ as you would like, doesn't mean that
> Python is being ignored to the extent you're trying to claim.
> 
> -alex23
> 

alex23 - please don't feed the trolls.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread C Barr Leigh
Oh, oops! Of course...  :)  A great and sensible feature if you're
expecting it.
Thanks very much, everyone, for the links and discussion!

Chris

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


Re: merits of Lisp vs Python

2007-03-07 Thread Paul Rubin
"alex23" <[EMAIL PROTECTED]> writes:
> > Hosting providers and distro
> > makers aren't concerned over whether Python works.  They
> > care if C, C++, Java, PHP, and Perl work, but not Python or LISP.
> > Ask them.
> 
> Do you have any real experience with recent linux distros? Or with any
> _real_ hosting providers?

Care to name a "real" hosting provider that cares whether Python works?
-- 
http://mail.python.org/mailman/listinfo/python-list


VIM: Python type indented-block command equivalent to % for C?

2007-03-07 Thread Paddy3118

  Not python:
but python type
indented text

Notice the blank line above.
It could have several
spaces or tabs, and still
be a part of the block
beginning 'Not python:':
  The block ends at the
  first non-blank line
  with less indent.

Assuming that only space characters are allowed
for indenting, is their a way to yank a Python
block like y% works for C , or a way to move to
the end of a block defined by indentation?

I have tried help indent but could not find
anything.

Thanks, Paddy.

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


Re: merits of Lisp vs Python

2007-03-07 Thread alex23
John Nagle wrote:
> Hosting providers and distro
> makers aren't concerned over whether Python works.  They
> care if C, C++, Java, PHP, and Perl work, but not Python or LISP.
> Ask them.

Do you have any real experience with recent linux distros? Or with any
_real_ hosting providers?

Because what you've said is clearly not true. Just because the
situation isn't as easy _for you_ as you would like, doesn't mean that
Python is being ignored to the extent you're trying to claim.

-alex23

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


Re: Debugging segmentation faults

2007-03-07 Thread John Nagle
George Sakkis wrote:
> On Mar 7, 4:15 pm, John Nagle <[EMAIL PROTECTED]> wrote:
> 
> 
>>You're using Python on a web server to do something
>>complicated.  You must suffer.
>>
>>Are you trying to fork off a subprocess in a multithreaded
>>program?  That's unlikely to work.  The sematics differ
>>from OS to OS (Solaris forks all the threads, most other
>>operating systems don't; most UNIX-based OSs copy all the
>>open file descriptors, but some give you control of which
>>open files are passed), and Python may not be thread-safe
>>in that area.
> 
> 
> I see the potential problem in general, but in my case every thread is
> exclusively responsible for the subprocesses it forks; no subprocess
> is inherited from the main thread or is shared in among the worker
> threads.

Forking itself may not be thread safe.  Forking is a process-level
operation, for historical reasons.

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


Re: More M2Crypto build problems

2007-03-07 Thread John Nagle
Now I understand what's wrong.  It's an incompatibility between
SWIG, OpenSSL, and M2Crypto.

OpenSSL was built with OPENSSL_NO_EC defined.  That's actually
defined via "opensslconf.h", which includes, based on whether
__i386__ is defined, the file "opensslconf-i386.h".  OpenSSL
didn't always work that way; the per-platform include file
thing is new.

M2Crypto uses SWIG.  (Usually a mistake, but..)  SWIG takes
in various definition files, and generates about 24,000 lines of
C code.  (This is just glue code; it's not really doing much.)
One of the the definition files is "_ec.i", which has:

%include 
#if OPENSSL_VERSION_NUMBER < 0x0090800fL || defined(OPENSSL_NO_EC)
#undef OPENSSL_NO_EC
%constant OPENSSL_NO_EC = 1;
#else
%constant OPENSSL_NO_EC = 0;

%{
#include 
... stuff to handle elliptical curve encryption

This looks reasonable.  The "%include" brings in the file for
SWIG processing.  But, under SWIG's rules, that does NOT bring
in files included from within the file being included.
(Otherwise, SWIG would generate Python interfaces for everything
in them.)

So "OPENSSL_NO_EC" is undefined, which results in compiling the
code for "EC", the elliptical curve stuff removed from Fedora
5 and 6 for patent reasons.

A workaround is to put:

#define OPENSSL_NO_EC

at the beginning of "_ec.i".  This turns off elliptical curve
crypto support.  M2Crypto will then build.

There's probably a correct way to do this, and get SWIG to properly
obtain the value from the OpenSSL include file, but I don't know
SWIG well enough to do it.

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


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> def factorial(n, _cache={}):
> try:
>return _cache[n]
> except KeyError:
> There are other ways of implementing caches, but this is quick and easy
> and works well for many functions.

I like this better (examples are untested):

def factorial(n):
   try:
  return factorial.cache[n]
   except KeyError: pass
   ...
factorial.cache = {}

you could even use a decorator:

def memoize(f):  # memoize a 1-arg function
   f.cache = {}
   def g(f,x):
  if x in f.cache: return f.cache[x]
  return f.cache.setdefault(x, f(x))
   return functools.partial(g,f)
...

@memoize
def factorial(n):
   return 1 if n==0 else n*factorial(n-1)
-- 
http://mail.python.org/mailman/listinfo/python-list


Jython Data Extraction problem

2007-03-07 Thread Steve Williams
The data is an 8-byte 2s complement binary integer stored in a MSSQL 
2005 CHAR column.  (COBOL did that, not me). I'm using zxJDBC to read 
the data and Jython to process.
I could extract the integer if it wasn't returned in the resultset as 
unicode.  Things like ord(char) and struct.unpack('>B',char) to get at 
the bits don't seem to work.  struct.unpack('>g',string) is not available.
I've tried fooling with charset in the url and the connect statement and 
tried encode, but I have no experience here.
Is there anyway to get Jython/zxJDBC to stop converting the string to 
unicode?
Any advice is welcome.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Debugging segmentation faults

2007-03-07 Thread George Sakkis
On Mar 7, 4:15 pm, John Nagle <[EMAIL PROTECTED]> wrote:

> You're using Python on a web server to do something
> complicated.  You must suffer.
>
> Are you trying to fork off a subprocess in a multithreaded
> program?  That's unlikely to work.  The sematics differ
> from OS to OS (Solaris forks all the threads, most other
> operating systems don't; most UNIX-based OSs copy all the
> open file descriptors, but some give you control of which
> open files are passed), and Python may not be thread-safe
> in that area.

I see the potential problem in general, but in my case every thread is
exclusively responsible for the subprocesses it forks; no subprocess
is inherited from the main thread or is shared in among the worker
threads.

George

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


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread Steven D'Aprano
On Thu, 08 Mar 2007 03:14:53 +, John Nagle wrote:

> Paul Rubin wrote:
>> "C Barr Leigh" <[EMAIL PROTECTED]> writes:
>> 
>>>Help! Have I found a serious bug?
>>>This seems like highly undesired behaviour to me. From the program
>>>below, I get output:
>> 
>> 
>> It is intentional, not a bug, see the docs.  Whether it's desirable is
>> a different question.
> 
> True.  It would make sense to disallow mutable values as
> initial values for optional arguments.  The present behavior
> is silly.

It's just *different*, not silly.

It's also quite useful in some circumstances, e.g. cheap caching without
using a global variable.

def factorial(n, _cache={}):
try:
   return _cache[n]
except KeyError:
   # fall back to slow calculation
   if n <= 1:
   result = 1
   else:
   result = factorial(n-1)*n
   _cache[n] = result
   return result

There are other ways of implementing caches, but this is quick and easy
and works well for many functions.


-- 
Steven D'Aprano 

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


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread George Sakkis
On Mar 7, 10:24 pm, Paul Rubin  wrote:
> John Nagle <[EMAIL PROTECTED]> writes:
> > True.  It would make sense to disallow mutable values as
> > initial values for optional arguments.  The present behavior is silly.
>
> That would be the worst of both worlds.  The main alternative to the
> present behavior is re-computing the default value every time the
> function is entered.

One can do this is today's Python if he's so inclined, albeit with a
more verbose syntax: 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502206

George

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


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread George Sakkis
On Mar 7, 10:14 pm, John Nagle <[EMAIL PROTECTED]> wrote:
> Paul Rubin wrote:
> > "C Barr Leigh" <[EMAIL PROTECTED]> writes:
>
> >>Help! Have I found a serious bug?
> >>This seems like highly undesired behaviour to me. From the program
> >>below, I get output:
>
> > It is intentional, not a bug, see the docs.  Whether it's desirable is
> > a different question.
>
> True.  It would make sense to disallow mutable values as
> initial values for optional arguments.  The present behavior
> is silly.

1. If you'd given it a little more thought than it took you to write
this, you would perhaps realize that it is in general impossible to
determine automatically whether an arbitrary object is mutable or
not.

2. Even if you could determine it, it would be overly restrictive to
disallow all mutable values from defaults. The fact that an object is
mutable doesn't mean that the function will try to mutate it:

def paintWall(ind, colormap={1:'red', 2:'blue', 5:'green'}):
print "Let's paint the wall %s" % colormap[ind]


George

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


Re: catching exceptions from an except: block

2007-03-07 Thread Steven D'Aprano
On Wed, 07 Mar 2007 10:32:53 -0800, Arnaud Delobelle wrote:

> Hi all,
> 
> Imagine I have three functions a(x), b(x), c(x) that each return
> something or raise an exception.  Imagine I want to define a function
> that returns a(x) if possible, otherwise b(x), otherwise c(x),
> otherwise raise CantDoIt.
> 
> Here are three ways I can think of doing it:
> 
> --
> # This one looks ugly
> def nested_first(x):
> try:
> return a(x)
> except:
> try:
> return b(x)
> except:
> try:
> return c(x)
> except:
> raise CantDoIt


Exceptions are great, but sometimes they get in the way. This is one of
those times.

NULL = object() # get a unique value
def result_or_special(func, x):
"""Returns the result of func(x) or NULL."""
try:
return func(x)
except Exception:
return NULL

def failer(x):
"""Always fail."""
raise CantDoIt

def function(x):
funcs = (a, b, c, failer)
for func in funcs:
result = func(x)
if result is not NULL: break
return result


Or if you prefer:

def function(x):
NULL = object()
funcs = (a, b, c)
for func in funcs:
try:
result = func(x)
except Exception:
pass
else:
break
else:
# we didn't break out of the loop
raise CantDoIt
# we did break out of the loop
return result



-- 
Steven D'Aprano 

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


Seo , Search Engine Optimizer , Seo Search engine Optimization , search engine optimization services, SEO Consulting

2007-03-07 Thread Se0 Guy
Search Engine Optimization http://www.yourseoconsulting.com/  Seo Optimization 
, Semantic Results, Artificial intelligence in Search, Auto Content Generators, 
Search Engine Results. SEO optimizer. SEO consulting

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


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread Paul Rubin
John Nagle <[EMAIL PROTECTED]> writes:
> True.  It would make sense to disallow mutable values as
> initial values for optional arguments.  The present behavior is silly.

That would be the worst of both worlds.  The main alternative to the
present behavior is re-computing the default value every time the
function is entered.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread John Nagle
Paul Rubin wrote:
> "C Barr Leigh" <[EMAIL PROTECTED]> writes:
> 
>>Help! Have I found a serious bug?
>>This seems like highly undesired behaviour to me. From the program
>>below, I get output:
> 
> 
> It is intentional, not a bug, see the docs.  Whether it's desirable is
> a different question.

True.  It would make sense to disallow mutable values as
initial values for optional arguments.  The present behavior
is silly.

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


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread Gabriel Genellina
En Wed, 07 Mar 2007 23:39:21 -0300, C Barr Leigh <[EMAIL PROTECTED]>  
escribió:

> Help! Have I found a serious bug?

Not at all! This is by design.

> def testPersistence(anarg,twooption=[]):
> #print anarg
> if not twooption:
> twooption.append('Set within test for '+anarg)

See  
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

-- 
Gabriel Genellina

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


Re: tkinter how to write

2007-03-07 Thread faulkner
On Mar 8, 7:07 pm, Gigs_ <[EMAIL PROTECTED]> wrote:
> as I write my first gui program (text editor) I wanna ask you guys how
> to separate code in classes.?
> Should I put in one class my menu and in another class text and
> scorllbars etc?
>
> or something else?
>
> thanks


Use the force. Do whatever feels most right. Remember that you can
always refactor.
A good rule of thumb for GUIs is MVC [a class or set of classes to
encapsulate the abstract relationships known as the Model, another
class or set of classes to handle translating changes to the model
into changes in the GUI aka View, and another class or set of classes
to encapsulate the Controlling of everything], but do not pursue this
to its extreme inanity as Java does. Follow guidelines only so long as
they clarify the code. The second you can no longer keep the overall
structure of the code in your head at once, hit control+z until you
can.

When I wrote my text editor, I wanted to keep everything in one class
because I thought it would be cleaner. Several thousand lines later, I
realized that the notion of a Tab is a significant and powerful
abstraction, as is the UndoStack and the entries in it [UndoEntry].
Right now, I'm thinking about separating all the menuitem callbacks
into their own class because they are different in kind from the
methods which encapsulate the Tabs, menubar, statusbar, etc. into an
application. The reason that I probably won't do this is that a class
is not for grouping methods, it's for representing objects.

UML is another expounded tool for achieving OOP zen before you set
fingertips to keyboard. i've never grokked it, but you should try it
at least once, if only so you can say that you have in a job interview.

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


Re: Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread Paul Rubin
"C Barr Leigh" <[EMAIL PROTECTED]> writes:
> Help! Have I found a serious bug?
> This seems like highly undesired behaviour to me. From the program
> below, I get output:

It is intentional, not a bug, see the docs.  Whether it's desirable is
a different question.
-- 
http://mail.python.org/mailman/listinfo/python-list


Bug in python!? persistent value of an optional parameter in function!

2007-03-07 Thread C Barr Leigh
Help! Have I found a serious bug?
This seems like highly undesired behaviour to me. From the program
below, I get output:

call1: ['sdf']
call2: ['Set within test for call2']
call3: ['Set within test for call2']

instead of what I should get,

call1: ['sdf']
call2: ['Set within test for call2']
call3: ['Set within test for call3']

I'm using Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02). The code is
below.


#!/usr/bin/python

def testPersistence(anarg,twooption=[]):
#print anarg
if not twooption:
twooption.append('Set within test for '+anarg)
print anarg +': '+str(twooption)

testPersistence('call1',twooption=['sdf']);
testPersistence('call2');
testPersistence('call3');

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


Re: is it possible to give an instance a value?

2007-03-07 Thread Steven D'Aprano
On Wed, 07 Mar 2007 16:02:05 +0100, egbert wrote:

> On Tue, 06 Mar 2007 14:45:45 -0800, manstey wrote:
>> 
>> class Test(object):
>>  def __init__(self, val):
>>self.val = val
>> 
>> a = Test('hello')
> 
>> Is there a way to make a have the value a.val when it is used as
>> above, or as an argument (eg function(a, 10, 'sdf') etc)?
>> 
> My impression is that you can do everything you want to
> by making your instance callable, and not using a but a().

You can't do this:

>>> a() = "some value"
SyntaxError: can't assign to function call


If you do this:

>>> a = "some value"

then we're back to the Original Poster's original problem.



-- 
Steven D'Aprano 

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


Re: merits of Lisp vs Python

2007-03-07 Thread John Nagle
Brian Adkins wrote:
> John Nagle wrote:

> If you want to restart a debate, please go back and reply to some 
> serious post in the thread - don't hijack mine for your own evil 
> purposes and cut out the good parts - did you even see the movie?

If you want to post jokes, try rec.humor.funny.  Although
they mave moderation and you may not

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


www.OutpatientSurgicare.com/video/

2007-03-07 Thread [EMAIL PROTECTED]
www.OutpatientSurgicare.com/video/
Outpatient Doctors Surgery Center is committed to offering the
healthcare the community needs. We offer patients a meaningful
alternative to traditional surgery. This state-of-the-art outpatient
surgery center, located in the heart of Orange County, at 10900 Warner
Avenue, Suite 101A, Fountain Valley, Ca 92708, offers the latest
innovations in outpatient surgery and technology.
Please Call For Our Special Cash Discount
Toll Free: 1-877-500-2525
Please Visit Our Websites:
We offer extreme cosmetic surgery makeover packages.
http://www.SurgeonToTheStars.com
http://www.1cosmeticsurgery.com
Specializing in the cure of hyperhidrosis, sweaty palms, underarm and
foot sweating.
http://www.CuresweatyPalms.com
http://www.ControlExcessiveSweating.com
No. 1 Weight Loss Surgery Center
http://www.ControlWeightLossNow.com
http://www.FreeLapBandSeminar.com
Hernia Treatment Center
http://www.HerniaDoc.com
Take care of your feet
http://www.CureFootPain.com
The Experts in CARPAL TUNNEL SYNDROME
http://www.CureHandPain.com

Accidental Urine Leaks ? End Urinary Incontinence
http://www.WomanWellnessCenter.com
Hemorrhoid Treatment Center
http://www.hemorrhoidtreatmentcenter.com

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


Re: catching exceptions from an except: block

2007-03-07 Thread MonkeeSage
On Mar 7, 4:58 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
>except_retry: # the missing(???) keyword you're after

What is 'except_retry'?

To the OP, with the loop and the callables you could also break out of
the loop when the condition is met and use the else condition to raise
the exception.

def test(arg):
for f in int, float, str, hex:
try:
return f(arg)
break # breaks on f==str
except:
pass
else:
raise ValueError # remove str above to see this
print test('^&%')

Regards,
Jordan


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


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Paul Rubin
"Sergio Correia" <[EMAIL PROTECTED]> writes:
> 2) Reduce
> eggs = reduce(lambda x, y: x+y, spam)
> 
> I feel the 1st way is too cumbersome (three lines), and although I
> like the 2nd way (except for the lambda part), I understand reduce is
> discouraged by Guido so I want to know if there is a "Better Way"(TM)
> ?

I thought map/reduce were considered ok again, but the above runs
in quadratic time, not good.

I'd use:

  eggs = list(itertools.chain(*spam))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Descriptor/Decorator challenge

2007-03-07 Thread Jack Diederich
On Tue, Mar 06, 2007 at 11:44:48AM -0800, Arnaud Delobelle wrote:
> On 5 Mar, 18:59, "Arnaud Delobelle" <[EMAIL PROTECTED]> wrote:
> [snip]
> > Well in fact I couldn't help but try to improve it a bit. Objects now
> > don't need a callerclass attribute, instead all necessary info is
> > stored in a global __callerclass__. Bits that didn't work now do.
> 
> OK that wasn't really thought through. Because I changed the design
> mid-way through writing it __callerclass__ wasn't doing the right
> thing. I've sorted the issues I could see and made it (hopefully)
> thread-safe. I'm not going to pollute this list again with my code so
> I've put it at the following address:
> 
> http://marooned.org.uk/local.py
> 

I fooled around with this a bit and even when using different techniques
than Arnaud (namely stack inspection and/or class decorators) it ends up
looking the same.  In order to pull this off you need to

1) mark the localmethods as special
   (@localmethod works here)
2) mark all non-localmethods as not special
   (metaclasses, class decorators, or module-level stack inspection)
3) keep track of the call stack
   (can be implemented as part of #1 and #2 but adds overhead regardless)

Double underscore names take care of #1 at compile time and by definition
anything not name-manged falls into the non-special class of #2.  After
that the special/non-special calls are given different names so the
native call semantics take care of the call stack for you.

With some bytecode manipulation it should be possible to fake the same 
name mangling by using just @localmethod decorators and adding some 
overhead to always checking the current class (eg A.m() for the function
am()) and falling back on doing the normal call of self.m().  This could 
be made more exact by doing inspection after the fact with any of 
metaclasses/class decorators/module inspection because then we could 
inspect what is a @localmethod and what isn't all the way through the class
tree.

I could be wrong on the byte-hack part as I've only recently learned
to read the chicken bones that are byte codes (thanks to PyCon sprints
I got to spend time picking python-devs's brains over burritos).  It
seem plausible if fragile.

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


Error 1 during install of python 2.5 on CentOS

2007-03-07 Thread nat
Hi guys,

I'm running CentOS 4.4 and the current version on my system is Python
2.3.4.   Ideally I wanted to use an RPM to update the system python
but a lot of dependencies failed and since I need to run the latest
Python for a particular script, I read on this group somewhere a
suggestion to run both on the same server and use:

"make altinstall"


So I downloaded the 2.5 tarball and ran ./configure and then 'make
altinstall'

Somewhere during the make it gave these errors. It continued after the
first error below but then that "Error 1" error is the last line and
it stopped there.


These are the errors:


Sorry: UnicodeError: ("\\N escapes not supported (can't load
unicodedata module)",)

make: *** [libinstall] Error 1



I can't find any information about this error.  I'm kind of new to
compiling from sources so I don't what to do from here.

/usr/bin has no phython2.5 in it, so I take it the install didn't
complete.


Any ideas what to do from here?


Thanks
Nat

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


Re: Calling a function with unknown arguments?

2007-03-07 Thread Rob
> You can do this with a list comprehension:
> bob(*[possible[k] for k in bob2.func_code.co_varnames])
>
> The LC creates a list of arg values in the same order as the var names
> for the function. Putting a * before the list when you call bob()
> turns that list into it's arguments.

Thanks Tom! This turns out to be exactly what I needed.

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


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Sergio Correia
 O_o

List comprehensions never cease to amaze me.

Thanks,


On 3/7/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Wed, 07 Mar 2007 21:41:16 -0300, Sergio Correia
> <[EMAIL PROTECTED]> escribió:
>
> > I forgot to say: I've already checked the discussions about
> > recursive/iterative/etc flatten() functions that can sweep through a
> > list of arbitrary length, but that's really overkill for what I want.
> >
> > However, "sum(eggs, [])" or itertools seem to do it w/out the need for
> > a new function.
> >
> > Thanks a lot!
>
> Just for being (a little!) constructive, given your preconditions on the
> list, you can use:
> eggs = [item for sublist in spam for item in sublist]
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Michael Spencer
Sergio Correia wrote:
> spam = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
> 
> Into something like
> eggs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
> 
> There are *no* special cases (no empty sub-lists).
eggs = [i for j in spam for i in j]

Michael

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


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Gabriel Genellina
En Wed, 07 Mar 2007 21:41:16 -0300, Sergio Correia  
<[EMAIL PROTECTED]> escribió:

> I forgot to say: I've already checked the discussions about
> recursive/iterative/etc flatten() functions that can sweep through a
> list of arbitrary length, but that's really overkill for what I want.
>
> However, "sum(eggs, [])" or itertools seem to do it w/out the need for
> a new function.
>
> Thanks a lot!

Just for being (a little!) constructive, given your preconditions on the  
list, you can use:
eggs = [item for sublist in spam for item in sublist]

-- 
Gabriel Genellina

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


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Matimus
> Any ideas?

how about list comprehension (should actually work even if there is an
empty sub-list):
>>> spam = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
>>> [parrot for egg in spam for parrot in egg]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

-m

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


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Sergio Correia
I forgot to say: I've already checked the discussions about
recursive/iterative/etc flatten() functions that can sweep through a
list of arbitrary length, but that's really overkill for what I want.

However, "sum(eggs, [])" or itertools seem to do it w/out the need for
a new function.

Thanks a lot!

Sergio

On 3/7/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Wed, 07 Mar 2007 21:14:43 -0300, Sergio Correia
> <[EMAIL PROTECTED]> escribió:
>
> > I'm looking for an easy way to flatten a two level list like this
>
> Try google.
>
> > PS: Why does `sum` works only with numbers?
>
> Try google.
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Virgil Dupras
On Mar 7, 7:14 pm, "Sergio Correia" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm looking for an easy way to flatten a two level list like this
>
> spam = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>
> Into something like
> eggs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>
> There are *no* special cases (no empty sub-lists).
>
> I have found two ways:
>
> 1) Accumulator
> eggs = []
> for x in eggs:
>eggs.extend(x)
>
> 2) Reduce
> eggs = reduce(lambda x, y: x+y, spam)
>
> I feel the 1st way is too cumbersome (three lines), and although I
> like the 2nd way (except for the lambda part), I understand reduce is
> discouraged by Guido so I want to know if there is a "Better Way"(TM)
> ?
>
> Any ideas?
>
> Thanks,
> Sergio
>
> PS: Why does `sum` works only with numbers?

A search in the python group should get you all the details you need.

Quick answer: "sum(eggs, [])", but the "correct" way is to have a
flatten() function, with those 3 lines.

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


Re: Flatten a two-level list --> one liner?

2007-03-07 Thread Gabriel Genellina
En Wed, 07 Mar 2007 21:14:43 -0300, Sergio Correia  
<[EMAIL PROTECTED]> escribió:

> I'm looking for an easy way to flatten a two level list like this

Try google.

> PS: Why does `sum` works only with numbers?

Try google.

-- 
Gabriel Genellina

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


Re: merits of Lisp vs Python

2007-03-07 Thread Ken Tilton


Brian Adkins wrote:
> John Nagle wrote:
> 
>>Neither Lisp nor Python is an "industrial strength language".
>> The infrastructure is too weak.  Hosting providers and distro
>> makers aren't concerned over whether Python works.  They
>> care if C, C++, Java, PHP, and Perl work, but not Python or LISP.
>> Ask them.
>>
>> John Nagle
> 
> 
> In your excitement to post a sweeping and inaccurate generalization (you 
> missed diss'ing Ruby), I think you may have missed the point of my post. 
> I surely wasn't trying to restart a dead thread, I just thought it was 
> funny that there was a similarity to a line from Princess Bride in the 
> thread (see relevant part below that you cut out).
> 
> If you want to restart a debate, please go back and reply to some 
> serious post in the thread - don't hijack mine for your own evil 
> purposes and cut out the good parts - did you even see the movie?

Yes. I think George did, too. (I was wondering what you were up to.)

:)

kt


> 
> George Sakkis wrote:
>  > You keep using that phrase. I don't think it means what you think it
>  > means.
> 
> [Vizzini has just cut the rope The Dread Pirate Roberts is climbing up]
> Vizzini: HE DIDN'T FALL? INCONCEIVABLE.
> Inigo Montoya: You keep using that word. I do not think it means what 
> you think it means.

-- 
Well, I've wrestled with reality for 35 years, Doctor, and
I'm happy to state I finally won out over it.
   -- Elwood P. Dowd

In this world, you must be oh so smart or oh so pleasant.
   -- Elwood's Mom
-- 
http://mail.python.org/mailman/listinfo/python-list


tkinter how to write

2007-03-07 Thread Gigs_
as I write my first gui program (text editor) I wanna ask you guys how 
to separate code in classes.?
Should I put in one class my menu and in another class text and 
scorllbars etc?

or something else?


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


Flatten a two-level list --> one liner?

2007-03-07 Thread Sergio Correia
Hi,

I'm looking for an easy way to flatten a two level list like this

spam = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

Into something like
eggs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

There are *no* special cases (no empty sub-lists).

I have found two ways:

1) Accumulator
eggs = []
for x in eggs:
   eggs.extend(x)

2) Reduce
eggs = reduce(lambda x, y: x+y, spam)

I feel the 1st way is too cumbersome (three lines), and although I
like the 2nd way (except for the lambda part), I understand reduce is
discouraged by Guido so I want to know if there is a "Better Way"(TM)
?

Any ideas?

Thanks,
Sergio

PS: Why does `sum` works only with numbers?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is it possible to give an instance a value?

2007-03-07 Thread manstey
Thanks everyone for your replies. The language is Cache Object Script,
a language used in  Intersystems Relational Dbase.

I think egbert's answer provides the simplest answer. It allows our
python interface to Cache to be almost identical to Cache Object
Script, with simeply the addition of (), which we prefer to .val
or .data for various reasons.

Using the example .type was a mistake, as I meant simply any metadata
about a value. If we make the instance callable, then we can have:

instance()
instance.calculated
instance.type
instance.whatever
instance.save()
etc

thanks.

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


Re: Calling a function with unknown arguments?

2007-03-07 Thread Tombo
On Mar 7, 10:55 pm, "Rob" <[EMAIL PROTECTED]> wrote:
> I can get a list of a function's arguments.>>> def bob(a, b):
>
> ... return a+b
> ...>>> bob.func_code.co_varnames
>
> ('a', 'b')
>
> Let's say that I also have a dictionary of possible arguments for this
> function.
>
> >>> possible = {'a':10, 'b':5, 'c':-3}
>
> How do I proceed to call bob(a=10, b=5) with this information?
>
> Thanks!

You can do this with a list comprehension:
bob(*[possible[k] for k in bob2.func_code.co_varnames])

The LC creates a list of arg values in the same order as the var names
for the function. Putting a * before the list when you call bob()
turns that list into it's arguments.


Alternativly (and this may not be useful) you can call a function with
a dictionary of arguments:

def bob(**kwargs):
print kwargs

possible = {'a' : 10, 'b':5, 'c':-3}


>>> bob(**possible)
{'a': 10, 'c': -3, 'b': 5}
>>>

Tom

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


Re: merits of Lisp vs Python

2007-03-07 Thread Brian Adkins
John Nagle wrote:
>Neither Lisp nor Python is an "industrial strength language".
> The infrastructure is too weak.  Hosting providers and distro
> makers aren't concerned over whether Python works.  They
> care if C, C++, Java, PHP, and Perl work, but not Python or LISP.
> Ask them.
> 
> John Nagle

In your excitement to post a sweeping and inaccurate generalization (you 
missed diss'ing Ruby), I think you may have missed the point of my post. 
I surely wasn't trying to restart a dead thread, I just thought it was 
funny that there was a similarity to a line from Princess Bride in the 
thread (see relevant part below that you cut out).

If you want to restart a debate, please go back and reply to some 
serious post in the thread - don't hijack mine for your own evil 
purposes and cut out the good parts - did you even see the movie?

George Sakkis wrote:
 > You keep using that phrase. I don't think it means what you think it
 > means.

[Vizzini has just cut the rope The Dread Pirate Roberts is climbing up]
Vizzini: HE DIDN'T FALL? INCONCEIVABLE.
Inigo Montoya: You keep using that word. I do not think it means what 
you think it means.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling a function with unknown arguments?

2007-03-07 Thread Gabriel Genellina
En Wed, 07 Mar 2007 19:55:08 -0300, Rob <[EMAIL PROTECTED]> escribió:

> I can get a list of a function's arguments.
 def bob(a, b):
> ... return a+b
> ...
 bob.func_code.co_varnames
> ('a', 'b')
>
> Let's say that I also have a dictionary of possible arguments for this
> function.
 possible = {'a':10, 'b':5, 'c':-3}
>
> How do I proceed to call bob(a=10, b=5) with this information?

You're almost done. Notice that co_varnames includes local variables too;  
only the first co_argcount are positional arguments.
If you only want to deal with positional arguments (no *args, no **kw):

py> def bob(a,b):
...   c = a+b
...   return c
...
py> bob.func_code.co_varnames
('a', 'b', 'c')
py> bob.func_code.co_argcount
2
py> args = dict((name, possible[name]) for name in  
bob.func_code.co_varnames[:bo
b.func_code.co_argcount] if name in possible)
py> args
{'a': 10, 'b': 5}
py> bob(**args)
15

It can handle missing arguments (if they have a default value, of course):

py> def bob(a, k=3):
...   return a+k
...
py> args = dict((name, possible[name]) for name in  
bob.func_code.co_varnames[:bo
b.func_code.co_argcount] if name in possible)
py> args
{'a': 10}
py> bob(**args)
13

-- 
Gabriel Genellina

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


Re: Best place for a function?

2007-03-07 Thread Sergio Correia
I also found out I can't use `unittest` with nested functions :-(

Thank you all for the responses,

Best,
Sergio

On 7 Mar 2007 14:57:54 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Diez B. Roggisch:
> > If it really has no other use as in this class, put it as an
> > instancemethod in there. Alternatively, you _could_ nest it like this:
>
> Using an instancemethod may be the most formally correct solution for
> that problem, but often nested function are the simpler solution. A
> downside of nested functions is that you can't give them a doctest (in
> a simple way).
>
> Bye,
> bearophile
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling a function with unknown arguments?

2007-03-07 Thread Grant Edwards
On 2007-03-07, Rob <[EMAIL PROTECTED]> wrote:
> I can get a list of a function's arguments.
 def bob(a, b):
> ... return a+b
> ...
 bob.func_code.co_varnames
> ('a', 'b')
>
> Let's say that I also have a dictionary of possible arguments for this
> function.
 possible = {'a':10, 'b':5, 'c':-3}
>
> How do I proceed to call bob(a=10, b=5) with this information?

bob(a=possible['a'],b=possible['b'])

-- 
Grant Edwards   grante Yow!  BRILL CREAM is
  at   CREAM O' WHEAT in another
   visi.comDIMENSION...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2007-03-07 Thread John Nagle
Brian Adkins wrote:
> George Sakkis wrote:
> 
>> [EMAIL PROTECTED] wrote:
>>
>>> 1. Lisp is the only industrial strength language

Neither Lisp nor Python is an "industrial strength language".
The infrastructure is too weak.  Hosting providers and distro
makers aren't concerned over whether Python works.  They
care if C, C++, Java, PHP, and Perl work, but not Python or LISP.
Ask them.

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


IronPython with Apache

2007-03-07 Thread edfialk
Hi all, I'm completely new to Python, but fairly experienced in PHP
and few other languages.

Long story short: The IronPython executable doesn't work for .cgi
scripts in my browser.


I've been assigned to write a service that pulls in parameters from
the URL, accesses a file and serves some data through a CSV.  The only
problem I foresee myself is accessing and reading this file, which is
a 'hyper-cube' in that it has many dimensions of data.

Anyway, the code for reading and writing this cube was already written
by a coworker in IronPython and .NET.  Again, I'm totally new to
Python but as I'm stepping through trying to pick out pieces that I
need, I can't even import clr.

So, I'm told I need IronPython, which I get, and I replace the #!c:
\Python25\python.exe with the IronPython executable (#!c:
\IronPython-1.0.1\ipy.exe), but I get a 500 Internal Server error and:

"[Wed Mar 07 17:02:21 2007] [error] [client 127.0.0.1] malformed
header from script. Bad header=  File , line 0, in __import__:
testing.cgi" in the Error log.

Does anyone know how to set up this 'IronPython' through Apache so I
can use it to read/write data?

Any help would be greatly appreciated.
Thanks!
-Ed

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


Re: Best place for a function?

2007-03-07 Thread bearophileHUGS
Diez B. Roggisch:
> If it really has no other use as in this class, put it as an
> instancemethod in there. Alternatively, you _could_ nest it like this:

Using an instancemethod may be the most formally correct solution for
that problem, but often nested function are the simpler solution. A
downside of nested functions is that you can't give them a doctest (in
a simple way).

Bye,
bearophile

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


Calling a function with unknown arguments?

2007-03-07 Thread Rob
I can get a list of a function's arguments.
>>> def bob(a, b):
... return a+b
...
>>> bob.func_code.co_varnames
('a', 'b')

Let's say that I also have a dictionary of possible arguments for this
function.
>>> possible = {'a':10, 'b':5, 'c':-3}

How do I proceed to call bob(a=10, b=5) with this information?

Thanks!

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


Re: image processing

2007-03-07 Thread Claudio Grondi
edurand wrote:
> Hi,
> 
> We are are pleased to announce the version 3.0 of the image processing
> library 'Filters'.
> You can use it in Python, and we have provided tutorials and samples
> in Python, with for exemple conversion from/to PIL image format.
> 
> Have a look at : http://filters.sourceforge.net/
> 
> it's open source of course
> 
> regards
> edurand
> 
In the context of this posting it would be interesting for me (and maybe 
also to others) to know:

What was the actual motivation behind the project?

What are other image processing packages missing, that is worth to be 
covered by a separate package?

(i.e. I checked http://filters.sourceforge.net/ out, but haven't yet 
found the mentioned questions answered )

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


Re: catching exceptions from an except: block

2007-03-07 Thread Diez B. Roggisch
Arnaud Delobelle schrieb:
> On Mar 7, 8:52 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> [snip]
>> Without knowing more about the functions and the variable it is somewhat
>> hard to tell what you are trying to accomplish.  If a, b, c are functions
>> that act on x when it is a different type, change to one function that
>> can handle all types.
> 
> I'm not really thinking about this situation so let me clarify. Here
> is a simple concrete example, taking the following for the functions
> a,b,c I mention in my original post.
>   - a=int
>   - b=float
>   - c=complex
>   - x is a string
> This means I want to convert x to an int if possible, otherwise a
> float, otherwise a complex, otherwise raise CantDoIt.
> 
> I can do:
> 
> for f in int, float, complex:
> try:
> return f(x)
> except ValueError:
> continue
> raise CantDoIt
> 
> But if the three things I want to do are not callable objects but
> chunks of code this method is awkward because you have to create
> functions simply in order to be able to loop over them (this is whay I
> was talking about 'abusing loop constructs').  

In your case, I don't consider it an abuse - au contraire. Because in 
such a situation where a possibly growing number of functions dealing 
with one value until one of them "fits" a loop is the natural thing to 
do, as it won't change in appearance just because you add a new 
conversion-function to some (semi-)global list. I'd consider it 
especially good style in that case.

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


Re: Best place for a function?

2007-03-07 Thread Bruno Desthuilliers
Sergio Correia a écrit :
> I'm writing a class, where one of the methods is kinda complex. The
> method uses a function which I know for certain will not be used
> anywhere else. This function does not require anything from self, only
> the args passed by the method.
> 
> Where should I put the function?

Somewhere in your module ?-)

(snip)

If your problem is to reduce the apparent complexity of the method, 
defining the function inside the method won't help that much (unless the 
function by itself is short enough - and event then...). Apart from 
having a direct access to the method's namespace, you don't gain much by 
doing so. And if it's a an implementation function that doesn't need to 
access the instance, it has no reason to be a method. Moreover, since 
it's not part of neither the class or the module interface, you can 
freely change your mind if and when you find a need to do so.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More M2Crypto build problems

2007-03-07 Thread John Nagle
Still more M2Crypto build problems:

In M2Crypto's file "SWIG/_ec.i", there's this:

#if OPENSSL_VERSION_NUMBER < 0x0090800fL || defined(OPENSSL_NO_EC)
#undef OPENSSL_NO_EC
%constant OPENSSL_NO_EC = 1;
#else
%constant OPENSSL_NO_EC = 0;

%{
#include 
#include 
#include 
#include 
#include 
#include 
%}

There's the assumption here that versions of OpenSSL greater than 0.9.08???
contain elliptical curve cryptography support.  There's
also the assumption that "ecdsa.h" is present; it is included
unconditionally, and definitions from it are used later.

Unfortunately, the ones that ship with Fedora Core 5 and 6 do not have it:

http://threebit.net/mail-archive/fedora-list/msg14507.html

Updating with "yum" doesn't help.  Apparently there are patent problems
with the algorithm, and Red Hat pulled that code.  See

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

I'm trying to get M2Crypto to build without elliptical cryptography, but
it's not working

John Nagle

"Python.  Embrace the pain".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: catching exceptions from an except: block

2007-03-07 Thread Bruno Desthuilliers
Gabriel Genellina a écrit :
> En Wed, 07 Mar 2007 18:48:18 -0300, Arnaud Delobelle  
> <[EMAIL PROTECTED]> escribió:
> 
>> for f in int, float, complex:
>> try:
>> return f(x)
>> except ValueError:
>> continue
>> raise CantDoIt
>>
>> But if the three things I want to do are not callable objects but
>> chunks of code this method is awkward because you have to create
>> functions simply in order to be able to loop over them (this is whay I
>> was talking about 'abusing loop constructs').  Besides I am not happy
>> with the other two idioms I can think of.
> 
> 
> Hmmm, functions are cheap 

To define. You pay the price when you call them !-)

(sorry, couldn't resist - I otherwise totally agree with you)

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


Re: Best place for a function?

2007-03-07 Thread Diez B. Roggisch
Sergio Correia schrieb:
> I'm writing a class, where one of the methods is kinda complex. The
> method uses a function which I know for certain will not be used
> anywhere else. This function does not require anything from self, only
> the args passed by the method.
> 
> Where should I put the function?
> 
> a) Inside the module but outside the class (to avoid cluttering it;
> besides the function does not require to access any property or method
> of the class).
> 
> # mymodule.py
> 
> def  _myfunction():
> ...
> 
> class myclass(object):
> def mymethod(self):
>  ...
>  spam = _myfunction()
>...
> 
> 
> b) Inside the class but outside the method
> 
> # mymodule.py
> 
> class myclass(object):
> def  _myfunction(self):
> ...
> 
> def mymethod(self):
>  ...
>  spam = self._myfunction()
>...
> 
> c) Inside the method:
> 
> # mymodule.py
> 
> class myclass(object):
> ...
> def mymethod(self):
> def  _myfunction(self):
>   ...
> ...
> spam = self._myfunction()
> ...
> 
> 
> I'm new to python (and couldn't find anything about this in PEP 8).
> What would you suggest me?

If it really has no other use as in this class, put it as an 
instancemethod in there. Alternatively, you _could_ nest it like this:

class Foo(object):

def bar(self):
def my_long_important_method(argument):
pass
pass


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


Best place for a function?

2007-03-07 Thread Sergio Correia
I'm writing a class, where one of the methods is kinda complex. The
method uses a function which I know for certain will not be used
anywhere else. This function does not require anything from self, only
the args passed by the method.

Where should I put the function?

a) Inside the module but outside the class (to avoid cluttering it;
besides the function does not require to access any property or method
of the class).

# mymodule.py

def  _myfunction():
 ...

class myclass(object):
 def mymethod(self):
  ...
  spam = _myfunction()
...


b) Inside the class but outside the method

# mymodule.py

class myclass(object):
 def  _myfunction(self):
 ...

 def mymethod(self):
  ...
  spam = self._myfunction()
...

c) Inside the method:

# mymodule.py

class myclass(object):
 ...
 def mymethod(self):
 def  _myfunction(self):
   ...
 ...
 spam = self._myfunction()
 ...


I'm new to python (and couldn't find anything about this in PEP 8).
What would you suggest me?

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


Re: catching exceptions from an except: block

2007-03-07 Thread Bruno Desthuilliers
Arnaud Delobelle a écrit :
> On Mar 7, 8:52 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> [snip]
> 
>>Without knowing more about the functions and the variable it is somewhat
>>hard to tell what you are trying to accomplish.  If a, b, c are functions
>>that act on x when it is a different type, change to one function that
>>can handle all types.
> 
> 
> I'm not really thinking about this situation so let me clarify. Here
> is a simple concrete example, taking the following for the functions
> a,b,c I mention in my original post.
>   - a=int
>   - b=float
>   - c=complex
>   - x is a string
> This means I want to convert x to an int if possible, otherwise a
> float, otherwise a complex, otherwise raise CantDoIt.
> 
> I can do:
> 
> for f in int, float, complex:
> try:
> return f(x)
> except ValueError:
> continue
> raise CantDoIt
> 
> But if the three things I want to do are not callable objects but
> chunks of code this method is awkward because you have to create
> functions 

You have to write the "chunks of code" anyway, don't you ? So just 
adding a def statement above each chunk is not such a big deal.

Remember that you can define nested funcs, that will close over the 
namespace of the enclosing one, so you dont necessarily have to pollute 
the global namespace nor explicitly pass the whole environment to each 
of these functions.

Using the generic higher order func I proposed in a previous answer:

def maincode(tati, pouffin):
   def a():
 # some
 # code
 # here
 # that may raise
 return foo

   def b():
 # some
 # shorter chunk
 return bar

   def c():
 # yet
 # some
 # other
 # code
 return quux

   return trythese(a, b)()

Is it really less readable than:

def maincode(tati, pouffin):
   try:
 # some
 # code
 # here
 # that may raise
 return foo

   except_retry: # the missing(???) keyword you're after
 # some
 # shorter chunk
 return bar

   except_retry:
 # yet
 # some
 # other
 # code
 return quux

   else:
 raise CantDoIt


> simply in order to be able to loop over them (this is whay I
> was talking about 'abusing loop constructs').  Besides I am not happy
> with the other two idioms I can think of.
> 
> --
> Arnaud
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2007-03-07 Thread Brian Adkins
George Sakkis wrote:
> [EMAIL PROTECTED] wrote:
> 
>> 1. Lisp is the only industrial strength language
>   ^^^
> You keep using that phrase. I don't think it means what you think it
> means.

[Vizzini has just cut the rope The Dread Pirate Roberts is climbing up]
Vizzini: HE DIDN'T FALL? INCONCEIVABLE.
Inigo Montoya: You keep using that word. I do not think it means what 
you think it means.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Direct memory access

2007-03-07 Thread Collin Stocks

One last thing. Does anyone know how to take a python object and measure how
much space it is taking up in memory? I'm thinking probably not, but it's
worth asking.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: catching exceptions from an except: block

2007-03-07 Thread Gabriel Genellina
En Wed, 07 Mar 2007 18:48:18 -0300, Arnaud Delobelle  
<[EMAIL PROTECTED]> escribió:

> for f in int, float, complex:
> try:
> return f(x)
> except ValueError:
> continue
> raise CantDoIt
>
> But if the three things I want to do are not callable objects but
> chunks of code this method is awkward because you have to create
> functions simply in order to be able to loop over them (this is whay I
> was talking about 'abusing loop constructs').  Besides I am not happy
> with the other two idioms I can think of.

Hmmm, functions are cheap - nobody is charging you $2 for each "def"  
statement you write, I presume :)

A bit more serious, if those "chunks of code" are processing its input and  
returning something that you further process... they *are* functions. If  
you don't want them to be publicly available, use inner functions:

def xxxfactory(x):
   def f1(x):
  ...
   def f2(x):
  ...
   def f3(x):
  ...

   for f in f1,f2,f3:
 try:
   return f(x)
   ... same as above...

-- 
Gabriel Genellina

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


Re: catching exceptions from an except: block

2007-03-07 Thread garrickp
On Mar 7, 3:04 pm, [EMAIL PROTECTED] wrote:
> On Mar 7, 2:48 pm, "Arnaud Delobelle" <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > I'm not really thinking about this situation so let me clarify. Here
> > is a simple concrete example, taking the following for the functions
> > a,b,c I mention in my original post.
> >   - a=int
> >   - b=float
> >   - c=complex
> >   - x is a string
> > This means I want to convert x to an int if possible, otherwise a
> > float, otherwise a complex, otherwise raise CantDoIt.
>
> > I can do:
>
> > for f in int, float, complex:
> > try:
> > return f(x)
> > except ValueError:
> > continue
> > raise CantDoIt
>
> > But if the three things I want to do are not callable objects but
> > chunks of code this method is awkward because you have to create
> > functions simply in order to be able to loop over them (this is whay I
> > was talking about 'abusing loop constructs').  Besides I am not happy
> > with the other two idioms I can think of.
>
> > --
> > Arnaud
>
> Wouldn't it be easier to do:
>
> if isinstance(x, int):
> # do something
> elif isinstance(x, float)t:
> # do something
> elif isinstance(x, complex):
> # do something
> else:
> raise CantDoIt
>
> or,
>
> i = [int, float, complex]
> for f in i:
> if isinstance(x, f):
> return x
> else:
> raise CantDoIt

I so missed the point of this. Not my day. Please ignore my post.

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


Re: catching exceptions from an except: block

2007-03-07 Thread Bruno Desthuilliers
Gabriel Genellina a écrit :
> En Wed, 07 Mar 2007 19:00:59 -0300, Bruno Desthuilliers  
> <[EMAIL PROTECTED]> escribió:
> 
>> this kind of cose is exactly what OO polymorphic dispatch is supposed to
> 
> 
> this kind of cose?

sorry
s/cose/code/

> Ce genre de chose?
> 
En quelques sortes, oui, quoique pas tout à fait !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python 2.1 and Daylight saving time

2007-03-07 Thread skip
removing webmaster email address...

Others reading this with more experience manipulating timezones please
reply.  This is completely out of the realm of my experience, but since I
pointed Wayne here from the webmaster mailing list I felt I should respond.
What I've written is based solely on reading a bit of the current time
module documentation and peeking at the time module source
(ever-so-briefly).

Wayne> I mainly needed to know if I could avert Daylight Saving Time
Wayne> issues by upgrading to Python 2.5.

Wayne> It appears that Python gets it UTC settings from a table in the C
Wayne> library. Does this still hold true for Python 2.5. It looks that
Wayne> it will fail to recognize the new DST 2007 changes.

Python's timezone code is reliant on the functions provided by your system's
libc routines.  Starting in Python 2.3 if your system has a working tzset()
function in libc the time module exposes a tzset() function which you can
use to change the rules used by your system.  If your system's timezone
information hasn't been updated I imagine you could coax the correct
behavior out of your application with tzset().  I suggest you read the
relevant documentation

http://docs.python.org/dev/lib/module-time.html

before contemplating upgrading from 2.1 to something more recent and/or
modifying your application to use tzset().  Given the minimal amount of time
between now and Sunday morning I suspect your best chance of correct
operation will be to have the correct timezone tables installed on your
computer.

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


Re: catching exceptions from an except: block

2007-03-07 Thread garrickp
On Mar 7, 2:48 pm, "Arnaud Delobelle" <[EMAIL PROTECTED]> wrote:
>
> I'm not really thinking about this situation so let me clarify. Here
> is a simple concrete example, taking the following for the functions
> a,b,c I mention in my original post.
>   - a=int
>   - b=float
>   - c=complex
>   - x is a string
> This means I want to convert x to an int if possible, otherwise a
> float, otherwise a complex, otherwise raise CantDoIt.
>
> I can do:
>
> for f in int, float, complex:
> try:
> return f(x)
> except ValueError:
> continue
> raise CantDoIt
>
> But if the three things I want to do are not callable objects but
> chunks of code this method is awkward because you have to create
> functions simply in order to be able to loop over them (this is whay I
> was talking about 'abusing loop constructs').  Besides I am not happy
> with the other two idioms I can think of.
>
> --
> Arnaud

Wouldn't it be easier to do:

if isinstance(x, int):
# do something
elif isinstance(x, float)t:
# do something
elif isinstance(x, complex):
# do something
else:
raise CantDoIt

or,

i = [int, float, complex]
for f in i:
if isinstance(x, f):
return x
else:
raise CantDoIt

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


Re: Direct memory access

2007-03-07 Thread Collin Stocks

Thanks. I didn't know about ctypes.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: catching exceptions from an except: block

2007-03-07 Thread Bruno Desthuilliers
Arnaud Delobelle a écrit :
> Hi all,
> 
> Imagine I have three functions a(x), b(x), c(x) that each return
> something or raise an exception.  Imagine I want to define a function
> that returns a(x) if possible, otherwise b(x), otherwise c(x),
> otherwise raise CantDoIt.
> 
> Here are three ways I can think of doing it:
> 
> --
> # This one looks ugly

Yes.

> def nested_first(x):
> try:
> return a(x)
> except:


Try avoiding bare except clauses. It's usually way better to specify the 
type(s) of exception you're expecting to catch, and let other propagate.


> try:
> return b(x)
> except:
> try:
> return c(x)
> except:
> raise CantDoIt
> 
> # This one looks long-winded

Yes. And not's very generic.

> def flat_first(x):
> try:
> return a(x)
> except:
> pass
> try:
> return b(x)
> except:
> pass
> try:
> return c(x)
> except:
> raise CantDoIt
> 
> # This one only works because a,b,c are functions

It works with any callable. Anyway, what else would you use here ???

> # Moreover it seems like an abuse of a loop construct to me

Why so ? loops are made for looping, adn functions are objects like any 
other.

> def rolled_first(x):
> for f in a, b, c:
> try:
> return f(x)
> except:
> continue
> raise CantDoIt

Here's an attempt at making it a bit more generic (it still 
lacks a way to specify which kind of exceptions should be silently 
swallowed.

def trythese(*functions):
   def try_(*args, **kw):
 for func in functions:
try:
  return func(*args, **kw)
except: # FIX ME : bare except clause
  pass
 else:
   # really can't do it, sorry
   raise CantDoIt
   return try_

result = trythese(a, b, c)(x)

> --
> # This one isn't correct but looks the clearest to me
> def wished_first(x):
> try:
> return a(x)
> except:
> return b(x)
> except:
> return c(x)
> except:
> raise CantDoIt

Having multiple except clauses is correct - but it has another semantic.


> Note: I've chosen functions a, b, c, but really I'm looking for a way
> that is suitable for any chunk of code.

A function is an object wrapping a chunk of code...

I personnaly find the loop-based approach quite clean and pythonic.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: catching exceptions from an except: block

2007-03-07 Thread Arnaud Delobelle
On Mar 7, 8:52 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
[snip]
> Without knowing more about the functions and the variable it is somewhat
> hard to tell what you are trying to accomplish.  If a, b, c are functions
> that act on x when it is a different type, change to one function that
> can handle all types.

I'm not really thinking about this situation so let me clarify. Here
is a simple concrete example, taking the following for the functions
a,b,c I mention in my original post.
  - a=int
  - b=float
  - c=complex
  - x is a string
This means I want to convert x to an int if possible, otherwise a
float, otherwise a complex, otherwise raise CantDoIt.

I can do:

for f in int, float, complex:
try:
return f(x)
except ValueError:
continue
raise CantDoIt

But if the three things I want to do are not callable objects but
chunks of code this method is awkward because you have to create
functions simply in order to be able to loop over them (this is whay I
was talking about 'abusing loop constructs').  Besides I am not happy
with the other two idioms I can think of.

--
Arnaud

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


Re: catching exceptions from an except: block

2007-03-07 Thread Gabriel Genellina
En Wed, 07 Mar 2007 19:00:59 -0300, Bruno Desthuilliers  
<[EMAIL PROTECTED]> escribió:

> this kind of cose is exactly what OO polymorphic dispatch is supposed to

this kind of cose? Ce genre de chose?

-- 
Gabriel Genellina

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


Re: catching exceptions from an except: block

2007-03-07 Thread Bruno Desthuilliers
Larry Bates a écrit :
(snip)

> def d(x):
> if isinstance(x, basestring):
> #
> # Code here for string
> #
> elif isinstance(x, int):
> #
> # Code here for int
> #
> elif isinstance(x, float):
> #
> # Code here for string
> #
> else:
> raise ValueError

As a side note : While there are a few corner cases where this is hardly 
avoidable (and yet I'd rather test on interface, not on concrete type), 
this kind of cose is exactly what OO polymorphic dispatch is supposed to 
avoid (no, don't tell me: I know you can't easily add methods to most 
builtin types).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: catching exceptions from an except: block

2007-03-07 Thread Bruno Desthuilliers
Miki a écrit :
> Hello Arnaud,
> 
> 
>>Imagine I have three functions a(x), b(x), c(x) that each return
>>something or raise an exception.  Imagine I want to define a function
>>that returns a(x) if possible, otherwise b(x), otherwise c(x),
>>otherwise raise CantDoIt.
> 
> Exceptions are for error handling, not flow control.

def until(iterable,sentinel):
   for item in iterable:
 if item == sentinel:
   raise StopIteration
 yield item

 >>> for item in until(range(10), 5):
... print item
...
0
1
2
3
4
 >>>

Exceptions *are* a form of flow control.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Debugging segmentation faults

2007-03-07 Thread John Nagle
You're using Python on a web server to do something
complicated.  You must suffer.

Are you trying to fork off a subprocess in a multithreaded
program?  That's unlikely to work.  The sematics differ
from OS to OS (Solaris forks all the threads, most other
operating systems don't; most UNIX-based OSs copy all the
open file descriptors, but some give you control of which
open files are passed), and Python may not be thread-safe
in that area.

John Nagle

SPE - Stani's Python Editor wrote:
> If the error is reproducable and you can run wxPython, you could use
> the excellent WinPdb debugger, which ships with SPE (python editor):
> http://www.digitalpeers.com/pythondebugger/
> 
> ... but if you can only run your script on a remote server this won't
> help you.
> 
> Stani
> 
> --
> SPE - http://pythonide.stani.be
> 
> On 7 Mrz., 20:15, "George Sakkis" <[EMAIL PROTECTED]> wrote:
> 
>>I have a pure python program (no C extensions) that occasionally core
>>dumps in a non-reproducible way. The program is started by a (non-
>>python) cgi script when a form is submitted. It involves running a
>>bunch of other programs through subprocess in multiple threads and
>>writing its output in several files. So the only suspicious parts I
>>can think of is subprocess and/or multithreading. For the
>>multithreading part I'm using a modified version of threadpool.py
>>(http://www.chrisarndt.de/en/software/python/threadpool/), which is
>>built on top of the threading and Queue stdlib modules. Whatever bugs
>>may linger there, I'd hope that they would show up as normal Python
>>exceptions instead of segfaults.
>>
>>All I have now is a few not particularly insightful core files (actual
>>path names and args changed for privacy):
>>
>>/home/gsakkis/foo>gdb --core core.20140
>>GNU gdb Red Hat Linux (5.2-2)
>>Copyright 2002 Free Software Foundation, Inc.
>>GDB is free software, covered by the GNU General Public License, and
>>you are
>>welcome to change it and/or distribute copies of it under certain
>>conditions.
>>Type "show copying" to see the conditions.
>>There is absolutely no warranty for GDB.  Type "show warranty" for
>>details.
>>This GDB was configured as "i386-redhat-linux".
>>Core was generated by `python2.5 /home/gsakkis/foo/foo.py --XXX --
>>max=30 --bar=/tmp/83840`
>>Program terminated with signal 11, Segmentation fault.
>>#0  0x080b222d in ?? ()
>>(gdb) backtrace
>>#0  0x080b222d in ?? ()
>>#1  0x080b28d1 in ?? ()
>>#2  0x080fa8ab in ?? ()
>>#3  0x0805c918 in ?? ()
>>(...)
>>#28 0x080b310f in ?? ()
>>#29 0x080dbfdd in ?? ()
>>#30 0x40021fef in ?? ()
>>
>>Any hints ?
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generator expression parenthesis mixed with function call ones

2007-03-07 Thread Gabriel Genellina
En Wed, 07 Mar 2007 15:21:57 -0300, Laurent Pointal  
<[EMAIL PROTECTED]> escribió:

> Gabriel Genellina wrote:
>
>> En Wed, 07 Mar 2007 12:53:43 -0300, Laurent Pointal
>> <[EMAIL PROTECTED]> escribió:
>>
>>> Why does Python allow generator expression parenthesis to be mixed with
>>> function call parenthesis when there is only one parameter ?
>Beginners generally know about list-comprehensions and associate the
> syntax "x for x in asequence" to a list expression. I'm not sure that

But list comprehensions have [] around... When you don't see the [], you  
should think "this is something different"...

> reading a "f(i for i in range(20))" they understand that they are dealing
> with a different object kind.

Exactly.

> If function f start by a if len(myparameter)...
>   TypeError: len() of unsized object
>
> If function f goes among its parameter with "for x in myparameter" more  
> than
> once, other loops goes throught an empty loop.

Then he thinks "Something is wrong!", and reads some Python books, or asks  
here, and somebody will point him to the Python Tutorial, section 9.11:  
http://docs.python.org/tut/node11.html#SECTION000

>>> IMHO this should be forbidden, usage must not be different when there  
>>> is only one parameter and when there are more parameters.

If you want to review the original discussion on how to spell a generator  
expression (called "accumulator display" by that time) see  
http://mail.python.org/pipermail/python-dev/2003-October/038868.html

-- 
Gabriel Genellina

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


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-07 Thread Robert Kern
John wrote:
> Then is there anyway to sort the numeric keys and avoid future implemetation 
> confusion?

sorted(mydict.keys())

-- 
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: Why does SocketServer default allow_reuse_address = false?

2007-03-07 Thread Joshua J. Kugler
Chris Mellon wrote:
>> My problem (and the reason I set reuse to True) is this: if I have
>> connections active when I restart my service, upon restart, the socket
>> will
>> fail to bind because there is still a connection in a WAIT state.
> 
> This is just the way sockets work on your platform. How exactly
> sockets shut down, and the exact effect that SO_REUSEADDR varies from
> platform to platform. In your case, using it is probably reasonable.

Thank you.  Glad to know I've chosen the best solution for my situation.

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

-- 
Posted via a free Usenet account from http://www.teranews.com

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

Re: Debugging segmentation faults

2007-03-07 Thread SPE - Stani's Python Editor
If the error is reproducable and you can run wxPython, you could use
the excellent WinPdb debugger, which ships with SPE (python editor):
http://www.digitalpeers.com/pythondebugger/

... but if you can only run your script on a remote server this won't
help you.

Stani

--
SPE - http://pythonide.stani.be

On 7 Mrz., 20:15, "George Sakkis" <[EMAIL PROTECTED]> wrote:
> I have a pure python program (no C extensions) that occasionally core
> dumps in a non-reproducible way. The program is started by a (non-
> python) cgi script when a form is submitted. It involves running a
> bunch of other programs through subprocess in multiple threads and
> writing its output in several files. So the only suspicious parts I
> can think of is subprocess and/or multithreading. For the
> multithreading part I'm using a modified version of threadpool.py
> (http://www.chrisarndt.de/en/software/python/threadpool/), which is
> built on top of the threading and Queue stdlib modules. Whatever bugs
> may linger there, I'd hope that they would show up as normal Python
> exceptions instead of segfaults.
>
> All I have now is a few not particularly insightful core files (actual
> path names and args changed for privacy):
>
> /home/gsakkis/foo>gdb --core core.20140
> GNU gdb Red Hat Linux (5.2-2)
> Copyright 2002 Free Software Foundation, Inc.
> GDB is free software, covered by the GNU General Public License, and
> you are
> welcome to change it and/or distribute copies of it under certain
> conditions.
> Type "show copying" to see the conditions.
> There is absolutely no warranty for GDB.  Type "show warranty" for
> details.
> This GDB was configured as "i386-redhat-linux".
> Core was generated by `python2.5 /home/gsakkis/foo/foo.py --XXX --
> max=30 --bar=/tmp/83840`
> Program terminated with signal 11, Segmentation fault.
> #0  0x080b222d in ?? ()
> (gdb) backtrace
> #0  0x080b222d in ?? ()
> #1  0x080b28d1 in ?? ()
> #2  0x080fa8ab in ?? ()
> #3  0x0805c918 in ?? ()
> (...)
> #28 0x080b310f in ?? ()
> #29 0x080dbfdd in ?? ()
> #30 0x40021fef in ?? ()
>
> Any hints ?


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


Re: catching exceptions from an except: block

2007-03-07 Thread Larry Bates
Arnaud Delobelle wrote:
> Hi all,
> 
> Imagine I have three functions a(x), b(x), c(x) that each return
> something or raise an exception.  Imagine I want to define a function
> that returns a(x) if possible, otherwise b(x), otherwise c(x),
> otherwise raise CantDoIt.
> 
> Here are three ways I can think of doing it:
> 
> --
> # This one looks ugly
> def nested_first(x):
> try:
> return a(x)
> except:
> try:
> return b(x)
> except:
> try:
> return c(x)
> except:
> raise CantDoIt
> 
> # This one looks long-winded
> def flat_first(x):
> try:
> return a(x)
> except:
> pass
> try:
> return b(x)
> except:
> pass
> try:
> return c(x)
> except:
> raise CantDoIt
> 
> # This one only works because a,b,c are functions
> # Moreover it seems like an abuse of a loop construct to me
> def rolled_first(x):
> for f in a, b, c:
> try:
> return f(x)
> except:
> continue
> raise CantDoIt
> --
> 
> I don't feel happy with any of these.  Is there a more satisfying way
> of doing this in Python? What I would like is something like:
> 
> --
> # This one isn't correct but looks the clearest to me
> def wished_first(x):
> try:
> return a(x)
> except:
> return b(x)
> except:
> return c(x)
> except:
> raise CantDoIt
> --
> 
> I guess what I'm looking for is some sort of
> if:
> elif:
> ...
> elif:
> else:
> 
> but for try: except:
> That's why
> try:
> except:
> except:
> ...
> except:
> 
> seemed natural to me :)  And I'd like to find a nice way to do this in
> a syntactically correct way.
> 
> Note: I've chosen functions a, b, c, but really I'm looking for a way
> that is suitable for any chunk of code.
> 
Without knowing more about the functions and the variable it is somewhat
hard to tell what you are trying to accomplish.  If a, b, c are functions
that act on x when it is a different type, change to one function that
can handle all types.

def d(x):
if isinstance(x, basestring):
#
# Code here for string
#
elif isinstance(x, int):
#
# Code here for int
#
elif isinstance(x, float):
#
# Code here for string
#
else:
raise ValueError


If they are different functions based on type do something like this:

#
# Set up a dictionary with keys for different types and functions
# that correspond.
#
fdict={type(''): a, type(1): b, type(1.0): c}
#
# Call the appropriate function based on type
#
fdict[type(x)](x)

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


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-07 Thread John
Then is there anyway to sort the numeric keys and avoid future implemetation 
confusion?


"Ant" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Mar 7, 8:18 pm, "John" <[EMAIL PROTECTED]> wrote:
> ...
>> However, I am not sure whether it is always like this. Can anybody 
>> confirm
>> my finding?
>
>>From the standard library docs:
>
> "Keys and values are listed in an arbitrary order which is non-random,
> varies across Python implementations, and depends on the dictionary's
> history of insertions and deletions."
>
> i.e. the behaviour you have discovered is an implementation detail,
> and could change in future versions.
> 


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


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-07 Thread Carsten Haese
On Wed, 2007-03-07 at 15:18 -0500, John wrote:
> I am coding a radix sort in python and I think that Python's dictionary may 
> be a choice for bucket.
> 
> The only problem is that dictionary is a mapping without order. But I just 
> found that if the keys are numeric, the keys themselves are ordered in the 
> dictionary.

No.

The sequence of keys in a dictionary is a coincidental side effect of
the particular Python implementation, the number of keys, the values of
the keys, and the order in which the keys are inserted. You must not
rely on the keys appearing in any particular order.

Here is a simple counterexample that breaks the ordering, at least for
the version I'm running:

>>> d = {}
>>> for i in range(0,6): d[10**i] = []
... 
>>> d
{10: [], 1: [], 100: [], 1000: [], 10: [], 1: []}

-Carsten


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


Re: Is numeric keys of Python's dictionary automatically sorted?

2007-03-07 Thread Ant
On Mar 7, 8:18 pm, "John" <[EMAIL PROTECTED]> wrote:
...
> However, I am not sure whether it is always like this. Can anybody confirm
> my finding?

>From the standard library docs:

"Keys and values are listed in an arbitrary order which is non-random,
varies across Python implementations, and depends on the dictionary's
history of insertions and deletions."

i.e. the behaviour you have discovered is an implementation detail,
and could change in future versions.

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


Re: finding monitor or screen resolution in Linux with standard python module

2007-03-07 Thread consmash
On Mar 7, 11:25 am, "akbar" <[EMAIL PROTECTED]> wrote:
> I googled and searched in archive. All I can find is finding
> resolution with Tkinter and pygame. Any idea to find monitor
> resolution with standard python module?
> I can check from output of: xprop -root
> _NET_DESKTOP_GEOMETRY(CARDINAL) . The problem is when you use Beryl or
> Xgl, it is not correct anymore because Beryl or Xgl set this value
> from amount of workspaces multiplied by monitor or screen resolution.

A method 'screen' from Python X Library looks promising:
http://python-xlib.sourceforge.net/doc/html/python-xlib_16.html#SEC15

More, or less if I understand right you just need to request from
server dimensions of the screen, over x protocol of course. So it will
be something associated with Xlib.

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


Re: Direct memory access

2007-03-07 Thread Travis Oliphant
Collin Stocks wrote:
> Does anyone know how to directly handle memory using python?
> I want to be able, for example, to copy the actual contents of a memory 
> address, or set the actual contents of a memory address.

This kind of thing is generally not what Python is used for, so it's not 
really easy to do.

Writing to arbitrary memory areas is an easy way to cause segmentation 
violations which Python and its extensions try to make segmentation 
violations (memory violations) as near impossible as they can.

If you really need to do this then you can use ctypes to do it.

Let N be the number of bytes you want to access, then

import ctypes
g = (ctypes.c_char*N).from_address(addr)

g is now a settable sequence of bytes that you can read and write to 
using strings.

g[0]  # read the first byte
g[1]  # read the second byte

g[0] = '\x24' # set the first byte to hexadecimal 24

etc...

If you don't have permission to write to addr then you will get memory 
violations and your program will crash if you try to read from or write 
to the resulting sequence.

-Travis


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


More M2Crypto build problems

2007-03-07 Thread John Nagle
Trying to build M2Crypto on a dedicated server running Red Hat Fedora Core 6.
I'm trying to do this right, without manual patching.

The error message I'm getting during build is:

python setup.py build
...
swig -python -I/usr/include -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i
/usr/include/openssl/opensslconf.h:27: Error: CPP #error ""This openssl-devel 
package does not work your architecture?"". Use the -cpperraswarn option to 
continue swig processing.
error: command 'swig' failed with exit status 1

We went through this before, but last time, the versions of OpenSSL and
of SWIG on the system were old, and I was running on a shared server
and couldn't update it.  Eventually, M2Crypto was hammered
into working, but it was ugly.  It was necessary to patch "setup.py" as
follows:

107,108d106
< target_cpu_str = '-D__i386__' # PATCH - assume Intel target. OpenSSL build 
needs this.
<
 > 116c114
<  swig_opts = [swig_opts_str,target_cpu_str]
---
 >  swig_opts = [swig_opts_str]

The problem is that the include file in OpenSSL assumes that some
system ID, like __i386__, is defined, which GCC does, but SWIG
does not. It might be considered a bug in SWIG.

This time, everything on the dedicated server has been updated with Yum,
so it ought to just work.

Yum says:
 >
 > Installed Packages
 > openssl.i686 0.9.8a-5.4 installed
 > openssl-devel.i386   0.9.8a-5.4 installed
 > python.i386  2.4.3-9.FC5installed
 > swig.i3861.3.31-0.fc5   installed
 > Available Packages
 > openssl.i386 0.9.8a-5.4 updates

All of those are later than the ones required for M2Crypto, so the system
should be current.
 >
But it doesn't.

Also reported as a SWIG bug, as #1676049.

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


  1   2   >