Re: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-21 Thread zaley
Of course, python scripts debugger

On 2月22日, 下午3时22分, zaley <[EMAIL PROTECTED]> wrote:
> My project need a simple scripts debugger . I hope I can find
> something instructive
>
> Stefan Behnel 写道:
>
> > zaley wrote:
> > > Is there a open souce IDE writen by C( C++) or partly writen by C( C+
> > > +)?
>
> > Tons of them. What do you want to do with it?
>
> > Stefan

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

Re: distutils and data files

2008-02-21 Thread Sam Peterson
Robert Bossy <[EMAIL PROTECTED]> on Wed, 20 Feb 2008 09:29:12
+0100 didst step forth and proclaim thus:

> Sam Peterson wrote:
>> I've been googling for a while now and cannot find a good way to deal
>> with this.
>>
>> I have a slightly messy python program I wrote that I've historically
>> just run from the extracted source folder.  I have pictures and sound
>> files in this folder that this program uses.  I've always just used
>> the relative path names of these files in my program.
>>
>> Lately, I had the idea of cleaning up my program and packaging it with
>> distutils, but I've been stuck on a good way to deal with these
>> resource files.  The package_data keyword seems to be the way to go,
>> but how can I locate and open my files once they've been moved?  In
>> other words, what should I do about changing the relative path names?
>> I need something that could work from both the extracted source
>> folder, AND when the program gets installed via the python setup.py
>> install command.
>>   
> This seems to be a classic distutils  question:  how a python module
> can access to data files *after* being installed?

Man, I was afraid of that.  Python is an awesome language, but this is
yet another instance of seeing something in the standard library
sucking.

> The following thread addresses this issue:
>http://www.gossamer-threads.com/lists/python/python/163159
>
> Carl Banks' solution seems to overcome the problem: his trick is to
> generate an additional configuration module with the relevant
> informations from the distutil data structure. However it is quite an
> old thread (2003) and I don't know if there has been progress made
> since then, maybe the distutils module now incorporates a similar
> mechanism.

Not if the documentation for 2.5's got anything to say about it.  If
it does, it's well hidden.

I think I'll kill the idea of using distutils for my program.  It
seems like distutils was primarily designed for modules and
extensions.

-- 
Sam Peterson
skpeterson At nospam ucdavis.edu
"if programmers were paid to remove code instead of adding it,
software would be much better" -- unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-21 Thread zaley
My project need a simple scripts debugger . I hope I can find
something instructive

Stefan Behnel 写道:
> zaley wrote:
> > Is there a open souce IDE writen by C( C++) or partly writen by C( C+
> > +)?
>
> Tons of them. What do you want to do with it?
>
> Stefan
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Return value of an assignment statement?

2008-02-21 Thread Ben Finney
Jeff Schwab <[EMAIL PROTECTED]> writes:

> Aahz wrote:
> > Notice very very carefully that Bruno is not using "variable".
> > Many expert Python programmers strongly prefer to talk about
> > "names" instead of "variables" (especially when explaining the
> > Python object model) precisely because using "variable" leads to
> > incorrect expectations.
> >
> > http://starship.python.net/crew/mwh/hacks/objectthink.html
> 
> So what is the "variable?" Or is Python the first HLL I've ever
> heard of that didn't have variables?

I don't know what HLLs you've heard of. I would bet that some of them
are languages which don't have "variables" *with all that the term
implies to most programmers*.

You don't have to go very far to find Python programmers using the
term "variable". What Aahz is pointing out is that the concepts that
people sloppily refer to by the term "variable" don't behave in Python
the way a programmer might expect who has used that term in reference
to concepts native to other languages.

Hence the term requires careful definition, and it's often best simply
not to use it and use the better analogy of "names" and "binding"
instead.

-- 
 \ "Pinky, are you pondering what I'm pondering?" "I think so, |
  `\Brain, but if the plural of mouse is mice, wouldn't the plural |
_o__)   of spouse be spice?"  -- _Pinky and The Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Carl Banks
On Feb 22, 12:23 am, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Carl Banks wrote:
> > On Feb 21, 7:17 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> >> Carl Banks wrote:
> >>> On Feb 21, 1:22 pm, Nicola Musatti <[EMAIL PROTECTED]> wrote:
>  There are other downsides to garbage collection, as the fact that it
>  makes it harder to implement the Resource Acquisition Is
>  Initialization idiom, due to the lack of deterministic destruction.
> >>> That's not a downside: it's at least a wash.
> >>> In C++ you manage memory and the language manages resourcewithout bringing
> anything of particular value to the table.s.  In
> >>> Python you manage resources and the language manages memory.
> >>> RAII is merely one way of minimizing complexity.  Garbage collection
> >>> is another way.
> >> If you've already got a generic, language-supported way to manage
> >> resources (like RAII with deterministic destruction), then why bother
> >> with garbage collection?
>
> > Because now you have to manage memory?  Did you read my post?  You
> > have to manage one thing or the other.
>
> Yes, I read your post.  You seem to be saying there's some kind of
> trade-off between automatic management of dynamically allocated memory,
> and automated management of other kinds of resources.  I don't
> understand why you believe that, so I asked.
>
> If you have proper RAII and deterministic destruction, the management is
> of resources is consistent, and mostly automated.

If you have garbage collection, the management of memory is
consistent, and mostly automated.

> Managing memory is
> just not that difficult,

Managing resources is just not that difficult,

> especially if the vast majority of objects are
> allocated on the stack or in static memory.

Especially if the there are fewer resources to manage than there would
have been heap objects

>  A special language feature
> for managing dynamically allocated memory robs the programmer of a
> reliable way to clean up resources automatically,

A special language feature more managing dynamically allocated robs
the programmer of a reliable way to free memory automatically,

> without bringing
> anything of particular value to the table.

without bringing
anything of particular value to the table.

It cuts both ways, chief.

You like managing your own memory, be my guest.  But please don't
imply that you're putting forth less effort because of it.  You're
just putting forth different effort.


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


n00b with urllib2: How to make it handle cookie automatically?

2008-02-21 Thread est
Hi all,

I need urllib2 do perform series of HTTP requests with cookie from
PREVIOUS request(like our browsers usually do ). Many people suggest I
use some library(e.g. pycURL) instead but I guess it's good practise
for a python beginner to DIY something rather than use existing tools.

So my problem is how to expand the urllib2 class

from cookielib import CookieJar
class SmartRequest():
cj=CookieJar()
def __init__(self, strUrl, strContent=None):
self.Request=   urllib2.Request(strUrl, strContent)
self.cj.add_cookie_header(self.Request)
self.Response   =   urllib2.urlopen(Request)
self.cj.extract_cookies(self.Response, self.Request)
def url
def read(self, intCount):
return self.Response.read(intCount)
def headers(self, strHeaderName):
return self.Response.headers[strHeaderName]

The code does not work because each time SmartRequest is initiated,
object 'cj' is cleared. How to avoid that?
The only stupid solution I figured out is use a global CookieJar
object. Is there anyway that could handle all this INSIDE the class?

I am totally new to OOP & python programming, so could anyone give me
some suggestions? Thanks in advance
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-21 Thread Stefan Behnel
zaley wrote:
> Is there a open souce IDE writen by C( C++) or partly writen by C( C+
> +)?

Tons of them. What do you want to do with it?

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


reg - timer........

2008-02-21 Thread Manikandan R
Hai..

 I have planned to access the web page via python coding, for that I
use

url = 'http:\\username:[EMAIL PROTECTED]'
urllib.urlopen(url)

   It opens fine when its correct web page else it hangs there  So I
have planned to start a timer when i launch the web page, if time exceeds it
will exit the thread. But I don't know how to do this can U please help me.

  Is there is any inbuilt command to do this.

 Note: I am going to open the web page via thread. Give me an idea
or code which will be helpful for me...

Thank's and Regard's,
R.Manikandan.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Return value of an assignment statement?

2008-02-21 Thread George Sakkis
On Feb 22, 12:26 am, Jeff Schwab <[EMAIL PROTECTED]> wrote:

> > On the other hand, "a = b" does always the same thing; unlike C++, '='
> > is not an operator and therefore it cannot be overriden by the class
> > of 'a'.
>
> "Not an operator?"  Then what is it?

In this context, it's just the token used for the assignment
statement. In short, if 'a' is an identifier, the statement means
"bind the name 'a' to the object 'b' (in the local or global
namespace)". It doesn't say anything about memory allocation,
initialization or copying. The only case where assigning an identifier
affects memory is the following [1]:

"""
The name is rebound if it was already bound. This may cause the
reference count for the object previously bound to the name to reach
zero, causing the object to be deallocated and its destructor (if it
has one) to be called.
"""

HTH,
George

[1] http://docs.python.org/ref/assignment.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Paul Rubin
George Sakkis <[EMAIL PROTECTED]> writes:
> Could Boo or Cobra fit the bill ? If not, what's missing at a
> technical level (i.e. ignoring current maturity, community size,
> marketing, etc.) ?

I just spent a minute looking at these and both are interesting,
though Cobra looks .NET specific and I'd rather have something that
makes standalone native executables.  Also, I don't see support in
either of these languages for higher-order functions, iterators,
libraries with powerful static datatypes, etc.  Also, no mention of
concurrency.  But, as I said, I only looked for a minute.

There is something called Links that looks interesting for web
programming:

  http://groups.inf.ed.ac.uk/links/

I don't know if it's still being worked on.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Torsten Bronger
Hallöchen!

Jeff Schwab writes:

> Aahz wrote:
>
>> [...]
>>
>> Notice very very carefully that Bruno is not using "variable".
>> Many expert Python programmers strongly prefer to talk about
>> "names" instead of "variables" (especially when explaining the
>> Python object model) precisely because using "variable" leads to
>> incorrect expectations.
>>
>> http://starship.python.net/crew/mwh/hacks/objectthink.html
>
> So what is the "variable?"  Or is Python the first HLL I've ever
> heard of that didn't have variables?

Since Python objects, names, their operations, and the syntax used
for it resemble very closely (but not completely) what is called
"variable" in other languages, Python names are mostly called
"variables", too.

But there is this one thing of changing mutable objects which may
also change the "value" of other "variables".  This can only be
understood if your nomenclature is strictly correct.

I find Python's model is this area great.  It makes many things
simpler and only one or two things more complicated.  I had my bad
experiences with it, too (e.g. initialising two lists with
"x_values=y_values=[]").  But only once per year I stumble over it.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Paul Rubin
Jeff Schwab <[EMAIL PROTECTED]> writes:
> So what is the "variable?"  Or is Python the first HLL I've ever heard
> of that didn't have variables?

I don't know what other HLL's you use, but some languages don't even
have mutable values.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Paul Rubin
Jeff Schwab <[EMAIL PROTECTED]> writes:
> The most traditional, easiest way to open a file in C++ is to use an
> fstream object, so the file is guaranteed to be closed when the
> fstream goes out of scope.  

Python has this too, except it's using a special type of scope
created by the "with" statement.

> CPython offers a similar feature, since
> you can create a temporary object whose reference count will become
> zero at the end of the statement where it is defined:

>  $ echo world >hello
>  $ python
>  >>> file('hello').read()
>  'world\n'

CPython does not guarantee that the reference count will become zero
at the end of the statement.  It only happens to work that way in your
example, because the file.read operation doesn't make any new
references to the file object anywhere.  Other code might well do
something different, especially in a complex multi-statement scope.
Your scheme's determinism relies on the programmer accurately keeping
track of reference counts in their head, which is precisely what
automatic resource management is supposed to avoid.  If you want
reliable destruction it's better to set it up explicitly, using
"with".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread George Sakkis
Paul Rubin wrote:

> It just seems to me that there is a killer language just around the
> corner, with Python's ease-of-use but with a serious compile-time type
> system, maybe some kind of cross between ML and Python.

Could Boo or Cobra fit the bill ? If not, what's missing at a
technical level (i.e. ignoring current maturity, community size,
marketing, etc.) ?

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


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
Aahz wrote:
> In article <[EMAIL PROTECTED]>,
> Jeff Schwab  <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>>> There's nothing like a variable "storing" anything in Python. All you
>>> have are names to (references to) objects binding in a namespace. Now
>>> the fact is that some types are mutable and other are not. In your
>>> above example, the augmented assignment does *not* rebind a, but
>>> invoke a.extend(). With integers, it would have rebind a. So while
>>> your observation is exact, your interpretation is wrong !-)
>> Thank you for the clarification.  For some reason, I had it in my head 
>> that ints were packed directly into the C structures that represent 
>> Python variables, in the same (union?) member that otherwise would store 
>> a pointer.
> 
> Notice very very carefully that Bruno is not using "variable".  Many
> expert Python programmers strongly prefer to talk about "names" instead
> of "variables" (especially when explaining the Python object model)
> precisely because using "variable" leads to incorrect expectations.
> 
> http://starship.python.net/crew/mwh/hacks/objectthink.html

So what is the "variable?"  Or is Python the first HLL I've ever heard 
of that didn't have variables?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
George Sakkis wrote:
> On Feb 21, 7:21 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>> Steve Holden wrote:
>>> Jeff Schwab wrote:
 [EMAIL PROTECTED] wrote:
>>> [...]
> Now there's no reason to feel nervous about this. All you have to
> remember is that Python never copy anything unless explicitely asked
> for.
 It's not that simple.  After a statement like:
 a = b
 Whether a and b denote the same object depends on what kind of object
 b represented in the first place.
>>> Surely this is exactly wrong. Is there a single example you can think of
>>> where
>>> a = b
>> a += b (my bad)
>>
>>> assert a is b, "Oops!"
>>> would raise and exception? Perhaps you meant to use an augmented
>>> assignment operation?
>> Why, yes I did!  Sorry about that.
> 
> It seems less surprising when you keep in mind that "+=" (and friends)
> can be syntax sugar for calling a method on the right hand side
> object: a += b <=> a.__iadd__(b). It's up to the class of 'a' to do
> whatever within this method (whether it's a good idea to do anything
> else other than modify 'self' in place is another thing). Would you be
> able to say anything about a.foo(b) without knowing what 'a' is ?

Yes: I would know that it didn't rebind a.


> The only difference is that for types that don't implement an
> augmented operator, "a `op`= b" translates to "a = a `op` b" for a
> binary operator `op`. There's no formal notion of mutable and
> immutable objects with respect to these operators; any class that
> doesn't implement them is "immutable" as far as augmented assignment
> goes (of course it may be mutated in other ways, e.g. by fiddling with
> a.__dict__ directly).

Thanks for explaining that.


> On the other hand, "a = b" does always the same thing; unlike C++, '='
> is not an operator and therefore it cannot be overriden by the class
> of 'a'.

"Not an operator?"  Then what is it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Jeff Schwab
Carl Banks wrote:
> On Feb 21, 7:17 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>> Carl Banks wrote:
>>> On Feb 21, 1:22 pm, Nicola Musatti <[EMAIL PROTECTED]> wrote:
 There are other downsides to garbage collection, as the fact that it
 makes it harder to implement the Resource Acquisition Is
 Initialization idiom, due to the lack of deterministic destruction.
>>> That's not a downside: it's at least a wash.
>>> In C++ you manage memory and the language manages resources.  In
>>> Python you manage resources and the language manages memory.
>>> RAII is merely one way of minimizing complexity.  Garbage collection
>>> is another way.
>> If you've already got a generic, language-supported way to manage
>> resources (like RAII with deterministic destruction), then why bother
>> with garbage collection?
> 
> Because now you have to manage memory?  Did you read my post?  You
> have to manage one thing or the other.

Yes, I read your post.  You seem to be saying there's some kind of 
trade-off between automatic management of dynamically allocated memory, 
and automated management of other kinds of resources.  I don't 
understand why you believe that, so I asked.

If you have proper RAII and deterministic destruction, the management is 
of resources is consistent, and mostly automated.  Managing memory is 
just not that difficult, especially if the vast majority of objects are 
allocated on the stack or in static memory.  A special language feature 
for managing dynamically allocated memory robs the programmer of a 
reliable way to clean up resources automatically, without bringing 
anything of particular value to the table.


>> I'm not trying to knock it; it was a big step
>> up from C-style "who forgot to delete a pointer" games.  It just seems
>> to me like a solution to something that's no longer a problem, at least
>> in well-written C++ code.  I'll take destructors over GC any day.
> 
> About 2% of the objects I creat have resources other than memory.  I
> would rather manage resources of 2% of objects than manage memory of
> 100%.

That's not how it works.  If I'm going to allocated a C++ object 
dynamically, I have to assign it to some kind of handle, anyway, so I 
might as well just use a smart pointer that will delete the object when 
there are no more references to it.  There is no extra effort involved.

The most traditional, easiest way to open a file in C++ is to use an 
fstream object, so the file is guaranteed to be closed when the fstream 
goes out of scope.  CPython offers a similar feature, since you can 
create a temporary object whose reference count will become zero at the 
end of the statement where it is defined:

 $ echo world >hello
 $ python
 >>> file('hello').read()
 'world\n'

It's graceful, easy to write, and a million times better than having to 
clean up the resource explicitly.  A book on Python I was reading 
recently (either Alex Martelli or Mark Lutz) used this idiom again and 
again, and every time had to have a footnote about how it wouldn't work 
right on (e.g.) JPython, because who knows if/when the resource-owning 
object's finalizer will ever get called.

Admittedly, you have to know enough to use the right kinds of objects, 
but that's something you have to learn anyway.


> YMMV, but I suspect mine is the more common opinion, if the
> recent (like, 10-year) trend in programming languages is any
> indication.

I agree that support for non-deterministic GC has grown very popular 
over the past ten years or so.  I don't think that is evidence of it 
being a good idea though; I suspect that opinion of being the product of 
widespread ignorance about alternatives to unpredictable GC.
-- 
http://mail.python.org/mailman/listinfo/python-list


Professional Grant Proposal Writing Workshop (April 2008: Vancouver, British Columbia)

2008-02-21 Thread Anthony Jones


The Grant Institute's Grants 101: Professional Grant Proposal Writing Workshop
 will be held in Vancouver, British Columbia, April 14 - 16, 2008. Interested development professionals, researchers, faculty, and graduate students should register as soon as possible, as demand means that seats will fill up quickly. Please forward, post, and distribute this e-mail to your colleagues and listservs. 
 
All participants will receive certification in professional grant writing from the Institute. For more information call (213) 817 - 5308 or visit The Grant Institute at www.thegrantinstitute.com.
 
Please find the program description below:
 
The Grant Institute
Grants 101: Professional Grant Proposal Writing Workshop
will be held in
Vancouver, British Columbia
April 14 - 16, 2008
8:00 AM - 5:00 PM
 

The Grant Institute's Grants 101 course is an intensive and detailed introduction to the process, structure, and skill of professional proposal writing. This course is characterized by its ability to act as a thorough overview, introduction, and refresher at the same time. In this course, participants will learn the entire proposal writing process and complete the course with a solid understanding of not only the ideal proposal structure, but a holistic understanding of the essential factors, 
which determine whether or not a program gets funded. Through the completion of interactive exercises and activities, participants will complement expert lectures by putting proven techniques into practice. This course is designed for both the beginner looking for a thorough introduction and the intermediate looking for a refresher course that will strengthen their grant acquisition skills. This class, simply put, is designed to get results by creating professional grant proposal writers. 

 
Participants will become competent program planning and proposal writing professionals after successful completion of the Grants 101 course. In three active and informative days, students will be exposed to the art of successful grant writing practices, and led on a journey that ends with a masterful grant proposal. 
 
Grants 101 consists of three (3) courses that will be completed during the three-day workshop. 
 
(1) Fundamentals of Program Planning
 
This course is centered on the belief that "it's all about the program." This intensive course will teach professional program development essentials and program evaluation. While most grant writing "workshops" treat program development and evaluation as separate from the writing of a proposal, this class will teach students the relationship between overall program planning and grant writing. 
 
(2) Professional Grant Writing
 

Designed for both the novice and experienced grant writer, this course will make each student an overall proposal writing specialist. In addition to teaching the basic components of a grant proposal, successful approaches, and the do's and don'ts of grant writing, this course is infused with expert principles that will lead to a mastery of the process. Strategy resides at the forefront of this course's intent to illustrate grant writing as an integrated, multidimensional, and dynamic endeavor. 
Each student will learn to stop writing the grant and to start writing the story. Ultimately, this class will illustrate how each component of the grant proposal represents an opportunity to use proven techniques for generating support.
 
(3) Grant Research
 

At its foundation, this course will address the basics of foundation, corporation, and government grant research. However, this course will teach a strategic funding research approach that encourages students to see research not as something they do before they write a proposal, but as an integrated part of the grant seeking process. Students will be exposed to online and database research tools, as well as publications and directories that contain information about foundation, corporation, and 
government grant opportunities. Focusing on funding sources and basic social science research, this course teaches students how to use research as part of a strategic grant acquisition effort.
 
Registration
$597.00 USD tuition includes all materials and certificates.
 
Each student will receive:
*The Grant Institute Certificate in Professional Grant Writing
*The Grant Institute's Guide to Successful Grant Writing
*The Grant Institute Grant Writer's Workbook with sample proposals, forms, and outlines
 
Registration Methods
 
1) On-Line - Complete the online registration form at www.thegrantinstitute.com under Register Now. We'll send your confirmation by e-mail. 
 
2) By Phone - Call (213) 817-5308 to register by phone. Our friendly Program Coordinators will be happy to assist you and answer your questions. 
 
3) By E-mail - Send an e-mail with your name, organization, and basic contact information to [EMAIL PROTECTED] and we will reserve your slot and send your Confirmation Packet. 
 
You have received this invitation due to 

Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Paul Rubin
Carl Banks <[EMAIL PROTECTED]> writes:
> FWIW, when I posted my comment about C++, I was mocking the article
> writer's notion that it was static typing and compile-time checking
> that made Java and C# "safer" for newbies, by presenting an example
> that clearly defied that.  I was taking it for granted the C++ is
> notoriously dangerous and newbie-unfriendly.

Well, sure, but the danger from C++ is precisely that it is untyped
(so you can dereference invalid pointers, etc).  Yes, C++ has a type
system, but it leaks, so the most you can say about it is that it's
better than nothing.  A better example than C++ might have been Ada,
which is in fact designed to be newbie-friendly in the sense that one
of its design criteria is that engineers who are not software
specialists (e.g. jet engine designers) are supposed to not be led
astray when reading it.  I have the impression that Ada programs are
much less likely to crash than C++ programs, unless you set special
compiler flags to make them unsafe (e.g. by disabling subscript
checking).

Yes, good programmers can keep track in their heads what types their
programs are supposed to compute, so Python doesn't stop them too
much, and the dynamicness makes some things easier (e.g. deserializing
arbitrary structures).  But it's the same way with assembly language.
It just seems to me that there is a killer language just around the
corner, with Python's ease-of-use but with a serious compile-time type
system, maybe some kind of cross between ML and Python.

I don't think Coq (http://coq.inria.fr) is beginner friendly
enough yet ;-).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Interactive apps with Python

2008-02-21 Thread Michael Torrie
[EMAIL PROTECTED] wrote:
> Folks,
> I am trying to build an interactive test application. I
> would like to generate interactive commands to an existing
> server(ftpd)
> so commands like ftp 192.68.20.1
> ace>login: 
> ace >password : 
> I should be able to mimic human intervention. Is this possible in
> perl.
> I do not want to add delay's . I prefer synching with the server. I
> know this is possible in Expect. Is there any other scripting language
> this is possible in say Tcl/tk/Perl/Python/Ruby? What language do you
> suggest for such application? this feature in addition with strong
> parsing capabilities is what I am looking for
>   
Perhaps this would fit the bill:

http://www.noah.org/wiki/Pexpect

> Thanks in advance
> Sunil
>   

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


Re: flattening a dict

2008-02-21 Thread Benjamin
On Feb 21, 9:13 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Feb 21, 8:04 pm, Benjamin <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Feb 17, 6:18 am, Terry Jones <[EMAIL PROTECTED]> wrote:
>
> > > Hi Arnaud & Benjamin
>
> > > Here's a version that's a bit more general. It handles keys whose values
> > > are empty dicts (assigning None to the value in the result), and also dict
> > > keys that are not strings (see the test data below). It's also less
> > > recursive as it only calls itself on values that are dicts.
>
> > > But it returns a dict whose keys are tuples. You then need to decide
> > > what to do with this. Hence the helper function strdictflatten for the 
> > > case
> > > when all dict keys can be converted to str.
>
> > > As I told Arnaud in email, I greatly prefer his version for its elegance.
>
> > > Terry
>
> > > def dictflatten(d, prefix=None):
> > > result = {}
> > > if prefix is None: prefix = tuple()
> > > for k, v in d.iteritems():
> > > key = prefix + (k,)
> > > if isinstance(v, dict):
> > > if v:
> > > result.update(dictflatten(v, key))
> > > else:
> > > result[key] = None
> > > else:
> > > result[key] = v
> > > return result
>
> > > def strdictflatten(d, sep='/'):
> > > return dict((sep.join(map(str, k)), v) for k, v in 
> > > dictflatten(d).iteritems())
>
> > Thanks. This is great. Now, how would I restrict the depth of the
> > flattening? For example, what if I just wanted something like this:
> > {
> > "mays" : {"eggs" : "spam"},
> > "jam" : {"soda" : "soda/love" : "dump"},
> > lamba" : 23}
>
> > They are left alone up the to second level of recursion.
>
> Why don't you do your homework on your own for a change ? Or at least
> pretend you're even trying ?

Here's a attempt:
def dictflatten(d, prefix=None, depth=2, cur_depth=0):
result = {}
if prefix is None: prefix = tuple()
if isinstance(prefix, basestring): prefix = (prefix,)
cur_depth += 1
for k, v in d.iteritems():
key = prefix + (k,)
print key, cur_depth
if isinstance(v, dict):
if v:
if cur_depth >= depth:
result.update(dictflatten(v, key, depth,
cur_depth))
else:
result.update(dictflatten(v, k, depth, cur_depth))
else:
result[key] = None
else:
result[k] = v
return result

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


Re: Return value of an assignment statement?

2008-02-21 Thread Aahz
In article <[EMAIL PROTECTED]>,
Jeff Schwab  <[EMAIL PROTECTED]> wrote:
>[EMAIL PROTECTED] wrote:
>> 
>> There's nothing like a variable "storing" anything in Python. All you
>> have are names to (references to) objects binding in a namespace. Now
>> the fact is that some types are mutable and other are not. In your
>> above example, the augmented assignment does *not* rebind a, but
>> invoke a.extend(). With integers, it would have rebind a. So while
>> your observation is exact, your interpretation is wrong !-)
>
>Thank you for the clarification.  For some reason, I had it in my head 
>that ints were packed directly into the C structures that represent 
>Python variables, in the same (union?) member that otherwise would store 
>a pointer.

Notice very very carefully that Bruno is not using "variable".  Many
expert Python programmers strongly prefer to talk about "names" instead
of "variables" (especially when explaining the Python object model)
precisely because using "variable" leads to incorrect expectations.

http://starship.python.net/crew/mwh/hacks/objectthink.html
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


Interactive apps with Python

2008-02-21 Thread sunilkjin
Folks,
I am trying to build an interactive test application. I
would like to generate interactive commands to an existing
server(ftpd)
so commands like ftp 192.68.20.1
ace>login: 
ace >password : 
I should be able to mimic human intervention. Is this possible in
perl.
I do not want to add delay's . I prefer synching with the server. I
know this is possible in Expect. Is there any other scripting language
this is possible in say Tcl/tk/Perl/Python/Ruby? What language do you
suggest for such application? this feature in addition with strong
parsing capabilities is what I am looking for.
Thanks in advance
Sunil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Handling locked db tables...

2008-02-21 Thread John Nagle
breal wrote:

> Thanks for the reply.  I understand that this is normal locking
> behavior.  What I am looking for is a standard method to either loop
> the query until the table is unlocked, or put the query into some sort
> of queue.  Basically my queries work like this.
> 
> Request comes in
> 
> PART I:
> LOCK TABLE port_usage READ;
> SELECT * FROM port_usage WHERE in_use = 0;
> Get available port
> UPDATE port_usage SET in_use = 1 WHERE port = available_port;
> UNLOCK TABLES;
> 
> send request to available port and do some stuff until finished with
> port
> 
> PART II:
> LOCK TABLE port_usage READ
> UPDATE port_usage SET in_use = 0 WHERE port = available_port;
> UNLOCK TABLES;
> 
> Several of these *may* be happening simultaneously so when a second
> request comes in, and the first one has the table locked, I want to
> have the PART I sql still work.  Any suggestions here?

Ah.  You're just using MySQL as a lock manager.  Check out
GET_LOCK, RELEASE_LOCK, and IS_FREE_LOCK.  That may be simpler
for this application.

http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html

I use those functions regularly, for coordinating multiple
processes and servers.  They're quite useful when you have
multiple servers, and OS-level locking isn't enough.

But what you're doing should work.  It could be improved;
use "SELECT * FROM port_usage WHERE in_use = 0 LIMIT 1;",
since you only need one value returned.  Also, unless port usage
persists over reboots or you have millions of ports, use the
MEMORY engine for the table; then it's just in RAM.  Each
restart of MySQL will clear the table.

You shouldn't get an error if the table is locked; the
MySQL connection just waits.  What error are you getting?
You wrote "But, when another cursor then tries to do the read
I get an error unless the first process has been completed...
unlocking the tables."  Bear in mind that you can only have one
cursor per database connection.  The MySQLdb API makes it look
like you can have multiple cursors, but that doesn't actually
work.

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


Re: flattening a dict

2008-02-21 Thread George Sakkis
On Feb 21, 8:04 pm, Benjamin <[EMAIL PROTECTED]> wrote:
> On Feb 17, 6:18 am, Terry Jones <[EMAIL PROTECTED]> wrote:
>
> > Hi Arnaud & Benjamin
>
> > Here's a version that's a bit more general. It handles keys whose values
> > are empty dicts (assigning None to the value in the result), and also dict
> > keys that are not strings (see the test data below). It's also less
> > recursive as it only calls itself on values that are dicts.
>
> > But it returns a dict whose keys are tuples. You then need to decide
> > what to do with this. Hence the helper function strdictflatten for the case
> > when all dict keys can be converted to str.
>
> > As I told Arnaud in email, I greatly prefer his version for its elegance.
>
> > Terry
>
> > def dictflatten(d, prefix=None):
> > result = {}
> > if prefix is None: prefix = tuple()
> > for k, v in d.iteritems():
> > key = prefix + (k,)
> > if isinstance(v, dict):
> > if v:
> > result.update(dictflatten(v, key))
> > else:
> > result[key] = None
> > else:
> > result[key] = v
> > return result
>
> > def strdictflatten(d, sep='/'):
> > return dict((sep.join(map(str, k)), v) for k, v in 
> > dictflatten(d).iteritems())
>
> Thanks. This is great. Now, how would I restrict the depth of the
> flattening? For example, what if I just wanted something like this:
> {
> "mays" : {"eggs" : "spam"},
> "jam" : {"soda" : "soda/love" : "dump"},
> lamba" : 23}
>
> They are left alone up the to second level of recursion.

Why don't you do your homework on your own for a change ? Or at least
pretend you're even trying ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there a open souce IDE writen by C( C++) or partly writen by C( C++)?

2008-02-21 Thread zaley
Is there a open souce IDE writen by C( C++) or partly writen by C( C+
+)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread George Sakkis
On Feb 21, 7:21 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Steve Holden wrote:
> > Jeff Schwab wrote:
> >> [EMAIL PROTECTED] wrote:
> > [...]
> >>> Now there's no reason to feel nervous about this. All you have to
> >>> remember is that Python never copy anything unless explicitely asked
> >>> for.
>
> >> It's not that simple.  After a statement like:
>
> >> a = b
>
> >> Whether a and b denote the same object depends on what kind of object
> >> b represented in the first place.
>
> > Surely this is exactly wrong. Is there a single example you can think of
> > where
>
> > a = b
>
> a += b (my bad)
>
> > assert a is b, "Oops!"
>
> > would raise and exception? Perhaps you meant to use an augmented
> > assignment operation?
>
> Why, yes I did!  Sorry about that.

It seems less surprising when you keep in mind that "+=" (and friends)
can be syntax sugar for calling a method on the right hand side
object: a += b <=> a.__iadd__(b). It's up to the class of 'a' to do
whatever within this method (whether it's a good idea to do anything
else other than modify 'self' in place is another thing). Would you be
able to say anything about a.foo(b) without knowing what 'a' is ?

The only difference is that for types that don't implement an
augmented operator, "a `op`= b" translates to "a = a `op` b" for a
binary operator `op`. There's no formal notion of mutable and
immutable objects with respect to these operators; any class that
doesn't implement them is "immutable" as far as augmented assignment
goes (of course it may be mutated in other ways, e.g. by fiddling with
a.__dict__ directly).

On the other hand, "a = b" does always the same thing; unlike C++, '='
is not an operator and therefore it cannot be overriden by the class
of 'a'.

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


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Carl Banks
On Feb 21, 11:17 am, "Reedick, Andrew" <[EMAIL PROTECTED]> wrote:
>  So I wouldn't be
> quick to dismiss the notion that Java/C#/C++ are more newbie-safe than
> Python. =/


FWIW, when I posted my comment about C++, I was mocking the article
writer's notion that it was static typing and compile-time checking
that made Java and C# "safer" for newbies, by presenting an example
that clearly defied that.  I was taking it for granted the C++ is
notoriously dangerous and newbie-unfriendly.

Obviously it is not a universal opinion (yet).  Too bad.

But all I was really saying is that there are far more more important
things when it comes to "safety" than dynamic typing.


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


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Carl Banks
On Feb 21, 7:17 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Carl Banks wrote:
> > On Feb 21, 1:22 pm, Nicola Musatti <[EMAIL PROTECTED]> wrote:
> >> There are other downsides to garbage collection, as the fact that it
> >> makes it harder to implement the Resource Acquisition Is
> >> Initialization idiom, due to the lack of deterministic destruction.
>
> > That's not a downside: it's at least a wash.
>
> > In C++ you manage memory and the language manages resources.  In
> > Python you manage resources and the language manages memory.
>
> > RAII is merely one way of minimizing complexity.  Garbage collection
> > is another way.
>
> If you've already got a generic, language-supported way to manage
> resources (like RAII with deterministic destruction), then why bother
> with garbage collection?

Because now you have to manage memory?  Did you read my post?  You
have to manage one thing or the other.


> I'm not trying to knock it; it was a big step
> up from C-style "who forgot to delete a pointer" games.  It just seems
> to me like a solution to something that's no longer a problem, at least
> in well-written C++ code.  I'll take destructors over GC any day.

About 2% of the objects I creat have resources other than memory.  I
would rather manage resources of 2% of objects than manage memory of
100%.  YMMV, but I suspect mine is the more common opinion, if the
recent (like, 10-year) trend in programming languages is any
indication.


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


Re: KeyboardInterrupt should not kill subprocess

2008-02-21 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Michael Goerz <[EMAIL PROTECTED]> wrote:


> But as it seems, a keyboard interrupt will automatically pass down to 
> the subprocesses, causing them to abort. Is there a way that I can 
> prevent the subprocesses from being canceled by a keyboard interrupt?


You might try posix.setsid(), from the child fork.

The object is to get the child fork out of the foreground
process group for the Berkeley terminal driver.  This defines
who gets signals, when they originate in terminal control keys.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Ideas for a first course using Python

2008-02-21 Thread Mike Driscoll
On Feb 21, 4:48 pm, [EMAIL PROTECTED] wrote:
> Sorry to butt in but I am shopping for some ideas.
>
> I am interested in putting together a programming course for non-
> programmers (outside the computer science domain) based on Pyhton. I
> envision the course
> similar to ones that used old-Basic interpreter.
>
> Any one out there has such a course (already designed) or has some
> experience
> of such a course?
>
> What could be a list of topics to be addressed in such a course
> (domain), other
> than the language syntax?
>
> -ishwar

This guy's been doing it for a while now as a college course:
http://mcsp.wartburg.edu/zelle/python/python-first.html

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


Re: can't set attributes of built-in/extension type

2008-02-21 Thread Neal Becker
Steve Holden wrote:

> Neal Becker wrote:
>> Steve Holden wrote:
>> 
>>> Neal Becker wrote:
 7stud wrote:

> On Feb 21, 11:19 am, Neal Becker <[EMAIL PROTECTED]> wrote:
>> I'm working on a simple extension.  Following the classic 'noddy'
>> example.
>>
>> In [15]: cmplx_int32
>> Out[15]: 
>>
>> Now I want to add an attribute to this type.  More precisely, I want
>> a class attribute.
>>
>> cmplx_int32.test = 0
>> ---
>> TypeError Traceback (most recent call
>> last)
>>
>> /home/nbecker/numpy/ in ()
>>
>> TypeError: can't set attributes of built-in/extension
>> type 'numpy.cmplx_int32'
>>
>> What am I missing?
> class Dog(object):
> def __setattr__(self, attr, val):
> print "TypeError: can't set attributes of built-in/extension"
> print "type 'Dog.cmplx_int32'"
>
> d = Dog()
> d.test = 0
>
> --output:--
> TypeError: can't set attributes of built-in/extension
> type 'Dog.cmplx_int32'
 Not quite, I'm setting a class attribute, not an attribute on an
 instance.

>>> Quite. The problem is that extension types' attributes are determined by
>>> the layout of the object's slots and forever fixed in the C code that
>>> implements them: the slots can't be extended, so there's no way to add
>>> attributes. This is an efficiency feature: it would be *extremely* slow
>>> to look up the basic types' attributes using late-binding (it would also
>>> change the nature of the language somewhat, making it more like Ruby or
>>> Self).
>>>
>>> So the reason you can't do what you want to is the same reason why you
>>> can't add attribute to the built-in types (which are, of course, clearly
>>> mentioned in the error message).
>>>
>>>  >>> object.anyoldname = "You lose!"
>>> Traceback (most recent call last):
>>>File "", line 1, in 
>>> TypeError: can't set attributes of built-in/extension type 'object'
>>>  >>>
>>>
>>> If you look in typeobject.c you'll find this error message occurs when
>>> the object's type isn't a PyHeapTypeObject (in other words, if it's one
>>> of the built-in or extension types).
>>>
>> Thanks, but I'm a bit confused.  After reading in my "Python in a
>> Nutshell", I found that if after calling PyReady on my type object, if I
>> use PyDict_SetItemString (my_type_obj.tp_dict,)
>> 
>> That seems to work fine (which isn't exactly what it said in the Nutshell
>> book, but close).
>> 

I wanted to add an attribute to my type.
Specifically, my type object is a static cmplx_int32_scalar_obj.

After calling PyType_Ready (&cmplx_int32_scalar_obj), then I did
PyDict_SetItemString (cmplx_int32_scalar_obj.tp_dict, "dtype", (PyObject*)d1);

Now my type has the property:
cmplx_int32.dtype
dtype('cmplx_int32')

Now, I do see that I still can't set it:

cmplx_int32.dtype = 2
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can't set attributes of built-in/extension type 'numpy.cmplx_int32'

In this case, I don't need to.

But I still don't know why I can have a python class and set class or instance
attributes as I like, but this type acts differently.  What would I need to 
do if I did want to allow arbitrary attributes to be set/added to my type?

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


Re: flattening a dict

2008-02-21 Thread Benjamin
On Feb 17, 6:18 am, Terry Jones <[EMAIL PROTECTED]> wrote:
> Hi Arnaud & Benjamin
>
> Here's a version that's a bit more general. It handles keys whose values
> are empty dicts (assigning None to the value in the result), and also dict
> keys that are not strings (see the test data below). It's also less
> recursive as it only calls itself on values that are dicts.
>
> But it returns a dict whose keys are tuples. You then need to decide
> what to do with this. Hence the helper function strdictflatten for the case
> when all dict keys can be converted to str.
>
> As I told Arnaud in email, I greatly prefer his version for its elegance.
>
> Terry
>
> def dictflatten(d, prefix=None):
> result = {}
> if prefix is None: prefix = tuple()
> for k, v in d.iteritems():
> key = prefix + (k,)
> if isinstance(v, dict):
> if v:
> result.update(dictflatten(v, key))
> else:
> result[key] = None
> else:
> result[key] = v
> return result
>
> def strdictflatten(d, sep='/'):
> return dict((sep.join(map(str, k)), v) for k, v in 
> dictflatten(d).iteritems())
Thanks. This is great. Now, how would I restrict the depth of the
flattening? For example, what if I just wanted something like this:
{
"mays" : {"eggs" : "spam"},
"jam" : {"soda" : "soda/love" : "dump"},
lamba" : 23
}
They are left alone up the to second level of recursion.
> if __name__ == '__main__':
> test = {
> "" : {},
> 4 : 5,
> "mays" : {"eggs" : "spam"},
> "jam" : {"soda" : {"love" : "dump"}},
> "lamba" : 23
> }
>
> d = dictflatten(test)
> print strdictflatten(test)
>
>  {'': None, 'lamba': 23, 'mays/eggs': 'spam', '4': 5, 'jam/soda/love': 
>  'dump'}

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


Re: Python on Windows Help

2008-02-21 Thread Mike Driscoll
On Feb 21, 10:09 am, [EMAIL PROTECTED] wrote:
> I've written the following script based on information I have found on
> the web.  The purpose of the script is to start an HTTP listener on
> the machine it's running on that will give status on a particular
> service running on that system.  I've tried to create this as a
> service on the windows server it's running on, and it will install
> fine.  The problem I'm having is that the service will not stop when I
> tell it to.  Any help that anyone could provide would be greatly
> appreciated.  I'm new to python so please let me know if there is a
> more efficient way to do what I'm trying to do.  The code follows:
>
> import win32service
> import win32serviceutil
> import wmi
> from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
>
> class BlobCheck(win32serviceutil.ServiceFramework):
> _svc_name_ = "BlobCheck"
> _svc_display_name_ = "Epic Blob Checker"
> _svc_description_ = "Checks the Epic Blob Service and Creates an HTTP
> listener that can be polled for status"
>
> def __init__(self,args):
> win32serviceutil.ServiceFramework.__init__(self,args)
> self.isAlive = True
>
> def SvcDoRun(self):
> import servicemanager
> c = wmi.WMI()
>
> while self.isAlive:
> class RequestHandler(BaseHTTPRequestHandler):
> def _writeheaders(self):
> self.send_response(200)
> self.send_header('Content-type', 
> 'text/html')
> self.end_headers()
>
> def do_HEAD(self):
> self._writeheaders()
>
> def do_GET(self):
> self._writeheaders()
> running = c.Win32_Process 
> (name="notepad.exe")
> if running:
> 
> self.wfile.write("""Monitor
> 
> Kool-Aid!!!""")
> else:
> 
> self.wfile.write("""Monitor
> Oh 
> No!!!""")
>
> serveraddr = ('', 12345)
> srvr = HTTPServer(serveraddr, RequestHandler)
> srvr.handle_request()
>
> def SvcStop(self):
> import servicemanager
>
> servicemanager.LogInfoMsg("aservice - Recieved stop signal")
> self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
> self.isAlive = False
>
> if __name__ == '__main__':
> win32serviceutil.HandleCommandLine(BlobCheck)

I would recommend cross-posting this to the PyWin32 mailing list.
They'll either know what to do or tell you you can't. You can sign up
here: http://mail.python.org/mailman/listinfo/python-win32

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


Re: OT: Ideas for a first course using Python

2008-02-21 Thread André
On Feb 21, 6:48 pm, [EMAIL PROTECTED] wrote:
> Sorry to butt in but I am shopping for some ideas.
>
> I am interested in putting together a programming course for non-
> programmers (outside the computer science domain) based on Pyhton. I
> envision the course
> similar to ones that used old-Basic interpreter.
>
> Any one out there has such a course (already designed) or has some
> experience
> of such a course?
>
> What could be a list of topics to be addressed in such a course
> (domain), other
> than the language syntax?
>
> -ishwar

You might want to ask on the edu-sig list.
Or, you could google for
python "non-programmers"
and find things like 
http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python

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


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Paul Rubin
John Nagle <[EMAIL PROTECTED]> writes:
> This has nothing to do with language efficiency or whether the
> language is interpreted.  Of the languages listed with both hiding
> and safety, Ada and Modula 3 are always compiled to hard machine code,
> and Java can be.  (GCC offers that option.)

But Java still takes a big performance hit because of method-call
overhead, unless the compiler does whole-program optimization, if I
understand it right.  This is required in order to make sure that
private instance variables are really private against access from
malicious objects running in the same JVM.  That really does seem to
me to be a weird and expensive requirement to put into a general
purpose language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can't set attributes of built-in/extension type

2008-02-21 Thread Steve Holden
Neal Becker wrote:
> Steve Holden wrote:
> 
>> Neal Becker wrote:
>>> 7stud wrote:
>>>
 On Feb 21, 11:19 am, Neal Becker <[EMAIL PROTECTED]> wrote:
> I'm working on a simple extension.  Following the classic 'noddy'
> example.
>
> In [15]: cmplx_int32
> Out[15]: 
>
> Now I want to add an attribute to this type.  More precisely, I want a
> class attribute.
>
> cmplx_int32.test = 0
> ---
> TypeError Traceback (most recent call
> last)
>
> /home/nbecker/numpy/ in ()
>
> TypeError: can't set attributes of built-in/extension
> type 'numpy.cmplx_int32'
>
> What am I missing?
 class Dog(object):
 def __setattr__(self, attr, val):
 print "TypeError: can't set attributes of built-in/extension"
 print "type 'Dog.cmplx_int32'"

 d = Dog()
 d.test = 0

 --output:--
 TypeError: can't set attributes of built-in/extension
 type 'Dog.cmplx_int32'
>>> Not quite, I'm setting a class attribute, not an attribute on an
>>> instance.
>>>
>> Quite. The problem is that extension types' attributes are determined by
>> the layout of the object's slots and forever fixed in the C code that
>> implements them: the slots can't be extended, so there's no way to add
>> attributes. This is an efficiency feature: it would be *extremely* slow
>> to look up the basic types' attributes using late-binding (it would also
>> change the nature of the language somewhat, making it more like Ruby or
>> Self).
>>
>> So the reason you can't do what you want to is the same reason why you
>> can't add attribute to the built-in types (which are, of course, clearly
>> mentioned in the error message).
>>
>>  >>> object.anyoldname = "You lose!"
>> Traceback (most recent call last):
>>File "", line 1, in 
>> TypeError: can't set attributes of built-in/extension type 'object'
>>  >>>
>>
>> If you look in typeobject.c you'll find this error message occurs when
>> the object's type isn't a PyHeapTypeObject (in other words, if it's one
>> of the built-in or extension types).
>>
> Thanks, but I'm a bit confused.  After reading in my "Python in a Nutshell",
> I found that if after calling PyReady on my type object, if I use
> PyDict_SetItemString (my_type_obj.tp_dict,)
> 
> That seems to work fine (which isn't exactly what it said in the Nutshell
> book, but close).
> 
> 
I'm having a little difficulty parsing that. Could we try again?

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

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


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

2008-02-21 Thread Mike Driscoll
On Feb 20, 4:19 am, Stani <[EMAIL PROTECTED]> wrote:
> Fred Pacquier  fredp.lautre.net> writes:
>
>
>
> > Steve Holden  holdenweb.com> said :
>
> > > Perhaps you could put a link to the source on the Windows instalL page?
> > > I don't mind being a second-class citizen, but it's annoying to have to
> > > jump around like that.
>
> > I'm interested too, and was also wondering if Phatch is as full-featured
> > unders Windows as under Linux, specifically the EXIF/IPTC functions made
> > available through pyexiv2 : exiv2 itself seems to discriminate between the
> > two, the Windows package only has the executable, not the library.
>
> Even without python-pyexiv2 Phatch features read-only EXIF support thanks to
> PIL. So you can name your files or write data stamps (date, aperature, 
> velocity,
> ...) based on EXIF information. If you want to save EXIF and IPTC information 
> to
> files you need python-pyexiv2. From its website:
> "However, the library and all the tools used are cross-platform, so very 
> little
> tweaking should be needed to get it to work fine on Windows or MacOS 
> X."http://tilloy.net/dev/pyexiv2/developers.htm
>
> The exiv2 website says:
> "The Windows package only contains the command line utility exiv2.exe
> (statically linked), manpage and a sample command file; get the source and doc
> packages for the library, documentation and other 
> tools."http://www.exiv2.org/download.html
>
> So maybe someone can compile it.


I'm confused. What needs to be compiled exactly? Are there any
directions? I'm not seeing any at  that website. I can give it a go if
someone can give me advice.

>
> But... Phatch is designed with flexibility in mind. If someone can point me 
> to a
> free python library for Windows for EXIF and other metadata, I'll be happy to
> integrate support for it in Phatch. Ideas anyone?
>
> Or you could write a python wrapper around the executable.
>
> Stani
> --
> Phatch -http://photobatch.stani.be
> SPE -http://pythonide.stani.be

Thanks,

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


Re: can't set attributes of built-in/extension type

2008-02-21 Thread Neal Becker
Steve Holden wrote:

> Neal Becker wrote:
>> 7stud wrote:
>> 
>>> On Feb 21, 11:19 am, Neal Becker <[EMAIL PROTECTED]> wrote:
 I'm working on a simple extension.  Following the classic 'noddy'
 example.

 In [15]: cmplx_int32
 Out[15]: 

 Now I want to add an attribute to this type.  More precisely, I want a
 class attribute.

 cmplx_int32.test = 0
 ---
 TypeError Traceback (most recent call
 last)

 /home/nbecker/numpy/ in ()

 TypeError: can't set attributes of built-in/extension
 type 'numpy.cmplx_int32'

 What am I missing?
>>>
>>> class Dog(object):
>>> def __setattr__(self, attr, val):
>>> print "TypeError: can't set attributes of built-in/extension"
>>> print "type 'Dog.cmplx_int32'"
>>>
>>> d = Dog()
>>> d.test = 0
>>>
>>> --output:--
>>> TypeError: can't set attributes of built-in/extension
>>> type 'Dog.cmplx_int32'
>> 
>> Not quite, I'm setting a class attribute, not an attribute on an
>> instance.
>> 
> Quite. The problem is that extension types' attributes are determined by
> the layout of the object's slots and forever fixed in the C code that
> implements them: the slots can't be extended, so there's no way to add
> attributes. This is an efficiency feature: it would be *extremely* slow
> to look up the basic types' attributes using late-binding (it would also
> change the nature of the language somewhat, making it more like Ruby or
> Self).
> 
> So the reason you can't do what you want to is the same reason why you
> can't add attribute to the built-in types (which are, of course, clearly
> mentioned in the error message).
> 
>  >>> object.anyoldname = "You lose!"
> Traceback (most recent call last):
>File "", line 1, in 
> TypeError: can't set attributes of built-in/extension type 'object'
>  >>>
> 
> If you look in typeobject.c you'll find this error message occurs when
> the object's type isn't a PyHeapTypeObject (in other words, if it's one
> of the built-in or extension types).
> 
> regards
>   Steve

Thanks, but I'm a bit confused.  After reading in my "Python in a Nutshell",
I found that if after calling PyReady on my type object, if I use
PyDict_SetItemString (my_type_obj.tp_dict,)

That seems to work fine (which isn't exactly what it said in the Nutshell
book, but close).


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


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
Steve Holden wrote:
> mrstephengross wrote:
>>> What you can't do (that I really miss) is have a tree of assign-and-test
>>> expressions:
>>> import re
>>> pat = re.compile('some pattern')
>>> if m = pat.match(some_string):
>>> do_something(m)
>>
>> Yep, this is exactly what I am (was) trying to do. Oh well Any
>> clever ideas on this front?
>>
> The syntax is the way it is precisely to discourage that kind of clever 
> idea. Of course, people nevertheless manage to work around the 
> restriction to try and make their Python read like some other language 
> they are more familiar with, and most of the time they get away with it.
> 
> The fat remains that in programming there *is* such a thing as being too 
> clever, and Python's syntax deliberately discourages that.

This isn't "clever."  It's what most of us were taught, from the 
beginning, was best practice.  In some languages (including C and C++) 
the above is extremely common and perfectly acceptable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
Steve Holden wrote:
> Jeff Schwab wrote:
>> [EMAIL PROTECTED] wrote:
> [...]
>>> Now there's no reason to feel nervous about this. All you have to
>>> remember is that Python never copy anything unless explicitely asked
>>> for.
>>
>> It's not that simple.  After a statement like:
>>
>> a = b
>>
>> Whether a and b denote the same object depends on what kind of object 
>> b represented in the first place.
> 
> Surely this is exactly wrong. Is there a single example you can think of 
> where
> 
> a = b

a += b (my bad)

> assert a is b, "Oops!"
> 
> would raise and exception? Perhaps you meant to use an augmented 
> assignment operation?

Why, yes I did!  Sorry about that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
[EMAIL PROTECTED] wrote:
> On 21 fév, 23:06, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>> John Henry wrote:
>>> On Feb 21, 1:48 pm, John Henry <[EMAIL PROTECTED]> wrote:
 On Feb 21, 1:43 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
> Hi all. In C, an assignment statement returns the value assigned. For
> instance:
>   int x
>   int y = (x = 3)
> In the above example, (x=3) returns 3, which is assigned to y.
> In python, as far as I can tell, assignment statements don't return
> anything:
>   y = (x = 3)
> The above example generates a SyntaxError.
> Is this correct? I just want to make sure I've understood the
> semantics.
> Thanks,
> --Steve
 That's true, and I am happy that they decided to make that a syntax
 error.
>>> BTW: The less obvious issues when coming from the C world are Python
>>> syntax like these:
>>> y = x = 3
>>> a = 4
>>> y = x = a
>>> print x,y
>>> a = 5
>>> print x,y
>> That's the same behavior I would expect in C, on the grounds that C
>> assignments do bit-wise copies.  What I found confusing at first was
>> that the same variable will either directly store or merely refer to an
>> object, depending on the type of the object:
>>
>>  >>> a = [ 'hello' ]
>>  >>> y = x = a
>>  >>> a += [ 'world' ]
>>  >>> print x, y
>> ['hello', 'world'] ['hello', 'world']
> 
> There's nothing like a variable "storing" anything in Python. All you
> have are names to (references to) objects binding in a namespace. Now
> the fact is that some types are mutable and other are not. In your
> above example, the augmented assignment does *not* rebind a, but
> invoke a.extend(). With integers, it would have rebind a. So while
> your observation is exact, your interpretation is wrong !-)

Thank you for the clarification.  For some reason, I had it in my head 
that ints were packed directly into the C structures that represent 
Python variables, in the same (union?) member that otherwise would store 
a pointer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
Terry Reedy wrote:
> "Jeff Schwab" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
> | That's the same behavior I would expect in C, on the grounds that C
> | What I found confusing at first was
> | that the same variable will either directly store or merely refer to an
> | object, depending on the type of the object:
> 
> Since names and collection slots always refer to objects, I find the above 
> confusing.  Can you clarify what difference you percieve?

a += b

Whether a refers to the same object before and after that statement 
depends on what type of object it referred to before the statement.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Jeff Schwab
Carl Banks wrote:
> On Feb 21, 1:22 pm, Nicola Musatti <[EMAIL PROTECTED]> wrote:
>> There are other downsides to garbage collection, as the fact that it
>> makes it harder to implement the Resource Acquisition Is
>> Initialization idiom, due to the lack of deterministic destruction.
> 
> That's not a downside: it's at least a wash.
> 
> In C++ you manage memory and the language manages resources.  In
> Python you manage resources and the language manages memory.
> 
> RAII is merely one way of minimizing complexity.  Garbage collection
> is another way.

If you've already got a generic, language-supported way to manage 
resources (like RAII with deterministic destruction), then why bother 
with garbage collection?  I'm not trying to knock it; it was a big step 
up from C-style "who forgot to delete a pointer" games.  It just seems 
to me like a solution to something that's no longer a problem, at least 
in well-written C++ code.  I'll take destructors over GC any day.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Steve Holden
Jeff Schwab wrote:
> [EMAIL PROTECTED] wrote:
[...]
>> Now there's no reason to feel nervous about this. All you have to
>> remember is that Python never copy anything unless explicitely asked
>> for.
> 
> It's not that simple.  After a statement like:
> 
>   a = b
> 
> Whether a and b denote the same object depends on what kind of object b 
> represented in the first place.

Surely this is exactly wrong. Is there a single example you can think of 
where

a = b
assert a is b, "Oops!"

would raise and exception? Perhaps you meant to use an augmented 
assignment operation?

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

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


Re: Web Development Project

2008-02-21 Thread Preston Landers
john_sm3853([EMAIL PROTECTED])@2008.02.21 15:34:44 -0800:
> 
> Hey guys, I am interested in knowing, what new Web Development projects you
> are doing, curious to know, what data base you use, and if you are using
> Linux or Windows platform.  

IMHO the best platform right now is:

 Apache 2 on Linux
 mod_python or mod_wsgi
 Postgresql database with psycopg connector
 SQL Alchemy database abstraction
 Pylons, Django or your toolkit of choice.


> Also, will like to know, if there are any
> alternatives to Adobe products, that you may be using

Which products in particular?  Some yes, some no.

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


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
[EMAIL PROTECTED] wrote:
> On 21 fév, 23:19, John Henry <[EMAIL PROTECTED]> wrote:
>> On Feb 21, 2:06 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> John Henry wrote:
 On Feb 21, 1:48 pm, John Henry <[EMAIL PROTECTED]> wrote:
> On Feb 21, 1:43 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
>> Hi all. In C, an assignment statement returns the value assigned. For
>> instance:
>>   int x
>>   int y = (x = 3)
>> In the above example, (x=3) returns 3, which is assigned to y.
>> In python, as far as I can tell, assignment statements don't return
>> anything:
>>   y = (x = 3)
>> The above example generates a SyntaxError.
>> Is this correct? I just want to make sure I've understood the
>> semantics.
>> Thanks,
>> --Steve
> That's true, and I am happy that they decided to make that a syntax
> error.
 BTW: The less obvious issues when coming from the C world are Python
 syntax like these:
 y = x = 3
 a = 4
 y = x = a
 print x,y
 a = 5
 print x,y
>>> That's the same behavior I would expect in C, on the grounds that C
>>> assignments do bit-wise copies.  What I found confusing at first was
>>> that the same variable will either directly store or merely refer to an
>>> object, depending on the type of the object:
>>>  >>> a = [ 'hello' ]
>>>  >>> y = x = a
>>>  >>> a += [ 'world' ]
>>>  >>> print x, y
>>> ['hello', 'world'] ['hello', 'world']
>> Yep.  Took me a while to realize there is mutable objects, and non-
>> mutable objects.  To be honest, I am still not too comfortable about
>> it.  For instance, I still get nervous for code like:
>>
>> def invoke_some_fct(parent):
>>y = parent.x
>>y += [ 'world' ]
>>print y, parent.x
>>
>> class abc:
>>def __init__(self):
>>   self.x=[ 'hello' ]
>>   invoke_some_fct(self)
>>   print self.x
>>
> 
> Explicitely using list.extend would make things clearer:
> 
> def invoke_some_fct(parent):
>   parent.x.extend(['world'])

Whether you use += or extend has nothing to do with it.  You omitted the 
relevant part.  Using extend, it would look like:

y = parent.x
y.extend(['world'])

The confusing part is that performing an operation on y may or may not 
alter parent.x, depending on whether the initial type of parent.x is 
immutable.  If parent.x is immutable, y is a copy of the value 
represented by parent.x, and modifying y has not effect on the value of 
parent.x.  If (OTOH) parent.x is mutable, then x and y are really 
references to the same object, and modifications to that object via y 
can be observed via x.  In C, you use pointers to get this effect.


> Now there's no reason to feel nervous about this. All you have to
> remember is that Python never copy anything unless explicitely asked
> for.

It's not that simple.  After a statement like:

a = b

Whether a and b denote the same object depends on what kind of object b 
represented in the first place.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Steve Holden
mrstephengross wrote:
>> What you can't do (that I really miss) is have a tree of assign-and-test
>> expressions:
>> import re
>> pat = re.compile('some pattern')
>> if m = pat.match(some_string):
>> do_something(m)
> 
> Yep, this is exactly what I am (was) trying to do. Oh well Any
> clever ideas on this front?
> 
The syntax is the way it is precisely to discourage that kind of clever 
idea. Of course, people nevertheless manage to work around the 
restriction to try and make their Python read like some other language 
they are more familiar with, and most of the time they get away with it.

The fat remains that in programming there *is* such a thing as being too 
clever, and Python's syntax deliberately discourages that.

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

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


Re: Inserting NULL values with pymssql

2008-02-21 Thread Steve Holden
Jayson Barley wrote:
> I am attempting to insert NULL values into a database. I have tried to 
> do this in multiple ways without any success, see below, and haven't 
> been able to find anything through Google to help out. I am hoping that 
> I am just overlooking something or that it is a rookie mistake. Below is 
> a test I came up with to prove this. I am on Windows XP using Python 2.5 
> and pymssql-0.8.0-py2.5.
> 
> CREATE TABLE [dbo].[Test](
>  [test] [varchar](50) NULL,
>  [inttest] [int] NULL
> ) ON [PRIMARY]
>  
> 1.
> import pymssql
>  
> TestDB = 
> pymssql.connect(host='Test',user='test',password='test',database='test')
> cursor = TestDB.cursor()
> query = """INSERT INTO test.dbo.test VALUES (?, ?);"""
> cursor.execute(query,('',''))
> Returns
>  
> Traceback (most recent call last):
>   File "C:\Test\db_info\test.py", line 6, in 
> cursor.execute(query,('',''))
>   File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
> self.executemany(operation, (params,))
>   File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany
> raise DatabaseError, "internal error: %s" % self.__source.errmsg()
> pymssql.DatabaseError: internal error: None
>  
> 2.
> import pymssql
>  
> TestDB = 
> pymssql.connect(host='Test',user='test',password='test',database='test')
> cursor = TestDB.cursor()
> query = """INSERT INTO test.dbo.test VALUES (?, ?);"""
> cursor.execute(query,('',None))
>  
> Returns
>  
> Traceback (most recent call last):
>   File "C:\Test\db_info\test.py", line 8, in 
> cursor.execute(query,('',None))
>   File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
> self.executemany(operation, (params,))
>   File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany
> raise DatabaseError, "internal error: %s" % self.__source.errmsg()
> pymssql.DatabaseError: internal error: None
>  
> 3.
> import pymssql
>  
> TestDB = 
> pymssql.connect(host='Test',user='test',password='test',database='test')
> cursor = TestDB.cursor()
> query = """INSERT INTO test.dbo.test VALUES (?, ?);"""
> cursor.execute(query,('','NULL'))
> Returns
>  
> Traceback (most recent call last):
>   File "C:\Test\db_info\test.py", line 6, in 
> cursor.execute(query,('','NULL'))
>   File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
> self.executemany(operation, (params,))
>   File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany
> raise DatabaseError, "internal error: %s" % self.__source.errmsg()
> pymssql.DatabaseError: internal error: None
>  
> I am wondering what I am missing that is preventing me from inserting a 
> NULL. I can perform the INSERT in Server Management Studio the problem 
> only exists in the Python script. If anyone can point me to a resource 
> that I may have missed or a flaw in my script I would really appreciate it.
>  
What you want is two NULL data values as the second argument to execute():

cursor.execute(query,(None, None))

> I also forgot to mention that this...
>  
> import pymssql
>  
> TestDB = 
> pymssql.connect(host='Test',user='test',password='test',database='test')
> cursor = TestDB.cursor()
> query = """INSERT INTO test.dbo.test (test) VALUES ('%s');"""
> cursor.execute(query,(None))
>  
> works. While
>  
That's a very naughty database module. It should complain, since you 
didn't provide a tuple as the second argument to execute().

> import pymssql
>  
> TestDB = 
> pymssql.connect(host='Test',user='test',password='test',database='test')
> cursor = TestDB.cursor()
> query = """INSERT INTO test.dbo.test (inttest) VALUES ('%d');"""
> cursor.execute(query,(None))
>  
> doesn't work and returns
>  
> Traceback (most recent call last):
>   File "C:\Test\db_info\test.py", line 6, in 
> cursor.execute(query,(None))
>   File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
> self.executemany(operation, (params,))
>   File "C:\Python25\lib\site-packages\pymssql.py", line 152, in executemany
> raise DatabaseError, "internal error: %s" % self.__source.errmsg()
> pymssql.DatabaseError: internal error: SQL Server message 245, severity 16, 
> state 1, line 1:
> Conversion failed when converting the varchar value '%d' to data type int.
> DB-Lib error message 10007, severity 5:
> General SQL Server error: Check messages from the SQL Server.

I don't know what pymssql's paramstyle is, but I suspect it requires a 
"%s" far all parameters regardless of their data type. That's SQL Server 
complaining about the %d, pymssql having failed to recognize it as a 
parameter marker and passed it through to the engine.

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

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


Re: Return value of an assignment statement?

2008-02-21 Thread [EMAIL PROTECTED]
> What you can't do (that I really miss) is have a tree of assign-and-test
> expressions:
>
> import re
> pat = re.compile('some pattern')
>
> if m = pat.match(some_string):
> do_something(m)
> else if m = pat.match(other_string):
> do_other_thing(m)
> else:
> do_default_thing()

What you want is:

for astring, afunc in ((some_string, do_something), (other_string,
do_other_thing)):
m = pat.match(astring)
if m:
afunc(m)
break
else:
do_default_thing()
-- 
http://mail.python.org/mailman/listinfo/python-list


Web Development Project

2008-02-21 Thread john_sm3853

Hey guys, I am interested in knowing, what new Web Development projects you
are doing, curious to know, what data base you use, and if you are using
Linux or Windows platform.  Also, will like to know, if there are any
alternatives to Adobe products, that you may be using
-- 
View this message in context: 
http://www.nabble.com/Web-Development-Project-tp15623493p15623493.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Return value of an assignment statement?

2008-02-21 Thread [EMAIL PROTECTED]
On 21 fév, 23:19, John Henry <[EMAIL PROTECTED]> wrote:
> On Feb 21, 2:06 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
>
>
>
> > John Henry wrote:
> > > On Feb 21, 1:48 pm, John Henry <[EMAIL PROTECTED]> wrote:
> > >> On Feb 21, 1:43 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
>
> > >>> Hi all. In C, an assignment statement returns the value assigned. For
> > >>> instance:
> > >>>   int x
> > >>>   int y = (x = 3)
> > >>> In the above example, (x=3) returns 3, which is assigned to y.
> > >>> In python, as far as I can tell, assignment statements don't return
> > >>> anything:
> > >>>   y = (x = 3)
> > >>> The above example generates a SyntaxError.
> > >>> Is this correct? I just want to make sure I've understood the
> > >>> semantics.
> > >>> Thanks,
> > >>> --Steve
> > >> That's true, and I am happy that they decided to make that a syntax
> > >> error.
>
> > > BTW: The less obvious issues when coming from the C world are Python
> > > syntax like these:
>
> > > y = x = 3
>
> > > a = 4
>
> > > y = x = a
>
> > > print x,y
>
> > > a = 5
>
> > > print x,y
>
> > That's the same behavior I would expect in C, on the grounds that C
> > assignments do bit-wise copies.  What I found confusing at first was
> > that the same variable will either directly store or merely refer to an
> > object, depending on the type of the object:
>
> >  >>> a = [ 'hello' ]
> >  >>> y = x = a
> >  >>> a += [ 'world' ]
> >  >>> print x, y
> > ['hello', 'world'] ['hello', 'world']
>
> Yep.  Took me a while to realize there is mutable objects, and non-
> mutable objects.  To be honest, I am still not too comfortable about
> it.  For instance, I still get nervous for code like:
>
> def invoke_some_fct(parent):
>y = parent.x
>y += [ 'world' ]
>print y, parent.x
>
> class abc:
>def __init__(self):
>   self.x=[ 'hello' ]
>   invoke_some_fct(self)
>   print self.x
>

Explicitely using list.extend would make things clearer:

def invoke_some_fct(parent):
  parent.x.extend(['world'])

Now there's no reason to feel nervous about this. All you have to
remember is that Python never copy anything unless explicitely asked
for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread [EMAIL PROTECTED]
On 21 fév, 23:06, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> John Henry wrote:
> > On Feb 21, 1:48 pm, John Henry <[EMAIL PROTECTED]> wrote:
> >> On Feb 21, 1:43 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
>
> >>> Hi all. In C, an assignment statement returns the value assigned. For
> >>> instance:
> >>>   int x
> >>>   int y = (x = 3)
> >>> In the above example, (x=3) returns 3, which is assigned to y.
> >>> In python, as far as I can tell, assignment statements don't return
> >>> anything:
> >>>   y = (x = 3)
> >>> The above example generates a SyntaxError.
> >>> Is this correct? I just want to make sure I've understood the
> >>> semantics.
> >>> Thanks,
> >>> --Steve
> >> That's true, and I am happy that they decided to make that a syntax
> >> error.
>
> > BTW: The less obvious issues when coming from the C world are Python
> > syntax like these:
>
> > y = x = 3
>
> > a = 4
>
> > y = x = a
>
> > print x,y
>
> > a = 5
>
> > print x,y
>
> That's the same behavior I would expect in C, on the grounds that C
> assignments do bit-wise copies.  What I found confusing at first was
> that the same variable will either directly store or merely refer to an
> object, depending on the type of the object:
>
>  >>> a = [ 'hello' ]
>  >>> y = x = a
>  >>> a += [ 'world' ]
>  >>> print x, y
> ['hello', 'world'] ['hello', 'world']

There's nothing like a variable "storing" anything in Python. All you
have are names to (references to) objects binding in a namespace. Now
the fact is that some types are mutable and other are not. In your
above example, the augmented assignment does *not* rebind a, but
invoke a.extend(). With integers, it would have rebind a. So while
your observation is exact, your interpretation is wrong !-)

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


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Carl Banks
On Feb 21, 1:22 pm, Nicola Musatti <[EMAIL PROTECTED]> wrote:
> There are other downsides to garbage collection, as the fact that it
> makes it harder to implement the Resource Acquisition Is
> Initialization idiom, due to the lack of deterministic destruction.

That's not a downside: it's at least a wash.

In C++ you manage memory and the language manages resources.  In
Python you manage resources and the language manages memory.

RAII is merely one way of minimizing complexity.  Garbage collection
is another way.


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


Re: Linux/Python Issues

2008-02-21 Thread [EMAIL PROTECTED]
On 21 fév, 13:57, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 21 Feb, 13:04, [EMAIL PROTECTED] wrote:
>

> > re DLing source
>
> > As a "solution" to the problem of wanting a program on my computer, it
> > sucks.
>
> It doesn't suck if you're just installing one program, but if there
> are a lot of dependencies it can quickly suck, yes. Even with systems
> that comprehensively manage dependencies like Gentoo's Portage (and
> unlike language-specific solutions such as easy_install and the CPAN
> tools) the convenience can become quickly overwhelmed by practical
> concerns such as whether your computer has enough CPU time available
> to compile all the updates coming in.
>

Hmm... I'm actually an happy gentoo user, and my computer is now
something like five years old. So yes, sure, I do not recompile
OpenOffice everyday, but with ccache installed, keeping the sytem up
to date is definitively not a problem.

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


Re: exec and closures

2008-02-21 Thread alitosis
On Feb 22, 3:18 am, Peter Otten <[EMAIL PROTECTED]> wrote:
> Alejandro Dubrovsky wrote:
> > def autoassign(_init_):
> > import inspect
> > import functools
>
> > argnames, _, _, defaults = inspect.getargspec(_init_)
> > argnames = argnames[1:]
>
> > indentation = ''
> > settings = ['self.%s = %s' % (arg[1:], arg) for arg in argnames
> > if arg[0] == '_']
>
> > if len(settings) <= 0:
> > return _init_
>
> > if defaults is None:
> > args = argnames[:]
> > else:
> > args = argnames[:-len(defaults)]
> > for key, value in zip(argnames[-len(defaults):],defaults):
> > args.append('%s=%s' % (key, repr(value)))
>
> > template = """def _autoassign(self, %(args)s):
> > %(setting)s
> > _init_(self, %(argnames)s)
> > """ % {'args' : ", ".join(args), 'setting' : "\n".join(['%s%s' %
> > (indentation, setting) for setting
> > in settings]), 'argnames' : ', '.join(argnames)}
>
> > try:
> > exec template
> > except SyntaxError, e:
> > raise SyntaxError('%s. line: %s. offset %s:\n%s' %
> > (e.msg, e.lineno, e.offset, template))
> > return _autoassign
>
>
[snip]
> > Is there a way to bind the _init_ name at exec time?
>
> Use a dedicated namespace:
>
> namespace = dict(_init_=_init_)
> exec template in namespace
> return namespace["_autoassign"]
>
> Peter

That works!  Excellent, thanks.
I still don't understand why the original doesn't work.  I thought
exec with no namespace specified used the current context, in which
_init_ would be _init_ already.  But understanding can wait.
ale

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


Re: Return value of an assignment statement?

2008-02-21 Thread Terry Reedy

"Jeff Schwab" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

| That's the same behavior I would expect in C, on the grounds that C
| What I found confusing at first was
| that the same variable will either directly store or merely refer to an
| object, depending on the type of the object:

Since names and collection slots always refer to objects, I find the above 
confusing.  Can you clarify what difference you percieve?

tjr




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


Re: Tkinter OSX and "lift"

2008-02-21 Thread Miki
Hello Kevin,

> "Lift" (which calls the Tk command "raise") doesn't work this way, at
> least not under Aqua. If your application has focus, "lift" will raise
> the widget being called to the top of the stacking order. However, it
> will not make the application frontmost. To do this you'd have to use
> Carbon calls (look at Carbon.CarbonEvt) or use a Tk extension and call
> it from Python. Of course, this is pretty much a non-issue if your
> application is wrapped as a standard Mac application bundle via
> py2app--most Mac users don't run Python apps from the Terminal but
> instead double-click an application icon. In that event, "lift" should
> work fine, because the application will already have focus.

Thanks,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


OT: Ideas for a first course using Python

2008-02-21 Thread ishwar . rattan
Sorry to butt in but I am shopping for some ideas.

I am interested in putting together a programming course for non-
programmers (outside the computer science domain) based on Pyhton. I
envision the course
similar to ones that used old-Basic interpreter.

Any one out there has such a course (already designed) or has some
experience
of such a course?

What could be a list of topics to be addressed in such a course
(domain), other
than the language syntax?

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


Re: Return value of an assignment statement?

2008-02-21 Thread Martin v. Löwis
> Hi all. In C, an assignment statement returns the value assigned.

No. C doesn't have an assignment statement. Instead, in C, assignment
is an expression (just like a binary operation or a function call);
that expression evaluates to the value assigned (i.e. the result is
the value, the assignment is just a side-effect).

What you consider the assignment statement is actually an expression
statement, of the syntax



So

   x = y;
   f();
   3+4;

are all the same kind of statement.

> In python, as far as I can tell, assignment statements don't return
> anything:

Right - that's because they are statements. No statement "returns"
a value - except for the return statement, of course, but it doesn't
return it in the sense that you could write

 foo = return 44

Because of the confusing meaning of "return", I find it better to
say that expressions evaluate to a value, not that they return
a value.

> The above example generates a SyntaxError.
> 
> Is this correct? I just want to make sure I've understood the
> semantics.

Please try to study more on the difference between expressions
and statements.

Regards,
Martin

P.S. Just to confuse matters: GNU C also has statement expressions,
of the form

   ({ int y = foo (); int z;
 if (y > 0) z = y;
 else z = - y;
 z; })

These are expressions, but allow the expressiveness of statements
(including variable declarations)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Globals or objects?

2008-02-21 Thread Steven D'Aprano
On Thu, 21 Feb 2008 16:37:56 +, tinnews wrote:

> Aahz <[EMAIL PROTECTED]> wrote:
>> In article <[EMAIL PROTECTED]>,
>>  <[EMAIL PROTECTED]> wrote:
>> >Aahz <[EMAIL PROTECTED]> wrote:
>> >> In article
>> >> <[EMAIL PROTECTED]>,
>> >>  <[EMAIL PROTECTED]> wrote:
>> >>>
>> >>>I had a global variable holding a count. One source Google found
>> >>>suggested that I wouldn't need the global if I used an object. So I
>> >>>created a Singleton class that now holds the former global as an
>> >>>instance attribute. Bye, bye, global.
>> >>>
>> >>>But later I thought about it. I cannot see a single advantage to the
>> >>>object approach. Am I missing something? Or was the original global
>> >>>a better, cleaner solution to the "I need a value I can read/write
>> >>>from several places" problem?
>> >> 
>> >> The advantage of the global singleton is that it is a container;
>> >> therefore, its contents are mutable and you don't need to keep using
>> >> the ``global`` statement.
>> >
>> > but you do keep having to use a longer reference to the value so
>> >what have you won?
>> 
>> Clarity, simplicity, robustness
> 
> Clarity - why is it clearer?

Consider two function calls:


x = ham(arg, counter)
y = spam(arg)

Both do exactly the same thing: ham() takes an explicit "counter" 
argument, while spam() uses a global variable. Which one makes it clear 
that it uses a counter, and which does not?

 
> Simplicity - no, you've added an extra layer.

Consider trying to run ham() and spam() twice, independently:

x1 = ham(arg, counter)
x2 = ham(arg, another_counter)

y1 = spam(arg)
saved_counter = counter  # save the global variable
counter = 0  # reset it to zero
y2 = spam(arg)
another_counter = counter
counter = saved_counter


Which is simpler?


 
> Robustness - how?

If you avoid the use of globals, this code will work as expected:

x = ham(arg, counter)
assert counter.n = 5  # or whatever value ham() sets it to...
function()
another_function()
yet_another_function()

At the end of this block of function calls, you can be confident that 
counter still has the same value.

Now consider using globals:

x = spam(arg)
assert counter = 5  # or whatever value spam() sets it to...
function()
another_function()
yet_another_function()

What value will counter have? The only way to tell is to carefully read 
through function(), another_function() and yet_another_function() and see 
whether or not they modify the global counter. Maybe they do, maybe they 
don't, who can tell?


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


Re: Return value of an assignment statement?

2008-02-21 Thread John Henry
On Feb 21, 2:06 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> John Henry wrote:
> > On Feb 21, 1:48 pm, John Henry <[EMAIL PROTECTED]> wrote:
> >> On Feb 21, 1:43 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
>
> >>> Hi all. In C, an assignment statement returns the value assigned. For
> >>> instance:
> >>>   int x
> >>>   int y = (x = 3)
> >>> In the above example, (x=3) returns 3, which is assigned to y.
> >>> In python, as far as I can tell, assignment statements don't return
> >>> anything:
> >>>   y = (x = 3)
> >>> The above example generates a SyntaxError.
> >>> Is this correct? I just want to make sure I've understood the
> >>> semantics.
> >>> Thanks,
> >>> --Steve
> >> That's true, and I am happy that they decided to make that a syntax
> >> error.
>
> > BTW: The less obvious issues when coming from the C world are Python
> > syntax like these:
>
> > y = x = 3
>
> > a = 4
>
> > y = x = a
>
> > print x,y
>
> > a = 5
>
> > print x,y
>
> That's the same behavior I would expect in C, on the grounds that C
> assignments do bit-wise copies.  What I found confusing at first was
> that the same variable will either directly store or merely refer to an
> object, depending on the type of the object:
>
>  >>> a = [ 'hello' ]
>  >>> y = x = a
>  >>> a += [ 'world' ]
>  >>> print x, y
> ['hello', 'world'] ['hello', 'world']

Yep.  Took me a while to realize there is mutable objects, and non-
mutable objects.  To be honest, I am still not too comfortable about
it.  For instance, I still get nervous for code like:

def invoke_some_fct(parent):
   y = parent.x
   y += [ 'world' ]
   print y, parent.x

class abc:
   def __init__(self):
  self.x=[ 'hello' ]
  invoke_some_fct(self)
  print self.x

hw = abc()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
mrstephengross wrote:
>> What you can't do (that I really miss) is have a tree of assign-and-test
>> expressions:
>> import re
>> pat = re.compile('some pattern')
>> if m = pat.match(some_string):
>> do_something(m)
> 
> Yep, this is exactly what I am (was) trying to do. Oh well Any
> clever ideas on this front?

I worked around it by defining a separate thigamabob with a "result" 
property.  A method of the thigamabob internally performs the 
assignment, and returns a boolean result.  The body of each branch in 
the tree can then retrieve the result object from the thigamabob. 
Here's an example hard-coded to match strings against patterns, but I 
think the idea should be extensible to other kinds of assign-and-test 
situations.

 # Just for the sake of this post.
 def do_something(m): pass
 def do_other_thing(m): pass
 def do_default_thing(): pass

 import re

 class Matcher(object):
 def __call__(self, pattern, string):
 self.result = pattern.match(string)

 if __name__ == '__main__':

 pat = re.compile('some pattern')
 match = Matcher()

 if match(pat, 'a'):
 do_something(match.result)
 elif match(pat, 'b'):
 do_other_thing(match.result)
 else:
 do_default_thing()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread John Nagle
Paul Boddie wrote:
> On 21 Feb, 19:22, Nicola Musatti <[EMAIL PROTECTED]> wrote:
>> On Feb 21, 6:31 pm, Paul Boddie <[EMAIL PROTECTED]> wrote:
>> [...]
>>
>>> The main reason why C++ has declined in usage is because almost
>>> everything of practical value is optional.
>> The main reason why C++ has declined in usage is because it never got
>> the kind of corporate marketing enjoyed by Java and C#.

No, the real problem is that C++ is the only major language to
have hiding ("abstraction") without memory safety.  C has neither hiding
nor safety.  Python, Java, Modula 3, Delphi, Ruby, C#, and Ada have hiding
with safety.  Javascript, Perl, and LISP have safety without hiding.  C++
stands alone as having hiding without safety, the least safe possibility.

The safety problems with C++ could be fixed, but the C++ committee
is off in template la-la land, ignoring safety issues in favor of
cute template features no one will use in production code.

This has nothing to do with language efficiency or whether the
language is interpreted.  Of the languages listed with both hiding
and safety, Ada and Modula 3 are always compiled to hard machine code,
and Java can be.  (GCC offers that option.)

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


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
John Henry wrote:
> On Feb 21, 1:48 pm, John Henry <[EMAIL PROTECTED]> wrote:
>> On Feb 21, 1:43 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>> Hi all. In C, an assignment statement returns the value assigned. For
>>> instance:
>>>   int x
>>>   int y = (x = 3)
>>> In the above example, (x=3) returns 3, which is assigned to y.
>>> In python, as far as I can tell, assignment statements don't return
>>> anything:
>>>   y = (x = 3)
>>> The above example generates a SyntaxError.
>>> Is this correct? I just want to make sure I've understood the
>>> semantics.
>>> Thanks,
>>> --Steve
>> That's true, and I am happy that they decided to make that a syntax
>> error.
> 
> BTW: The less obvious issues when coming from the C world are Python
> syntax like these:
> 
> y = x = 3
> 
> a = 4
> 
> y = x = a
> 
> print x,y
> 
> a = 5
> 
> print x,y

That's the same behavior I would expect in C, on the grounds that C 
assignments do bit-wise copies.  What I found confusing at first was 
that the same variable will either directly store or merely refer to an 
object, depending on the type of the object:

 >>> a = [ 'hello' ]
 >>> y = x = a
 >>> a += [ 'world' ]
 >>> print x, y
['hello', 'world'] ['hello', 'world']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python-ldap for plone 3 (python 2.4.4)

2008-02-21 Thread Michael Ströder
Erol Robaina Cepero wrote:
> On 19/02/2008 at 07:12 p.m. Michael Ströder wrote:
> 
>> Erol Robaina Cepero wrote:
>>> I need download python-ldap for my plone 3.0.5 that use python 2.4.4.
>>>
>>> Do you know where I can find it?
>> http://python-ldap.sourceforge.net/download.shtml
> 
> There I found the version 2.3.1 for python 2.5. It works in python 2.4.4 too?

Nope. Binary builds of C extension modules are only guaranteed to 
be compatible within a Python media release, like 2.4.x or either 
2.5.x. So you have to compile it yourself if you don't find a 
suitable build of python-ldap for your platform and Python version.

Ciao, Michael.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread mrstephengross
> What you can't do (that I really miss) is have a tree of assign-and-test
> expressions:
> import re
> pat = re.compile('some pattern')
> if m = pat.match(some_string):
> do_something(m)

Yep, this is exactly what I am (was) trying to do. Oh well Any
clever ideas on this front?

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


Re: Return value of an assignment statement?

2008-02-21 Thread John Henry
On Feb 21, 1:48 pm, John Henry <[EMAIL PROTECTED]> wrote:
> On Feb 21, 1:43 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi all. In C, an assignment statement returns the value assigned. For
> > instance:
>
> >   int x
> >   int y = (x = 3)
>
> > In the above example, (x=3) returns 3, which is assigned to y.
>
> > In python, as far as I can tell, assignment statements don't return
> > anything:
>
> >   y = (x = 3)
>
> > The above example generates a SyntaxError.
>
> > Is this correct? I just want to make sure I've understood the
> > semantics.
>
> > Thanks,
> > --Steve
>
> That's true, and I am happy that they decided to make that a syntax
> error.

BTW: The less obvious issues when coming from the C world are Python
syntax like these:

y = x = 3

a = 4

y = x = a

print x,y

a = 5

print x,y
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread 7stud
On Feb 21, 2:43 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
> Hi all. In C, an assignment statement returns the value assigned. For
> instance:
>
>   int x
>   int y = (x = 3)
>
> In the above example, (x=3) returns 3, which is assigned to y.
>
> In python, as far as I can tell, assignment statements don't return
> anything:
>
>   y = (x = 3)
>
> The above example generates a SyntaxError.
>
> Is this correct? I just want to make sure I've understood the
> semantics.
>
> Thanks,
> --Steve

x = y = 1
print x, y

--output:--
1 1

With parentheses, it looks like python thinks you are trying to do a
boolean == inside the parentheses.  It's the same error you get if you
write:

if x = y:
print 'yes'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread Jeff Schwab
mrstephengross wrote:
> Hi all. In C, an assignment statement returns the value assigned. For
> instance:
> 
>   int x
>   int y = (x = 3)
> 
> In the above example, (x=3) returns 3, which is assigned to y.
> 
> In python, as far as I can tell, assignment statements don't return
> anything:
> 
>   y = (x = 3)
> 
> The above example generates a SyntaxError.
> 
> Is this correct? I just want to make sure I've understood the
> semantics.

Yes, but there is valid syntax for the common case you mentioned:

 y = x = 3

What you can't do (that I really miss) is have a tree of assign-and-test 
expressions:

import re
pat = re.compile('some pattern')

if m = pat.match(some_string):
do_something(m)
else if m = pat.match(other_string):
do_other_thing(m)
else:
do_default_thing()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-21 Thread John Henry
On Feb 21, 1:43 pm, mrstephengross <[EMAIL PROTECTED]> wrote:
> Hi all. In C, an assignment statement returns the value assigned. For
> instance:
>
>   int x
>   int y = (x = 3)
>
> In the above example, (x=3) returns 3, which is assigned to y.
>
> In python, as far as I can tell, assignment statements don't return
> anything:
>
>   y = (x = 3)
>
> The above example generates a SyntaxError.
>
> Is this correct? I just want to make sure I've understood the
> semantics.
>
> Thanks,
> --Steve

That's true, and I am happy that they decided to make that a syntax
error.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Inserting NULL values with pymssql

2008-02-21 Thread Jayson Barley
I also forgot to mention that this...
 
import pymssql
 
TestDB =
pymssql.connect(host='Test',user='test',password='test',database='test')
cursor = TestDB.cursor()
query = """INSERT INTO test.dbo.test (test) VALUES ('%s');"""
cursor.execute(query,(None))
 
works. While 
 
import pymssql
 
TestDB =
pymssql.connect(host='Test',user='test',password='test',database='test')
cursor = TestDB.cursor()
query = """INSERT INTO test.dbo.test (inttest) VALUES ('%d');"""
cursor.execute(query,(None))
 
doesn't work and returns
 
Traceback (most recent call last):
  File "C:\Test\db_info\test.py", line 6, in 
cursor.execute(query,(None))
  File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
self.executemany(operation, (params,))
  File "C:\Python25\lib\site-packages\pymssql.py", line 152, in
executemany
raise DatabaseError, "internal error: %s" % self.__source.errmsg()
pymssql.DatabaseError: internal error: SQL Server message 245, severity
16, state 1, line 1:
Conversion failed when converting the varchar value '%d' to data type
int.
DB-Lib error message 10007, severity 5:
General SQL Server error: Check messages from the SQL Server.
 
Jayson



From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On
Behalf Of Jayson Barley
Sent: Thursday, February 21, 2008 1:20 PM
To: python-list@python.org
Subject: Inserting NULL values with pymssql


I am attempting to insert NULL values into a database. I have tried to
do this in multiple ways without any success, see below, and haven't
been able to find anything through Google to help out. I am hoping that
I am just overlooking something or that it is a rookie mistake. Below is
a test I came up with to prove this. I am on Windows XP using Python 2.5
and pymssql-0.8.0-py2.5.

CREATE TABLE [dbo].[Test](
 [test] [varchar](50) NULL,
 [inttest] [int] NULL
) ON [PRIMARY]
 
1.
import pymssql
 
TestDB =
pymssql.connect(host='Test',user='test',password='test',database='test')
cursor = TestDB.cursor()
query = """INSERT INTO test.dbo.test VALUES (?, ?);"""
cursor.execute(query,('',''))

Returns
 
Traceback (most recent call last):
  File "C:\Test\db_info\test.py", line 6, in 
cursor.execute(query,('',''))
  File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
self.executemany(operation, (params,))
  File "C:\Python25\lib\site-packages\pymssql.py", line 152, in
executemany
raise DatabaseError, "internal error: %s" % self.__source.errmsg()
pymssql.DatabaseError: internal error: None
 
2.
import pymssql
 
TestDB =
pymssql.connect(host='Test',user='test',password='test',database='test')
cursor = TestDB.cursor()
query = """INSERT INTO test.dbo.test VALUES (?, ?);"""
cursor.execute(query,('',None))
 
Returns
 
Traceback (most recent call last):
  File "C:\Test\db_info\test.py", line 8, in 
cursor.execute(query,('',None))
  File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
self.executemany(operation, (params,))
  File "C:\Python25\lib\site-packages\pymssql.py", line 152, in
executemany
raise DatabaseError, "internal error: %s" % self.__source.errmsg()
pymssql.DatabaseError: internal error: None
 
3.
import pymssql
 
TestDB =
pymssql.connect(host='Test',user='test',password='test',database='test')
cursor = TestDB.cursor()
query = """INSERT INTO test.dbo.test VALUES (?, ?);"""
cursor.execute(query,('','NULL'))

Returns
 
Traceback (most recent call last):
  File "C:\Test\db_info\test.py", line 6, in 
cursor.execute(query,('','NULL'))
  File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
self.executemany(operation, (params,))
  File "C:\Python25\lib\site-packages\pymssql.py", line 152, in
executemany
raise DatabaseError, "internal error: %s" % self.__source.errmsg()
pymssql.DatabaseError: internal error: None
 
I am wondering what I am missing that is preventing me from inserting a
NULL. I can perform the INSERT in Server Management Studio the problem
only exists in the Python script. If anyone can point me to a resource
that I may have missed or a flaw in my script I would really appreciate
it.
 
Jayson
-- 
http://mail.python.org/mailman/listinfo/python-list

Return value of an assignment statement?

2008-02-21 Thread mrstephengross
Hi all. In C, an assignment statement returns the value assigned. For
instance:

  int x
  int y = (x = 3)

In the above example, (x=3) returns 3, which is assigned to y.

In python, as far as I can tell, assignment statements don't return
anything:

  y = (x = 3)

The above example generates a SyntaxError.

Is this correct? I just want to make sure I've understood the
semantics.

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


Re: Linux/Python Issues

2008-02-21 Thread Bjoern Schliessmann
[EMAIL PROTECTED] wrote:

> As a "solution" to the problem of wanting a program on my
> computer, it sucks. On Windows I'll DL an install package,
> "accept" a license agreement, click Next a few times (no, I can't
> make a cup of coffee because the minute I step away the "Wizard"
> will ask a question), ... With CNR the commitment is that I CAN
> walk away. I do not know who should be responsible for putting
> things in the warehouse. 

The... maintainer perhaps? A.k.a. the distributor?

> I do wish that the *n*x community would create some sensible
> standards so the 'our distro doesn't put things where others do'
> would stop being an issue. 

There are certainly mory than fifty GNU/Linux and Unix flavours of
different versions which are all POSIX compatible, but not binary
compatible. Of Windows, there are very few versions which are
mostly binary compatible, and widely used. Do you think the Python
maintainers should create fifty different Python packages every
release? The common software "flow" is: developer => distributor =>
user. But due to some cool tools compiling isn't something one
can't learn by doing, since the developers already did the most for
you; more or less you just have to get your environment right
(dependencies) and hit "start". I admit that's nothing for the "I
just want it to work!!!11" kind of people, but those should stick
to better supported flavours.

> Looking in "/usr/bin" and its brethren makes "c:\Program Files"
> seem organized. 

I'm afraid not, since mixing executables, libraries and data in an
unsorted directory tree is just horrible. POSIX compatible systems
usually sort everything in directories where it belongs
(/usr/bin, /usr/lib, /usr/share/*, ...) and employ a packet manager
to keep the system in a well-defined state. Self-compiled stuff can
be "incorporated" or just installed to the /usr/local subhierarchy.

The Windows way, contrarily, is:

- All program files go anywhere on the hard disk in a custom
directory tree. (Recently, they are often installed to something
like "Program Files" or a translated equivalent, luckily.)

- Most programs use a custom installer which alone has the task to
track files installed to the system; the system itself usually has
no knowledge about it (apart from how to call the uninstaller).
Dependency handling is completely up to the applications
themselves.

- Often, libraries and/or drivers are installed somewhere
in %WINDIR% and get lost ... no wonder Windows systems are commonly
reinstalled quite often compared to POSIX compatible systems.
 
Additionally, exotic or older program in Windows are often bundled
in a (today) malfunctioning installer. Older programs for POSIX
compatible OS are often available in source which often need only
few adaptations to compile properly.

> I've no interest in mastering the art of installing Linux. 

I'd appreciate if you weren't complaining about things you didn't
know ...

Regards,


Björn

-- 
BOFH excuse #297:

Too many interrupts

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


Re: packing things back to regular expression

2008-02-21 Thread Paul McGuire
On Feb 20, 6:29 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Wed, 20 Feb 2008 11:36:20 -0800, Amit Gupta wrote:
> > Before I read the message: I screwed up.
>
> > Let me write again
>
> >>> x = re.compile("CL(?P[a-z]+)")
> > # group name "name1" is attached to the match of lowercase string of
> > alphabet
> > # Now I have a dictionary saying {"name1", "iamgood"}
> > # I would like a function, that takes x and my dictionary and
> > return "CLiamgood"
> > # If my dictionary instead have {"name1", "123"}, it gives error on
> > processingit
> > #
> > # In general, I have reg-expression where every non-trivial match has a
> > group-name. I want to do the reverse of reg-exp match. The function can
> > take reg-exp and replace the group-matches from dictionary
> > # I hope, this make it clear.
>

>
> Good luck.
>
> --
> Steven

Oh, pshaw!  Try this pyparsing ditty.

-- Paul
http://pyparsing.wikispaces.com



from pyparsing import *
import re

# replace patterns of (?Pxxx) with dict
# values iff value matches 'xxx' as re

LPAR,RPAR,LT,GT = map(Suppress,"()<>")
nameFlag = Suppress("?P")
rechars = printables.replace(")","").replace("(","")+" "
regex = Forward()("fld_re")
namedField = (nameFlag + \
LT + Word(alphas,alphanums+"_")("fld_name") + GT + \
regex )
regex << Combine(OneOrMore(Word(rechars) |
r"\(" | r"\)" |
nestedExpr(LPAR, RPAR, namedField |
regex,
ignoreExpr=None ) ))

def fillRE(reString, nameDict):
def fieldPA(tokens):
fieldRE = tokens.fld_re
fieldName = tokens.fld_name
if fieldName not in nameDict:
raise ParseFatalException(
"name '%s' not defined in name dict" %
(fieldName,) )
fieldTranslation = nameDict[fieldName]
if (re.match(fieldRE, fieldTranslation)):
return fieldTranslation
else:
raise ParseFatalException(
"value '%s' does not match re '%s'" %
(fieldTranslation, fieldRE) )
namedField.setParseAction(fieldPA)
try:
return (LPAR + namedField + RPAR).transformString(reString)
except ParseBaseException, pe:
return pe.msg

# tests start here
testRE = r"CL(?P[a-z]+)"

# a simple test
test1 = { "name1" : "iamgood" }
print fillRE(testRE, test1)

# harder test, including nested names (have to be careful in
# constructing the names dict)
testRE = \
r"CL(?P[a-z]+)XY(?P(:?AB)[aeiou]+)" \
r"(?PCD(?P..)\?EF)"
test3 = { "name1" : "iamgoodZ",
  "name2" : "CD@@?EF",
  "name3" : "@@",
  "name4" : "ABeieio",
}
print fillRE(testRE, test3)

# test a non-conforming field
test2 = { "name1" :"123" }
print fillRE(testRE, test2)


Prints:

CLiamgood
CLiamgoodZXYABeieioCD@@?EF
value '123' does not match re '[a-z]+'

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


Inserting NULL values with pymssql

2008-02-21 Thread Jayson Barley
I am attempting to insert NULL values into a database. I have tried to
do this in multiple ways without any success, see below, and haven't
been able to find anything through Google to help out. I am hoping that
I am just overlooking something or that it is a rookie mistake. Below is
a test I came up with to prove this. I am on Windows XP using Python 2.5
and pymssql-0.8.0-py2.5.

CREATE TABLE [dbo].[Test](
 [test] [varchar](50) NULL,
 [inttest] [int] NULL
) ON [PRIMARY]
 
1.
import pymssql
 
TestDB =
pymssql.connect(host='Test',user='test',password='test',database='test')
cursor = TestDB.cursor()
query = """INSERT INTO test.dbo.test VALUES (?, ?);"""
cursor.execute(query,('',''))

Returns
 
Traceback (most recent call last):
  File "C:\Test\db_info\test.py", line 6, in 
cursor.execute(query,('',''))
  File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
self.executemany(operation, (params,))
  File "C:\Python25\lib\site-packages\pymssql.py", line 152, in
executemany
raise DatabaseError, "internal error: %s" % self.__source.errmsg()
pymssql.DatabaseError: internal error: None
 
2.
import pymssql
 
TestDB =
pymssql.connect(host='Test',user='test',password='test',database='test')
cursor = TestDB.cursor()
query = """INSERT INTO test.dbo.test VALUES (?, ?);"""
cursor.execute(query,('',None))
 
Returns
 
Traceback (most recent call last):
  File "C:\Test\db_info\test.py", line 8, in 
cursor.execute(query,('',None))
  File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
self.executemany(operation, (params,))
  File "C:\Python25\lib\site-packages\pymssql.py", line 152, in
executemany
raise DatabaseError, "internal error: %s" % self.__source.errmsg()
pymssql.DatabaseError: internal error: None
 
3.
import pymssql
 
TestDB =
pymssql.connect(host='Test',user='test',password='test',database='test')
cursor = TestDB.cursor()
query = """INSERT INTO test.dbo.test VALUES (?, ?);"""
cursor.execute(query,('','NULL'))

Returns
 
Traceback (most recent call last):
  File "C:\Test\db_info\test.py", line 6, in 
cursor.execute(query,('','NULL'))
  File "C:\Python25\lib\site-packages\pymssql.py", line 126, in execute
self.executemany(operation, (params,))
  File "C:\Python25\lib\site-packages\pymssql.py", line 152, in
executemany
raise DatabaseError, "internal error: %s" % self.__source.errmsg()
pymssql.DatabaseError: internal error: None
 
I am wondering what I am missing that is preventing me from inserting a
NULL. I can perform the INSERT in Server Management Studio the problem
only exists in the Python script. If anyone can point me to a resource
that I may have missed or a flaw in my script I would really appreciate
it.
 
Jayson
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Adding Priority Scheduling feature to the subprocess

2008-02-21 Thread TimeHorse
On Feb 21, 1:17 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>         Why imagine... AmigaOS ran -128..+127 (though in practice, one never
> went above +20 as the most time critical system processes ran at that
> level; User programs ran at 0, the Workbench [desktop] ran at +1... I
> think file system ran +5 and disk device handlers ran +10)
>
>         On the other side, VMS ran 0..31, with 16..31 being fixed realtime
> priorities, and 0..15 being variable (they don't drop below the process
> base, but can and are boosted higher the longer they are preempted)

Thanks for the info!  Actually, many peices of the WinNT kernel were
based on VMS, interestingly enough (go back to the NT 3.5 days and you
can see this) and of course Windows 2000, XP and Vista are all derived
from NT.  So I guess one long-time holdover from the VMS days of NT is
just as you say, it's still true in Windows: processes run 0..15 for
anything but realtime, even if the thread is boosted to Time Critical,
but in realtime the priorities go from 16..31.

Anyway, on the one hand AmigaOS support where -128 -> p = 0.0 and +127
-> p = 1.0 would be a good example of why simply using a 41 point UNIX
scale is defecient in representing all possible priorities, but apart
from the support AmigaOS argument, you bring up another issue which
may be dangerous: are priorities linear in nature?  For instance, a
with-Focus Windows App running Normal-Normal runs at priority 9, p ~=
0.29 (as well as likely for VMS), where as UNIX and Amiga have 0 for
normal processes, p ~= 0.50.  In many ways, the "Normal" mode being
the epoch makes sense, but this clearly cannot be done on a linear
scale.  Perhaps I should modify the PEP to instead having the generic
priorities from 0.0 to 1.0, to have them go from -1.0 to +1.0, with
0.0 considered normal priority.  Then, the negative and positive
regions can be considered linearly but not necessairily with the same
spacing since on Windows -1.0 to 0.0 spans 0 to 9 priorities and 0.0
to +1.0 spans 10 to 31 priorities.  And then, since +20 is the highest
AmigaOS priority in practice, yet the scale goes up to +127, the would
mean that from p ~= +0.16 to p ~= -1.0 you get obscenely high
priorities which do not seem practical.

I will need to think about this problem so more.  I'd hate to think
there might be a priority scale based on a Normal Distribution!  I'm
already going bald; I can't afford to loose any more hair!  :)

Anyway, thanks for info Dennis; you've given me quite a bit to think
about!

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


how to flush child_stdin

2008-02-21 Thread [EMAIL PROTECTED]
I'm opening up a subprocess like this where slave.py is a text based
app that receives commands and responds with output:

r, w, e = popen2.popen3('python slave.py')

I need to send slave.py a command and see the output,
so I'll do something like:

w.write("command here")
then i'll try this:
w.flush()

A separate thread is reading from r to retrieve output of slave.py.

The problem is that slave.py doesn't seem to receive commands unless I
also do:
w.close()

But I don't want to do this because I'll want to send more commands.

Any idea what is going on?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how can i profile every line of code

2008-02-21 Thread Tim Lesher
On Feb 21, 3:27 pm, Tim Lesher <[EMAIL PROTECTED]> wrote:
> On Feb 21, 10:06 am, scsoce <[EMAIL PROTECTED]> wrote:
>
> > I want to profile a function which has some lines of statement. It seem
> > that profile module only report function's stats instead of every  line
> > of code, how can i profile every line of code?
> > thanks.
>
> Use the hotshot profiler, and when creating the profiler instance,
> specify linetimings=True:
>
> http://docs.python.org/lib/module-hotshot.html

Err, that should be "lineevents=True", not linetimings.

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


Re: Help on help()

2008-02-21 Thread Martin v. Löwis
> If I do:
> 
> import my_module
> help(my_module)
> 
> I'd like to see ONLY help on my_module, NOT help on all the functions
> inherited from the various parent classes . . .

I would do

print my_module.__doc__

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


Re: how can i profile every line of code

2008-02-21 Thread Tim Lesher
On Feb 21, 10:06 am, scsoce <[EMAIL PROTECTED]> wrote:
> I want to profile a function which has some lines of statement. It seem
> that profile module only report function's stats instead of every  line
> of code, how can i profile every line of code?
> thanks.

Use the hotshot profiler, and when creating the profiler instance,
specify linetimings=True:

http://docs.python.org/lib/module-hotshot.html


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


Re: can't set attributes of built-in/extension type

2008-02-21 Thread Steve Holden
Neal Becker wrote:
> 7stud wrote:
> 
>> On Feb 21, 11:19 am, Neal Becker <[EMAIL PROTECTED]> wrote:
>>> I'm working on a simple extension.  Following the classic 'noddy'
>>> example.
>>>
>>> In [15]: cmplx_int32
>>> Out[15]: 
>>>
>>> Now I want to add an attribute to this type.  More precisely, I want a
>>> class attribute.
>>>
>>> cmplx_int32.test = 0
>>> ---
>>> TypeError Traceback (most recent call
>>> last)
>>>
>>> /home/nbecker/numpy/ in ()
>>>
>>> TypeError: can't set attributes of built-in/extension
>>> type 'numpy.cmplx_int32'
>>>
>>> What am I missing?
>>
>> class Dog(object):
>> def __setattr__(self, attr, val):
>> print "TypeError: can't set attributes of built-in/extension"
>> print "type 'Dog.cmplx_int32'"
>>
>> d = Dog()
>> d.test = 0
>>
>> --output:--
>> TypeError: can't set attributes of built-in/extension
>> type 'Dog.cmplx_int32'
> 
> Not quite, I'm setting a class attribute, not an attribute on an instance.
> 
Quite. The problem is that extension types' attributes are determined by 
the layout of the object's slots and forever fixed in the C code that 
implements them: the slots can't be extended, so there's no way to add 
attributes. This is an efficiency feature: it would be *extremely* slow 
to look up the basic types' attributes using late-binding (it would also 
change the nature of the language somewhat, making it more like Ruby or 
Self).

So the reason you can't do what you want to is the same reason why you 
can't add attribute to the built-in types (which are, of course, clearly 
mentioned in the error message).

 >>> object.anyoldname = "You lose!"
Traceback (most recent call last):
   File "", line 1, in 
TypeError: can't set attributes of built-in/extension type 'object'
 >>>

If you look in typeobject.c you'll find this error message occurs when 
the object's type isn't a PyHeapTypeObject (in other words, if it's one 
of the built-in or extension types).

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

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


Re: packing things back to regular expression

2008-02-21 Thread MRAB
On Feb 20, 7:36 pm, Amit Gupta <[EMAIL PROTECTED]> wrote:
> Before I read the message: I screwed up.
>
> Let me write again
>
> >> x = re.compile("CL(?P[a-z]+)")
>
> # group name "name1" is attached to the match of lowercase string of
> alphabet
> # Now I have a dictionary saying {"name1", "iamgood"}
> # I would like a function, that takes x and my dictionary and return
> "CLiamgood"
> # If my dictionary instead have {"name1", "123"}, it gives error on
> processingit
> #
> # In general, I have reg-expression where every non-trivial match has
> a group-name. I want to do the reverse of reg-exp match. The function
> can take reg-exp and replace the group-matches from dictionary
> # I hope, this make it clear.

If you want the string that matched the regex then you can use
group(0) (or just group()):

>>> x = re.compile("CL(?P[a-z]+)")
>>> m = x.search("something CLiamgood!something else")
>>> m.group()
'CLiamgood'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Paul Boddie
On 21 Feb, 19:22, Nicola Musatti <[EMAIL PROTECTED]> wrote:
> On Feb 21, 6:31 pm, Paul Boddie <[EMAIL PROTECTED]> wrote:
> [...]
>
> > The main reason why C++ has declined in usage is because almost
> > everything of practical value is optional.
>
> The main reason why C++ has declined in usage is because it never got
> the kind of corporate marketing enjoyed by Java and C#.

What? C++ was practically the favoured language for serious
applications development on the win32 platform for a good decade. It
was all about Visual C++/Studio until Microsoft dabbled with J++, got
sued and eventually came up with C# (and Managed C++). You can't
really ask for a more influential patron than Microsoft.

[...]

> > Back to those C++ newbies, then. Of course, none of them pushed into a
> > C++ project is going to have much say about which memory management
> > "best practice" is going to be used - the decisions are already set in
> > stone by the project - and so it's all about coping with the tedious
> > tracking of "who owns which pointer" and hoping that different
> > libraries don't have different policies. Taking the quotes out of
> > order...
>
> Sorry, but although this was probably true in the early 90's that's
> not the way it goes in practice nowadays, thanks to automatic
> variables, destructors, the standard library containers and smart
> pointers.

Yes, but support for a lot of this stuff usually lags behind the best
practices, so there are usually the tools that actually do attempt to
provide this stuff, then there are the tools which people have to use
(such as Visual Studio) and which don't work satisfactorily, although
I'll admit that the situation was improving (on the Free Software
side, at least) when I last had anything to do with C++ in a project.

Sadly, it took most of the 1990s for widespread support for several
key C++ features to become available. The joke always used to be about
templates and exceptions, but I've had pages full of bizarre errors
from libraries like Boost more recently than the 1990s. And I've seen
plenty of libraries this century which probably don't follow the best
practices, possibly because the people involved have no faith in the
language implementations.

[...]

> It's not just a matter of memory consumption patterns, it's also a
> question of explicitly resetting your memory references to ensure that
> the GC can reclaim them. This can be less than obvious when complex
> data structures and/or callback objects are involved.

As I said, the caveats are fewer, but there are caveats involved, yes.

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


Re: Choosing a Metaclass?

2008-02-21 Thread Steve Holden
Jeff McNeil wrote:
> Hi list,
> 
> Hopefully a quick metaclass question. In the following example, MyMeta 
> is a metaclass that does not inherit directly from type:
> 
> #!/usr/bin/python
> 
> class MyMeta(object):
> def __new__(cls, name, bases, vars):
> print "MyMeta.__new__ called for %s" % name
> return type(name, bases, vars)
> 
> class MetaWrapper(object):
> __metaclass__ = MyMeta
> 
> class M(MetaWrapper):
> pass
> 
> [EMAIL PROTECTED] ~]$ python t.py
> MyMeta.__new__ called for MetaWrapper
> [EMAIL PROTECTED] ~]$
> 
> When I run that script, it's apparent that although M inherits from 
> MetaWrapper, it does not use MyMeta as it's metaclass.  However, if I 
> change MyMeta to be a subclass of builtin type, it works as I would expect:
> 
> [EMAIL PROTECTED] ~]$ cat t.py
> #!/usr/bin/python
> 
> class MyMeta(type):
> def __new__(cls, name, bases, vars):
> print "MyMeta.__new__ called for %s" % name
> return super(MyMeta, cls).__new__(cls, name, bases, vars)
> 
> class MetaWrapper(object):
> __metaclass__ = MyMeta
> 
> class M(MetaWrapper):
> pass
> 
> [EMAIL PROTECTED] ~]$ python t.py
> MyMeta.__new__ called for MetaWrapper
> MyMeta.__new__ called for M
> [EMAIL PROTECTED] ~]$
> 
> How exactly does Python choose which MC it will use when building a 
> class?  It doesn't seem to me that the parent class of MyMeta should 
> matter in this case?
> 
When you create a subclass M of MetaWrapper in your first example, 
MetaWrapper is a subclass of object that has no metaclass of its own, 
and therefore it resolves __new__() from object:

 >>> MetaWrapper.__bases__
(,)
 >>> MetaWrapper.__metaclass__

 >>> dir(MyMeta)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', 
'__hash__', '__init__', '__module__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']
 >>> MetaWrapper.__new__


In your second example MyMeta is a subclass of type, and therefore it 
resolves type's __new__(), which is what takes the special actions you 
observe when a subclass is defined:

 >>> MetaWrapper.__bases__
(,)
 >>> MetaWrapper.__metaclass__

 >>> dir(MyMeta)
['__base__', '__bases__', '__basicsize__', '__call__', '__class__', 
'__cmp__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', 
'__flags__', '__getattribute__', '__hash__', '__init__', '__itemsize__', 
'__module__', '__mro__', '__name__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__subclasses__', 
'__weakrefoffset__', 'mro']
 >>> MetaWrapper.__new__

 >>>

Hope this helps. Remember that when there is no __metaclass__ defined in 
a class's body (and the module namespace has no default __metaclass__) 
the class's metaclass is the type of the class's first base class.

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

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


Re[2]: python-ldap for plone 3 (python 2.4.4)

2008-02-21 Thread Erol Robaina Cepero
On 19/02/2008 at 07:12 p.m. Michael Ströder wrote:

>Erol Robaina Cepero wrote:
>> I need download python-ldap for my plone 3.0.5 that use python 2.4.4.
>> 
>> Do you know where I can find it?
>
>http://python-ldap.sourceforge.net/download.shtml

There I found the version 2.3.1 for python 2.5. It works in python 2.4.4 too?

thank a lot



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

Re: Choosing a Metaclass?

2008-02-21 Thread Jeff McNeil
Never mind, I've figured it out.  The build_class function looks at the
'__class__' attribute of the first base class if there's no explicit
__metaclass__ attribute. By calling type directly, the __class__ attribute
as returned by MyMeta is, in fact, type.

Should have just looked at the source to begin with.

On 2/21/08, Jeff McNeil <[EMAIL PROTECTED]> wrote:
>
> Hi list,
>
> Hopefully a quick metaclass question. In the following example, MyMeta is
> a metaclass that does not inherit directly from type:
>
> #!/usr/bin/python
>
> class MyMeta(object):
> def __new__(cls, name, bases, vars):
> print "MyMeta.__new__ called for %s" % name
> return type(name, bases, vars)
>
> class MetaWrapper(object):
> __metaclass__ = MyMeta
>
> class M(MetaWrapper):
> pass
>
> [EMAIL PROTECTED] ~]$ python t.py
> MyMeta.__new__ called for MetaWrapper
> [EMAIL PROTECTED] ~]$
>
> When I run that script, it's apparent that although M inherits from
> MetaWrapper, it does not use MyMeta as it's metaclass.  However, if I change
> MyMeta to be a subclass of builtin type, it works as I would expect:
>
> [EMAIL PROTECTED] ~]$ cat t.py
> #!/usr/bin/python
>
> class MyMeta(type):
> def __new__(cls, name, bases, vars):
> print "MyMeta.__new__ called for %s" % name
> return super(MyMeta, cls).__new__(cls, name, bases, vars)
>
> class MetaWrapper(object):
> __metaclass__ = MyMeta
>
> class M(MetaWrapper):
> pass
>
> [EMAIL PROTECTED] ~]$ python t.py
> MyMeta.__new__ called for MetaWrapper
> MyMeta.__new__ called for M
> [EMAIL PROTECTED] ~]$
>
> How exactly does Python choose which MC it will use when building a
> class?  It doesn't seem to me that the parent class of MyMeta should matter
> in this case?
>
> Thanks!
>
> Jeff
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Steve Holden
Jeff Schwab wrote:
> Bruno Desthuilliers wrote:
>> Carl Banks a écrit :
>>> On Feb 20, 8:58 am, Tim Chase <[EMAIL PROTECTED]> wrote:
> You Used Python to Write WHAT?
> http://www.cio.com/article/185350
 """
 Furthermore, the power and expressivity that Python offers means
 that it may require more skilled developers.
 [...down to the summary...]
 Python may not be an appropriate choice if you:
 [...]
 *  Rely on teams of less-experienced programmers. These
 developers may benefit from the wider availability of training
 for languages like Java and are less likely to make mistakes with
 a compile-time, type-checked language.
 """

>> (snip)
>>> C++ is a compile-time, type-checked language, which means it is
>>> totally safer for newbies than Python.  Yep, your big company is
>>> totally safe with newbie C++ programmers.
>>>
>> Mouarf ! Brillant demonstration, thanks Carl !-)
>>
>> (and BTW, +1 QOTW)
> 
> 
> NB:  This is not a troll.  (Please, nobody try to be cute with a "yes it 
> is" reply.)
> 
> c.l.python seem to be about the most close-minded of any of the 
> currently popular language-specific news groups.  It's just taken for 
> granted that Perl and C++, two of my personal favorite things in this 
> world, inherently favor ugly, buggy code.  That is the farthest thing 
> from the truth as I see it.  You can (and plenty of people will) write 
> terrible code in any language, including Python.
> 
I'm not sure I agree with that opinion. There is, however, a certain 
amount of what we might term "defensive push back" against static 
language bigots, some of whom come from the C++ camp. You are certainly 
right about bad programmers producing bad programs in any language.

As far as C++ goes I usually defer to Alex Martelli, who used it a long 
time at IBM and is therefore well able to address its deficiencies. I 
believe you are also right in that the defensive posture tends to remain 
even after the bigots go away.

For the record, there are many fine systems crafted in a mix of C++ and 
Python (EVE Online being a prime example). For any sufficiently large 
software system there will always be engineering problems, some of which 
are conditioned by choice of language and some by other factors.

> To use Python effectively, you have to know something about how it 
> works, and the same is true of Perl and C++.  But a newbie who's 
> learning from a decent source (avoid the "C++ for Morons" style books) 
> is likely (I contend) to be writing semi-useful programs about as fast 
> as with Python, and to be writing heavy-duty work-horse programs far sooner.
> 

I agree that C++ is a nice language conceptually, and haven't used it 
enough to hit the hard problems.

> Perl is, and always has been, a language for getting your job done; when 
> everything else failed, Perl and C++ got me through some of the toughest 
> tasks of my life.  Translating file formats, automating system-level 
> tasks...  And now that the C++ standard library is getting regular 
> expressions, I can replace plenty of glued-together scripts with 
> single-language, cohesive applications.
> 
Yes, Perl has always been a pragmatist's language (and indeed the 
author's favored acronym has the P stand for "practical"). I *did* have 
to use Perl for quite a while in the early days of the web and so got to 
experience its many delights at first hand. Again, you are probably 
right in saying we should accept Perl for its efficiencies (I believe 
even now it will generally beat Python on regular expression processing) 
and stop knocking it for its ill-though-out syntax and clumsy object 
implementation.

> I like Python, and I think it's got a brilliant future ahead of it.  It 
> is rapidly becoming the dynamic language of choice, especially for C++ 
> projects.  I am glad that Python can be extended straightforwardly in 
> any C-linkable language.  But this bashing of other powerful languages 
> on the basis that they're hard to read and hard to use correctly is, 
> frankly, nonsense.

Agreed, mostly. I think Perl *is* hard to read (and frankly have been 
amazed at the intentions of the Perl 6 designers), but that shouldn't 
stop people using it, and isn't something that needs constant repetition.

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

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


Re: Double underscores -- ugly?

2008-02-21 Thread benhoyt

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

Okay, I just emailed the BDFL and asked if he could tell me the origin
of the double underscore syntax for __special__ methods, and what he
said I'm pretty sure he won't mind me posting here:

> [Guido van Rossum said:]
> The specific naming convention was borrowed from the C standard, which
> reserves names like __FILE__ and __LINE__. The reason for needing a
> convention for "system-assigned" names was that I didn't want users to
> be surprised by the system giving a special meaning to methods or
> variables they had defined without intending that special meaning,
> while at the same time not wanting to introduce a physically separate
> namespace (e.g. a separate dict) for system names. I have no regrets.

After that and this thread, I'm pretty good with it, I guess. :-)

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


Re: understaning "self"

2008-02-21 Thread D'Arcy J.M. Cain
On Thu, 21 Feb 2008 11:07:18 -0800 (PST)
7stud <[EMAIL PROTECTED]> wrote:
> d = Dog()
> d.bark('Woof!')
> 
> and the call:
> 
> d.bark('Woof!')
> 
> would be transformed into:
> 
> d.bark(d, 'Woof!')

Actually, Dog.bark(d, 'Woof!')

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Script Running Time

2008-02-21 Thread Tim Chase
> I am trying to find a way to output how long a script took to run.
> 
> Obviously the print would go at the end of the script, so it would be
> the time up till that point. I also run a PostgreSQL query inside the
> script and would like to separately show how long the query took to
> run.
> 
> Is this even possible?

Of course...depending on the resolution you need, you can do 
something like

   import datetime
   start_script = datetime.datetime.now()
   # do stuff
   start_postgresql = datetime.datetime.now()
   # make your PG call
   end_postgresql = datetime.datetime.now()
   # do remaining stuff
   end_script = datetime.datetime.now()
   pg_time_taken = end_postgresql - start_postgresql
   script_time_taken = end_script - start_script

You than have pg_time_taken and script_time_taken (which are 
timedelta objects) that you can use for whatever display purposes 
you need.

Alternatively, you can use time.clock()

   from time import clock
   clock()
   # do stuff
   start_pg = clock()
   # do pg stuff
   end_pg = clock()
   # rest of script
   end_script = clock()
   print "Your script took %i seconds" % end_script
   print "Your PG took %i seconds" % (end_pg - start_pg)

-tkc



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


Re: understaning "self"

2008-02-21 Thread 7stud
On Feb 21, 11:49 am, 7stud <[EMAIL PROTECTED]> wrote:
> On Feb 21, 6:34 am, "Poppy" <[EMAIL PROTECTED]> wrote:
>
>
>
> > I've been searching online to try get a better understanding of what "self"
> > does when I define this parameter in my class functions. All I'm finding is
> > debates on whether  "self" has any value to the language but that doesn't
> > help me in my newbie question. So the code excerpt below is from "Beginning
> > Python" Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, Parker,
> > and Roberts.
>
> > What I think "self" is doing is limiting the function call to only function
> > in "this" class. So in the function below "has" calls self.has_various(), if
> > I had a function called "has_various" in my program or another included
> > class using "self" insures that the "has_various" below is the one used. Am
> > I correct in my understanding?
>
> > thanks,
>
> > Zach-
>
> >     def has(self, food_name, quantity=1):
> >         """
> > has(food_name, [quantity]) - checks if the string food_name is in the
> > fridge. quantity defaults to 1
> > returns True if there is enough, false otherwise.
> > """
>
> >         return self.has_various({food_name:quantity})
>
> >     def has_various(self, foods):
> >         """
> > has various(foods) determines if the dictionary food_name
> > has enough of every element to satisfy a request.
> > returns true if there's enough, Fasle if there's not or if an element does
> > not exist.
> > """
> >         try:
> >             for food in foods.keys():
> >                 if self.items[food] < foods[food]:
> >                     return False
> >             return True
> >         except KeyError:
> >             return False
>
> def bark():
>     print "Yip, yip."
>
> class Dog(object):
>     def __init__(the_obj_that_called_this_method):
>         the_obj_that_called_this_method.name = "Blackie"
>         print "Initializing a dog object."
>
>     def bark(the_obj_that_called_this_method):
>         print 'My name is', the_obj_that_called_this_method.name
>         print "Woof, woof."
>
> d = Dog()
> d.bark()
>
> Because the variable name: 'the_obj_that_called_this_method' is too
> hard to type, by convention people use the variable name: 'self'
> instead.
>
> > What I think "self" is doing is limiting the function
> > call to only function in "this" class.
>
> No.  Whenever you write obj.method_name, the '.' directs python to
> look inside obj's class definition for the specified method.  When you
> call a function like this:
>
> def show(x):
>     print x
>
> show('hello')
>
> python assigns the argument 'hello' to the parameter variable x.  When
> you write:
>
> d.bark()
>
> even though there are no arguments specified in that method call,
> python secretly passes one argument to the method: the object on the
> left side of the '.'.

self is just a parameter variable in a function definition, and just
like any other parameter variable in a function definition, self
stands ready to have any argument passed to the function assigned to
it.   It just so happens, that *you* aren't the one specifying the
*first* argument when you call a function in a class.  Functions in a
class are called 'methods', and all method calls of the form:

d.bark()

are transformed into this:

d.bark(d)

so bark() in d's class needs to be defined with one parameter
variable--even though the method call looks like bark() should be
defined with no parameter variables.  On the other hand, if bark()
were defined like this:


class Dog(object):
def __init__(the_obj_that_called_this_method):
the_obj_that_called_this_method.name = "Blackie"
print "Initializing a dog object."

def bark(the_obj_that_called_this_method, sound):
print 'My name is', the_obj_that_called_this_method.name
print sound


Then you would call bark() like this:

d = Dog()
d.bark('Woof!')

and the call:

d.bark('Woof!')

would be transformed into:

d.bark(d, 'Woof!')

As a result, bark() must be defined with two parameter variables: one
for d and one for the string.
-- 
http://mail.python.org/mailman/listinfo/python-list


Odd behaviour of *.pth files and Apache

2008-02-21 Thread D'Arcy J.M. Cain
I tried searching the archives for information on this but nothing
seemed to be germane.  I am running Python sripts as CGI under Apache
and I have a .pth file in site-packages that includes directory that
has another .pth in it.  Sometimes it picks up the paths in the
second .pth and sometimes it does not.  It always seems to work if I am
working in a location not in the ServerRoot but if I use the main site
it does not pick up the directories in the included .pth.

I have tried changing just about everything with no difference.  Can
somone suggest any reason why Python would not recurse the .pth files
sometimes and not others?

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can't set attributes of built-in/extension type

2008-02-21 Thread Neal Becker
7stud wrote:

> On Feb 21, 11:19 am, Neal Becker <[EMAIL PROTECTED]> wrote:
>> I'm working on a simple extension.  Following the classic 'noddy'
>> example.
>>
>> In [15]: cmplx_int32
>> Out[15]: 
>>
>> Now I want to add an attribute to this type.  More precisely, I want a
>> class attribute.
>>
>> cmplx_int32.test = 0
>> ---
>> TypeError                                 Traceback (most recent call
>> last)
>>
>> /home/nbecker/numpy/ in ()
>>
>> TypeError: can't set attributes of built-in/extension
>> type 'numpy.cmplx_int32'
>>
>> What am I missing?
> 
> 
> class Dog(object):
> def __setattr__(self, attr, val):
> print "TypeError: can't set attributes of built-in/extension"
> print "type 'Dog.cmplx_int32'"
> 
> d = Dog()
> d.test = 0
> 
> --output:--
> TypeError: can't set attributes of built-in/extension
> type 'Dog.cmplx_int32'

Not quite, I'm setting a class attribute, not an attribute on an instance.

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

Re: understaning "self"

2008-02-21 Thread 7stud
On Feb 21, 6:34 am, "Poppy" <[EMAIL PROTECTED]> wrote:
> I've been searching online to try get a better understanding of what "self"
> does when I define this parameter in my class functions. All I'm finding is
> debates on whether  "self" has any value to the language but that doesn't
> help me in my newbie question. So the code excerpt below is from "Beginning
> Python" Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, Parker,
> and Roberts.
>
> What I think "self" is doing is limiting the function call to only function
> in "this" class. So in the function below "has" calls self.has_various(), if
> I had a function called "has_various" in my program or another included
> class using "self" insures that the "has_various" below is the one used. Am
> I correct in my understanding?
>
> thanks,
>
> Zach-
>
>     def has(self, food_name, quantity=1):
>         """
> has(food_name, [quantity]) - checks if the string food_name is in the
> fridge. quantity defaults to 1
> returns True if there is enough, false otherwise.
> """
>
>         return self.has_various({food_name:quantity})
>
>     def has_various(self, foods):
>         """
> has various(foods) determines if the dictionary food_name
> has enough of every element to satisfy a request.
> returns true if there's enough, Fasle if there's not or if an element does
> not exist.
> """
>         try:
>             for food in foods.keys():
>                 if self.items[food] < foods[food]:
>                     return False
>             return True
>         except KeyError:
>             return False



def bark():
print "Yip, yip."


class Dog(object):
def __init__(the_obj_that_called_this_method):
the_obj_that_called_this_method.name = "Blackie"
print "Initializing a dog object."

def bark(the_obj_that_called_this_method):
print 'My name is', the_obj_that_called_this_method.name
print "Woof, woof."


d = Dog()
d.bark()

Because the variable name: 'the_obj_that_called_this_method' is too
hard to type, by convention people use the variable name: 'self'
instead.

> What I think "self" is doing is limiting the function
> call to only function in "this" class.

No.  Whenever you write obj.method_name, the '.' directs python to
look inside obj's class definition for the specified method.  When you
call a function like this:

def show(x):
print x

show('hello')

python assigns the argument 'hello' to the parameter variable x.  When
you write:

d.bark()

even though there are no arguments specified in that method call,
python secretly passes one argument to the method: the object on the
left side of the '.'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Script Running Time

2008-02-21 Thread ewanfisher
Hello,

I am trying to find a way to output how long a script took to run.

Obviously the print would go at the end of the script, so it would be
the time up till that point. I also run a PostgreSQL query inside the
script and would like to separately show how long the query took to
run.

Is this even possible?

Thanks,

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


Re: can't set attributes of built-in/extension type

2008-02-21 Thread 7stud
On Feb 21, 11:19 am, Neal Becker <[EMAIL PROTECTED]> wrote:
> I'm working on a simple extension.  Following the classic 'noddy' example.
>
> In [15]: cmplx_int32
> Out[15]: 
>
> Now I want to add an attribute to this type.  More precisely, I want a class
> attribute.
>
> cmplx_int32.test = 0
> ---
> TypeError                                 Traceback (most recent call last)
>
> /home/nbecker/numpy/ in ()
>
> TypeError: can't set attributes of built-in/extension
> type 'numpy.cmplx_int32'
>
> What am I missing?


class Dog(object):
def __setattr__(self, attr, val):
print "TypeError: can't set attributes of built-in/extension"
print "type 'Dog.cmplx_int32'"

d = Dog()
d.test = 0

--output:--
TypeError: can't set attributes of built-in/extension
type 'Dog.cmplx_int32'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Article of interest: Python pros/cons for the enterprise

2008-02-21 Thread Nicola Musatti
On Feb 21, 6:31 pm, Paul Boddie <[EMAIL PROTECTED]> wrote:
[...]
> The main reason why C++ has declined in usage is because almost
> everything of practical value is optional.

The main reason why C++ has declined in usage is because it never got
the kind of corporate marketing enjoyed by Java and C#.

> Meanwhile, those C++
> newbies we were talking about are having to deal with decisions that
> everyone else can quite happily ignore, knowing that the right choice
> has probably already been made for them, where automatic memory
> management is probably the right choice for the biggest decision of
> them all, as Java demonstrated quite successfully to the hordes of
> enterprise programmers (and their managers) at the end of the 1990s.

A choice that is available to C++ programmers too, altough I admit
it's not a common one and does usually require an external library. As
to it being the right choice it's debatable: it took Java something
like ten years to come out with usable GUI applications and, judging
from many articles and postings across the internet memory management
*is* an issue with Java, especially for long running applications.

There are other downsides to garbage collection, as the fact that it
makes it harder to implement the Resource Acquisition Is
Initialization idiom, due to the lack of deterministic destruction.
Other languages, such as Python and C#, are recognizing this fact and
provide the with/using statement, which serves this purpose but is
definitely more clumsy.

> Back to those C++ newbies, then. Of course, none of them pushed into a
> C++ project is going to have much say about which memory management
> "best practice" is going to be used - the decisions are already set in
> stone by the project - and so it's all about coping with the tedious
> tracking of "who owns which pointer" and hoping that different
> libraries don't have different policies. Taking the quotes out of
> order...

Sorry, but although this was probably true in the early 90's that's
not the way it goes in practice nowadays, thanks to automatic
variables, destructors, the standard library containers and smart
pointers.

> > At least C++ programmers tend to know that memory
> > must be managed, while newbies in other languages are often lead to
> > believe - wrongly - that the garbage collector takes care of
> > everything.
>
> Sure, there are some issues with memory consumption patterns with
> various garbage collectors, but the "it's good for you" attitude has
> scant justification unless you're dealing with constrained
> environments.

It's not just a matter of memory consumption patterns, it's also a
question of explicitly resetting your memory references to ensure that
the GC can reclaim them. This can be less than obvious when complex
data structures and/or callback objects are involved.

> And even with people watching the dials in their C++
> application, you still get obscene resource misuse, which is why
> Firefox eventually consumes over 1GB memory on this desktop. There are
> considerably fewer caveats involved with regard to languages with
> garbage-collected runtime environments.

Unfortunately C++ by itself cannot ensure that only top programmers
use it ;-)

> I seem to remember that Hans Boehm had some interesting observations
> about garbage collection myths, especially around performance, but
> since the mindset persists in large tracts of the C++ development
> landscape that it must somehow be cheating to use a garbage collector,
> I suppose we still have a few more years of applications accessing the
> wrong memory locations and showing the usual useless backtrace
> dialogues for submission to uninterested developers who insisted on
> using C++ because "everything else is slow".

Things change. Boehm himself is working for the inclusion of -
optional - garbage collection in the C++ standard.

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


Re: psycopg2: connect copy_from and copy_to

2008-02-21 Thread james . pye
On Feb 20, 9:27 am, Thomas Guettler <[EMAIL PROTECTED]> wrote:
> Up to now I am happy with psycopg2.

Yeah. psyco is good.

>  Why do you develop pg_proboscis?

[Good or bad as they may be]

1. Alternate interface ("greentrunk")
2. Non-libpq implementation yields better control over the wire that
allows:
a. Custom communication channels (not limited to libpq's
worldview)
b. Leveraging of protocol features that libpq's API does not fully
accommodate (think bulk INSERTs using prepared statements with less
round-trip costs)
c. Allows custom "sub-protocols"(I use this to implement a remote
python command/console[pdb'ing stored Python procedures, zero network
latency
   scripts]).
3. Makes use of binary types to reduce bandwidth usage. (I started
developing this before libpq had the ability to describe statements to
derive statement
   parameter types and cursor column types(?), so using the binary
format was painful at best)
4. Has potential for being used in event driven applications without
threads.
5. Better control/understanding of running queries allows for
automatic operation interrupts in exception cases:
   [The last two may be possible using libpq's async interfaces, but
I'm not entirely sure]
6. Arguably greater(well, *easier* is likely a better word)
portability. While I have yet to get it to work with other
Pythons(pypy, ironpython, jython), the potential to work with these
alternate implementations is there. The real impediment here is
missing/inconsistent features in the implementations(setuptools
support, missing os module in ironpython(i know, i know, and I don't
care. Last time I checked, it's missing from the default install
that's broken :P), jython is still at 2.2, iirc)
7. Bit of a license zealot. psycopg2 is [L?]GPL, pg_proboscis is
BSD[or MIT if you like] like PostgreSQL. (Yes, Darcy's interface is
BSD licensed(iirc), but it too is libpq based)

In sum, it yields greater control over the connection which I believe
will lead to a more flexible and higher quality interface than a libpq
solution.
[The primary pain point I've had is implementing all the
authentication mechanisms supported by PG]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why must implementing Python be hard unlike Scheme?

2008-02-21 Thread Kay Schluehr
On 21 Feb., 18:28, John Nagle <[EMAIL PROTECTED]> wrote:

>  The run-time data implementation is all dictionaries.  In Python,
> everything is a variable-sized hash.  You don't even have to allocate
> storage during compile time.  The run-time environment is a tree of hashes.

Except that it is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >