Re: Death to tuples!

2005-11-28 Thread Sybren Stuvel
Mike Meyer enlightened us with:
> Is there any place in the language that still requires tuples
> instead of sequences, except for use as dictionary keys?

Anything that's an immutable sequence of numbers. For instance, a pair
of coordinates. Or a value and a weight for that value.

> If not, then it's not clear that tuples as a distinct data type
> still serves a purpose in the language. In which case, I think it's
> appropriate to consider doing away with tuples.

I really disagree. There are countless examples where adding or
removing elements from a list just wouldn't be right.

> The new intended use is as an immutable sequence type, not a
> "lightweight C struct".

It's the same, really. A lightweight list of elements, where each
element has its own meaning, is both an immutable sequence as well as
a lightweight C struct.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


yahoo sender name

2005-11-28 Thread john boy
hey...I know this is off the "python" topicbut I have yahoo mail and would like to change my "sender name"  I have gone to the "edit account" area and have changed all names that can be edited to a consistent name other than the current sender name...but for some reason it will not change the sender name...is anybody familiar with yahoo mail and changing names?     -thanks in advance-
		 Yahoo! Music Unlimited - Access over 1 million songs. Try it free.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: best cumulative sum

2005-11-28 Thread Peter Otten
[EMAIL PROTECTED] wrote:

>> def ireduce(op, iterable, *init):
>> iterable = chain(init, iterable)
>> accu = iterable.next()
>> yield accu
>> for item in iterable:
>> accu = op(accu, item)
>> yield accu

> I believe there is only one initializer in reduce. 

Throw in a 

if len(init) > 1: raise TypeError

for increased similarity to reduce(). 

> Also it is possible to not provide it.

Try it. 

Peter

PS: Did I mention that I prefer for-loops over reduce() most of the time?


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


Re: return in loop for ?

2005-11-28 Thread Duncan Booth
Steven D'Aprano wrote:

> Since real source code verifiers make no such sweeping claims to
> perfection (or at least if they do they are wrong to do so), there is
> no such proof that they are impossible. By using more and more
> elaborate checking algorithms, your verifier gets better at correctly
> verifying source code -- but there is no guarantee that it will be
> able to correctly verify every imaginable program.
> 
I'm sure you can make a stronger statement than your last one. Doesn't 
Godel's incompleteness theorem apply? I would have thought that no matter 
how elaborate the checking it is guaranteed there exist programs which are 
correct but your verifier cannot prove that they are.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing big XML files where beginning depends on end.

2005-11-28 Thread Magnus Lycka
Gerard Flanagan wrote:
> what about multiple xml files? 

We have deployed code that relies of the XML files
looking the way they do, and we'd prefer not to
change that.

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


Re: return in loop for ?

2005-11-28 Thread Sybren Stuvel
Duncan Booth enlightened us with:
> I would have thought that no matter how elaborate the checking it is
> guaranteed there exist programs which are correct but your verifier
> cannot prove that they are.

Yep, that's correct. I thought the argument was similar to the proof
that no program (read: Turing machine) can determine whether a program
will terminate or not.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exception KeyboardInterrupt and os.system command

2005-11-28 Thread malv
That's also kind of what I expected.
However, I quickly tried:
import os
while 1:
 y = os.system("sleep 1")
 z = (y >> 8) & 0xFF
 print z

I never get anything in return but 0, hitting c-C or not.
I have uset the above code to get exit code returns in the past though.
Would there be anything special with sleep?

Regards,
malv

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


Re: General question about Python design goals

2005-11-28 Thread Antoon Pardon
Op 2005-11-28, Aahz schreef <[EMAIL PROTECTED]>:
> In article <[EMAIL PROTECTED]>,
> Christoph Zwerschke  <[EMAIL PROTECTED]> wrote:
>>
>>For instance, I just wanted to use the index() method on a tuple which 
>>does not work. It only works on lists and strings, for no obvious 
>>reason. Why not on all sequence types?
>
> Because Guido believes that tuples should be primarily used as
> lightweight replacements for C structs.  Therefore they have minimal
> functionality.

I find that a bit contradictory with the fact that if you want list like
structures as a dictionary key, you are mostly advised to cast them
as tuples.

So suppose I want a dictionary, where the keys are colours, represented
as RGB triplets of integers from 0 to 255. A number of things can be
checked by index-like methods.

e.g.
  
  def iswhite(col):
return col.count(255) == 3

  def primary(col):
return col.count(255) == 1 and col.count(0) == 2

  def secondary(col):
return col.count(255) == 2 and col.count(0) == 1


So, what should I use to implement this? Whether I choose
lists or tuples, I will end up either copying a lot from
lists to tuples or vice versa, to get the functionality
I need, or I will have to implement functionality myself
that basically is already in the language.

I also find the use of C-structs and tuples completly different.
If I need a C-struct like object, I go for Bunch, Rec or something
similar. Something that uses field identifiers to address components,
Not something that uses indexing.

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


Re: How to make tkFileDialog GUI larger?

2005-11-28 Thread Martin Franklin
John Wheez wrote:
> Hi all,
> 
> I'm using teh  tkFileDialog to let teh user select a directory. We have 
> long names which make
> it difficult to view the directories.
> 
> For some reason the GUI windows doesn;t expand on Windows like it does 
> on OS X or Linux.
> Is there a method to make the widths of the  tkFileDialog windows larger 
> when using Windows XP?
> 
> Thanks for any info.
> 
> .JW

this is due to Tk using a native Windows file dialog and I guess this is
the default behavior on Windows...  There may be a special Windows only
hack but I'm sorry I don't know what it would be

Martin

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


Re: General question about Python design goals

2005-11-28 Thread Fredrik Lundh
Christoph Zwerschke wrote:

> What about design goals such as:
>
> - orthogonality
> - coherence, consistency
> - principle of least astonishment ("Python fits my brain")
> - simplicity ("kiss" principle)
> - aesthetics, symmetry
>
> Actually, which priority have the above design goals for Python? Are
> other design goals considered more important?

- A Foolish Consistency is the Hobgoblin of Little Minds
- Hypergeneralization Sucks





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


Re: Making immutable instances

2005-11-28 Thread Antoon Pardon
Op 2005-11-26, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
> On Thu, 24 Nov 2005 12:55:07 +, Antoon Pardon wrote:
>
>> Suppose I have the following code.
>> 
>> from module import __take_care__
>> 
>> __private_detail__ = ...
>> 
>> I now have two variable that are flaged the same way, but they are not.
>
> No, you have two names written using a poor naming convention.

Well if it is a poor naming convention, why react to me, and not to
Mike who was defending this poor naming convention?

> __name__ should be used only for Python's special methods.
>
>> __take_care__ is a private variable from an other module which I should
>> use with extreme care not to break the other package.
>
> Python doesn't do any special treatment of __name or __name__ from
> modules. The only information hiding techniques Python enforces are that
> module._name (single leading underscore) is not imported by "from module
> import *", and class.__name (double leading underscore) is mangled to
> class._Class__name.

We were not talkin about special treatment by python. We were talking
about conventions to communicate purpose to other readers of the
software.

>> It are other modules that should take special care if they
>> should choose to import this variable.
>
> I'm not sure what the difference is. If there is a difference, why are you
> using the same naming convention for different sorts of names ("private
> module variable" and "private module data"). If there is no difference, I
> don't understand the point of your example.

Well it seems you didn't seem to understand the point of my answer.
Maybe you should first reread the article I responded too.

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


resume TCP comunication

2005-11-28 Thread zunbeltz
Hi,

I'am writing a program to cotrol a machine. I use socket comunication
(TCP) to do it.
I do a measurement in my machine like this:

def DoMeasurement():
setup1()
setup2()
while MeasurementNotFinished():
move()
measure()
finalizeMeasurement()


Each funciton setup1, setup2, move,mesure, ... call a method in a class
that contains a socket that do the comunication staff

class DiSock(socekt):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def comunicate(self):
self.sock.sendall(Request.struct2string())

msg = ''
MSGLEN = 608
while len(msg) < MSGLEN:
chunk = self.sock.recv(MSGLEN-len(msg))
if chunk == '':
raise RuntimeError,"socket connection broken"
msg = msg + chunk
data = msg
Answer.string2struct(data)


Request and Anser are objects in where i put the information i whant to
send and recive from the
machine.

All the measurement is done in a new thread.

The problem is that sometimes i loose the conenction whith the
machines. In the case a ConnectionFailure exception is raised. How can
i do resume the Measurement when the conection is  resumed? Can i use a
yield for this?

Thanks in advance

Zunbeltz

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


Re: Python as Guido Intended

2005-11-28 Thread Antoon Pardon
Op 2005-11-25, Mike Meyer schreef <[EMAIL PROTECTED]>:
> Antoon Pardon <[EMAIL PROTECTED]> writes:
>> Op 2005-11-24, Mike Meyer schreef <[EMAIL PROTECTED]>:
>>> Antoon Pardon <[EMAIL PROTECTED]> writes:
> The usual response is "That's not the Python way." That's not calling
> someone dumb, just pointing out that they don't yet fully understand
> the Python way.
 "That is not the Python way", is just saying "Python doesn't have it"
 in other words. So it can't be the answer to why python can't have
 something.
>>>
>>> No, it isn't. At least, it isn't when I use it. A language is more
>>> than just an accumulation of features. Well, a good language is more
>>> than just an accumulation of features - there's a philosophy
>>> underlying the language, that guides what features are added and what
>>> features aren't. Other languages have other philosophies, and wind up
>>> being good for other things.
>>
>> But how this philosophy influences design is not straight forward.
>>
>> The ternary operator was thought of to go against the philosopy,
>
> By who?

I would guess in the first place by Guido. Just look at the history
of how it finaly came to be present and IMO the only conclusion
is that Guido doesn't like a ternary operator.

Then there were those who always argued against the ternary
operator. I'm sure you can dig up some names if you go
through google groups.

>> and now seems to be at least compatible with the philosophy.
>>
>> So when someone asks why it is not in python, saying "It is not
>> the python way" still doesn't answer the question, because the
>> person would probably still like to know what in his proposal
>> is against the python philosophy and why.
>
> Sometimes, such things are easy to explain, and they'll generally get
> that explanation. Sometimes they aren't,

Well maybe that are not that easy to explain because they aren't.

> so you're reduced to
> pointing out similar - but more obvious - things that aren't in the
> language, and "import this", and suggesting that they try it for a
> while and see how it works
>
>>> My vision
>>> isn't perfect - I've changed my mind about things: I used to want real
>>> macros, and I initially disliked list comprehensions. My vision
>>> doesn't agree with the developers - notably including Guido's - a lot
>>> of the time. On the other hand, they haven't done anything that
>>> strikes me as so wrong that I want to spend the time required working
>>> on Python rather than in Python to allow me to get it fixed.
>>
>> I see nothing wrong with that. But I would apreciate it, should
>> you be more open about something being your personal vision.
>> To me something like: "That is not the python way" comes accross
>> as: "You just don't understand about python, if you ask/propose
>> something like that"
>
> That's essentially true. In some cases, the reasons can be explained
> without understanding about python. In some cases, they can't.

Which IMO makes python like a cult. The characteristic of certain
things only explainable to those who have seen the light, makes
for a view that never needs to fear being contradicted. Well
I'm sorry that I can't explain it to you, but you just don't
understand Python.

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


Re: Writing pins to the RS232

2005-11-28 Thread Richard Brodie

"Roy Smith" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>> While I realize this is more on a driver/hardware level it's
>> interesting that it's so difficult to use a different protocol for an
>> existing driver.  For example, all serial does is a series of high and
>> low voltages on specific pins.  Why should it be so hard to use an
>> existing driver and hold a pin on high?
>
> It's been a long time since I've looked at this low-level hardware, but 
> the
> answer is almost certainly, "No just 'so hard', but 'impossible'".

If you just need one or two signals, then it might be practical to use one
of the control lines, and PySerial supports this (UPS monitoring software
often works this way). Setting 8 pins to 1 would be impossible, because
there plain won't be that number of outputs wired, in addition to all the
good stuff about UARTs Roy said. 


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


Re: Python as Guido Intended

2005-11-28 Thread Antoon Pardon
Op 2005-11-25, Mike Meyer schreef <[EMAIL PROTECTED]>:
> Antoon Pardon <[EMAIL PROTECTED]> writes:
>> Well this is, is one thing I have a problem with.
>>
>> The python people seem to be more concerned with fighting things
>> that could be used counter the python philosophy, than search for
>> things that enable working in the python philosophy.
>
> And what's wrong with that?

It seems a bit intollerant and contraproductive to me.

If thet would just concentrated on what they want, they could
have progressed further on that road, then where they are now,
because progress sometimes simple stops because other could
use something for what it was not intended.

>>> Yes. And if you need a red hammmer, you should get a red hammer, not
>>> use red spray paint on one that wasn't designed to be red. Just
>>> because *you* don't see how providing a red option violates the
>>> philosophy of python doesn't mean that it doesn't do so.
>>
>> Well this seems to be the main conflict between those who would
>> like Python to go a bit further and those that oppose it.
>>
>> Should the priority be to enable python's philosophy or should
>> it be the priority to limit python to only allow it's philosophy.
>
> Those two statements say the same thing.

They are not. 

> Part of the Python philosphy,
> from "import this", is that there should only be one obvious way to do
> it.

It doesn't say that. It says:

There should be one-- and preferably only one --obvious way to do it.

Here you see the difference on emphasis. You are focussing on the
only one, while the original Python Koan seems to focus on the
there should be one.

So supose someone proposes a change that will introduce one
obvious way, to solve a particular problem. However it
introduces a second obvious way to solve an other problem
too.

I think we should accept such a proposal. It seems you and
a lot of others seem to think such proposals should be
rejected.

> By enabling that part of Python's philosphy, you're automatically
> limiting python to not allow other - specifically non-pythonic - ways
> to do the same thing.

No it doesn't.

Supose someone proposes a change that will introduce one
obvious way, to solve a particular problem. However it introduces a
second non pythonic way to solve an other problem.

I don't think there is something wrong with accepting this
change. However it seems you do.

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


Re: Newbie question: Tab key giving different output

2005-11-28 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I'm a newbie to python. I run python under Manddrake Linux 10.2 from a
> terminal.
>
> While in the interactive mode, i need to use the tab key to indent my
> code. However, i get a message "List all 174 possibilities? (Y/N)"
> instead of an indent. So i use spaces.
>
> How do i tell python to give me indents?

see section A.3, Key Bindings, in the tutorial:

http://docs.python.org/tut/node15.html





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


Re: Python as Guido Intended

2005-11-28 Thread Antoon Pardon
Op 2005-11-28, Serge Orlov schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>> No it wasn't. From what I have picked up, the ternary operator
>> was finaly introduced after one of the developers tripped over
>> the commonly used idiom to simulate a ternary operator, which
>> can fail in certain cases.
>
>>
>> Anyway, when I was arguing for a ternary operator in python,
>> those who opposed me, certainly gave me the impression that
>> they thought I wanted to mangle the language, the mere idea
>> of a ternary operator was against the spirit of python.
>>
>> When I argued for a more general loop construct similar
>> objections were made and the proposal was fiercely fought.
>> Someone even started a PEP, with the intention to bury
>> the idea. (That can be from before I argued for it)
>>
>> Now I have read about both that they will be introduced in
>> Python 2.5 without a whisper of protest.
>
> Protesting BDFL is absolutely useless by definition even if you
> disagree. Tim Peters wanted generators for 10 years
>
> and he has much more power of convincing Guido than you. Why do you
> think your proposal should be immediately accepted?

I don't think that. I was just illustrating that using:
"That is unpythonic" isn't really an argument, because
things that were thought unpythonic before are now
accepted as the pythonic way.

> By the way, I don't see the features you mentioned neither in
>
> nor among PEPs. Perhaps they are not final?

There were people who annouced these features in this newsgroup
for version 2.5 with a rather clear titles and those from the
dev-list that frequent this newsgroup didn't protest.

Among the PEP's I see that at least PEP 308 is accepted.
So although it may not be implemented for version 2.5
a ternary operator is now an accepted as being pythonic.

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


Re: Python as Guido Intended

2005-11-28 Thread Antoon Pardon
Op 2005-11-25, EP schreef <[EMAIL PROTECTED]>:
>
> What is the philosophy?  I'm not the one to answer that,
> but I do use "import this" for reference, and it seems to
> answer some of the points in this thread:
>
 import this
> The Zen of Python, by Tim Peters
>
> Beautiful is better than ugly.
> Explicit is better than implicit.
> Simple is better than complex.
> Complex is better than complicated.
> Flat is better than nested.
> Sparse is better than dense.
> Readability counts.
> Special cases aren't special enough to break the rules.
> Although practicality beats purity.
> Errors should never pass silently.
> Unless explicitly silenced.
> In the face of ambiguity, refuse the temptation to guess.
> There should be one-- and preferably only one --obvious way to do it.
> Although that way may not be obvious at first unless you're Dutch.
> Now is better than never.
> Although never is often better than *right* now.
> If the implementation is hard to explain, it's a bad idea.
> If the implementation is easy to explain, it may be a good idea.
> Namespaces are one honking great idea -- let's do more of those!
 

No, it doesn't answer anything. My impression is that the Zen of
Python gets used a lot by the python people like the bible is
used by the christions: You can always find a verse/Koan that
supports your view.

If someone comes with a pratical proposal that breaks a rule,
the proponents will cite: "practical beats purity" and
the opponents will cite: "Special cases aren't special enough
to break the rules:

And each will be convince that his view is the pythonic one.

I'm even of the impression that what is considered pythonic
or not is more related to who proposes it that to what the
proposal is and that after one has so decided the right
rules are selected to defend that decision.

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


ANN: Dao Language v.0.9.6-beta is release!

2005-11-28 Thread [EMAIL PROTECTED]
Dear all,

This is just to let you know that the lastest version Dao language is
released.
This Dao was previously called Tao, and now is changed to Dao to avoid
confusion
with another Tao langauge. There are a number of new features
implemented in
this version, of which the most important one is the supporting for
multi-threaded
programming. A new concurrent garbage collector is also implemented to
for the
multi-threaded interpreter. Now unicode is also supported for string
manipulation
and regular expression (regex) matching etc. The algorithm for regex
matching
is enhanced with fixing of a few bugs which prevent finding the most
reasonable
matching in some case, and allowing reverse matching from the end of
string.
The interface for creating Dao plugin in C++ is further simplified and
matured.
Of course, many bugs are also fixed. For more information,
please visite: http://www.xdao.org.

By the way, a console named DaoConsole with graphical user interface is
also released.

With best regards,

Limin Fu

-
ChangLog for this release:
-

+ : added
! : changed
* : fixed
- : removed

MULTITHREADING:
+   Multi-threaded programming is supported as a kernel feature of
Dao language. Posix thread library is used in the implementation.
And the thread API in Dao is similar to that in Posix thread.
Parts of the Dao interpreter is re-structured for multithreading.
+   A novel concurrent garbage collector based on reference counting
is implemented to support multithreading.
+   A upper bound for GC amount is applied to prevent memory "avalanche",
where mutators generate garbage faster than GC can collect them.
gcmin(), gcmax().

UNICODE:
+   UNICODE is supported. String quotated with double quotation symbol
is internally represented as Wide Character String(WCS), while string
quotated with single quotation symbol is internally represented
Multi Bytes String(MBS). Corresponding operations on WCS is also
supported.

REGEX:
+   Regex reverse matching is supported.
+   Now internal representation of Regex uses both MBS and WCS for both
efficiency and proper matching character class for unicode. When a
regex is applied to MBS or WCS, the corresponding representation is
used.
+   Regex datatype is added, a regex pattern can be compiled and stored
for later use, by using: define regex: rgx = /\d+\w/;
or, rgx = regex( "\\d+\\w" );
+   New character class abbreviations \u and \U are added for unicode.
+   Customized character class abbreviations are support. Users can
define
their own character class abbreviations by:
define regex: \2 = [WhateverChars];
!   Algorithm for regex matching is modified to extend matching when
possible, and is also modified to match regex group correctly.

NUMERIC ARRAY:
+   Specification of precision in numeric array enumeration is supported:
[EMAIL PROTECTED] array];
!   Transpose operator(right operator) is changed from ' to ~.
-   Function convolute() for numeric arrays is removed.

EXTENDING AND EMBEDDING:
+   Some abstract classes are added for supporting easy embedding
of Dao interpreter ( the daoMain.cpp source file is an example
for embedding ).
+   Some wrapper classes for Dao data objects are provide in daoType.h
to faciliate the using of Dao data objects in plugins or other
programs in which Dao is embedded.
!   A new technique is implemented to allow more tranparent passing
data between Dao interpreter and C++ modules. Creation of shadow
classes is also supported by the way.

IO:
+   Instead of using STL stream classes, new DaoStream classes are
added mainly for handling unicode in many places.
+   For file IO, more open modes such as "rwat" are supported, and
more methods such as eof(), seek(), tell() ... are implemented.
read() is enhanced such that it can read until meeting EOF.

OTHERS:
+   Multi inheritance is supported for OOP. And the passing parameters
and calling to parent constructor is simplified.
+   Negative subindex is supported for string.
+   Added a feature that allows using Alternate KeyWord (*.akw) to
write Dao scripts in non-english languages. The only requirement
is the character encoding for the .akw file must be the same as the
script files.
!   Variable scope specification keyword "global" is added; keyword
"extern" is remove; keyword "share" is changed to "shared"
!   Data states are added for constant and frozen data. Now a const
data is a really const, and can not be modified anymore. Function
freeze() is added to freeze some data structures as well as those
are reachable from them, to prevent them from being modified;
And d

Re: General question about Python design goals

2005-11-28 Thread Antoon Pardon
Op 2005-11-28, Fredrik Lundh schreef <[EMAIL PROTECTED]>:
> Christoph Zwerschke wrote:
>
>> What about design goals such as:
>>
>> - orthogonality
>> - coherence, consistency
>> - principle of least astonishment ("Python fits my brain")
>> - simplicity ("kiss" principle)
>> - aesthetics, symmetry
>>
>> Actually, which priority have the above design goals for Python? Are
>> other design goals considered more important?
>
> - A Foolish Consistency is the Hobgoblin of Little Minds

What is so foolish about the consistency that all sequence types
have a count method?

The way this "pearl of wisdom" is used in this newsgroup, I expect
one day someone to use "+" for substraction and '-" for addition and
then when people complain about that not being consistent they get
answered by the above quote.

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


type of form field

2005-11-28 Thread Ajar
Is there any way to retrieve the type(checkbox,radio...) of the form
field from cgi.FieldStorage. I tried something like form['name'].type,
but this field seems to be None for all the form fields

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


Re: importing a method

2005-11-28 Thread Flavio
Because, by the time the user function is imported and attributed to
the custom method, soandso has already been instantiated and contains
the information tha needs to accessed by the user's function.

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


Re: General question about Python design goals

2005-11-28 Thread Sebastien Douche
On 11/28/05, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> Sometimes I find myself stumbling over Python issues which have to do
> with what I perceive as a lack of orthogonality.

I use this thread to asking on python conception : why python have so
many builtins ?
I cannot understand why we use a builtins for open a file. Is it a old
decision ? If anyone have a pointer of this or can explain me.

Regards.


--
Sébastien Douche <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: importing a method

2005-11-28 Thread Flavio
If you read my original post, I had no intention of atributing the
user's method to the class, but to the instance.

Anyway I figure it out myself, and its quite a Pythonic solution:
>>> class Foo:
name='John'

>>> a=Foo()

>>> def p(parent):
self=parent
print 'Hi, %s!'%self.name


>>> a.met=p

>>> a.met(a)
Hi, John!

This works the same way an object's built-in method would work, since
all methods receive a reference to the parent object through the
required argument "self".

class Foo:
   def met(self):
   print self

Thanks for all the replies, they helped to catalize my own thoughts!

Flávio

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


Re: How to get started in GUI Programming?

2005-11-28 Thread paron
I think the best route is through the browser. Good cross-platform, has
a reasonable toolkit, and it's familiar for users.

You could look at TurboGears.

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


Re: importing a method

2005-11-28 Thread Flavio
There only one puzzle left to solve:

altough the solution I proposed works, this variant has problems:

>>> class Foo:
name='John'

>>> a=Foo()
>>> def p():
print 'Hi, %s!'%self.name
>>> a.met=p
>>> a.met.self = a
>>>a.met()
NameError: global name 'self' is not defined

This error is paradoxical since:

>>> a.met.self
<__main__.Foo instance at 0x405ed2ec>

Can anyone explain this?

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


Re: type of form field

2005-11-28 Thread Mike Meyer
"Ajar" <[EMAIL PROTECTED]> writes:
> Is there any way to retrieve the type(checkbox,radio...) of the form
> field from cgi.FieldStorage. I tried something like form['name'].type,
> but this field seems to be None for all the form fields

There isn't. cgi.FieldStorage parses data sent via an HTTP
request. The type of the input element isn't part of the data sent in
an HTTP request. So not only is there no way to get it from
cgi.FieldStorage, there's no way to get it from any HTTP handling
facility, unless it gets stored somewhere outside the element in
question for you to retrieve.

While you do have to store it outside the element, you don't have to
store it outside the form. You could create a series of hidden input
elements with names "foo.type" whose value was the type of the element
foo.  If your pages are dynamically generated, you could create a
dictionary mapping element names -> types, and then pickle that and
store the results in a hidden element. Or - well, I'm sure you get the
idea.

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


Re: How to enable bash mode at the interative mode?

2005-11-28 Thread Baz Walter
Anthony Liu  yahoo.com> writes: 
> Look what I have: 
>  
> $ python 
> Python 2.4.2 (#1, Nov 20 2005, 13:03:38)  
> [GCC 3.3.1 (Mandrake Linux 9.2 3.3.1-2mdk)] on linux2 
>  
> Yes, I realize that I don't have readline module 
> available. 
>  
> The same Mandrake system has Python 2.3 as well, and 
> it has the readline module. 
>  
> I don't know how to install the readline module.  I 
> tried what was suggested from the newsgroup, but got 
> an error at make: 
>  
> make: *** [Modules/readline.o] Error 1 
>  
> Thanks 
 
You need to have the development stuff for readline installed before you 
compile Python 2.4.2 from source. For Mandrake 9.2, there should be an rpm 
package named something like libreadline*-devel available. Install that, 
recompile python, and you should be okay. 
 
HTH 
-- 
Baz 

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


Re: Writing big XML files where beginning depends on end.

2005-11-28 Thread Laurent Pointal
Magnus Lycka wrote:
> We're using DOM to create XML files that describes fairly
> complex calculations. The XML is structured as a big tree,
> where elements in the beginning have values that depend on
> other values further down in the tree. Imagine something
> like below, but much bigger and much more complex:
> 
> 
> 
> 7
> 
> 2
> 1
> 
> 
> 
> 5
> 
> 
> 
> We have to stick with this XML structure for now.
> 
> In some cases, building up a DOM tree in memory takes up
> several GB of RAM, which is a real showstopper. The actual
> file is maybe a magnitute smaller than the DOM tree. The
> app is using libxml2. It's actually written in C++. Some
> library that used much less memory overhead could be
> sufficient.
> 
> We've thought of writing a file that looks like this...
> 
> 
> 
> 7
> 
> 2
> 1
> 
> 
> 
> 5
> 
> 
> 
> ...and store {"#": "15", "#1.1", "10" ... } in a map
> and then read in a piece at a time and performs some
> simple change and replace to get the correct values in.
> Then we need something that allows parts of the XML file
> to be written to file and purged from RAM to avoid the
> memory problem.
> 
> Suggestions for solutions are appreciated.

An idea.

Put spaces in your names 
Store { "#1":  }.

When you have collected all your final data, go throught your stored #,
seek at their position in the file, and replace the data (writting same
amount of chars than reserved).

A kind of direct access to nodes in an XML document file.

A+

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


Re: How to get started in GUI Programming?

2005-11-28 Thread UrsusMaximus
I agree with Paron, using HTML forms and such as a minimal GUI front
end meant to be run in a browser is often a good way to go.

But I just want to mention, again, Stephen Ferg's "Easygui" at
http://www.ferg.org/easygui/index.html which is a very easy way to go
for desktop GUI's. You know, I just had a thought: I wonder if Easygui
could be used on handhelds like Pocket PC's, Zaurus, Palm etc? If it
could just be imported as a module it might be an awfully simple way to
create GUI's for handhelds.


Ron Stephens
http://www.awaretek.com/plf.html

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


Re: General question about Python design goals

2005-11-28 Thread Duncan Booth
Antoon Pardon wrote:

> So suppose I want a dictionary, where the keys are colours, represented
> as RGB triplets of integers from 0 to 255. A number of things can be
> checked by index-like methods.
> 
> e.g.
>   
>   def iswhite(col):
> return col.count(255) == 3
> 
>   def primary(col):
> return col.count(255) == 1 and col.count(0) == 2
> 
>   def secondary(col):
> return col.count(255) == 2 and col.count(0) == 1

Just because you *can* implement these by treating your colour like a list 
doesn't make it a good idea. Treating them as opaque values makes these 
particular tests clearer:

def iswhite(col):
   return col==WHITE

def primary(col):
   return col in (RED,GREEN,BLUE)

def secondary(col):
   return col in (CYAN,MAGENTA,YELLOW)

If you relax your definition of primary to simply require that two planes 
are black then you may have a case where you want to treat the colour 
planes as a list, but if you convert it explicitly then you'll be better 
placed to keep the code working when someone decides to add an alpha 
channel or to switch the representation to CMYK.

def anyshadeprimary(col):
   return [col.red, col.green, col.blue].count(0)==2
   # or
   return col.toRGB().count(0)==2

So it looks to me as though you want col to be a type (which might be a 
subclass of tuple) but a list would be a mistake.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison problem

2005-11-28 Thread Peter Hansen
Tim Henderson wrote:
> peter

(Thanks for clarifying to whom you were responding... I saw the other 
post but wouldn't have responded since it didn't seem to be in response 
to one of mine. :-) )

> would not the more correct way to do this be short circuit
> evaluation. somthing along lines of
> 
> if (len(item) > 0) and (item[0] == '-'): pass

This is "correct" only in a narrow sense.  I wouldn't call it "correct 
Python" if I saw it in code around here.  Most likely (since this always 
depends on context), I would replace it with this:

  if item and item[0] == '-':
  pass

I think it's probably unlikely that the first test would be needed only 
on that one line, so it's even more likely that "if item" test would be 
done first, by itself, and then other tests on item[0] would be done.

If this was code that needed high performance (i.e. had been detected 
with proper profiling as a serious bottleneck) then the slicing approach 
would be better (as Fredrik demonstrated).

Hmm... just realized we're going way off track, since we actually have 
the original code here and don't need to comment on hypotheticals.

It appears to me that the original input is being treated as some sort 
of fixed-length record, with certain characters and text in predefined 
positions, specified by index number.  With that in mind, I'd actually 
say the original code is just fine with "if item[0:1] == '-'" and given 
the context it is pretty readable (ignoring the awful formatting with no 
whitespace around operators) and "correct".  Using ".startswith()" might 
have been equally appropriate, but without knowing more detail of the 
input data I couldn't say.

-Peter

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


Re: Death to tuples!

2005-11-28 Thread Peter Hansen
Mike Meyer wrote:
> It seems that the distinction between tuples and lists has slowly been
> fading away. What we call "tuple unpacking" works fine with lists on
> either side of the assignment, and iterators on the values side. IIRC,
> "apply" used to require that the second argument be a tuple; it now
> accepts sequences, and has been depreciated in favor of *args, which
> accepts not only sequences but iterators.
> 
> Is there any place in the language that still requires tuples instead
> of sequences, except for use as dictionary keys?

Would it be possible to optimize your "frozenlist" so that the objects 
would be created during compilation time and rather than only during 
runtime?  If not then tuples() have a distinct performance advantage in 
code like the following where they are used as local constants:

 >>> def func(x):
...   if x in (1, 3, 5, 7, 8):
... print 'x is really odd'
...
 >>> import dis
 >>> dis.dis(func)

   3  20 LOAD_FAST0 (x)
  23 LOAD_CONST   8 ((1, 3, 5, 7, 8))
  26 COMPARE_OP   6 (in)

 >>> def func(x):
...   if x in [1,3,5,7,8]:
...  print 'x is really odd'
...
 >>> dis.dis(func)
...
   3  20 LOAD_FAST0 (x)
  23 LOAD_CONST   2 (1)
  26 LOAD_CONST   3 (3)
  29 LOAD_CONST   4 (5)
  32 LOAD_CONST   5 (7)
  35 LOAD_CONST   6 (8)
  38 BUILD_LIST   5
  41 COMPARE_OP   6 (in)


-Peter

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


Re: Writing pins to the RS232

2005-11-28 Thread Peter Hansen
Richard Brodie wrote:
> If you just need one or two signals, then it might be practical to use one
> of the control lines, and PySerial supports this (UPS monitoring software
> often works this way). Setting 8 pins to 1 would be impossible, because
> there plain won't be that number of outputs wired, in addition to all the
> good stuff about UARTs Roy said. 

All true, but then Jay might get into electrical compatibility issues, 
and may not realize that the output levels of RS-232 serial hardware are 
not simply 0 and 5V levels, but rather +9V (or so) and -9V (and with 
variations from 6V up to 13V seen in the wild), and without much in the 
way of drive capability.  Using this to control custom hardware would 
probably be an exercise in frustration and kind of pointless in 
comparison to using parallel hardware, which at least has more typical 
logic voltage levels.

-Peter

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


Re: General question about Python design goals

2005-11-28 Thread Antoon Pardon
Op 2005-11-28, Duncan Booth schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>
>> So suppose I want a dictionary, where the keys are colours, represented
>> as RGB triplets of integers from 0 to 255. A number of things can be
>> checked by index-like methods.
>> 
>> e.g.
>>   
>>   def iswhite(col):
>> return col.count(255) == 3
>> 
>>   def primary(col):
>> return col.count(255) == 1 and col.count(0) == 2
>> 
>>   def secondary(col):
>> return col.count(255) == 2 and col.count(0) == 1
>
> Just because you *can* implement these by treating your colour like a list 
> doesn't make it a good idea. Treating them as opaque values makes these 
> particular tests clearer:

You are getting sidetracked. Whether this is the best possible
implementation here is not the issue. This example is just
to illustrate.

I'm sure I could come up with an other example where I would like
to have both some list method and use it as a dictionary key and
again people could start about that implementation having some
flaws and give better implementations.

I'm just illustrating that some list-like methods with tuples
could be usefull.

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


Re: How to get started in GUI Programming?

2005-11-28 Thread forodejazz
Have you tried Gambas?
http://gambas.sourceforge.net

It's a VB-like tool.
But the programming language is not Pyhton :-(

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


Re: Death to tuples!

2005-11-28 Thread Antoon Pardon
Op 2005-11-28, Peter Hansen schreef <[EMAIL PROTECTED]>:
> Mike Meyer wrote:
>> It seems that the distinction between tuples and lists has slowly been
>> fading away. What we call "tuple unpacking" works fine with lists on
>> either side of the assignment, and iterators on the values side. IIRC,
>> "apply" used to require that the second argument be a tuple; it now
>> accepts sequences, and has been depreciated in favor of *args, which
>> accepts not only sequences but iterators.
>> 
>> Is there any place in the language that still requires tuples instead
>> of sequences, except for use as dictionary keys?
>
> Would it be possible to optimize your "frozenlist" so that the objects 
> would be created during compilation time and rather than only during 
> runtime?  If not then tuples() have a distinct performance advantage in 
> code like the following where they are used as local constants:
>
> >>> def func(x):
> ...   if x in (1, 3, 5, 7, 8):
> ... print 'x is really odd'
> ...
> >>> import dis
> >>> dis.dis(func)
> 
>3  20 LOAD_FAST0 (x)
>   23 LOAD_CONST   8 ((1, 3, 5, 7, 8))
>   26 COMPARE_OP   6 (in)
>
> >>> def func(x):
> ...   if x in [1,3,5,7,8]:
> ...  print 'x is really odd'
> ...
> >>> dis.dis(func)
> ...
>3  20 LOAD_FAST0 (x)
>   23 LOAD_CONST   2 (1)
>   26 LOAD_CONST   3 (3)
>   29 LOAD_CONST   4 (5)
>   32 LOAD_CONST   5 (7)
>   35 LOAD_CONST   6 (8)
>   38 BUILD_LIST   5
>   41 COMPARE_OP   6 (in)

I'm probably missing something, but what would be the problem if this
list was created during compile time?

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


Why I need to declare import as global in function

2005-11-28 Thread didier . doussaud
I have a stange side effect in my project :

in my project I need to write "gobal" to use global symbol :

...
import math
...
def f() :
   global math # necessary ?? else next line generate an error
message  ?
   print math.pi

(the problem is for all global module symbol)

I have certainly change somthing in my project, but I can't find what ?

(just a small program wort fine without this global of course)

Can anybody help me : where can I search the mistake in my project ?

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


Re: importing a method

2005-11-28 Thread Antoon Pardon
Op 2005-11-27, Flavio schreef <[EMAIL PROTECTED]>:
> hi,
>
> I have an object defined with a number of hardcoded methods.
>
> Class soandso:
> def __init__(self):
> self.this = 0
> self.that = 1
> def meth1(self):
> ...
> def meth2(self):
> ...
> def custom(self):
> pass
>
> I want to allow the user to write a python module that declares a
> function so that myprogram can import it and attribute it to the custom
> method of the soandso object. So far so good, that is an easy thing to
> do in Python.
>
> import usermodule
> a=soandso()
> a.custom = usermodule.function
>
> But, what if the method had to access the self attributes (self.this
> and self.that) of the soandso object?
>
> Can it be done? and if so, what is the most Pythonic way of doing it?

You mean something like this:

>>> class Foo:
...   def __init__(self, v):
... self.value = v
... 
>>> def show(self):
...   print self.value
... 
>>> import new
>>> f = Foo(17)
>>> f.show = new.instancemethod(show, f)
>>> f.show()
17

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


speeding up Python when using wmi

2005-11-28 Thread rbt
Here's a quick and dirty version of winver.exe written in Python:

http://filebox.vt.edu/users/rtilley/public/winver/winver.html

It uses wmi to get OS information from Windows... it works well, but 
it's slow... too slow. Is there any way to speed up wmi?

In the past, I used the platform and sys modules to do some of what 
winver.exe does and they were rather fast. However, since switching to 
wmi (for a more accurate representation) thinngs have gotten slow... 
real slow.

I suppose this could be a wmi only issue not related at all to Python.

Any tips or ideas?

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


Re: return in loop for ?

2005-11-28 Thread Steven D'Aprano
On Mon, 28 Nov 2005 08:44:04 +, Duncan Booth wrote:

> Steven D'Aprano wrote:
> 
>> Since real source code verifiers make no such sweeping claims to
>> perfection (or at least if they do they are wrong to do so), there is
>> no such proof that they are impossible. By using more and more
>> elaborate checking algorithms, your verifier gets better at correctly
>> verifying source code -- but there is no guarantee that it will be
>> able to correctly verify every imaginable program.
>> 
> I'm sure you can make a stronger statement than your last one. Doesn't 
> Godel's incompleteness theorem apply? I would have thought that no matter 
> how elaborate the checking it is guaranteed there exist programs which are 
> correct but your verifier cannot prove that they are.

Yes, of course. By saying "no guarantee" I was guilty of understatement:
at the very least, we can guarantee that the verifier will *not* correctly
verify every possible program. (Which of course is no different from human
programmers.)

-- 
Steven.

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


Re: How to get started in GUI Programming?

2005-11-28 Thread peter . mosley
A big thank you to all who responded.  There are too many to reply
individually, but to summarise ...

Thomas Güttler gave a link to an example program, editMetadata.py
which uses yes no dialogs and scaled images.  I've not yet tried to
learn from this, but looking at the code it seems to provide exactly
what I am looking for.  It uses the gtkMessageDialog class, which I
hadn't come across (the tutorial doesn't seem to mention it?)

Others recommended wxPython, PyQt and various derivatives.  The trouble
is there's too much choice!  But my experience is that under Linux
nothing ever works out of the box, and so I am reluctant to invite more
grief by installing fresh packages until I am sure those already
installed are not adequate.

Easygui had some supporters. I had already come across this, and while
I agree it is a delightfully simple tool to use, and ideal for i/o
operations, it is not sufficiently flexible for my needs.

One development is that my local public library has, to my surprise,
managed to locate a copy of 'Python and Tkinter Programming' by J.
Grayson.  I've not read it yet, and an initial flick through
doesn't look too promising but maybe I am mistaken..  I acknowledge
that Tkinter is a bit dated, and may not have a native 'look and
feel', but for me this would be outweighed by an accessible textbook.

So currently the choice is between continuing with PyGtk, using the
editMetadata.py code as a model, or Tkinter using Grayson's book.
I'll try both and see which is more successful.

Once again thank you to all who responded.

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


Re: Why I need to declare import as global in function

2005-11-28 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I have a stange side effect in my project :
>
> in my project I need to write "gobal" to use global symbol :
>
> ...
> import math
> ...
> def f() :
>global math # necessary ?? else next line generate an error
> message  ?

what error message?

>print math.pi

you only need global in this case if you assign to the name somewhere
later in the function (e.g. "math = ..." or "import math" or some other
assignment)

please post the error message (the entire traceback).





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


Re: Writing pins to the RS232

2005-11-28 Thread Ian Vincent
Peter Hansen <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 
> 
> All true, but then Jay might get into electrical compatibility issues,
> and may not realize that the output levels of RS-232 serial hardware
> are not simply 0 and 5V levels, but rather +9V (or so) and -9V (and
> with variations from 6V up to 13V seen in the wild), and without much
> in the way of drive capability.  Using this to control custom hardware
> would probably be an exercise in frustration and kind of pointless in 
> comparison to using parallel hardware, which at least has more typical
> logic voltage levels.

You can get ICs that convert RS232 to TTL voltage levels.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why I need to declare import as global in function

2005-11-28 Thread Tim N. van der Leeuw
Sounds like something, either in your program, in another lib you
imported, or perhaps some extension you recently installed (and which
automatically starts), overrides 'import' (replaces it with it's own
version) -- and forgets to add the imported modules properly to the
globlals?
Or something, some option, that perhaps changes the way that Python
recognizes globals?

If you declare another global variable, then try to use it in your
function, then what's the result?

What Python version do you use?

cheers,

--Tim

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


Re: should python have a sort list-map object in the std-lib?

2005-11-28 Thread Steven D'Aprano
On Sun, 27 Nov 2005 23:35:03 -0500, Tim Henderson wrote:

> Hi
> 
> The question why are there no sorted dictionaries in python, seems to
> pop up with unseeming regularity. That question in itself in
> nonsensical sense dictionaries are hash-maps, however should python
> have a sorted map type object is a good question.
> 
> clearly many people like have a sorted map, and sorting the keys every
> time seems rather wasteful, as does keeping a separate sorted list of
> the keys.

Another good question is, does it *seem* wasteful or is it *actually*
wasteful? More or less wasteful than having special code in Python to
implement "sorted dictionaries" (whatever that means)?

It is good to have a rich, powerful set of tools in a programming
language. It is bad to expect that, no matter what task you need, that
your language should have a single function or object to do it. That just
leads to a bloated language where it is harder to find the feature you
want than it is to simply write it yourself.



> a related question is, in python is it more efficient to a maintain a
> list type in sorted order by inserting each new object in the correct
> location (by say finding it with a binary search and then using del
> list[x]) or appending each new item to the end of said list and using
> the built-in .sort method, or sorted() function?

I don't think using del to insert an object into a list would be very
efficient, no matter how little time the deletion took :-)

Why don't you try it for yourself? You only need some quick and dirty code
to discover which approach is better (for a quick and dirty definition of
"better"). Don't forget to check out the bisect module too.


-- 
Steven.

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


Re: General question about Python design goals

2005-11-28 Thread Duncan Booth
Antoon Pardon wrote:

> I'm sure I could come up with an other example where I would like
> to have both some list method and use it as a dictionary key and
> again people could start about that implementation having some
> flaws and give better implementations.
> 
> I'm just illustrating that some list-like methods with tuples
> could be usefull.
> 
But you aren't illustrating that at all. You came up with an example which 
showed, at least to me, a good argument why tuples should *not* have list 
methods.

If you can come up with a better example that would be good; if any other 
example is as flawed then perhaps it shows that your basic assumption is 
wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nesting for statements?

2005-11-28 Thread tpcolson
Hi. Thanks for the tip. However, implementing that example, the script
will only generate the second output "file", (or it's overwriting the
first one), so all I get when run is "fileb".

# Import system modules
import sys, string, os, win32com.client

# Create the Geoprocessor object
from win32com.client import Dispatch
gp = Dispatch("esriGeoprocessing.GpDispatch.1")

# Check out any necessary licenses
gp.CheckOutExtension("spatial")

# Iterate 2 thru 4 in increments of 2 for DEF
# Name the "2" dem "outa" and the "4" dem "outb"
sor = 2 # start of range
eor = 4 # end of range

filenames = ['file' + chr((x-sor) + ord('a')) for x in range(sor, eor)]

for x in range(sor, eor):
 Out_Dem = filenames[x - sor]


try:

# Process: Topo to Raster...
gp.TopoToRaster_sa("C:\\temp\\test.shp Z PointElevation",
   "C:\\temp\\"+Out_Dem, # Variable for name of
output raster. This should increment name of output based on the for
statement
   "5", # Output raster cell size: each pixel is 5
feet by 5 feet
   "2103763.27 813746.12 2111850.32 822518.65",
#extent of raster borders, SPF, NC, NAD83
   "20", # #Grid Margin
   "", #Smallest z value to be used in
interpolation (optional)
   "", #Largest z value to be used in interpolation
(optional)
   "NO_ENFORCE", #Drainage option
   "SPOT", #Spot data option
   "40", #Maximum number of iterations (optional)
   "", #Roughness penalty (optional)
   "0" #Discretisation error factor: This should
increment DEF based on the for statement
   "0", #Vertical standard error (optional)
   "", #Tolerance 1 (optional)
   "" #Tolerance 2 (optional)
   )
except:
print "ERROR OCCURED"
print gp.GetMessages()

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


Re: return in loop for ?

2005-11-28 Thread Steven D'Aprano
On Mon, 28 Nov 2005 10:02:19 +0100, Sybren Stuvel wrote:

> Duncan Booth enlightened us with:
>> I would have thought that no matter how elaborate the checking it is
>> guaranteed there exist programs which are correct but your verifier
>> cannot prove that they are.
> 
> Yep, that's correct. I thought the argument was similar to the proof
> that no program (read: Turing machine) can determine whether a program
> will terminate or not.

No, that is not right -- it is easy to create a program to determine
whether *some* programs will terminate, but it is impossible to create a
program which will determine whether *all* programs will terminate.


-- 
Steven.

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


RE: speeding up Python when using wmi

2005-11-28 Thread Tim Golden
[rbt]

> Here's a quick and dirty version of winver.exe written in Python:

[.. snip ..]

> It uses wmi to get OS information from Windows... it works well, but 
> it's slow... too slow. Is there any way to speed up wmi?

> In the past, I used the platform and sys modules to do some of what 
> winver.exe does and they were rather fast. However, since switching to

> wmi (for a more accurate representation) thinngs have gotten slow... 
> real slow.

> I suppose this could be a wmi only issue not related at all to Python.

In short, I recommend replacing the wmi module by the underlying
calls which it hides, and replacing Tkinter by a win32gui MessageBox.
The wmi module does some magicish things which are useful for
interactive
browsing, but will only slow you down if you know exactly what you need.
As you don't need anything more than a native message box, don't
bother with GUI loops etc. Windows will do that for you in a Modal
Dialog (here message box).

This was going to be a longer post comparing versions, but in short
running this code:


import win32gui
import win32com.client

for os in win32com.client.GetObject ("winmgmts:").InstancesOf
("Win32_OperatingSystem"):
  win32gui.MessageBox (
0,
os.Properties_ ("Caption").Value + "\n" + \
  os.Properties_ ("TotalVisibleMemorySize").Value + "\n" + \
  os.Properties_ ("Version").Value + "\n" + \
  os.Properties_ ("CSDVersion").Value,
"Platform Info", 
0
  )


is nearly as fast as running its VBS equivalent:


For Each os in GetObject("winmgmts:").InstancesOf
("Win32_OperatingSystem")
  
  WScript.Echo os.Caption & VbCr & _
os.TotalVisibleMemorySize & VbCr & _
os.Version & VbCr & _
os.CSDVersion & VbCr

Next


So, if you want to use Python, you could use the script above,
but if you don't care, use VBScript, which probably has a favoured
place in the Windows World (tm).

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: General question about Python design goals

2005-11-28 Thread Antoon Pardon
Op 2005-11-28, Duncan Booth schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>
>> I'm sure I could come up with an other example where I would like
>> to have both some list method and use it as a dictionary key and
>> again people could start about that implementation having some
>> flaws and give better implementations.
>> 
>> I'm just illustrating that some list-like methods with tuples
>> could be usefull.
>> 
> But you aren't illustrating that at all. You came up with an example which 
> showed, at least to me, a good argument why tuples should *not* have list 
> methods.

No I gave an example, you would implement differently. But even
if you think my example is bad, that would make it a bad argument
for tuples having list methods. That is not the same as being
a good argument against tuples having list methods. The trouble is
to really convince would probably require a complete worked out module,
but then I don't have the time to come up with a complete worked out
module just to illustrate something. So I come up with just a skeleton
of something to get the idea across and what happens is that the
attention goes to how the skeleton could be approved in other ways,
instead of trying to understand what ideas are trying to be
communicated.

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


RE: Multiple versions

2005-11-28 Thread Tim Golden
[Me]

> I need to install both 2.3 and 2.4 on my Win2000 system. Can someone
please
> give me a pointer as to how to do this? Thanks!

It depends on your other requirements. The simple answer is: just
install
them (in different directories, eg c:\python23, c:\python24), installing

last the one which you want your .py/.pyw files to be associated with.

If you have more specific requirements concerning shared modules and
so on, the answer might be slightly different. Personally, these
days, I install the versions I want (I have 2.1 - 2.4 on this 
machine) and reinstall external modules for each version. My
own modules I keep in a Subversion repository and update as needed.
This avoids slight messiness with mismatched .pyc files, I find.

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Death to tuples!

2005-11-28 Thread Duncan Booth
Antoon Pardon wrote:

>> >>> def func(x):
>> ...   if x in [1,3,5,7,8]:
>> ...  print 'x is really odd'
>> ...
>> >>> dis.dis(func)
>> ...
>>3  20 LOAD_FAST0 (x)
>>   23 LOAD_CONST   2 (1)
>>   26 LOAD_CONST   3 (3)
>>   29 LOAD_CONST   4 (5)
>>   32 LOAD_CONST   5 (7)
>>   35 LOAD_CONST   6 (8)
>>   38 BUILD_LIST   5
>>   41 COMPARE_OP   6 (in)
> 
> I'm probably missing something, but what would be the problem if this
> list was created during compile time?

Not much in this particular instance. 'x in aList' is implemented as 
aList.__contains__(x), so there isn't any easy way to get hold of the 
list[*] and keep a reference to it. On the other hand:

def func(x):
return x + [1, 3, 5, 7, 8]

we could pass in an object x with an add operator which gets hold of its 
right hand operand and mutates it.

So the problem is that we can't just turn any list used as a constant into 
a constant list, we need to be absolutely sure that the list is used only 
in a few very restricted circumstances, and since there isn't actually any 
benefit to using a list here rather than a tuple it hardly seems 
worthwhile.

There might be some mileage in compiling the list as a constant and copying 
it before use, but you would have to do a lot of timing tests to be sure.

[*] except through f.func_code.co_consts, but that doesn't count.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode in MIMEText

2005-11-28 Thread Damjan
patch submitted... 

> Thanks for taking the time to improve the quality of the Python library.

Do you think it would be possible to do some kind of an automatic 
comprehensive test of compatibility of the standard library with unicode
strings?


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


Multiple versions

2005-11-28 Thread Me
I need to install both 2.3 and 2.4 on my Win2000 system. Can someone please
give me a pointer as to how to do this? Thanks!


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


Re: General question about Python design goals

2005-11-28 Thread Fredrik Lundh
Duncan Booth wrote:

> > I'm just illustrating that some list-like methods with tuples
> > could be usefull.
> >
> But you aren't illustrating that at all.

"But assume that I have some other use case"





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


Data Structure in Python like STL Stack?

2005-11-28 Thread Matt Keyes
Is there a data structure in Python that is akin to the STL stack object in C++?
 
Thanks!-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to get started in GUI Programming?

2005-11-28 Thread Brian Elmegaard
[EMAIL PROTECTED] writes:

> Others recommended wxPython, PyQt and various derivatives.  The trouble
> is there's too much choice!  

Agreed, I tried to find /the answer/ some time ago, and I got to the
same conclusion. In addition it is even more difficult to find the
advantages and disadvantages of the different toolkits. 

My main reasons for choosing wxpython (but never really try to do
something useful with it) was the native look-and-feel on different
platforms and the many different examples, and the demo application
pysketch. 

Unfortunately, even wxpython supports two or three ways of doing
drawings on a canvas, and not that many examples were available for
this. 

In addition pyqt should be great, I read. So i have been waiting for
trolltech to release qt4 and just saw that they have. pyqt is not
updated yet.

> One development is that my local public library has, to my surprise,
> managed to locate a copy of 'Python and Tkinter Programming' by J.
> Grayson.  I've not read it yet, and an initial flick through
> doesn't look too promising but maybe I am mistaken..  

I had the same experience with it. I got more from
http://infohost.nmt.edu/tcc/help/pubs/tkinter.pdf. 

-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
http://www.rugbyklubben-speed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Data Structure in Python like STL Stack?

2005-11-28 Thread jepler
What property of the STL stack is important to you?

You can use a Python list as a stack.  It has methods append() and
pop() which run in amortized-constant-time.  It can be tested for
empty/nonempty in constant time too (if st: # stack is not empty).

Jeff


pgpU1CCrfIPhk.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Data Structure in Python like STL Stack?

2005-11-28 Thread Matt Keyes
I didn't know the list has a pop function - that is what I was looking for.
 
Thanks for the help![EMAIL PROTECTED] wrote:
What property of the STL stack is important to you?You can use a Python list as a stack. It has methods append() andpop() which run in amortized-constant-time. It can be tested forempty/nonempty in constant time too (if st: # stack is not empty).Jeff-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Data Structure in Python like STL Stack?

2005-11-28 Thread Fredrik Lundh
Matt Keyes wrote:

> Is there a data structure in Python that is akin to the STL stack
> object in C++?

>>> import collections
>>> help(collections.deque)

...

class deque(__builtin__.object)
 |  deque(iterable) --> deque object
 |
 |  Build an ordered collection accessible from endpoints only.

...





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


Book: Cross-Platform GUI Programming with wxWidgets?

2005-11-28 Thread kdahlhaus
I was wondering if people using wxPython found this book useful?  Is it
worth the money? Thanks

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


Problem with exchange mail server

2005-11-28 Thread Vinayakc
I am new for python. I have written one code which generates RFC2822
file.
I have header in string format.

i am using following code.

emailData[SMTP_HEADER_POS] = emailData[SMTP_HEADER_POS].encode("utf-8")
hdr = email.message_from_string(emailData[SMTP_HEADER_POS])
tmpContentType = msg['Content-Type']
del msg['Content-Type']

for key in hdr.keys():
values = hdr.get_all(key)
if values != None:
if key not in msg:
for value in values:
msg.add_header(key,value)

if msg['Content-Type'] is None or msg['Content-Type'] == '':
msg['Content-Type'] = tmpContentType

is this right way to add the header??

This code is not doing well for exchange server mails. Python could not
parse this mail header. Because first line is 'Microsoft exchange mail
server version 2.0'.
If I remove this line, it works. Could not understand this. Please
help.

Thanks and Regards
Vinayakc

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


Re: speeding up Python when using wmi

2005-11-28 Thread rbt
Tim Golden wrote:
> [rbt]
> 
>> Here's a quick and dirty version of winver.exe written in Python:
> 
> [.. snip ..]
> 
>> It uses wmi to get OS information from Windows... it works well, but 
>> it's slow... too slow. Is there any way to speed up wmi?
> 
>> In the past, I used the platform and sys modules to do some of what 
>> winver.exe does and they were rather fast. However, since switching to
> 
>> wmi (for a more accurate representation) thinngs have gotten slow... 
>> real slow.
> 
>> I suppose this could be a wmi only issue not related at all to Python.
> 
> In short, I recommend replacing the wmi module by the underlying
> calls which it hides, and replacing Tkinter by a win32gui MessageBox.
> The wmi module does some magicish things which are useful for
> interactive
> browsing, but will only slow you down if you know exactly what you need.
> As you don't need anything more than a native message box, don't
> bother with GUI loops etc. Windows will do that for you in a Modal
> Dialog (here message box).
> 
> This was going to be a longer post comparing versions, but in short
> running this code:
> 
> 
> import win32gui
> import win32com.client
> 
> for os in win32com.client.GetObject ("winmgmts:").InstancesOf
> ("Win32_OperatingSystem"):
>   win32gui.MessageBox (
> 0,
> os.Properties_ ("Caption").Value + "\n" + \
>   os.Properties_ ("TotalVisibleMemorySize").Value + "\n" + \
>   os.Properties_ ("Version").Value + "\n" + \
>   os.Properties_ ("CSDVersion").Value,
> "Platform Info", 
> 0
>   )
> 

Wow... thanks. I didn't expect someone to completely rewrite it like 
that. I'll use your example and name it PyWinver and attribute it to 
you. Hope you don't mind. Great learning experience.

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


Re: General question about Python design goals

2005-11-28 Thread Duncan Booth
Antoon Pardon wrote:

> 
> No I gave an example, you would implement differently. But even
> if you think my example is bad, that would make it a bad argument
> for tuples having list methods. That is not the same as being
> a good argument against tuples having list methods. 

Tuples don't have list methods, therefore any code which seems to require a 
tuple with list methods should make you stop and consider whether your 
design is wrong. Your example made me consider your design was wrong. If 
tuples did have list methods you would have gone ahead with a poor design.

That is why I said that, to me, it is an argument against giving tuples the 
additional methods. It is a fairly weak argument though, so if you do have 
some other use case you could easily prove me wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: speeding up Python when using wmi

2005-11-28 Thread Tim Golden
[rbt]
>> Here's a quick and dirty version of winver.exe written in Python:

[Tim Golden]
> In short, I recommend replacing the wmi module by the underlying
> calls which it hides, and replacing Tkinter by a win32gui MessageBox.

[rbt]
>Wow... thanks. I didn't expect someone to completely rewrite it like 
>that. I'll use your example and name it PyWinver and attribute it to 
>you. Hope you don't mind. Great learning experience.
>Thanks!

My pleasure. It wasn't that much of a rewrite; there were
only, what, a dozen lines in the original. One of those
rare occasions when I have to *not* recommend using the 
wmi module!

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: importing a method

2005-11-28 Thread Flavio
This "new" module sounds pretty cool, too bad its deprecated...

I would not want to add a dependancy to a deprecated module in my code.
But maybe I'll check the code for instancemethod within it and see what
it does.

Flávio

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


Precision for equality of two floats?

2005-11-28 Thread Anton81
Hi!

When I do simple calculation with float values, they are rarely exactly
equal even if they should be. What is the threshold and how can I change
it?

e.g. "if f1==f2:" will always mean "if abs(f1-f2)<1e-6:"

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


Re: General question about Python design goals

2005-11-28 Thread Paul Boddie
Antoon Pardon wrote:
> Duncan Booth wrote:
> > But you aren't illustrating that at all. You came up with an example which
> > showed, at least to me, a good argument why tuples should *not* have list
> > methods.

For what it's worth, I don't agree with that analysis, but anyway...

> No I gave an example, you would implement differently. But even
> if you think my example is bad, that would make it a bad argument
> for tuples having list methods. That is not the same as being
> a good argument against tuples having list methods.

In this case, I rather agree with the pragmatic responses earlier in
the thread: that it was probably an oversight that tuples lack the
count, index and (arguably) sorted methods, and that patches would
probably be welcome to rectify this state of affairs. Personally, I
find certain sequence-like characteristics of strings more irritating
on occasions, and if one had to convert strings to lists in order to
iterate over the characters (as one has to do in various other
high-level languages), I probably wouldn't find that so inconvenient.
But then, such a change would probably disrupt the existence of other
useful aspects of strings: index-based access to characters, slicing,
and so on. I'm therefore not inclined to shout about such matters in
such a way that I then have to defend my subjective line of thinking
whilst proposing an objectively acceptable alternative.

I actually think it's good to question certain aspects of the language
in the way being done in this thread, despite unconvincing attempts to
defend the status quo (and the ever present threat of a giant hedgehog
emerging from behind a building with large signs reading "Pythonic" and
"Zen of Python" stuck on its spines), but I personally wouldn't spend
too much time on such matters myself.

Paul

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


Re: should python have a sort list-map object in the std-lib?

2005-11-28 Thread Alex Martelli
Tim Henderson <[EMAIL PROTECTED]> wrote:

> ahh, i hadn't thought of using a proirity queue but that is the correct
> solution most of the time, except i suppose when you have input that
> causes you to excessively reheap which could be problematic.

The worst case is still O(N logN) for heap as well as timsort.  But
since timsort can take advantage of order or reverse order already
present in the sequence, it's surely possible to find real use cases in
which one sort at the end of all insertions is O(N) and thus much
faster.  Nevertheless, that also depends on having a lot of insertions
before you need any sorting; if you need to "walk sorted" after each
insertion or thereabouts, I would guess heap would be faster again.


> i may still look into writing a general sorted map though, it could be
> useful especially if there were and easy way to set the type of
> functionality required with out resorting to several different types of
> sorted-maps.

You can record a callable equivalent to sort's key= once and for all at
the creation of the "sorted map".  heapq's functions don't directly
support that in 2.4 (they will in 2.5) but it's easy to implement via
explicit key-extraction upon insertion (once known as the D step in the
DSU, decorate-sort-undecorate, idiom).  It's unclear whether you want to
be able to key the sorting off keys only, or keys AND values: the latter
is more general but also takes more work and complication.

As for "different types", if I catch your drift...:

I would suggest avoiding the temptation to overload the type with a
bazillion options-flags requiring deeply different behavior, e.g.
copying keys and/or values versus just taking references to either or
both, or either requiring or foregoing hashable keys (with different
implementations).  If such differences are warranted by use cases, it's
better to have several different types than one complicated one.  I
would personally suggest mimicking dict's semantic: require hashable
keys, make no copies.


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


RE: Problem with exchange mail server

2005-11-28 Thread Tim Golden
[Vinayakc]
> I am new for python. 

Welcome to Python.

> I have written one code which generates RFC2822 file.
> I have header in string format.
> i am using following code.

[... snip code fragment ...]

I'm afraid you're going to have to be a little more
precise and give a more useful fragment of code. I
can't work out from your description and your code
where the data is coming from which you're managing,
or even what you're trying to do with it.

Can you produce a short *complete* (that someone can paste
into an interpreter) piece of code which demonstrates what
the problem is which you're encountering?

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Precision for equality of two floats?

2005-11-28 Thread Alex Martelli
Anton81 <[EMAIL PROTECTED]> wrote:

> Hi!
> 
> When I do simple calculation with float values, they are rarely exactly
> equal even if they should be. What is the threshold and how can I change
> it?

Python's builtin floats compare for exact bit-by-bit equality -- no
"threshold".  You may want to look at the allclose function in the
Numeric extension package, at least for its specs (it consider both
absolute and relative difference).  Extension module gmpy might also
help, since its mpf floating numbers implement a fast reldiff (relative
difference) method.


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


Re: importing a method

2005-11-28 Thread Alex Martelli
Flavio <[EMAIL PROTECTED]> wrote:

> This "new" module sounds pretty cool, too bad its deprecated...
> 
> I would not want to add a dependancy to a deprecated module in my code.
> But maybe I'll check the code for instancemethod within it and see what
> it does.

If you have a function f and want to make an instancemethod out of it,
you can simply call f.__get__(theinstance, theclass) and that will build
and return the new instancemethod you require.


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


Re: Precision for equality of two floats?

2005-11-28 Thread Fredrik Lundh
"Anton81" wrote:

> When I do simple calculation with float values, they are rarely exactly
> equal even if they should be. What is the threshold

http://www.lahey.com/float.htm
http://docs.python.org/tut/node16.html

> and how can I change it?

you cannot.

> e.g. "if f1==f2:" will always mean "if abs(f1-f2)<1e-6:"

use your own equal function, e.g.

def equal(a, b):
return abs(a - b) < 1e-6

if equal(f1, f2):
...

(see the "safe comparision" section of the lahey.com paper
for better ways to test for "approximate equality")





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


Re: General question about Python design goals

2005-11-28 Thread Aahz
In article <[EMAIL PROTECTED]>,
Paul Boddie <[EMAIL PROTECTED]> wrote:
>
>In this case, I rather agree with the pragmatic responses earlier in
>the thread: that it was probably an oversight that tuples lack the
>count, index and (arguably) sorted methods, and that patches would
>probably be welcome to rectify this state of affairs. 

You're wrong.  I don't have time/energy to look up the relevant posts,
but Guido has been extremely clear in the past that tuples are *NOT*
going to grow methods.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Extracting documentation for user relevant functions only?

2005-11-28 Thread Anton81
Hi,

I've written a python script and added short docstrings. Now I'd like to
create a short overview of commands the user can use. However I don't want
the internal stuff that I also commented. Is there a way to create a fancy
documentation (e.g. pydoc) of certain functions only?

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


Re: importing a method

2005-11-28 Thread Flavio
Addendum to my last reply:

although the New Method is deprecated,

new.instancemethod (from Antoon's message) can be replaced by

from types import MethodType

f.show = MethodType(show,f)

and every thing still works.

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


Re: General question about Python design goals

2005-11-28 Thread Fredrik Lundh
Christoph Zwerschke wrote:

> But the problem is that the tutorials and manuals give the impression
> that the difference between lists and tuples is only mutablity versus
> immutability.

both the tutorial and the FAQ discusses the difference in terms of use
cases and recommended usage.

> Maybe I am I lacking the satori of a real Python Zen master?

I suggest you look up the phrase "bike shed effect".  next, go read some
recent PEP:s to see what's really going on in the Python design universe.





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


Re: importing a method

2005-11-28 Thread Martin Miller
First of all,why do you think the new module is deprecated?  (I can't
find anything in the docs to indicate this.)

As for using MethodType in the types module:  There's nothing in the
module documentation that suggests that you can call MethodType as a
function as you suggest, only that it is the name of the type of
methods of user-defined class instances..  So, while calling it might
work, it sounds like you are using an undocumented feature...

Lastly, in an earlier post after Ben Finney suggested using the
new.instancemethod function, you replied:
> If you read my original post, I had no intention of atributing the
> user's method to the class, but to the instance.

I'd like to point out that the instancemethod() function returns a
method object, bound to its *instance* argument if it isn't None --
which sounds like exactly what you want/need.

-Martin


Flavio wrote:
> Addendum to my last reply:
>
> although the New Method is deprecated,
>
> new.instancemethod (from Antoon's message) can be replaced by
>
> from types import MethodType
> 
> f.show = MethodType(show,f)
> 
> and every thing still works.

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


Re: Extracting documentation for user relevant functions only?

2005-11-28 Thread Micah Elliott
On Nov 28, Anton81 wrote:
> I've written a python script and added short docstrings. Now I'd
> like to create a short overview of commands the user can use.
> However I don't want the internal stuff that I also commented. Is
> there a way to create a fancy documentation (e.g. pydoc) of certain
> functions only?

You can use the leading underscores convention
http://docs.python.org/ref/id-classes.html> to "hide" the
intended invisible names.  pydoc and epydoc both honor this...

$ cat foo.py
"""Foo test mod.
"""

def spam():
"Like ham."
pass

def _secret():
"Can't see this docstring."
pass

class Mustard(object):
__name1 = 1
_name2  = 2
name3   = 3


$ pydoc foo
Help on module foo:

NAME
foo - Foo test mod.

CLASSES
...
class Mustard(__builtin__.object)
 ...
 |  name3 = 3

FUNCTIONS
spam()
Like ham.


-- 
_ _ ___
|V|icah |- lliott <>< [EMAIL PROTECTED]
" " """
-- 
http://mail.python.org/mailman/listinfo/python-list


No apos in htmlentitydefs

2005-11-28 Thread Kent Johnson
I see that htmlentitydefs.name2codepoint does not include 'apos' as one of the 
recognized names. Is this intentional or a bug?

In fact ' is not a recognized entity in HTML 4.01; see this list:
http://www.w3.org/TR/html4/sgml/entities.html#misc

But it is recognized in XHTML 1.0:
http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters

and AFAIK it is commonly supported by browsers which IMO argues that it should 
be included.

Any thoughts?
Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: importing a method

2005-11-28 Thread Martin Miller
I'd like to point out to the OP that using a function's __get__ method
this way only works with new-style classes and their instances...not
with the example in the shown in original post.

-Martin


Alex Martelli wrote:
> Flavio <[EMAIL PROTECTED]> wrote:
>
> > This "new" module sounds pretty cool, too bad its deprecated...
> >
> > I would not want to add a dependancy to a deprecated module in my code.
> > But maybe I'll check the code for instancemethod within it and see what
> > it does.
>
> If you have a function f and want to make an instancemethod out of it,
> you can simply call f.__get__(theinstance, theclass) and that will build
> and return the new instancemethod you require.
> 
> 
> Alex

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


Re: Death to tuples!

2005-11-28 Thread Steven Bethard
Dan Bishop wrote:
> Mike Meyer wrote:
> 
>>Is there any place in the language that still requires tuples instead
>>of sequences, except for use as dictionary keys?
> 
> The % operator for strings.  And in argument lists.
> 
> def __setitem__(self, (row, column), value):
>...

Interesting that both of these two things[1][2] have recently been 
suggested as candidates for removal in Python 3.0.

[1]http://www.python.org/dev/summary/2005-09-01_2005-09-15.html#string-formatting-in-python-3-0
[2]http://www.python.org/dev/summary/2005-09-16_2005-09-30.html#removing-nested-function-parameters

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


Re: General question about Python design goals

2005-11-28 Thread Paul Boddie
Aahz wrote:
> You're wrong.  I don't have time/energy to look up the relevant posts,
> but Guido has been extremely clear in the past that tuples are *NOT*
> going to grow methods.

Ah, I misread some of those other posts. Still, at least that is
consistent with saying that it wasn't worth spending much time on such
matters. ;-)

Paul

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


Re: No apos in htmlentitydefs

2005-11-28 Thread Fredrik Lundh
Kent Johnson wrote:

> I see that htmlentitydefs.name2codepoint does not include 'apos'
> as one of the recognized names. Is this intentional or a bug?
>
> In fact ' is not a recognized entity in HTML 4.01; see this list:
> http://www.w3.org/TR/html4/sgml/entities.html#misc
>
> But it is recognized in XHTML 1.0:
> http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters
>
> and AFAIK it is commonly supported by browsers which IMO argues
> that it should be included.

it's a predefined XML entity.  a classic HTML parser won't understand
it, and the W3C HTML validator chokes on it, so it should definitely not
appear in a list of *HTML* entities.





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


Re: return in loop for ?

2005-11-28 Thread Mike Meyer
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> On Mon, 28 Nov 2005 10:02:19 +0100, Sybren Stuvel wrote:
>> Duncan Booth enlightened us with:
>>> I would have thought that no matter how elaborate the checking it is
>>> guaranteed there exist programs which are correct but your verifier
>>> cannot prove that they are.
>> Yep, that's correct. I thought the argument was similar to the proof
>> that no program (read: Turing machine) can determine whether a program
>> will terminate or not.
> No, that is not right -- it is easy to create a program to determine
> whether *some* programs will terminate, but it is impossible to create a
> program which will determine whether *all* programs will terminate.

Which means you can't create a verifier which will verify all
programs. Is there a reason to believe that you can't have a verifier
with three possible outcomes: Correct, Incorrect, and I don't know,
and it is always correct in doing so? Note that "I don't know" could
be "I ran longer than I think is reasonable and gave up trying."

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


New Ordered Dictionery to Criticise

2005-11-28 Thread Fuzzyman
Sorry for this hurried message - I've done a new implementation of out
ordered dict. This comes out of the discussion on this newsgroup (see
blog entry for link to archive of discussion).

See the latest blog entry to get at it :
http://www.voidspace.org.uk/python/weblog/index.shtml

Criticism solicited (honestly) :-)

We (Nicola Larosa and I) haven't yet made any optimisations - but there
are two implementations to play with.

One allows you to access the keys attribute as if it was a sequence (as
well as a method).

All the best,

Fuzzyman
 http://www.voidspace.org.uk/python/index.shtml

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


pcm format to wav...

2005-11-28 Thread [EMAIL PROTECTED]
Hi !

I have WinXP.
I want to convert my PySonic recorded (raw) pcm format files to wav files.
How can I do it ?

Please help me !

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


Re: Precision for equality of two floats?

2005-11-28 Thread Mike Meyer
Anton81 <[EMAIL PROTECTED]> writes:
> When I do simple calculation with float values, they are rarely exactly
> equal even if they should be. What is the threshold and how can I change
> it?

Implementation dependent, because floats use an underlying C type, and
there's no portable way to do that.

> e.g. "if f1==f2:" will always mean "if abs(f1-f2)<1e-6:"

This is a *bad* idea. What happens if f1=1e-12 and f2=1e-112? Do you
really want to values that 100 orders of magnitude different to
compare as equal? You should use something like "if abs(f1 - f2) <
abs(f1) * 1e-6" (been a long time since I worried about this; there's
probably a better version).

DSepending on why you need it, you might consider using decimals
(introduced in 2.4) instead of floats.

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


build_opener()

2005-11-28 Thread Steve Young
Hello, I had a question about urllib2's  build_opener() statement. I am trying to just get the html from any  webpage as a string but I need everything on the page to be the same as  what it'd be if I would browse to that page (and at the very least, all  the href's). This is my code:  url = ''  req = Request(url)  f = build_opener().open(req)  page = f.read()  f.close()  return page      so looking at the source of the page browsing to the  page, one of the links has an href that looks like this:href = "">  http://news.yahoo.com/s/ap/20051118/ap_on_re_mi_ea/iraq_051118153857;_ylt=AiPsFWWIyLLbGdlCQFLMn8NX6GMA;_ylu=X3oDMTBiMW04NW9mBHNlYwMlJVRPUCUl  after running the code and looking at the returned page's same link, it looks like this:href = "">  http://192.168.23.106/s/ap/20051118/ap_on_re_mi_ea/iraq_051118153857it seems that everything after the semi-colon is missing after runningthe build_opener(). Is there a way that I can get the page as a stringwith all the links (href's) to not be missing anything? Thanks.-Steve  
		 Yahoo! Music Unlimited - Access over 1 million songs. Try it free.
		 Yahoo! Music Unlimited - Access over 1 million songs. Try it free.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: best cumulative sum

2005-11-28 Thread David Isaac

"Peter Otten" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> sufficiently similar

I think I understand your points now.
But I wanted to match these cases:

>>> import operator
>>> reduce(operator.add,[],42)
42
>>> reduce(operator.add,[1],42)
43

The idea is that the i-th yield of i-reduce shd be the
result of reduce on seq[:i] with the given initializer.

That said, for the applications I first intended,
yes it is sufficiently similar.  For now, I'll stick
with the version below.

Thanks,
Alan

def ireduce(func, iterable, init=None):
iterable = iter(iterable)
if init is None:
init = iterable.next()
yield init
else:
try:
init = func(init, iterable.next())
yield init
except StopIteration:
yield init
for item in iterable:
init = func(init, item)
yield init


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


Re: General question about Python design goals

2005-11-28 Thread Aahz
In article <[EMAIL PROTECTED]>,
Sebastien Douche  <[EMAIL PROTECTED]> wrote:
>
>I use this thread to asking on python conception : why python have so
>many builtins ?
>I cannot understand why we use a builtins for open a file. Is it a old
>decision ? If anyone have a pointer of this or can explain me.

One of the primary goals for Python is to make it easy to use for new
programmers.  Particularly for sysadmins, opening a file for reading and
writing is considered such a basic task that it's part of the builtins.

There are some builtins slated for removal in Python 3.0 (e.g. apply(),
which is superseded by *args/**kwargs being allows on the calling side).
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing pins to the RS232

2005-11-28 Thread Philippe C. Martin
Hi,

Some of it should be doable on windows:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcecoreos5/html/wce50lrfescapecommfunction.asp

Yet this might require a new wrapper module for I am not sure what the
current interface lets you do.

Not sure about Linux.

Regards;

Philippe







On Fri, 25 Nov 2005 13:25:44 -0800, [EMAIL PROTECTED] wrote:

> I want to write to the pins of an RS232 without using the serial
> protocol.  The use would be every pin could act to complete a circuit
> in customized hardware.  I could use python to communicate serially to
> a BASIC stamp or a Javelin stamp and then use the stamp to set however
> many pins as 0's or 1's but should it be that hard to do with python.
> I've looked through how python does serial with the "serial" module but
> it just uses Java's javax.comm libraries.  Is there anyway to do very
> low level device writing to COM ports?
> 
> In summary I'm looking for something like:
> ser = serial.Serial(0)
> ser.pin0 = 1
> ser.pin1 = 1
> ser.pin2 = 1
> 
> 
> 
> or
> ser.write('0xFF')
> which would set 8 pins on the RS232 cable to 1's

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


Re: exception KeyboardInterrupt and os.system command

2005-11-28 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 "malv" <[EMAIL PROTECTED]> wrote:
> That's also kind of what I expected.
> However, I quickly tried:
> import os
> while 1:
>  y = os.system("sleep 1")
>  z = (y >> 8) & 0xFF
>  print z
> 
> I never get anything in return but 0, hitting c-C or not.
> I have uset the above code to get exit code returns in the past though.
> Would there be anything special with sleep?

That algorithm will give you the same thing as os.WEXITSTATUS(),
on most platforms, though not necessarily all so it's better
to use the function.

On platforms where it works, exit status is of course stored in
2nd byte from the low end, and signal status is stored separately,
in the low byte.  So naturally, your right shift discards the
signal status and you're left with 0.

On the other hand, if you use os.spawnv, signal status will
be returned as a negative integer, instead of a positive
integer exit status.  spawnv() is safer than system() if the
command is constructed from data, and it also doesn't block
SIGINT in the caller like system does, so it would work for
the problem posed in the original post.

But it might be just as well to watch the process status for
any non-zero value, and then call the graceful exit procedure.

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


Re: Death to tuples!

2005-11-28 Thread Aahz
In article <[EMAIL PROTECTED]>, Mike Meyer  <[EMAIL PROTECTED]> wrote:
>
>Is there any place in the language that still requires tuples instead
>of sequences, except for use as dictionary keys?
>
>If not, then it's not clear that tuples as a distinct data type
>still serves a purpose in the language. In which case, I think it's
>appropriate to consider doing away with tuples. Well, not really:
>just changing their intended use, changing the name to note that, and
>tweaking the implementation to conform to this.

There's still the obstacle known as Guido.  I suggest you write a PEP so
that whatever decision gets made, there's a document.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which License Should I Use?

2005-11-28 Thread Rocco Moretti
Steven D'Aprano wrote:
> On Fri, 25 Nov 2005 11:30:46 -0800, mojosam wrote:
> 
>>I guess I don't care too much about how other people use it.
> 
> Then probably the best licence to use is just to follow the lead of
> Python. For that sort of small program of limited value, I put something
> like this in the code:
> 
> Copyright (c) 2005 Steven D'Aprano.
> Released under the same license as used by Python 2.3.2 itself. 
> See http://www.python.org/psf/license.html for details, and 
> http://www.python.org/2.3.2/license.html for the full text of the license.

Gaak! No! The Python license you point to contains horrible amounts of 
cruft due to the ownership ping-pong game. (And just using the hyperlink 
like you did leaves it vauge as to who is doing the liscensing - Steven 
D'Aprano? the PSF? BeOpen? CNRI? Stichting Mathematisch Centrum?) As I 
understand it, the PSF's official position is that the Python license 
(even just the top most one) is not appropriate for any program besides 
Python itself.

http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq

Note that the Python license is not even appropriate for third party 
code that's intended to be contributed to the Python standard library or 
core!

If you want a "like Python" license, try the MIT or "new-BSD" license 
instead:
http://www.opensource.org/licenses/mit-license.php
http://www.opensource.org/licenses/bsd-license.php
-- 
http://mail.python.org/mailman/listinfo/python-list


[pyparsing] How to get arbitrary text surrounded by keywords?

2005-11-28 Thread Inyeol Lee
I'm trying to extract module contents from Verilog, which has the form
of;

module foo (port1, port2, ... );

// module contents to extract here.
...

endmodule

To extract the module contents, I'm planning to do something like;

from pyparsing import *

ident = Word(alphas+"_", alphanums+"_")
module_begin = Group("module" + ident + "(" + OneOrMore(ident) + ")" + ";")
module_contents = ???
module_end = Keyword("endmodule")
module = Group(module_begin + module_contents + module_end)

(abobe code not tested.)

How should I write the part of 'module_contents'? It's an arbitrary text
which doesn't contain 'endmodule' keyword. I don't want to use full
scale Verilog parser for this task.

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


After migrating from debian to ubuntu, tkinter "hello world" doesn't work

2005-11-28 Thread mortuno
Hi

My tkinter apps worked fine in debian linux (woody and sarge)
I moved to ubuntu 5.10

I follow the 'hello world' test as seen in
http://wiki.python.org/moin/TkInter


import _tkinter # with underscore, and lowercase 't'
import Tkinter # no underscore, uppercase 'T'
Tkinter._test() # note underscore in _test()

and at the third point I get:

  File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1569, in __init__
self.tk = _tkinter.create(screenName, baseName, className,
interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: this isn't a Tk applicationi


Some posts relate this error to locales, but I didn't change them

locale.getlocale()
('es_ES', 'iso-8859-15')

any help will be appreciated

Miguel

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


Re: Which License Should I Use?

2005-11-28 Thread Steve Holden
Steven D'Aprano wrote:
> On Fri, 25 Nov 2005 11:30:46 -0800, mojosam wrote:
> 
> 
>>I guess I don't care too much about how other people use it.
> 
> 
> Then probably the best licence to use is just to follow the lead of
> Python. For that sort of small program of limited value, I put something
> like this in the code:
> 
> Copyright (c) 2005 Steven D'Aprano.
> Released under the same license as used by Python 2.3.2 itself. 
> See http://www.python.org/psf/license.html for details, and 
> http://www.python.org/2.3.2/license.html for the full text of the license.
> 
> I use that as a no-brainer licence: it is weaker than but compatible with
> the GPL, and requires less documentation.
> 
Not only is this inappropriate, it doesn't even license users to use 
your software, it licenses them to use Python! The official advice of 
the PSF is that the unmodified Python license should *not* (and, really, 
can not) be used to license any other software.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: How to write an API for a Python application?

2005-11-28 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Alex Martelli <[EMAIL PROTECTED]> wrote:
.
.
.
>Note also that you can freely download all of the code in my book as
>http://examples.oreilly.com/pythonian/pythonian-examples.zip (it's just
>36 KB).  In that same chapter you will find several implementations of
.
.
.
1.  Private e-mail to all the addresses I have for you has
been bouncing.
2.  Both 19-7 and 19-8 in the ZIP I found at that URL have
a curious typo that I'll describe this way:
  s/_  _/__/g
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >